-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTRANK_lib.py
1463 lines (1039 loc) · 47.8 KB
/
TRANK_lib.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
from tmm import inc_tmm
from numpy import sqrt, array
def TMM_spectrum_wrapper(nk_fit, lamda, snell_angle_front, layer_index_of_fit, nk_f_list, thickness_list, coherency_list, tm_polarization_fraction, spectrum): #this is just a fancy wrapper for inc_tmm
nk_list = [ nk_f(lamda) for nk_f in nk_f_list]
try: # just try iterating through the layer_index_of_fit to see if its a list of just an int
for index in layer_index_of_fit:
nk_list[index] = nk_fit # overwrite input nk_f with the fit one.
except:
nk_list[layer_index_of_fit] = nk_fit
te_result = inc_tmm('s', nk_list, thickness_list, coherency_list, snell_angle_front, lamda)
tm_result = inc_tmm('p', nk_list, thickness_list, coherency_list, snell_angle_front, lamda)
T = tm_polarization_fraction * tm_result['T'] + (1.0-tm_polarization_fraction) * te_result['T']
R = tm_polarization_fraction * tm_result['R'] + (1.0-tm_polarization_fraction) * te_result['R']
if callable(spectrum)==False:
A = 1 - T - R
result_dict = { 'T': T,
'R': R,
'A': A }
result = result_dict[spectrum]
else:
result = spectrum(T,R) # allows you to create things like extiction where the spectrum is 1-T
return result
def spectrum_lamda_error(params): # This has to be at the top level because map is strange and wont pickle onless it is at the top level
lamda = params[0] # these params are per Wavelength, we could get more ganular parallelism with this!
nk = params[1]
spectrum_list_generator = params[2]
parameter_list_generator = params[3]
spectrum_list = spectrum_list_generator(lamda)
sqrt_point_multiplicity = sqrt(len(spectrum_list))
list_of_parameters = parameter_list_generator(lamda)
sub_error_list=[]
if len(spectrum_list) > 0:
for spectrum, parameters in zip (spectrum_list, list_of_parameters ):
spectrum_calculated = TMM_spectrum_wrapper(nk_fit = nk, **parameters) # these parameters are per measurement, set of parameters for a single point tmm model
error = (spectrum_calculated - spectrum)/sqrt_point_multiplicity # in the formulation this gets squared later, and we look at the per Wavelength rms error and normalizing it gives portability to weights
#we'll put wieghting somewhere else so that the formulation is clear
sub_error_list.append( error)
else:
print ("WARNING: No spectra at lamda = %f point, nk values here are only interpolations!" % lamda)
return sub_error_list
def pointwise_rms_error_sum_wrapper(params): # for each Wavelength, wraps the previous function TRA_lamda_error to quikcly compute error spectrum
from numpy import sqrt
point_error_list = spectrum_lamda_error(params)
sum_err_square = 0.0
for err in point_error_list:
sum_err_square += err**2
return sqrt(sum_err_square)
def rms_error_spectrum(lamda_list, nk_f, spectrum_list_generator, parameter_list_generator, threads = 0 ):
muh_inputs = []
for lamda in lamda_list:
muh_inputs.append( (lamda, nk_f(lamda), spectrum_list_generator, parameter_list_generator ) )
from multiprocessing import Pool, cpu_count
if threads <= 0:
threads = cpu_count()
my_pool = Pool(threads)
#print ('Using %i Threads' % threads)
error_spectrum = my_pool.map(pointwise_rms_error_sum_wrapper, muh_inputs)
my_pool.terminate()
return error_spectrum
def sqr_rms_gradient_at_lamda(params, h_nk = 1e-6):
from numpy import array
def shift_nk(params, shift): # i use this code to make it clearer
return [params[0], params[1]+shift, params[2], params[3]]
e_p_0 = pointwise_rms_error_sum_wrapper(shift_nk(params, h_nk ))**2
e_m_0 = pointwise_rms_error_sum_wrapper(shift_nk(params, -h_nk ))**2
e_0_p = pointwise_rms_error_sum_wrapper(shift_nk(params, h_nk*1.0j ))**2
e_0_m = pointwise_rms_error_sum_wrapper(shift_nk(params, -h_nk*1.0j ))**2
e_n = (e_p_0 - e_m_0)/(2.0*h_nk)
e_k = (e_0_p - e_0_m)/(2.0*h_nk)
gradient = array([e_n, e_k])
return gradient
def sqr_rms_hessian_at_lamda(params, h_nk = 1e-4):
from numpy import array
def shift_nk(params, shift): # i use this code to make it clearer
return [params[0], params[1]+shift, params[2], params[3]]
e_0_0 = pointwise_rms_error_sum_wrapper(shift_nk(params, 0.0 ))**2
e_p_0 = pointwise_rms_error_sum_wrapper(shift_nk(params, h_nk*( 1.0+0.0j) ))**2
e_m_0 = pointwise_rms_error_sum_wrapper(shift_nk(params, -h_nk*( 1.0+0.0j) ))**2
e_0_p = pointwise_rms_error_sum_wrapper(shift_nk(params, h_nk*( 0.0+1.0j) ))**2
e_0_m = pointwise_rms_error_sum_wrapper(shift_nk(params, -h_nk*( 0.0+1.0j) ))**2
e_p_p = pointwise_rms_error_sum_wrapper(shift_nk(params, h_nk*( 1.0+1.0j) ))**2
e_m_m = pointwise_rms_error_sum_wrapper(shift_nk(params, h_nk*(-1.0-1.0j) ))**2
e_p_m = pointwise_rms_error_sum_wrapper(shift_nk(params, h_nk*( 1.0-1.0j) ))**2
e_m_p = pointwise_rms_error_sum_wrapper(shift_nk(params, h_nk*(-1.0+1.0j) ))**2
e_nn = (e_p_0 - 2.0*e_0_0 + e_m_0)/(h_nk**2.0)
e_kk = (e_0_p - 2.0*e_0_0 + e_0_m)/(h_nk**2.0)
e_nk = (e_p_p - e_p_0 - e_0_p + 2.0*e_0_0 - e_m_0 - e_0_m + e_m_m)/(2.0*h_nk*h_nk) # two difference methods..., the first is supposed to be cheaper
e_nk = (e_p_p - e_p_m - e_m_p + e_m_m)/(4.0*h_nk*h_nk)
hessian = array([[e_nn, e_nk],[e_nk, e_kk]])
return hessian
def pointwise_reducible_rms_error_sum_wrapper(params): # for each Wavelength, wraps the previous function TRA_lamda_error to quikcly compute error spectrum
## calculates numeric derivatives
#does some hessians and matrix match
#from wikipedia
e_0_0 = pointwise_rms_error_sum_wrapper(params = params)**2
grad = sqr_rms_gradient_at_lamda(params = params)# h_nk = h_nk)
hessian = sqr_rms_hessian_at_lamda(params = params)#, h_nk = h_nk)
from numpy.linalg import det, inv
from numpy import dot, array, sqrt
if det(hessian) > 0.0: # minima predicted
hessian_inv = inv(hessian)
#reducible_error = 1/2.0 * dot(grad, dot( hessian_inv, grad))
#if reducible_error > e_0_0: # can't go negative this way
# reducible_error = e_0_0
#irreducible_error = e_0_0 - reducible_error
S_change = 1.0/2.0 * dot(grad, dot( hessian_inv, grad))
Smin = e_0_0 - S_change
irreducible_error = Smin
reducible_error = e_0_0 - irreducible_error
if irreducible_error < 0.0: # removing this might make better results even if unrealisitc
reducible_error = e_0_0 # bascially its predicting negative error is posible, nah just meas it can go to zero
irreducible_error = 0.0
#if reducible_error < 0.0:
# print( params[0], det(hessian), S_change, [reducible_error, irreducible_error])
else: # what else should i do here, I assume it means the band is caught on a peak?
#irreducible_error = e_0_0
#reducible_error = 0.0
irreducible_error = 0.0
reducible_error = e_0_0
#print( params[0], det(hessian), [reducible_error, irreducible_error])
return [reducible_error, irreducible_error]
def reducible_rms_error_spectrum(lamda_list, nk_f, spectrum_list_generator, parameter_list_generator, threads = 0):
muh_inputs = []
for lamda in lamda_list:
muh_inputs.append( (lamda, nk_f(lamda), spectrum_list_generator, parameter_list_generator ) )
from numpy import array, sqrt
from multiprocessing import Pool, cpu_count
if threads <= 0:
threads = cpu_count()
my_pool = Pool(threads)
#print ('Using %i Threads' % threads)
error_spectra = array(my_pool.map(pointwise_reducible_rms_error_sum_wrapper, muh_inputs)).T
my_pool.terminate()
reducible_error_spectrum = sqrt(error_spectra[0])
irreducible_error_spectrum = sqrt(error_spectra[1])
return reducible_error_spectrum, irreducible_error_spectrum
def single_lamda_rms_error_map(lamda, nlist, klist, spectrum_list_generator, parameter_list_generator, threads = 0):
muh_inputs = []
for n in nlist:
for k in klist:
muh_inputs.append( (lamda, n+1.0j*k, spectrum_list_generator, parameter_list_generator ) )
from multiprocessing import Pool, cpu_count
if threads <= 0:
threads = cpu_count()
my_pool = Pool(threads)
#print ('Using %i Threads' % threads)
from numpy import reshape, array
error_list = my_pool.map(pointwise_rms_error_sum_wrapper, muh_inputs)
error_map = reshape( array(error_list), (len(nlist), len(klist) ))
my_pool.terminate()
return error_map #[nindex,kindex]
def spectrum_TMM_lamda(params): # This has to be at the top level because map is strange and wont pickle onless it is at the top level
'''Returns a list of the spectrum values for each single point at a Wavelength'''
lamda = params[0]
nk = params[1]
parameter_list_generator = params[2]
list_of_parameters = parameter_list_generator(lamda)
spectrum_list = []
for parameters in list_of_parameters :
spectrum_list.append( TMM_spectrum_wrapper(nk_fit = nk, **parameters) )
return spectrum_list
def TMM_spectra(lamda_list, nk_f, parameter_list_generator, threads = 0):
''''''
#returns data in block like spectra[lamda][ spectrum] there are computational reasons why this order is this way
muh_inputs = []
for lamda in lamda_list:
muh_inputs.append( (lamda, nk_f(lamda), parameter_list_generator ) )
from multiprocessing import Pool, cpu_count
if threads <= 0:
threads = cpu_count()
my_pool = Pool(threads)
#print ('Using %i Threads' % threads))
spectra = my_pool.map(spectrum_TMM_lamda, muh_inputs)
my_pool.terminate()
#
return spectra
###################
def fit_spectra_nk_sqr(lamda_list, spectrum_list_generator, parameter_list_generator, nk_f_guess, delta_weight = 0.1, k_weight_fraction = 1.0, tolerance = 1e-5, no_negative = True, interpolation_type = 'cubic', method = 'least_squares', threads = 0):
'''n_front and n_back must be real valued for this to work without caveats.
thickness and lambda can be any units, so long as they are the same, lamda_list must be sorted'''
from numpy import pi,exp,abs,sqrt, array, matmul, loadtxt, zeros, savetxt, inf, diff, ones
from scipy.optimize import root, least_squares, minimize
from TRANK import extrap
#point_multiplicity = len(spectrum_list_generator(lamda_list[0]))
#print(point_multiplicity)
#point_multiplicity_list = [len(spectrum_list_generator(lamda)) for lamda in lamda_list ]
#point_multiplicity = point_multiplicity_list[0]
abs_delta_weight = sqrt(delta_weight**2 * (len(lamda_list)/(len(lamda_list)-1.0)))
from multiprocessing import Pool, cpu_count
if threads <= 0:
threads = cpu_count()
my_pool = Pool(threads)
print ('Using %i Threads' % threads)
def F_error(nk_list):
c_nk_list = []
muh_inputs = []
for i in range(len(lamda_list)):
nk = nk_list[2*i] + 1.0j*nk_list[2*i+1]
c_nk_list.append(nk)
muh_inputs.append( (lamda_list[i], nk, spectrum_list_generator, parameter_list_generator ) )
error_list_lists = my_pool.map(spectrum_lamda_error, muh_inputs)
#combine the sub error lists into
error_list = []
for sub_error_list in error_list_lists:
error_list = error_list + sub_error_list
delta_array = diff(c_nk_list)*abs_delta_weight
error_list = error_list + list(delta_array.real) + list(k_weight_fraction * delta_array.imag)
return error_list
####### now for a guess list ##############
nk_guess_list = []
for i in range(len(lamda_list)):
nk = nk_f_guess(lamda_list[i])
n, k = nk.real, nk.imag
if no_negative and k < 0.0: k = 0
if no_negative and n < 0.0: n = 0
nk_guess_list.append(n)
nk_guess_list.append(k)
######### test
if False: print(F_error(nk_guess_list))
############ nk guessing over, time for creating and minimizing error function
if method == 'least_squares':
inputs = dict(fun = F_error,
x0 = nk_guess_list,
ftol = tolerance,
xtol = tolerance,
gtol = tolerance,
verbose = 2)
if no_negative:
inputs.update(dict( bounds = [zeros(2*len(lamda_list)),inf*ones(2*len(lamda_list))] ))
solution = least_squares(**inputs ).x
elif method == 'L-BFGS-B':
inputs = dict(fun = lambda x: 0.5*sum(array(F_error(x))**2),
x0 = nk_guess_list,
method = 'L-BFGS-B',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = 2*len(lamda_list)*[(0,inf)]))
solution = minimize(**inputs ).x
elif method == 'SLSQP':
inputs = dict(fun = lambda x: 0.5*sum(array(F_error(x))**2),
x0 = nk_guess_list,
method = 'SLSQP',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = 2*len(lamda_list)*[(0,inf)]))
solution = minimize(**inputs ).x
elif method == 'TNC':
inputs = dict(fun = lambda x: 0.5*sum(array(F_error(x))**2),
x0 = nk_guess_list,
method = 'TNC',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = 2*len(lamda_list)*[(0,inf)]))
solution = minimize(**inputs ).x
else:
raise ValueError("Invalid minimization method!")
my_pool.terminate()
my_pool.close()
nk_list=[]
for i in range(len(lamda_list)):
nk_list.append(solution[2*i] + 1.0j*solution[2*i+1] )
fit_nk_f = extrap(lamda_list, nk_list, kind = interpolation_type)
return fit_nk_f
def fit_spectra_nk_sqr_KK_compliant(lamda_list, spectrum_list_generator, parameter_list_generator, nk_f_guess,
delta_weight = 0.1, k_weight_fraction = 1.0, tolerance = 1e-5, no_negative = True, interpolation_type = 'cubic', method = 'least_squares', threads = 0):
'''n_front and n_back must be real valued for this to work without caveats.
thickness and lambda can be any units, so long as they are the same, lamda_list must be sorted'''
from numpy import pi,exp,abs,sqrt, array, matmul, loadtxt, zeros, savetxt, inf, diff, ones, mean, trapz
from scipy.optimize import root, least_squares, minimize
from TRANK import extrap
#from TRANK import parallel_DKKT_n_from_lamda_k as KKT
from TRANK import parallel_DKKT_n_from_lamda_k_with_edge_corrections as KKT
#point_multiplicity = len(TR_pair_list_generator(lamda_list[0]))
#print(point_multiplicity)
abs_delta_weight = sqrt(delta_weight**2 * (len(lamda_list)/(len(lamda_list)-1.0)))
from multiprocessing import Pool, cpu_count
if threads <= 0:
threads = cpu_count()
my_pool = Pool(threads)
print ('Using %i Threads' % threads)
def F_error(k_and_p_list):
# the last value is the principle value
#FYI -> k = array(k_and_p_list[0:-1])
k = k_and_p_list[0:-1]
p = k_and_p_list[-1]
n = p + KKT(lamda_list = lamda_list, k = k, compute_pool = my_pool )
muh_inputs = []
for i in range(len(lamda_list)):
nk = n[i]+1.0j*k[i]# double check this works properly later
muh_inputs.append( (lamda_list[i], nk, spectrum_list_generator, parameter_list_generator ) )
#print (zip(lamda_list, c_nk_list))
error_list_lists = my_pool.map(spectrum_lamda_error, muh_inputs)
#error_list_lists =my_pool.map(lamda_error, zip(lamda_list, c_nk_list))
#print (error_list_lists)
error_list = []
for sub_error_list in error_list_lists:
error_list = error_list + sub_error_list
error_list = error_list + list( abs_delta_weight*diff(n) ) + list( k_weight_fraction * abs_delta_weight * diff(k))
return error_list
####### now for a guess list ##############
guess_k_and_p_list= []
n_list = []
for i in range(len(lamda_list)):
nk = nk_f_guess(lamda_list[i])
n, k = nk.real, nk.imag
if no_negative and k < 0.0: k = 0
if no_negative and n < 0.0: n = 0
guess_k_and_p_list.append( k)
n_list.append(n)
# now we put p at the end
p = trapz(n_list, lamda_list)/(lamda_list[-1] - lamda_list[0]) # this is a guess for the principle value
print ('principle value guess:',p)
guess_k_and_p_list.append(p)
######### test
if False: print(F_error(guess_k_and_p_list)) #use this to see if the TR_error works
############ nk guessing over, time for creating and minimizing error function
if method == 'least_squares':
inputs = dict(fun = F_error,
x0 = guess_k_and_p_list,
ftol = tolerance,
xtol = tolerance,
gtol = tolerance,
verbose = 2)
if no_negative:
inputs.update(dict( bounds = [len(lamda_list)*[0.0]+[-inf],len(lamda_list)*[inf]+[inf]] ))
solution = least_squares(**inputs ).x
elif method == 'SLSQP':
inputs = dict(fun = lambda x: 0.5*sum(array(F_error(x))**2),
x0 = guess_k_and_p_list,
method = 'SLSQP',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = len(lamda_list)*[(0,inf)] + [(-inf,inf)] ))
solution = minimize(**inputs ).x
elif method == 'L-BFGS-B':
inputs = dict(fun = lambda x: 0.5*sum(array(F_error(x))**2),
x0 = guess_k_and_p_list,
method = 'L-BFGS-B',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = len(lamda_list)*[(0,inf)] + [(-inf,inf)] ))
solution = minimize(**inputs ).x
elif method == 'TNC':
inputs = dict(fun = lambda x: 0.5*sum(array(F_error(x))**2),
x0 = guess_k_and_p_list,
method = 'TNC',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = len(lamda_list)*[(0,inf)] + [(-inf,inf)] ))
solution = minimize(**inputs ).x
else:
raise ValueError("Invalid minimization method!")
k_and_p_list = solution
k = k_and_p_list[0:-1]
p = k_and_p_list[-1]
n = p + KKT(lamda_list = lamda_list, k = k, compute_pool = my_pool )
print ('Final principle value:',p)
fit_nk_f = extrap(lamda_list, n + 1.0j*k, kind = interpolation_type)
my_pool.terminate()
my_pool.close()
return fit_nk_f
def epsilon_d_to_nk_function(lamda_list, sigma_bar0, lamda_tau, interpolation_type = 'cubic'):
epsilon_d = -sigma_bar0 *(lamda_list**2/( 1.0j*lamda_list + lamda_tau ))
epsilon_abs = sqrt(epsilon_d * epsilon_d.conjugate())
n_d = sqrt((epsilon_abs + epsilon_d.real)/2.0).real
k_d = sqrt((epsilon_abs - epsilon_d.real)/2.0).real
from TRANK import extrap
nk_d_f = extrap(lamda_list, n_d + 1.0j*k_d, kind = interpolation_type)
return nk_d_f
def fit_spectra_nk_sqr_drude_KK_compliant(lamda_list, spectrum_list_generator, parameter_list_generator, nk_f_guess, sigma_bar0_guess = 0.0, lamda_tau_guess = 0.0, epsilon_f1p_guess = 0.0,
delta_weight = 0.1, k_weight_fraction = 1.0, tolerance = 1e-5, no_negative = True, interpolation_type = 'cubic', method = 'least_squares', threads = 0):
'''n_front and n_back must be real valued for this to work without caveats.
thickness and lambda can be any units, so long as they are the same, lamda_list must be sorted'''
from numpy import pi,exp,abs,sqrt, array, matmul, loadtxt, zeros, savetxt, inf, diff, ones, mean, trapz
from scipy.optimize import root, least_squares, minimize
from TRANK import extrap
#from TRANK import parallel_DKKT_n_from_lamda_k as KKT
from TRANK import parallel_DKKT_n_from_lamda_k_with_edge_corrections as KKT
from TRANK import spectrum_lamda_error
abs_delta_weight = sqrt(delta_weight**2 * (len(lamda_list)/(len(lamda_list)-1.0)))
from multiprocessing import Pool, cpu_count
if threads <= 0:
threads = cpu_count()
my_pool = Pool(threads)
print ('Using %i Threads' % threads)
lamda_list = array(lamda_list)
def F_error(epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list):
# the last values are the principle value
epsilon_f2 = epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list[0:-3]
epsilon_f1p = epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list[-3]
lamda_tau = epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list[-2]
sigma_bar0 = epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list[-1]
epsilon_f1 = epsilon_f1p + KKT(lamda_list = lamda_list, k = epsilon_f2, compute_pool = my_pool )
epsilon_f = epsilon_f1 + 1.0j*epsilon_f2
epsilon_d = -sigma_bar0 *(lamda_list**2/( 1.0j*lamda_list + lamda_tau ))
epsilon = epsilon_f + epsilon_d
epsilon_abs = sqrt(epsilon*epsilon.conjugate())
n = sqrt((epsilon_abs + epsilon.real)/2.0).real
k = sqrt((epsilon_abs - epsilon.real)/2.0).real # since we are casting the imaginary part as real
muh_inputs = []
for i in range(len(lamda_list)):
nk = n[i]+1.0j*k[i]# double check this works properly later
muh_inputs.append( (lamda_list[i], nk, spectrum_list_generator, parameter_list_generator ) )
#print (zip(lamda_list, c_nk_list))
error_list_lists = my_pool.map(spectrum_lamda_error, muh_inputs)
#error_list_lists =my_pool.map(lamda_error, zip(lamda_list, c_nk_list))
#print (error_list_lists)
error_list = []
for sub_error_list in error_list_lists:
error_list = error_list + sub_error_list
only_penalize_free = True
if only_penalize_free:
epsilon_f_abs = sqrt(epsilon_f.conjugate() * epsilon_f)
n_f = sqrt((epsilon_f_abs + epsilon_f1)/2.0).real
k_f = sqrt((epsilon_f_abs - epsilon_f1)/2.0).real # since we are casting the imaginary part as real
error_list = error_list + list( abs_delta_weight*diff(n_f) ) + list( k_weight_fraction * abs_delta_weight * diff(k_f))
else:
error_list = error_list + list( abs_delta_weight*diff(n) ) + list( k_weight_fraction * abs_delta_weight * diff(k))
return error_list
####### now for a guess list ##############
nk_d_f = epsilon_d_to_nk_function(lamda_list, sigma_bar0_guess, lamda_tau_guess, interpolation_type = 'cubic')
epsilon_f2_list = []
epsilon_f1_list = []
for i in range(len(lamda_list)):
nk = nk_f_guess(lamda_list[i])
n, k = nk.real, nk.imag
nk_d = nk_d_f(lamda_list[i])
n_d, k_d = nk_d.real, nk_d.imag
if no_negative:
if n < 0.0: n = 0
if k < 0.0: k = 0
epsilon_f1_list.append( (n**2 - k**2) - (n_d**2 - k_d**2) ) # subtracting the drude component
epsilon_f2 = 2*n*k - 2*n_d*k_d
if no_negative and epsilon_f2 < 0.0: epsilon_f2 = 0.0
epsilon_f2_list.append( epsilon_f2)
if epsilon_f1p_guess == 0.0:
epsilon_f1p = trapz(epsilon_f1_list, lamda_list)/(lamda_list[-1] - lamda_list[0])
else:
epsilon_f1p = epsilon_f1p_guess
if sigma_bar0_guess == 0.0:
from numpy import polyfit
sigma_bar0 = polyfit(lamda_list, epsilon_f2_list, 1)[0]
else:
sigma_bar0 = sigma_bar0_guess
if lamda_tau_guess == 0.0:
lamda_tau = max(lamda_list)*10
else:
lamda_tau = lamda_tau_guess
if no_negative:
if sigma_bar0 < 0.0: sigma_bar0 = 0
if lamda_tau < 0.0: lamda_tau = 0
guess_epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list = array( epsilon_f2_list + [epsilon_f1p] + [lamda_tau] + [sigma_bar0 ] )
print ('epsilon_f1p (principle value) guess:',epsilon_f1p)
print ('lambda_tau guess: ',lamda_tau)
print ('sigma_bar0 guess: ',sigma_bar0)
######### test
if False: print(F_error(guess_epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list)) #use this to see if the TR_error works
############ nk guessing over, time for creating and minimizing error function
if method == 'least_squares':
inputs = dict(fun = F_error,
x0 = guess_epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list,
ftol = tolerance,
xtol = tolerance,
gtol = tolerance,
verbose = 2)
if no_negative:
inputs.update(dict( bounds = [len(lamda_list)*[0.0]+[-inf]+[0.0]+[0.0], len(lamda_list)*[inf]+[inf]+[inf]+[inf]] ))
solution = least_squares(**inputs ).x
elif method == 'SLSQP':
inputs = dict(fun = lambda x: 0.5*sum(array(F_error(x))**2),
x0 = guess_epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list,
method = 'SLSQP',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = len(lamda_list)*[(0,inf)] + [(-inf,inf), (0,inf), (0,inf)] ))
solution = minimize(**inputs ).x
elif method == 'L-BFGS-B':
inputs = dict(fun = lambda x: 0.5*sum(array(F_error(x))**2),
x0 = guess_epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list,
method = 'L-BFGS-B',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = len(lamda_list)*[(0,inf)] + [(-inf,inf), (0,inf), (0,inf)] ))
solution = minimize(**inputs ).x
elif method == 'TNC':
inputs = dict(fun = lambda x: 0.5*sum(array(F_error(x))**2),
x0 = guess_epsilonf2_epsilonf1p_lamdatau_and_sigmabar0_list,
method = 'TNC',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = len(lamda_list)*[(0,inf)] + [(-inf,inf), (0,inf), (0,inf)] ))
solution = minimize(**inputs ).x
else:
raise ValueError("Invalid minimization method!")
##### now for unpacking
epsilon2_epsilon1p_lamdatau_and_sigmabar0_list = solution
epsilon_f2 = epsilon2_epsilon1p_lamdatau_and_sigmabar0_list[0:-3]
epsilon_f1p = epsilon2_epsilon1p_lamdatau_and_sigmabar0_list[-3]
lamda_tau = epsilon2_epsilon1p_lamdatau_and_sigmabar0_list[-2]
sigma_bar0 = epsilon2_epsilon1p_lamdatau_and_sigmabar0_list[-1]
epsilon_f1 = epsilon_f1p + KKT(lamda_list = lamda_list, k = epsilon_f2, compute_pool = my_pool )
epsilon_f = epsilon_f1 + 1.0j*epsilon_f2
epsilon_d = -sigma_bar0 *(lamda_list**2/( 1.0j*lamda_list + lamda_tau ))
epsilon = epsilon_f + epsilon_d
epsilon_abs = sqrt(epsilon*epsilon.conjugate())
n = sqrt((epsilon_abs + epsilon.real)/2.0)
k = sqrt((epsilon_abs - epsilon.real)/2.0)
print ('Final epsilon_f1p (principle value):',epsilon_f1p)
print ('Final lambda_tau :',lamda_tau)
print ('Final sigma_bar0 value :',sigma_bar0)
fit_nk_f = extrap(lamda_list, n + 1.0j*k, kind = interpolation_type)
my_pool.terminate()
my_pool.close()
return fit_nk_f, lamda_tau, sigma_bar0, epsilon_f1p
######## these are depricated #######
def TR(nk_fit, lamda, snell_angle_front, layer_index_of_fit, nk_f_list, thickness_list, coherency_list, tm_polarization_fraction): #this is just a fancy wrapper for inc_tmm
nk_list = [ nk_f(lamda) for nk_f in nk_f_list]
nk_list[layer_index_of_fit] = nk_fit # overwrite input nk_f with the fit one. basically, it would make the code much uglier if I made an excption
te_result = inc_tmm('s', nk_list, thickness_list, coherency_list, snell_angle_front, lamda)
tm_result = inc_tmm('p', nk_list, thickness_list, coherency_list, snell_angle_front, lamda)
T = tm_polarization_fraction * tm_result['T'] + (1.0-tm_polarization_fraction) * te_result['T']
R = tm_polarization_fraction * tm_result['R'] + (1.0-tm_polarization_fraction) * te_result['R']
return T, R
def TRA_lamda(params): # This has to be at the top level because map is strange and wont pickle onless it is at the top level
'''Returns a list of TRA for each single point at a Wavelength'''
lamda = params[0]
nk = params[1]
parameter_list_generator = params[2]
list_of_parameters = parameter_list_generator(lamda)
TRA_list = []
for parameters in list_of_parameters :
T, R = TR(nk_fit = nk, **parameters)
A = 1.0 - T - R
TRA_list.append([T, R, A])
return TRA_list
def TRA_lamda_error(params): # This has to be at the top level because map is strange and wont pickle onless it is at the top level
lamda = params[0] # these params are per Wavelength
nk = params[1]
TR_pair_list_generator = params[2]
parameter_list_generator = params[3]
TR_pair_list = TR_pair_list_generator(lamda)
list_of_parameters = parameter_list_generator(lamda)
sub_error_list=[]
for TR_pair, parameters in zip (TR_pair_list, list_of_parameters ):
Tc,Rc = TR(nk_fit = nk, **parameters) # these parameters are per measurement, set of parameters for a single point tmm model
Ac = 1.0 - Tc - Rc
A_pair = 1.0 - TR_pair[0] - TR_pair[1]
sub_error_list.append(TR_pair[0]-Tc)
sub_error_list.append(TR_pair[1]-Rc)
sub_error_list.append(A_pair -Ac)
return sub_error_list
###################
def fit_TRA_nk_sqr(lamda_list, TR_pair_list_generator, parameter_list_generator, nk_f_guess, delta_weight = 0.1, tolerance = 1e-4, no_negative = True, interpolation_type = 'cubic', method = 'least_squares'):
'''n_front and n_back must be real valued for this to work without caveats.
thickness and lambda can be any units, so long as they are the same, lamda_list must be sorted'''
from numpy import pi,exp,abs,sqrt, array, matmul, loadtxt, zeros, savetxt, inf, diff, ones
from scipy.optimize import root, least_squares, minimize
from TRANK import extrap
point_multiplicity = len(TR_pair_list_generator(lamda_list[0]))
#print(point_multiplicity)
# 3.0 is from T, R, and A
abs_delta_weight = sqrt(delta_weight**2 * point_multiplicity * 3.0 * (len(lamda_list)/(len(lamda_list)-1.0)))
from multiprocessing import Pool, cpu_count
my_pool = Pool(cpu_count())
#my_pool = Pool()
#my_pool = Pool(1)
def TR_error(nk_list):
c_nk_list = []
muh_inputs = []
for i in range(len(lamda_list)):
nk = nk_list[2*i] + 1.0j*nk_list[2*i+1]
c_nk_list.append(nk)
muh_inputs.append( (lamda_list[i], nk, TR_pair_list_generator, parameter_list_generator ) )
#print (zip(lamda_list, c_nk_list))
error_list_lists = my_pool.map(TRA_lamda_error, muh_inputs)
#error_list_lists =my_pool.map(lamda_error, zip(lamda_list, c_nk_list))
#print (error_list_lists)
error_list = []
for sub_error_list in error_list_lists:
error_list = error_list + sub_error_list
delta_array = diff(c_nk_list)*abs_delta_weight
#delta_errors =(delta_array.real**2 + delta_array.imag**2) * abs_delta_weight
#error_list = error_list + list(delta_errors)
error_list = error_list + list(delta_array.real) + list(delta_array.imag)
return array(error_list)
####### now for a guess list ##############
nk_guess_list = []
for i in range(len(lamda_list)):
nk = nk_f_guess(lamda_list[i])
nk_guess_list.append(abs(nk.real))
nk_guess_list.append(abs(nk.imag))
######### test
#print(TR_error(nk_guess_list))
############ nk guessing over, time for creating and minimizing error function
if method == 'least_squares':
inputs = dict(fun = TR_error,
x0 = nk_guess_list,
ftol = tolerance,
xtol = tolerance,
gtol = tolerance,
verbose = 2)
if no_negative:
inputs.update(dict( bounds = [zeros(2*len(lamda_list)),inf*ones(2*len(lamda_list))] ))
solution = least_squares(**inputs ).x
elif method == 'L-BFGS-B':
inputs = dict(fun = lambda x: 0.5*sum(TR_error(x)**2),
x0 = nk_guess_list,
method = 'L-BFGS-B',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = 2*len(lamda_list)*[(0,inf)]))
solution = minimize(**inputs ).x
elif method == 'SLSQP':
inputs = dict(fun = lambda x: 0.5*sum(TR_error(x)**2),
x0 = nk_guess_list,
method = 'SLSQP',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = 2*len(lamda_list)*[(0,inf)]))
solution = minimize(**inputs ).x
elif method == 'TNC':
inputs = dict(fun = lambda x: 0.5*sum(TR_error(x)**2),
x0 = nk_guess_list,
method = 'TNC',
tol = tolerance,
options = {'disp' : True, 'iprint': 2} )
if no_negative:
inputs.update(dict( bounds = 2*len(lamda_list)*[(0,inf)]))
solution = minimize(**inputs ).x
else:
raise ValueError("Invalid minimization method!")
my_pool.terminate()
my_pool.close()
n_list=[]
k_list=[]
for i in range(len(lamda_list)):
n_list.append(solution[2*i] )
k_list.append(solution[2*i+1])
nf = extrap(lamda_list, n_list, kind = interpolation_type)
kf = extrap(lamda_list, k_list, kind = interpolation_type)
def fit_nk_f(lamda):
return nf(lamda) + 1.0j*kf(lamda)
return fit_nk_f
def fit_TRA_nk_sqr_KK_compliant(lamda_list, lamda_fine, TR_pair_list_generator, parameter_list_generator, nk_f_guess,
delta_weight = 0.1, tolerance = 1e-5, no_negative = True, interpolation_type = 'cubic', method = 'least_squares'):
'''n_front and n_back must be real valued for this to work without caveats.
thickness and lambda can be any units, so long as they are the same, lamda_list must be sorted'''
from numpy import pi,exp,abs,sqrt, array, matmul, loadtxt, zeros, savetxt, inf, diff, ones, mean
from scipy.optimize import root, least_squares, minimize
from TRANK import extrap
point_multiplicity = len(TR_pair_list_generator(lamda_list[0]))
#print(point_multiplicity)
# 3.0 is from T, R, and A
abs_delta_weight = sqrt(delta_weight**2 * point_multiplicity * 3.0 * (len(lamda_list)/(len(lamda_list)-1.0)))
from multiprocessing import Pool, cpu_count
my_pool = Pool(cpu_count())
#my_pool = Pool()
#my_pool = Pool(1)
def TR_error(k_and_p_list):
# the last value is the principle value
#FYI -> k = array(k_and_p_list[0:-1])
k = k_and_p_list[0:-1]
p = k_and_p_list[-1]
n = p + KK_lamda(lamda_list = lamda_list, lamda_fine = lamda_fine, k = k )
muh_inputs = []
for i in range(len(lamda_list)):
nk = n[i]+1.0j*k[i]# double check this works properly later
muh_inputs.append( (lamda_list[i], nk, TR_pair_list_generator, parameter_list_generator ) )
#print (zip(lamda_list, c_nk_list))
error_list_lists = my_pool.map(TRA_lamda_error, muh_inputs)
#error_list_lists =my_pool.map(lamda_error, zip(lamda_list, c_nk_list))
#print (error_list_lists)
error_list = []
for sub_error_list in error_list_lists:
error_list = error_list + sub_error_list
error_list = error_list + list( abs_delta_weight*diff(n) ) + list( abs_delta_weight * diff(k))
return error_list
####### now for a guess list ##############
guess_k_and_p_list= []
p = 0.0
for i in range(len(lamda_list)):
nk = nk_f_guess(lamda_list[i])
if no_negative and nk.imag < 0.0:
k = 0
else:
k = nk.imag
guess_k_and_p_list.append( k)
p+= nk.real
# now we put p at the end
p = p/len(lamda_list) - 1.0 # this is a guess for the principle value
print ('principle value guess:',p)
guess_k_and_p_list.append(p)
######### test