-
Notifications
You must be signed in to change notification settings - Fork 0
/
multilayers.py
1797 lines (1553 loc) · 69.2 KB
/
multilayers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Name : multilayers
Author : Joan Juvert <trust.no.one.51@gmail.com>
Version : 1.0
Description : A class library to simulate light propagation in
: multilayer systems.
Copyright 2012 Joan Juvert
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
################################# ToDo ################################
#
# Some attributes that have a 'get' method could be decorated as
# properties in order to supress the parantheses in the method call.
#
# The reflection coefficients for TE and TM waves, rte and rtm, as well
# as their ratio -rtm/rte, could be expressed in terms of ellipsometric
# angles Psi and Delta (see Handbook of ellipsometry, Tompkins)
#
#######################################################################
import bphysics as bp
import numpy as np
import scipy.interpolate as interpolation
############################ Class definitions ########################
class Medium(object):
"""
The Medium class implements an object representing an optical
medium (basically its refractive index).
It contains the minimum and maximum wavelengths for which the
refractive index is known and a couple of interpolators to calculate
the refractive index and extintion coefficient at any wavelength in
the available range.
All the attributes are private and accessed through the provided
methods.
"""
def __init__(self, filename, comments='#', delimiter=None,
converters=None, skiprows=0, usecols=None):
"""
Initialize a Medium instance.
The refractive indices that characterize the medium are read
from a text file. After loading the table of refractive indices
an interpolator is built that allows to calculate the refractive
index at any wavelength within the available range.
Note that the table is actually read through the numpy.loadtxt
function. The loaded text file must have a column with the
wavelength values, another with the real part of the refractive
index, and another with its imaginary part. If there are other
columns in your file, or there are not in that order, the
'usecols' optional argument can be used to select which columns
to read.
Parameters
----------
filename : str
Path to the file containing the table of triplets
(wavelenght, n, k) that characterize the index of refraction
of the medium.
comments : str, optional
The character used to indicate the start of a comment;
default: '#'.
delimiter : str, optional
The string used to separate values. By default, this is any
whitespace.
converters : dict, optional
A dictionary mapping column number to a function that will
convert that column to a float. E.g., if column 0 is a date
string:``converters = {0: datestr2num}``. Converters can
also be used to provide a default value for missing data
(but see also `genfromtxt`):
``converters = {3: lambda s: float(s.strip() or 0)}``.
Default: None.
skiprows : int, optional
Skip the first `skiprows` lines; default: 0.
usecols : sequence, optional
Which columns to read, with 0 being the first. For example,
``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th
columns. The default, None, results in all columns being
read.
Returns
-------
out : Medium
A Medium instance.
See also
--------
numpy.loadtxt
"""
# Initialize variables
self.__maxWlength = None
self.__minWlength = None
self.__nInterpolator = None
self.__kInterpolator = None
# Load the table of refractive indices and generate the
# interpolators.
table = np.loadtxt(filename, 'float', comments, delimiter,
converters, skiprows, usecols)
wavelengths = table[:, 0]
refrIndex = table[:, 1]
extCoef = table[:, 2]
self.__maxWlength = wavelengths.max()
self.__minWlength = wavelengths.min()
self.__nInterpolator = interpolation.interp1d(
wavelengths, refrIndex, kind='cubic')
self.__kInterpolator = interpolation.interp1d(
wavelengths, extCoef, kind='cubic')
def getRefrIndex(self, wavelength):
"""
Returns the complex refractive index at the given wavelength.
Parameters
----------
wavelength : float
The wavelength at which we want to calculate the complex
refractive index. In the same units as in the file from
which the refractive indices were loaded.
Returns
-------
out : numpy.complex128
The complex refractive index.
"""
try:
return self.__nInterpolator(wavelength) + \
self.__kInterpolator(wavelength) * 1j
except ValueError:
print("Error: you are trying to work at a wavelength outside " + \
"the range where the refractive indices are known")
raise
def getMinMaxWlength(self):
"""
Returns a tuple (min, max) with the shortest and longest
wavelengths for which the refractive index is known.
Returns
-------
out : tuple
A tuple with the minimum and maximum wavelengths for which
the refractive index can be calculated. In the same units as
in the file from which the refractive indices were loaded.
"""
return (self.__minWlength, self.__maxWlength)
class Multilayer(object):
"""
The Multilayer class implements a layered optical medium in a
logical way. That allows to perform some complex calculations in an
understandable and flexible way.
All the attributes are private and accessed through the provided
methods. The structure is the following:
workingWavelength
minMaxWlength
polarization
charMatrixUpDown
charMatrixDownUp
coefficientsUpDown --> {'r', 't', 'R', 'T'}
coefficientsDownUp --> {'r', 't', 'R', 'T'}
stack --> [
top medium,
layer 1
.
.
.
layer N,
bottom medium ----> {
] 'medium', ------> Medium instance
'position',
'thickness',
'angle',
'matrix'
'refindex'
}
#There are properties that are common to the whole system:
- Wavelength of the light.
- Minimum and maximum wavelengths at which the refractive
indices can be calculated in all the layers.
- Polarization of the light.
- The characteristic matrix in the up-down direction of
propagation.
- The characteristic matrix in the down-up direction of
propagation.
- The optical coefficients (reflection coefficient, refraction
coefficient, reflectance and transmittance).
The stack is implemented as a list and contains parameters that
change in each layer. Each layer is a dictionary with the following
data:
- The medium (determines the refractive index). This is a
reference to a Medium instance.
- The position (z coordinate) of the layer.
- The thickness of the layer.
- The propagation angle of the light
- The characteristic matrix of the layer.
- The complex refractive index of the layer at the current
wavelength.
"""
def __init__(self, mediums):
"""
Generates a multilayer structure.
Note that a system with a layer of zero thickness is physically
the same as the system without that layer, and the results of
the simulations will be the same. However, bear in mind that you
cannot "grow" a nonexistent layer but you can "grow" an existing
zero thickness layer (i.e, change its thickness).
Initializing the multilayer does not involve providing any
information regarding the properties of the light propagating
across it. Before any calculation can be made you must enter the
wavelength, polarization and propagation angle of the light
using the appropiate methods.
Parameters
----------
mediums : list
A list containing the Medium instances that form the
multilayer system. The first element of the list corresponds
to the upper medium and the last one corresponds to the
bottom medium. At least two mediums must be given.
Each element of the list (except the first and the last) is
another list with two elements: the first is a reference to
a Medium instance, and the second is a scalar representing
the thickness of that layer. If only a Medium instance is
given instead of a list with two elements, then the
thickness will be considered zero. If the thickness is an
'int' it will be promoted to 'float'. The thickness must be
in the same units as the wavelength.
The first and last elements of "mediums" are just a
reference to the corresponding Medium instances. The
thickness is not necessary because they represent the top
and bottom mediums and the thickness will be considered
infinite.
Returns
-------
out : Multilayer
A multilayer instance.
Example
-------
If topmedium, layer1, layer2 and bottommedium are Medium
instances, then the following statement builds a system with
topmedium and bottommedium as top and bottom mediums
respectively, and two layers, one of layer1 10 units thick and
another of layer2 15 units thick. The thickness in the same
units as the wavelengths.
system = Multilayer([
topmedium,
[layer1, 10],
[layer2, 15],
bottommedium])
"""
# Properties of the light common to all the layers of the system
self.__workingWavelength = None
self.__polarization = None
self.__minMaxWlength = None
# List of the mediums conforming the multilayer system. Each
# element is a dictionary with the following elements keys:
# - medium: a reference to the corresponding Medium instance.
# - position: position of the lower interface of the layer.
# This is calculated automatically. The origin is at the
# boundary between the lower medium and the next layer.
# - thickness: thickness of the layer.
# - propangle: propagation angle of the light.
# - matrix: characteristic matrix of the layer.
self.__stack = []
# The following instance variables contain the characteristic
# matrices of the system (one for the up->down direction and
# another for the opposite) and a the coefficients of the system
# (also for both directions). The coefficients are stored in a
# dictionary with the following keys:
# - r: reflection coefficient
# - t: transmission coefficient
# - R: reflectivity
# - T: transmittivity
self.__charMatrixUpDown = None
self.__charMatrixDownUp = None
self.__coefficientsUpDown = {
'r': None, 't': None, 'R': None, 'T': None}
self.__coefficientsDownUp = {
'r': None, 't': None, 'R': None, 'T': None}
# Check that we get at least two mediums
try:
len(mediums)
except TypeError:
error = "Multilayer creation error: a list of mediums is expected"
print(error)
raise
if len(mediums) < 2:
error = "Multilayer creation error: at least two mediums must " + \
"be given"
print(error)
raise ValueError
# Start the creation of the multilayer
for (index, medium) in enumerate(mediums):
if (index == 0) or (index == len(mediums) - 1):
# First and last mediums.
# Check that we are given a Medium instance.
if not isinstance(medium, Medium):
error = "Multilayer creation error: element " + \
"%i is not a Medium instance" % index
print(error)
raise TypeError
self.__stack.append({
'medium': medium, 'position': None,
'thickness': np.infty, 'propangle': None,
'matrix': None, 'refindex': None})
else:
# Intermediate layers.
# If we have a Medium instance we consider the
# thickness to be zero. Otherwise we expect a list
# [medium, thickness]
if isinstance(medium, Medium):
self.__stack.append({
'medium': medium, 'position': None,
'thickness': 0.0, 'propangle': None,
'matrix': None, 'refindex': None})
elif isinstance(medium, list):
if len(medium) != 2:
error = "Multilayer creation error: " + \
"element %i must be either a " % index + \
"Medium instance or a list [Medium, thickness]"
print(error)
raise TypeError
if not isinstance(medium[0], Medium):
error = "Multilayer creation error: first " + \
"component of element %i must be " % index + \
"a Medium instance"
print(error)
raise TypeError
try:
thick = np.float(medium[1])
except TypeError:
error = "Multilayer creation error: element " + \
"%i, thickness must be a 'float' " % index + \
"or 'float'"
print(error)
raise
except ValueError:
error = "Multilayer creation error: element " + \
"%i thickness must be an 'float' " % index + \
"or 'float'"
print(error)
raise
if medium[1] < 0:
error = "Multilayer creation error: element " + \
"%i, thickness must be >= 0" % index
print(error)
raise ValueError
self.__stack.append({
'medium': medium[0], 'position': None,
'thickness': thick, 'propangle': None,
'matrix': None, 'refindex': None})
else:
error = "Multilayer creation error: element " + \
"%i must be either a Medium instance " % index + \
"or a list [Medium, thickness]"
print(error)
raise TypeError
# Calculate the positions of each layer
self.calcPositions()
# Make sure that there is a common range of wavelengths where
# the refractive index can be calculated.
# What we have to do is find de shortest and longest wavelength
# for each medium of the multilayer and then find de longest of
# the shortest and the shortest of the longest.
minimums = np.empty(self.numLayers())
maximums = np.empty(self.numLayers())
for index, layer in enumerate(self.__stack):
minimums[index] = layer['medium'].getMinMaxWlength()[0]
maximums[index] = layer['medium'].getMinMaxWlength()[1]
minimum = np.max(minimums)
maximum = np.min(maximums)
# Check that minimum is lower than maximum. Otherwise the
# intersection of the ranges of all the mediums is zero and
# therefore we do not have any refractive index common to all
# the layers
if minimum >= maximum:
error = "Fatal error: it is not possible to calculate any " + \
"refractive index common to all mediums"
print(error)
raise ValueError
self.__minMaxWlength = (minimum, maximum)
def calcPositions(self):
"""
This method calculates the positions of each layer along the
z axis (the direction perpendicular to the interfaces between
layers.
The position of a layer corresponds to the z coordinate of its
lower surface. The origin is located at the interface between
the last layer and the bottom medium. Therefore, the position of
the bottom medium is -infinity, the position of the last layer
is 0, the one above is at 0 + the thickness of the one below,
and so on.
This method does not return anything, it just sets the position
of each layer. It is automatically executed during instantiation
of a multilayer. The user typically does not need to call it.
"""
# We start setting the positions from below
reverseIndex = range(len(self.__stack))
reverseIndex.reverse()
self.__stack[reverseIndex[0]]['position'] = -np.infty
self.__stack[reverseIndex[1]]['position'] = 0.0
for layerIndex in reverseIndex[2:]:
self.__stack[layerIndex]['position'] = self.__stack[
layerIndex + 1]['position'] + \
self.getThickness(layerIndex + 1)
def getPosition(self, layerIndex):
"""
This method returns the position of the layer with index
'layerIndex'.
Parameters
----------
layerIndex : int
The index of the layer. Index 0 corresponds to the top
medium.
Returns
-------
out : float
The position of the layer, which corresponds to the z
coordinate of its lower surface.
"""
if layerIndex < 0:
error = "Negative index not accepted"
print(error)
raise IndexError
return self.__stack[layerIndex]['position']
def setThickness(self, thickness, layerIndex):
"""
This method changes the thickness of the layer with index
'layerIndex' to a new value.
Index 0 corresponds to the top medium. The positions of the
layers above the one being changed will be recalculated
accordingly.
Note that the thickness of the top and bottom mediums cannot be
changed because they are infinite.
The characteristic matrices of the system and the coefficients
will be reset to zero because they must be recalculated after
the thickness change. However, only the individual matrix of
the layer being modified will be reset to zero. The individual
matrices of all other layers remain the same.
Parameters
----------
thickness : float
The thickness of the layer. In the same units as the
wavelengths.
layerIndex : int
The index of the layer. Index 0 corresponds to the top
medium.
"""
# Change the thickness of the layer
if thickness < 0:
error = "Negative thickness not accepted"
print(error)
raise ValueError
if layerIndex < 0:
error = "Negative index not accepted"
print(error)
raise IndexError
if (layerIndex == 0) or (layerIndex == len(self.__stack) - 1):
error = "Error setting thickness: the thickness of the top " + \
"and bottom mediums cannot be changed"
print(error)
raise IndexError
self.__stack[layerIndex]['thickness'] = np.float(thickness)
# Recalculate the z coordinates of the layers and reset matrices
# and coefficients.
self.calcPositions()
self.__stack[layerIndex]['matrix'] = None
self.__charMatrixUpDown = None
self.__charMatrixDownUp = None
self.__coefficientsUpDown['r'] = None
self.__coefficientsUpDown['t'] = None
self.__coefficientsUpDown['R'] = None
self.__coefficientsUpDown['T'] = None
self.__coefficientsDownUp['r'] = None
self.__coefficientsDownUp['t'] = None
self.__coefficientsDownUp['R'] = None
self.__coefficientsDownUp['T'] = None
def getThickness(self, layerIndex):
"""
This method returns the thickness of the layer with index
'layerindex'. Index 0 corresponds to the top medium.
Parameters
----------
layerIndex : int
The index of the layer. Index 0 corresponds to the top
medium.
Returns
-------
out : float
The thickness of the layer. In the same units as the
wavelengths.
"""
if layerIndex < 0:
error = "Negative index not accepted"
print(error)
raise IndexError
return self.__stack[layerIndex]['thickness']
def getMinMaxWlength(self):
"""
This method returns a tuple (min, max) with the shortest and
longest wavelengths for which the refractive index can be
calculated in all the layers forming the multilayer system.
Returns
-------
out : tuple
A tuple containing the minimum and maximum wavelengths
within which the refractive index can be interpolated in all
the mediums of the multilayer. In the same units as in the
file from which the refractive indices were loaded.
"""
return self.__minMaxWlength
def numLayers(self):
"""
This method returns the number of layers of the multilayer
system including the top and bottom mediums.
Returns
-------
out : int
The number of layers of the multilayer system, including the
top and bottom mediums.
"""
return len(self.__stack)
def getIndexAtPos(self, z):
"""
Returns the index of the layer within which z lies.
Parameters
----------
z : float
A z coordinate. z = 0 is at the surface between the bottom
medium and the next layer. The position of a layer is the z
coordinate of its lower interface. The units are the same as
the thickness and wavelengths.
Returns
-------
out : int
The index of the layer within which z lies.
"""
# For each layer starting at the upper medium, check if the
# given z is larger or equal than the position of the layer. If
# it is, then z lies in the current layer, otherwise move to the
# next one.
for index in range(self.numLayers()):
if z >= self.getPosition(index):
return index
def setWlength(self, wavelength, rilist=None):
"""
This method sets the wavelength of the light going through the
multilayer system and sets the actual refractive index in each
layer.
Since changing the working wavelength also changes the
refractive index in effect, the propagation angles must be
recalculated. For that reason, this method will reset the
propagation angle in all the layers to 'None'. That will force
the user to execute again the setPropAngle() method.
Otherwise the calculation of the characteristic matrices will
rise an error.
Also, the characteristic matrices must be recalculated.
Therefore, they will also be reset to None along with the
coefficients.
Optionally, the refractive indices of the layers can be
passed explicitly with a list. This avoids calculating each
refractive index using the interpolator. Using this is
dangerous and discouraged. Use it only if you know what you are
doing.
Parameters
----------
wavelength : float
The wavelength of the light going across the system. In the
same units as in the file from which the refractive indices
were loaded.
rilist : list, optional
A list containing the refractive index of each layer at the
wavelength being set. The items must be ordered, the first
one corresponding to the top layer and the last one to the
bottom layer. Remember that the refractive indices are
complex numbers. If you pass a real number, it will be
converted to numpy.complex128. The use of this option is
discouraged. Use it only if you know what you are doing.
"""
# Only accept wavelengths within the available range
minimum, maximum = self.getMinMaxWlength()
if wavelength < minimum or wavelength > maximum:
error = "Error: Wavelength out of bounds"
print(error)
raise ValueError
self.__workingWavelength = np.float64(wavelength)
# Calculate the refractive indices of each layer and reset the
# variables that must be recalculated due to the change in the
# wavelength.
if rilist == None:
for index in range(self.numLayers()):
self.__stack[index]['propangle'] = None
self.__stack[index]['matrix'] = None
self.__stack[index]['refindex'] = \
self.__stack[index]['medium'].getRefrIndex(wavelength)
else:
for index in range(self.numLayers()):
self.__stack[index]['propangle'] = None
self.__stack[index]['matrix'] = None
try:
ri = rilist[index]
except:
error = "rilist must be an ordered sequence and have " + \
"as many items as layers in the system"
print(error)
raise TypeError
try:
ri = np.complex128(ri)
except:
error = "The refractive index must be a number"
print(error)
raise TypeError
self.__stack[index]['refindex'] = ri
self.__charMatrixUpDown = None
self.__charMatrixDownUp = None
self.__coefficientsUpDown['r'] = None
self.__coefficientsUpDown['t'] = None
self.__coefficientsUpDown['R'] = None
self.__coefficientsUpDown['T'] = None
self.__coefficientsDownUp['r'] = None
self.__coefficientsDownUp['t'] = None
self.__coefficientsDownUp['R'] = None
self.__coefficientsDownUp['T'] = None
def getWlength(self):
"""
This method returns the current wavelength of the light going
through the multilayer.
Returns
-------
out : float
The wavelength of the light going across the system. In the
same units as in the file from which the refractive indices
were loaded.
"""
return self.__workingWavelength
def setPolarization(self, polarization):
"""
Sets the polarization of the light going through the multilayer
system.
Since the characteristic matrices will change, they will be
reset to None in order to force the user to calculate them again
with the corresponding methods. The same goes for the
coefficients.
Parameters
----------
polarization : str
The polarization of the ligth going across the system. It
may be "te" or "tm", case insensitive.
"""
try:
polarization = polarization.upper()
if (polarization != 'TE') and (polarization != 'TM'):
raise ValueError
except ValueError:
error = "Error setting polarization: polarization must be " + \
"'te' or 'tm'"
print(error)
raise ValueError
except AttributeError:
error = "Error setting polarization: polarization must be " + \
"'te' or 'tm'"
print(error)
raise AttributeError
self.__polarization = polarization
# Reset the characteristic matrices and coefficients
for index in range(self.numLayers()):
self.__stack[index]['matrix'] = None
self.__charMatrixUpDown = None
self.__charMatrixDownUp = None
self.__coefficientsUpDown['r'] = None
self.__coefficientsUpDown['t'] = None
self.__coefficientsUpDown['R'] = None
self.__coefficientsUpDown['T'] = None
self.__coefficientsDownUp['r'] = None
self.__coefficientsDownUp['t'] = None
self.__coefficientsDownUp['R'] = None
self.__coefficientsDownUp['T'] = None
def getPolarization(self):
"""
Returns the polarization of the light going through the
multilayer system.
Returns
-------
out : str
The polarization of the ligth going across the system. It
may be "TE" or "TM".
"""
return self.__polarization
def setPropAngle(self, angle, index=0):
"""
Sets the propagation angle of light in the layer of given
index.
The propagation angle in all other layers is automatically
calculated using Snell's Law. The angle must be given in
radians.
If a list is given instead of a single angle, the angles will
be set to those found in the list following the natural order
(first angle to top medium, last angle to bottom medium). Use
of this feature is strongly discouraged. Use it only if you
know what you are doing.
Since the characteristic matrices and coefficients must be
recalculated, they will be reset to None to force the user to
execute again the relevant methods for its calculation.
Parameters
----------
angle : float or complex or list of floats or complexes
Propagation angle in radians. Use of a list instead of a
single angle is strongly discouraged. Use it only if you
know what you are doing.
index : int, optional
The index of the layer at which light propagates with the
given angle. If not specified, it will be assumed that the
angle corresponds to the propagation in the upper medium
(index = 0).
"""
# Do not accept a negative index.
if index < 0:
error = "Negative index not accepted"
print(error)
raise IndexError
if index >= self.numLayers():
error = "Layer %i does not exist" % index
print(error)
raise IndexError
# We want to work always with complex angles for when we have
# propagation beyond the critical angle.
angle = np.complex128(angle)
if self.getWlength() == None:
error = "Error setting propagation angle: a working " + \
"wavelength has not been set"
print(error)
raise ValueError
wavelength = self.getWlength()
if type(angle) == np.complex128:
# We set the angle in the layer specified in the argument. All
# other layers get the appropiate angle calculated using Snell's
# law
sine_i = np.sin(angle)
n_i = self.getRefrIndex(index)
for layerIndex in range(self.numLayers()):
if layerIndex == index:
self.__stack[layerIndex]['propangle'] = angle
else:
n_f = self.getRefrIndex(layerIndex)
if n_f == n_i:
self.__stack[layerIndex]['propangle'] = angle
else:
self.__stack[layerIndex]['propangle'] = np.arcsin(
n_i * sine_i / n_f)
else:
# In this case we have a list of angles. We copy them
# directly to the layer.
for layerIndex in range(self.numLayers()):
try:
self.__stack[layerIndex]['propangle'] = angle[layerIndex]
except:
error = "angle must be a number or a list of numbers " + \
"with as many items as layers in the system"
print(error)
raise TypeError
# Reset the characteristic matrices and the coefficients
for index in range(self.numLayers()):
self.__stack[index]['matrix'] = None
self.__charMatrixUpDown = None
self.__charMatrixDownUp = None
self.__coefficientsUpDown['r'] = None
self.__coefficientsUpDown['t'] = None
self.__coefficientsUpDown['R'] = None
self.__coefficientsUpDown['T'] = None
self.__coefficientsDownUp['r'] = None
self.__coefficientsDownUp['t'] = None
self.__coefficientsDownUp['R'] = None
self.__coefficientsDownUp['T'] = None
def getPropAngle(self, index):
"""
Returns the propagation angle of the light in the layer with the
given index.
Parameters
----------
index : int
The index of the layer. Index 0 corresponds to the upper
medium.
Returns
-------
out : complex
The propagation angle. It may be complex if there has been
total internal reflection in a lower interface.
"""
if index < 0:
error = "Negative index not accepted"
print(error)
raise IndexError
if index >= self.numLayers():
error = "Layer %i does not exist" % index
print(error)
raise IndexError
return self.__stack[index]['propangle']
def getRefrIndex(self, index):
"""
Returns the complex refractive index at the current wavelength
within the layer with the given index.
For example, multilayer.getRefrIndex(0) would return the complex
refractive index at 400 units of length (nm typically) in the
top medium.
Parameters
----------
index : int
The index of the layer. Index 0 corresponds to the upper
medium.
Returns
-------
out : complex128
The complex refractive index for the given wavelength at the
medium of given index.
"""
if index < 0:
error = "Negative index not accepted"
print(error)
raise IndexError
if index >= self.numLayers():
error = "Layer %i does not exist" % index
print(error)
raise IndexError
return self.__stack[index]['refindex']
def calcMatrices(self, layerIndexes=[]):
"""
This method calculates the characteristic matrix of the
specified layers.
Note that the top and bottom medium do not have characteristic
matrices. An error will be raised if you try to calculate their
characteristic matrices.
The matrix is stored in a numpy.ndarray variable. Note that this
method does not return anything, it just stores the calculated
matrices in the corresponding field of the multilayer.
Parameters
----------
layerIndexes : list, optional
A list of the indices of the layers whose characteristic
matrix should be calculated. If the list is empty, the
matrices of all the layers (except top and bottom mediums)
will be calculated. Same if the parameter is skipped.
See Also
--------
getMatrix
"""
if not isinstance(layerIndexes, list):
error = "Error: the argument of calcMatrices must be a list"
print(error)
raise ValueError
if len(layerIndexes) == 0:
# Calculate all the characteristic matrices
layerList = range(1, self.numLayers() - 1)
else:
# Calculate only the characteristic matrices of the given
# layers.
layerList = layerIndexes
# Perform here the actual calculation
for layerIndex in layerList:
if not isinstance(layerIndex, int):
error = "Error: the layer index must be an integer"
print(error)
raise ValueError
if (layerIndex == 0) or (layerIndex == self.numLayers() - 1):
error = "Error: the characteristic matrix of the top and " + \
"bottom mediums cannot be calculated"
print(error)
raise ValueError
if (layerIndex >= self.numLayers()) or (layerIndex < 0):
error = "Error: valid layer indices from %i to %i" % \
(1, self.numLayers() - 2)