-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvariableapec.py
executable file
·4548 lines (3874 loc) · 214 KB
/
variableapec.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
"""This module contains methods for looking at emission and line ratios
as a function of varying atomic data from the AtomDB files. Requires
PyAtomdB, Python 3, LaTeX, (and astroML if you wish to use LaTeX font with plots)."""
__version__ = "1.0.2" #Nov 3, 2020
__author__ = "Keri Heuer"
__email__ = "[email protected]"
__status__ = "Development"
import matplotlib.pyplot as plt, matplotlib.ticker as mtick, scipy.stats as stats, \
pyatomdb, numpy, pickle, pathlib, csv, os, errno, hashlib, requests, urllib.request, \
urllib.parse, urllib.error, time, subprocess, shutil, wget, glob, datetime, ftplib, \
pathlib, collections, operator, requests, matplotlib.pylab as pylab, glob, math
from io import StringIO
from matplotlib.ticker import FormatStrFormatter, LogFormatterSciNotation
from matplotlib.lines import Line2D
from astropy.io import fits
from astropy.table import Table, Column, vstack
from matplotlib.offsetbox import AnchoredText
from decimal import Decimal
from matplotlib import cm
try:
import astropy.io.fits as pyfits
except:
import pyfits
""" User can/should update plot settings before calling
any plotting routine. Below are the defaults.
cmap : str
matplotlib color map string name
fontsize : int
size of x and y axis labels
ticksize : int
size of x and y ticks
legendsize : str
string of legend size
legendloc : int or str
legend location (default is 'best')
tickstep : float
size of y ticks for error (bottom) panels of plots
important_ticks : tuple or list
list of important y ticks for error (bottom) panels of plots,
i.e. 0.1 to draw a tick at 0.1 fractional error if not already in default ticks
grid_kwargs : dict
dictionary of optional arguments for turning on axis grid
for error (bottom) panels, i.e. keys include 'color', 'alpha',
'linestyle', 'which', 'axis', etc.
use_latex_font : bool
True to use LaTeX font on plots (default)
will be False if cannot find astroML or LaTeX installed"""
global plot_settings
plot_settings = {'cmap': 'hsv', 'fontsize': 12, 'ticksize': 12,
'legendsize': 'xx-small', 'legendloc': 'best', 'tickstep': 0.1,
'important_ticks': {}, 'grid_kwargs': {}, 'use_latex_font': False}
if plot_settings['use_latex_font'] == True:
try:
from astroML.plotting import setup_text_plots
except:
use_latex_font = False
print("Using regular matplotlib font for plotting. Install astroML to setup plots with LaTeX font.")
#if setup_text_plots in globals():
#setup_text_plots(uselatex = plot_settings['use_latex_font'])
#set up datacache anytime variableapec is imported
global d
d = {}
""" CSD errors: to be added to
These are typical systematic uncertainties from experiments
measuring ionization and recombination rate coefficients.
To add to this, {key: val} should be
{Z: {'ionize': {z1: fractional error}, 'recomb':{z1: fractional error}}}
*note: the max_ionize and max_recomb dictionaries do not need to have
errors for every z1, variableapec will fill in the dictionary using
the average of adjacent ions. Adding even a single z1 error will be
useful for users to calculate CSD error estimates."""
systematics = {8: {'ionize': {8: 0.1, 7: 0.2, 6: 0.05, 5: 0.05, 4: 0.05, 3: 0.05, 2: 0.05, 1: 0.05},
'recomb': {8: 0.18, 7: 0.2, 6: 0.16, 5: 0.3, 4: 0.3, 3: 0.3, 2: 0.3, 1: 0.3}},
26: {'ionize': {26: 0.15, 25: 0.14, 24: 0.13, 23: 0.265, 22: 0.4, 21: 0.4, 20: 0.4,
19: 0.4, 18: 0.15, 17: 0.16, 16: 0.2, 15: 0.26, 14: 0.06, 13: 0.06,
12: 0.14, 11: 0.09, 10: 0.09, 9: 0.16, 8: 0.12, 7: 0.12, 6: 0.12,
5: 0.12, 4: 0.13, 3: 0.12, 2: 0.12, 1: 0.12},
'recomb':{26: 0.2, 25: 0.2, 24: 0.2, 23: 0.2, 22: 0.2, 21: 0.2, 20: 0.2,
19: 0.2, 18: 0.2, 17: 0.2, 16: 0.2, 15: 0.26, 14: 0.18, 13: 0.18,
12: 0.13, 11: 0.25, 10: 0.25, 9: 0.29, 8: 0.25, 7: 0.25, 6: 0.25,
5: 0.25, 4: 0.25, 3: 0.25, 2: 0.25, 1: 0.25}}}
def ionize(Z, z1, Te, dens, in_range, pop_fraction, datacache):
z1_drv = z1-1
#get rates and set up CR matrix
init, final, rates = pyatomdb.apec.gather_rates(Z, z1_drv, Te, dens, do_la= True, \
do_ec=True, do_ir=True, do_pc=True, do_ai=True, datacache=datacache)
lvdat = pyatomdb.atomdb.get_data(Z, z1_drv, 'LV', datacache=datacache)
lvdat = lvdat[1].data
nlev = len(lvdat)
drv_matrix = numpy.zeros((nlev,nlev))
drv_B = numpy.zeros(nlev)
#populate full CR matrix by summing rates for all processes
for x,y,z in zip(final, init, rates):
drv_matrix[x][y] += z
#set up and solve CR matrix for level populations
drv_matrix[0][:], drv_B[0] = 1.0, 1.0
drv_lev_pop = numpy.linalg.solve(drv_matrix,drv_B)
#get level populations and make linelist
ion_levpop = pyatomdb.apec.calc_ioniz_popn(drv_lev_pop*pop_fraction[z1_drv-1], Z, z1, z1_drv, Te, dens, datacache=datacache, do_xi=True)
ion_linelist = numpy.zeros(len(in_range), dtype=pyatomdb.apec.generate_datatypes('linetype'))
ion_linelist['upperlev'], ion_linelist['lowerlev'] = in_range['UPPER_LEV'], in_range['LOWER_LEV']
#use observational wavelength if exists, otherwise theoretical
i = numpy.where(numpy.isnan(in_range['WAVE_OBS']) == True)
ion_linelist[i]['lambda'] = in_range[i]['WAVELEN']
i = numpy.where(numpy.isnan(in_range['WAVE_OBS']) == False)
ion_linelist[i]['lambda'] = in_range[i]['WAVE_OBS']
#calculate epsilon
ion_linelist['epsilon'] = in_range['EINSTEIN_A'] * ion_levpop[in_range['UPPER_LEV'] - 1]
return ion_linelist
def recombine(Z, z1, Te, dens, in_range, pop_fraction, datacache):
z1_drv = z1+1
if z1 < Z:
init, final, rates = pyatomdb.apec.gather_rates(Z, z1_drv, Te, dens, do_la=True, \
do_ec=True, do_ir=True, do_pc=True, do_ai=True, datacache=datacache)
lvdat = pyatomdb.atomdb.get_data(Z, z1_drv, 'LV', datacache=datacache)
lvdat = lvdat[1].data
nlev = len(lvdat)
drv_matrix = numpy.zeros((nlev, nlev))
drv_B = numpy.zeros(nlev)
# populate full CR matrix by summing rates for all processes
for x, y, z in zip(final, init, rates):
drv_matrix[x][y] += z
# set up and solve CR matrix for level populations
drv_matrix[0][:], drv_B[0] = 1.0, 1.0
drv_lev_pop = numpy.linalg.solve(drv_matrix, drv_B)
else:
# declare 1 level, fully populated
drv_lev_pop = numpy.ones(1, dtype=float)
# get level populations and make linelist
recomb_levpop = pyatomdb.apec.calc_recomb_popn(drv_lev_pop * pop_fraction[z1_drv - 1], Z, z1, z1_drv, Te, dens,
drlevrates=0, rrlevrates=0,datacache=datacache)
recomb_linelist = numpy.zeros(len(in_range), dtype=pyatomdb.apec.generate_datatypes('linetype'))
recomb_linelist['upperlev'], recomb_linelist['lowerlev'] = in_range['UPPER_LEV'], in_range['LOWER_LEV']
#use observational wavelength if exists, otherwise theoretical
i = numpy.where(numpy.isnan(in_range['WAVE_OBS']) == True)
recomb_linelist[i]['lambda'] = in_range[i]['WAVELEN']
i = numpy.where(numpy.isnan(in_range['WAVE_OBS']) == False)
recomb_linelist[i]['lambda'] = in_range[i]['WAVE_OBS']
#calculate epsilon
recomb_linelist['epsilon'] = in_range['EINSTEIN_A'] * recomb_levpop[in_range['UPPER_LEV'] - 1]
return recomb_linelist
def set_up(Z, z1, Te, dens, extras={}):
"""
Z : int
element
z1 : int
ion charge +1
Te : int
temperature in K
dens :
density in cm-3
extras : dict
dictionary of extra inputs if varying rate,
dictionary is empty if running set_up() on its own
(i.e. to get original epsilons at Te, dens)
should be dict of {}
Sets up linelist from excitation, recombination and ionization
and creates sensitivity tables. Returns a dictionary "inputs"
and the transition varied if extras is not empty."""
print("\n***********************************************************************************")
print("Setting up linelists at Te={:.3e} and dens={:.3e}".format(Te, dens))
init, final, rates = pyatomdb.apec.gather_rates(Z, z1, Te, dens, do_la=True, \
do_ec=True, do_ir=True, do_pc=True, do_ai=True, datacache=d)
lvdat = pyatomdb.atomdb.get_data(Z, z1, 'LV')
lvdat = lvdat[1].data
nlev = len(lvdat)
matrix = numpy.zeros((nlev, nlev))
B = numpy.zeros(nlev)
# populate full CR matrix by summing rates for all processes
for x,y,z in zip(final, init, rates):
matrix[x][y] += z
# set up and solve CR matrix for level populations
matrix[0][:] = 1.0
B[0] = 1.0
lev_pop = numpy.linalg.solve(matrix, B)
# convert level populations into line lists & intensities for excitation only
ladat = pyatomdb.atomdb.get_data(Z, z1, 'LA', datacache=d)
in_range = ladat[1].data
# find fraction of each ion in plasma
pop_frac = pyatomdb.apec._solve_ionbal_eigen(Z, Te, teunit='K', datacache=d)
#get epsilon from excitation only
linelist = numpy.zeros(len(in_range), dtype=pyatomdb.apec.generate_datatypes('linetype'))
linelist['epsilon'] = in_range['EINSTEIN_A'] * lev_pop[in_range['UPPER_LEV'] - 1] * pop_frac[z1-1]
linelist['upperlev'], linelist['lowerlev'] = in_range['UPPER_LEV'], in_range['LOWER_LEV']
# get wavelengths - use observational lambda if exists, otherwise theoretical
wavelens = numpy.zeros(len(in_range))
i = numpy.where(numpy.isnan(in_range['WAVE_OBS']) == True)[0]
wavelens[i] = in_range[i]['WAVELEN']
i = numpy.where(numpy.isnan(in_range['WAVE_OBS']) == False)[0]
wavelens[i] = in_range[i]['WAVE_OBS']
linelist['lambda'] = wavelens
# set up complete line list (emiss only due to excitation at this point)
full_linelist = numpy.zeros(len(in_range), dtype=pyatomdb.apec.generate_datatypes('linetype'))
full_linelist['lambda'] = linelist['lambda']
full_linelist['epsilon'] = linelist['epsilon']
# now add emissivity from ionization and recombination to excitation linelist (depending on z1)
if z1 == 1: # skip ionization
recomb_emiss = recombine(Z, z1, Te, dens,in_range, pop_frac, d)
full_linelist['epsilon'] += recomb_emiss['epsilon']
elif z1 == Z + 1: # skip recombination
ion_emiss = ionize(Z, z1, Te, dens, in_range, pop_frac, d)
full_linelist['epsilon'] += ion_emiss['epsilon']
else: # do both
recomb_emiss = recombine(Z, z1, Te, dens,in_range, pop_frac, d)
ion_emiss = ionize(Z, z1, Te, dens,in_range, pop_frac, d)
full_linelist['epsilon'] += recomb_emiss['epsilon']
full_linelist['epsilon'] += ion_emiss['epsilon']
# set up sensitivity & partial derivatives tables
table = Table([full_linelist['lambda'], in_range['UPPER_LEV'].astype(int), in_range['LOWER_LEV'].astype(int), full_linelist['epsilon']], \
names=('Lambda', 'Upper', 'Lower', 'Epsilon_orig'))
new_table = Table([full_linelist['lambda'], in_range['UPPER_LEV'].astype(int), in_range['LOWER_LEV'].astype(int), full_linelist['epsilon']],
names=('Lambda', 'Upper', 'Lower', 'Epsilon_orig'))
# save variables
inputs = {'Z': Z, 'z1': z1, 'Te': Te, 'dens': dens}
values = {'matrix': matrix, 'B': B, 'in_range': in_range, 'linelist': linelist, 'table': table,
'new_table': new_table}
if extras != {}:
process, delta_r, transition, transition_2, wavelen, \
Te_range, dens_range, corrthresh, e_signif, pop_fraction = [extras.get(k) for k in extras]
#print out emissivity from excitation, ionization, recombination
if process == 'exc':
i = numpy.where([(linelist['upperlev'] == transition[1]) & (linelist['lowerlev'] == transition[0])])[1]
#check for multiple wavelengths with same (up, lo), prompt for theoretical wavelen if so
if len(i) > 1:
wave = input("Found multiple lines w/ (up,lo) = " + str(
transition) + ", input theoretical wavelength in A of your transition to continue: ")
i = numpy.where([math.isclose(in_range['WAVELEN'], float(wave), rel_tol=1e-5) == True])[1][0]
transition = (in_range[i]['UPPER_LEV'], in_range[i]['LOWER_LEV'])
else:
i = i[0]
print("Excitation emiss =", linelist[i]['epsilon'])
i = numpy.where([(ion_emiss['upperlev'] == transition[1]) & (ion_emiss['lowerlev'] == transition[0])])[1][0]
print("Ionization emiss =", ion_emiss[i]['epsilon'])
i = numpy.where([(recomb_emiss['upperlev'] == transition[1]) & (recomb_emiss['lowerlev'] == transition[0])])[1][0]
print("Recombination emiss =", recomb_emiss[i]['epsilon'])
elif process == 'A':
i = numpy.where([(linelist['upperlev'] == transition[0]) & (linelist['lowerlev'] == transition[1])])[1]
print(i)
#check for multiple wavelengths with same (up, lo), prompt for theoretical wavelen if so
if len(i) > 1:
wave = input("Found multiple lines w/ (up,lo) = " + str(
transition) + ", input theoretical wavelength in A of your transition to continue: ")
i = numpy.where([math.isclose(in_range['WAVELEN'], float(wave), rel_tol=1e-5) == True])
transition = (in_range[i]['UPPER_LEV'], in_range[i]['LOWER_LEV'])
else:
i = i[0]
print("Excitation emiss =", linelist[i]['epsilon'])
i = numpy.where([(ion_emiss['upperlev'] == transition[0]) & (ion_emiss['lowerlev'] == transition[1])])[1][0]
print("Ionization emiss =", ion_emiss[i]['epsilon'])
i = numpy.where([(recomb_emiss['upperlev'] == transition[0]) & (recomb_emiss['lowerlev'] == transition[1])])[1][0]
print("Recombination emiss =", recomb_emiss[i]['epsilon'])
inputs.update({'process': process, 'delta_r': delta_r, 'transition': transition, 'transition_2': transition_2,
'wavelen': wavelen, 'Te_range': Te_range, 'dens_range': dens_range,
'corrthresh': corrthresh, 'e_signif': e_signif, 'pop_fraction': pop_frac})
#use pop_fraction specified by user if not {}
if isinstance(pop_fraction, numpy.ndarray):
inputs['pop_fraction'] = pop_fraction
values.update({'index': i})
return inputs, values, transition
else:
return inputs, values
def vary_a(inputs, values, which_transition):
"""
inputs : dict
returned by set_up()
values : dict
returned by set_up()
which_transition : tuple
returned by set_up()
Recalculates the emissivities from varying
the A value of which_transition and updates
sensitivity tables and values dictionary.
Returns the dictionaries input and values."""
Z, z1, Te, dens, process, delta_r, transition, transition_2, \
wavelen, Te_range, dens_range, corrthresh, e_signif, pop_fraction = [inputs.get(k) for k in inputs]
matrix, B, in_range, linelist, table, new_table, idx = [values.get(k) for k in values]
print("Varying A-value for", str(which_transition), "by", str(delta_r*100)+"%")
initial_lev, final_lev = which_transition[0], which_transition[1]
a_index = numpy.where([(in_range['UPPER_LEV'] == initial_lev) & (in_range['LOWER_LEV'] == final_lev)])[1][0]
old_a = in_range[a_index]['EINSTEIN_A']
table['Epsilon_orig'].unit = 'A'
if old_a == 0: old_a = 1e-40
# vary A values
new_a = [old_a * (1 - delta_r), old_a * (1 + delta_r)]
q_min, q_max = new_a[0], new_a[1]
# store the original ARAD_TOT, and invert
lvdat = pyatomdb.atomdb.get_data(Z, z1, 'LV', datacache=d)
orig_arad_tot = lvdat[1].data['ARAD_TOT'][initial_lev - 1] * 1.0
excitation, ionization, recombination = [], [], []
for index, x in enumerate(new_a):
# update LA data for specified transition
in_range['EINSTEIN_A'][a_index] = x
lvdat[1].data['ARAD_TOT'][initial_lev - 1] = orig_arad_tot + x - old_a
# get new CR matrix and resolve level pops with new A
frac = str(round(x / old_a, 2))
new_matrix = matrix.copy()
new_matrix[final_lev - 1, initial_lev - 1] += (x - old_a) # off diagonal term
new_matrix[initial_lev - 1, initial_lev - 1] -= (x - old_a) # diagonal term
new_matrix[0][:] = 1.0
# find new level populations and get new epsilon values from excitation
new_lev_pop = numpy.linalg.solve(new_matrix, B) * pop_fraction[z1-1]
#fill in new_linelist
new_linelist = numpy.zeros(len(in_range), dtype=pyatomdb.apec.generate_datatypes('linetype'))
new_linelist['epsilon'] = in_range['EINSTEIN_A'] * new_lev_pop[in_range['UPPER_LEV'] - 1]
new_linelist['upperlev'], new_linelist['lowerlev'] = in_range['UPPER_LEV'], in_range['LOWER_LEV']
if z1 == 1: # skip ionization
recomb_emiss = recombine(Z, z1, Te, dens, in_range, pop_fraction, d)
new_linelist['epsilon'] += recomb_emiss['epsilon']
elif z1 == Z + 1: # skip recombination
ion_emiss = ionize(Z, z1, Te, dens, in_range, pop_fraction, d)
new_linelist['epsilon'] += ion_emiss['epsilon']
else: # do both
recomb_emiss = recombine(Z, z1, Te, dens, in_range, pop_fraction, d)
ion_emiss = ionize(Z, z1, Te, dens, in_range, pop_fraction, d)
new_linelist['epsilon'] += recomb_emiss['epsilon']
new_linelist['epsilon'] += ion_emiss['epsilon']
#update sensitivity table
if index == 0:
print("Adding the min epsilon", new_linelist[idx]['epsilon'])
excitation.append(new_linelist[idx]['epsilon'])
if 'ion_emiss' in locals(): ionization.append(ion_emiss[idx]['epsilon'])
if 'recomb_emiss' in locals(): recombination.append(recomb_emiss[idx]['epsilon'])
new_col = Column(name='Epsilon_min', data=new_linelist['epsilon'], unit=frac + ' A')
elif index == 1:
print("Adding the max epsilon", new_linelist[idx]['epsilon'])
excitation.append(new_linelist[idx]['epsilon'])
if 'ion_emiss' in locals(): ionization.append(ion_emiss[idx]['epsilon'])
if 'recomb_emiss' in locals(): recombination.append(recomb_emiss[idx]['epsilon'])
new_col = Column(name='Epsilon_max', data=new_linelist['epsilon'], unit=frac + ' A')
table.add_columns([new_col])
#reset LA data to old_a
in_range['EINSTEIN_A'][a_index] = old_a
lvdat[1].data['ARAD_TOT'][initial_lev - 1] = orig_arad_tot
for label, array in zip(['excitation', 'ionization', 'recombination'], [excitation, ionization, recombination]):
print("Min and max", str(label), "emiss =", array)
print("***********************************************************************************")
values = {'table': table, 'new_table': new_table, 'new_linelist': new_linelist, 'q_max': q_max, 'q_min': q_min}
return inputs, values
def vary_exc(inputs, values, which_transition):
"""
inputs : dict
returned by set_up()
values : dict
returned by set_up()
which_transition : tuple
returned by set_up()
Recalculates the emissivities from varying
the direct excitation rate of which_transition
and updates sensitivity tables and values dictionary.
Returns the dictionaries input and values."""
Z, z1, Te, dens, process, delta_r, transition, transition_2, wavelen, \
Te_range, dens_range, corrthresh, e_signif, pop_fraction = [inputs.get(k) for k in inputs]
matrix, B, in_range, linelist, table, new_table, idx = [values.get(k) for k in values]
print("Varying excitation rate for", str(which_transition), "by", str(delta_r*100)+"%")
exc_init, exc_final, exc_rates = pyatomdb.apec.gather_rates(Z, z1, Te, dens, do_la=False, \
do_ec=True, do_ir=False, do_pc=False, do_ai=False,
datacache=d)
initial_lev, final_lev = which_transition[0], which_transition[1]
#get original excitation rate of which_transition
try:
i = numpy.where([(exc_init == which_transition[0]-1) & (exc_final == which_transition[1]-1)])[1][0]
old_rate = exc_rates[i]
if old_rate == 0: old_rate = 1e-40
except:
print("Could not find transition", which_transition, " - please check input transition levels")
table['Epsilon_orig'].unit = 'orig rate'
# vary rate
new_rate = [(1-delta_r) * old_rate, (1+delta_r) * old_rate]
q_max, q_min = new_rate[-1], new_rate[0]
excitation, ionization, recombination = [], [], []
for index, x in enumerate(new_rate):
# loop through varied rates, get new matrix and resolve level pops
frac = str(round(x / old_rate, 2))
new_matrix = matrix.copy()
new_matrix[final_lev - 1, initial_lev - 1] += (x - old_rate) # off diagonal term
new_matrix[initial_lev - 1, initial_lev - 1] -= (x - old_rate) # diagonal term
new_matrix[0][:] = 1.0
# find new level populations and get new epsilon values from excitation
new_lev_pop = numpy.linalg.solve(new_matrix, B) * pop_fraction[z1 - 1]
new_linelist = numpy.zeros(len(in_range), dtype=pyatomdb.apec.generate_datatypes('linetype'))
new_linelist['epsilon'] = in_range['EINSTEIN_A'] * new_lev_pop[in_range['UPPER_LEV'] - 1]
new_linelist['upperlev'], new_linelist['lowerlev'] = in_range['UPPER_LEV'], in_range['LOWER_LEV']
if z1 == 1: # skip ionization
recomb_emiss = recombine(Z, z1, Te, dens, in_range, pop_fraction, d)
new_linelist['epsilon'] += recomb_emiss['epsilon']
elif z1 == Z + 1: # skip recombination
ion_emiss = ionize(Z, z1, Te, dens, in_range, pop_fraction, d)
new_linelist['epsilon'] += ion_emiss['epsilon']
else: # do both
recomb_emiss = recombine(Z, z1, Te, dens, in_range, pop_fraction, d)
ion_emiss = ionize(Z, z1, Te, dens, in_range, pop_fraction, d)
new_linelist['epsilon'] += recomb_emiss['epsilon']
new_linelist['epsilon'] += ion_emiss['epsilon']
# update sensitivity table and print out excitation, ionization, and recombination emiss
if index == 0:
excitation.append(new_linelist[idx]['epsilon'])
if 'ion_emiss' in locals(): ionization.append(ion_emiss[idx]['epsilon'])
if 'recomb_emiss' in locals(): recombination.append(recomb_emiss[idx]['epsilon'])
new_col = Column(name='Epsilon_min', data=new_linelist['epsilon'], unit=frac + ' rate')
elif index == 1:
excitation.append(new_linelist[idx]['epsilon'])
if 'ion_emiss' in locals(): ionization.append(ion_emiss[idx]['epsilon'])
if 'recomb_emiss' in locals(): recombination.append(recomb_emiss[idx]['epsilon'])
new_col = Column(name='Epsilon_max', data=new_linelist['epsilon'], unit=frac + ' rate')
table.add_columns([new_col])
for label, array in zip(['excitation', 'ionization', 'recombination'], [excitation, ionization, recombination]):
print("Min and max", label, "emiss =", array)
print("***********************************************************************************")
values = {'table': table, 'new_table': new_table, 'new_linelist': new_linelist, 'q_max': q_max, 'q_min': q_min}
return inputs, values
def get_tables(inputs, values):
"""
inputs: dict outputted by vary_exc() or vary_a()
values: dict outputted by vary_exc() or vary_a()
Updates and returns the following:
table (epsilon values and dE/dR)
new_table (epsilon changes dE/E, sorted by greatest to smallest)
inputs (dict)
results (dict)
Tables will be filtered if user specifies corrthresh, e_signif,
i.e. table will only have values of dE/E > corrthresh
and lines with original epsilon > e_signif
Note:
dE/dR = difference in epsilon calculated from
rate-error and rate+error divided by the change in the rate.
dE/E = averaged fractional change in emissivity
(i.e. half the change in epsilon from rate-error and rate+error
divided by the original emissivity)."""
Z, z1, Te, dens, process, delta_r, transition, transition_2, \
wavelen, Te_range, dens_range, corrthresh, e_signif, pop_fraction = [inputs.get(k) for k in inputs]
table, new_table, new_linelist, q_max, q_min = [values.get(k) for k in values]
min, max = table['Epsilon_min'], table['Epsilon_max']
#add partial derivative dE/dR (change in emissivity dE normalized by varied rate dR) and epsilon orig
new_table['dE/dR'] = abs((max-min)/(q_max-q_min)).round(5)
new_table['dE/dR'][new_table['dE/dR'] < 0.0001] = 0
new_table['dE/dR'].unit = None
#add "correlation factor" dE/E -> **redefined dE/E to be the +/- error from orig epsilon**
new_table['|dE/E|'] = ((numpy.abs(max-min)/table['Epsilon_orig'])/2).round(5)
new_table['|dE/E|'][new_table['|dE/E|'] < 0.0001] = 0
new_table['|dE/E|'].unit = None
try:
new_table.sort('|dE/E|', reverse=True)
except TypeError:
new_table.sort('|dE/E|')
new_table = new_table[::-1]
#apply filters
if corrthresh != 0.0: #only show lines whose "epsilon correlation" >= than specified value
new_table = new_table[new_table['|dE/E|'] >= corrthresh]
elif e_signif != 0.0: #only show lines with partial epsilon/partial rate derivative is >= specified value
new_table = new_table[new_table['Epsilon_orig'] >= e_signif]
results = {'inputs': inputs, 'wavelength': table['Lambda'], 'upper': new_table['Upper'],
'lower': new_table['Lower'], 'dE/dR': new_table['dE/dR'], 'epsilon_orig': new_table['Epsilon_orig'],\
'|dE/E|': new_table['|dE/E|'], 'min_eps': min,'max_eps': max}
return table, new_table, inputs, results
def is_integer(value: str, *, base: int=10) -> bool:
try:
int(value, base=base)
return True
except ValueError:
return False
def get_file_num(filename, ext):
a = os.listdir('./')
b = [f.strip(ext) for f in a if (ext and filename) in f]
numbers = [int(x[-1]) for x in b if is_integer(x[-1])]
if len(numbers) == 0:
return 1
else:
return max(numbers)+1
def plot_ratio(fnames, ratio={}, opacity=0.4, show=True, labels=[]):
""" Plots line ratio and error from specified files.
fnames : str or list
contains fits file names of runs to plot
ratio : str
{} = regular 2 line ratio (default)
'r' = R ratio
'g' = G ratio
'b' = 3 line blended ratio
opacity : float or list
float less than 1 supplied as alpha arg to plt.plot()
if float, uses same opacity for all fnames
supply list of same length of fnames for individual alphas
show : boolean
Show to screen if True
(plot will be saved as pdf either way)
labels : list
list of legend labels in same order as files in fname
important_ticks : list
list of floats specifying any important ticks
for fractional error, i.e. 0.1 for a tick to
be drawn at 10% error
"""
print("Plotting files:", fnames)
#check inputs for colormap, alpha, and how many files to plot
if isinstance(fnames, (list, tuple)):
clist = get_cmap(len(fnames)+1, name=plot_settings['cmap'])
if isinstance(opacity, float):
alphas = [opacity] * len(fnames)
else: alphas = opacity
else:
fnames = [fnames]
if isinstance(opacity, float): alphas = [opacity]
clist = get_cmap(1, name=plot_settings['cmap'])
if labels == []:
labels = ['']*len(fnames)
name = fnames[0].split('_')[0]
gs_kw = dict(width_ratios=[3], height_ratios=[2, 1])
fig, (ax, ax2) = plt.subplots(nrows=2, sharex=True, gridspec_kw=gs_kw)
ax2.set_ylabel('Fractional Error', fontsize=plot_settings['labelsize'])
ax2.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
for axis in [ax, ax2]:
for which in ['x', 'y']: axis.tick_params(axis=which, labelsize=plot_settings['labelsize'])
if ratio == {}: # plot regular 2 line ratio
print("Plotting", name, "line ratio")
ax.set_ylabel('Line Ratio', fontsize=plot_settings['fontsize'])
max_y_tick = 0
for i, file in enumerate(fnames):
with fits.open(file) as hdul:
data = hdul[1].data
if 'temp' in file:
type = 'temp'
temps, Te_orig, Te_min, Te_max = data['temps'], data['Te_orig'], data['Te_min'], data['Te_max']
if 'density' in [hdul[1].header[x] for x in hdul[1].header.keys()]:
string = "{:.0e}".format(data['density'][0]).split("e+")
if string[1] == '00': density = "$N_e = " + "{}".format(string[0]) + " cm^{-3}$"
else:
density = "$N_e = " + "{}\\times 10^{}".format(string[0], round(int(string[1]))) + " cm^{-3}$"
elif 'dens' in file:
ax2.set_xlabel('Density in cm$^{-3}$', fontsize=plot_settings['fontsize'])
type = 'dens'
dens, dens_orig, dens_min, dens_max = data['dens'], data['dens_orig'], data['dens_min'], data['dens_max']
if 'temperatures' in [hdul[1].header[x] for x in hdul[1].header.keys()]:
string = "{:.0e}".format(data['temperatures'][0]).split("e+")
temperature = "$T_e$ = " + "{}\\times 10^{}$K".format(string[0], round(int(string[1])))
if type == 'temp': # plot emissivity versus temperature
ax.semilogx(temps, Te_orig, color=clist(i))
if labels[i] == '':
ax.fill_between(temps, Te_min, Te_max, alpha=alphas[i], color=clist(i), label=density)
else:
ax.fill_between(temps, Te_min, Te_max, alpha=alphas[i], color=clist(i), label=labels[i])
error = (abs(Te_max - Te_min) / Te_orig)/2
if max(error) > max_y_tick: max_y_tick = max(error)
ax2.semilogx(temps, error, color=clist(i))
ax2.set_xlabel('Temperature in K', fontsize=plot_settings['fontsize'])
if Te_max[-1] > Te_max[0]: left = True
else: left = False
elif type == 'dens':
ax.semilogx(dens, dens_orig, color=clist(i))
if labels[i] == '':
ax.fill_between(dens, dens_min, dens_max, alpha=alphas[i], color=clist(i), label=temperature)
else:
ax.fill_between(dens, dens_min, dens_max, alpha=alphas[i], color=clist(i), label=labels[i])
error = (abs(dens_max - dens_min) / dens_orig)/2
if max(error) > max_y_tick: max_y_tick = max(error)
ax2.semilogx(dens, error, color=clist(i))
if dens_max[-1] > dens_max[0]: left = True
else: left = False
# set y ticks for error subplot if user didn't specify
if tickstep == {}:
if max_y_tick < 0.05: tickstep = 0.01
elif 0.05 < max_y_tick < 0.1: tickstep = 0.02
elif 0.1 < max_y_tick < 0.2: tickstep = 0.05
elif 0.2 < max_y_tick < 0.4: tickstep = 0.1
elif 0.4 < max_y_tick < 0.8: tickstep = 0.2
elif 0.8 < max_y_tick < 1.5: tickstep = 0.25
elif 1.5 < max_y_tick: tickstep = 0.5
ticks = numpy.arange(0, max_y_tick + tickstep, tickstep)
if plot_settings['important_ticks'] != {}:
ticks += numpy.array(plot_settings['important_ticks'])
ax2.set_yticks(ticks)
if plot_settings['grid_kwargs'] != {}:
ax2.grid(plot_settings['grid_kwargs'])
fig.subplots_adjust(left=0.16, right=0.96, bottom=0.14, top=0.95)
if plot_settings['legendloc'] != 'best': ax.legend(fontsize=plot_settings['legendsize'], loc=plot_settings['legendloc'])
else:
if left == True: ax.legend(fontsize=plot_settings['legendsize'], loc='upper left')
else: ax.legend(fontsize=plot_settings['legendsize'], loc='upper right')
fig.align_ylabels()
plt.savefig(name + " line ratio.pdf")
elif ratio.lower() == 'r': # density dependent R ratio
print("Plotting", name, "R ratio")
ax.set_ylabel(name + ' R Ratio', fontsize=plot_settings['fontsize'])
ax2.set_xlabel('Density in cm$^{-3}$', fontsize=plot_settings['fontsize'])
# retrieve diagnostics
max_y_tick = 0
for i, file in enumerate(fnames):
with fits.open(file) as hdul:
data = hdul[1].data
dens_bins, r_orig, r_min, r_max = data['dens'], data['r orig'], data['r min'], data['r max']
f_orig, f_min, f_max = data['f orig'], data['f min'], data['f max']
i_orig, i_min, i_max = data['i orig'], data['i min'], data['i max']
i2_orig, i2_min, i2_max = data['i2 orig'], data['i2 min'], data['i2 max']
if 'temperature' in [hdul[1].header[x] for x in hdul[1].header.keys()]:
string = "{:.0e}".format(data['temperature'][0]).split("e+")
temperature = "$T_e = " + "{}\\times 10^{}$K".format(string[0], round(int(string[1])))
# do math
R_orig = f_orig/(i_orig+i2_orig)
numpy.nan_to_num(R_orig)
# error propagation for positive dg
dr, df, di, di2 = (r_max - r_orig), (f_max - f_orig), (i_max - i_orig), (i2_max - i2_orig)
f_term = df ** 2 / (i_orig + i2_orig) ** 2
i_term = di ** 2 * (-f_orig / (i_orig + i2_orig) ** 2) ** 2
i2_term = di2 ** 2 * (-f_orig / (i_orig + i2_orig) ** 2) ** 2
dR = numpy.sqrt(f_term + i_term + i2_term)
R_max = R_orig + dR
#error propagation for negative dg
dr, df, di, di2 = (r_orig - r_min), (f_orig - f_min), (i_orig - i_min), (i2_orig - i2_min)
f_term = df ** 2 / (i_orig + i2_orig) ** 2
i_term = di ** 2 * (-f_orig / (i_orig + i2_orig) ** 2) ** 2
i2_term = di2 ** 2 * (-f_orig / (i_orig + i2_orig) ** 2) ** 2
dR = numpy.sqrt(f_term + i_term + i2_term)
R_min = R_orig - dR
if labels[i] != '':
ax.semilogx(dens_bins, R_orig, color=clist(i), label=labels[i])
else:
ax.semilogx(dens_bins, R_orig, color=clist(i), label=temperature)
ax.fill_between(dens_bins, R_min, R_max, alpha=alphas[i], color=clist(i))
error = (abs(R_max-R_min)/R_orig)/2
if max(error) > max_y_tick: max_y_tick = max(error)
ax2.semilogx(dens_bins, error, color=clist(i))
if R_orig[-1] > R_orig[0]: left = True
else: left = False
# set y ticks for error subplot if user didn't specify
if tickstep == {}:
if max_y_tick < 0.05: tickstep = 0.01
elif 0.05 < max_y_tick < 0.1: tickstep = 0.02
elif 0.1 < max_y_tick < 0.2: tickstep = 0.05
elif 0.2 < max_y_tick < 0.4: tickstep = 0.1
elif 0.4 < max_y_tick < 0.8: tickstep = 0.2
elif 0.8 < max_y_tick < 1.5: tickstep = 0.25
elif 1.5 < max_y_tick: tickstep = 0.5
ticks = numpy.arange(0, max_y_tick + tickstep, tickstep)
if plot_settings['important_ticks'] != {}:
ticks += numpy.array(plot_settings['important_ticks'])
ax2.set_yticks(ticks)
if plot_settings['grid_kwargs'] != {}:
ax2.grid(plot_settings['grid_kwargs'])
fig.subplots_adjust(left=0.16, right=0.96, bottom=0.14, top=0.95)
if plot_settings['legendloc'] != 'best':
ax.legend(fontsize=plot_settings['legendsize'], loc=plot_settings['legendloc'])
else:
if left == True:
ax.legend(fontsize=plot_settings['legendsize'], loc='upper left')
else:
ax.legend(fontsize=plot_settings['legendsize'], loc='upper right')
fig.align_ylabels()
fig.savefig(name + ' R ratio.pdf')
elif ratio.lower() == 'g': # temp dependent g ratio
print("Plotting", name, "G ratio")
ax2.set_xlabel('Temperature in K', fontsize=plot_settings['fontsize'])
ax.set_ylabel(name + ' G Ratio', fontsize=plot_settings['fontsize'])
max_y_tick = 0
for i, file in enumerate(fnames):
with fits.open(file) as hdul:
data = hdul[1].data
temp_bins, r_orig, r_min, r_max = data['temp'], data['r orig'], data['r min'], data['r max']
f_orig, f_min, f_max = data['f orig'], data['f min'], data['f max']
i_orig, i_min, i_max = data['i orig'], data['i min'], data['i max']
i2_orig, i2_min, i2_max = data['i2 orig'], data['i2 min'], data['i2 max']
if 'density' in [hdul[1].header[x] for x in hdul[1].header.keys()]:
string = "{:.0e}".format(data['density'][0]).split("e+")
if string[1] == '00':
density = "$N_e = " + "{}".format(string[0]) + " cm^{-3}$"
else:
density = "$N_e = " + "{}\\times 10^{}".format(string[0], round(int(string[1]))) + " cm^{-3}$"
# do math
g_orig = (f_orig + i_orig + i2_orig) / r_orig
numpy.nan_to_num(g_orig)
# error propagation for positive dg
dr, df, di, di2 = (r_max - r_orig), (f_max - f_orig), (i_max - i_orig), (i2_max - i2_orig)
r_term = (((-f_orig - i_orig - i2_orig) / r_orig ** 2) ** 2) * (dr ** 2)
f_term = df ** 2 / r_orig ** 2
i_term = di ** 2 / r_orig ** 2
i2_term = di2 ** 2 / r_orig ** 2
dg = numpy.sqrt(r_term + f_term + i_term + i2_term)
g_max = g_orig + dg
# error propagation for negative dg
dr, df, di, di2 = (r_orig - r_min), (f_orig - f_min), (i_orig - i_min), (i2_orig - i2_min)
r_term = (((-f_orig - i_orig - i2_orig) / r_orig ** 2) ** 2) * (dr ** 2)
f_term = df ** 2 / r_orig ** 2
i_term = di ** 2 / r_orig ** 2
i2_term = di2 ** 2 / r_orig ** 2
dg = numpy.sqrt(r_term + f_term + i_term + i2_term)
g_min = g_orig - dg
ax.semilogx(temp_bins, g_orig, color=clist(i))
if labels[i] == '':
ax.fill_between(temp_bins, g_min, g_max, alpha=alphas[i], color=clist(i), label=density)
else:
ax.fill_between(temp_bins, g_min, g_max, alpha=alphas[i], color=clist(i), label=labels[i])
error = (abs(g_max-g_min)/g_orig)/2
error = error[3:]
if max(error) > max_y_tick: max_y_tick = max(error)
ax2.semilogx(temp_bins[3:], error, color=clist(i))
if g_orig[-1] > g_orig[0]: left = True
else: left = False
# set y ticks for error subplot if user didn't specify
if tickstep == {}:
if max_y_tick < 0.05: tickstep = 0.01
elif 0.05 < max_y_tick < 0.1: tickstep = 0.02
elif 0.1 < max_y_tick < 0.2: tickstep = 0.05
elif 0.2 < max_y_tick < 0.4: tickstep = 0.1
elif 0.4 < max_y_tick < 0.8: tickstep = 0.2
elif 0.8 < max_y_tick < 1.5: tickstep = 0.25
elif 1.5 < max_y_tick: tickstep = 0.5
ticks = numpy.arange(0, max_y_tick + tickstep, tickstep)
if plot_settings['important_ticks'] != {}:
ticks += numpy.array(plot_settings['important_ticks'])
ax2.set_yticks(ticks)
if plot_settings['grid_kwargs'] != {}:
ax2.grid(plot_settings['grid_kwargs'])
fig.subplots_adjust(left=0.16, right=0.96, bottom=0.14, top=0.95)
if plot_settings['legendloc'] != 'best':
ax.legend(fontsize=plot_settings['legendsize'], loc=plot_settings['legendloc'])
else:
if left == True: ax.legend(fontsize=plot_settings['legendsize'], loc='upper left')
else: ax.legend(fontsize=plot_settings['legendsize'], loc='upper right')
fig.align_ylabels()
fig.savefig(name + ' G ratio.pdf')
elif ratio.lower() == 'b': #plot blended ratio
print("Plotting", name, "blended ratio")
ax.set_ylabel('Blended Line Ratio', fontsize=plot_settings['fontsize'])
max_y_tick = 0
for i, file in enumerate(fnames):
if 'dens' in file:
ax2.set_xlabel('Density in cm$^{-3}$', fontsize=plot_settings['fontsize'])
with fits.open(file) as hdul:
data = hdul[1].data
dens_bins, dens_total_min, dens_total_max, dens_total_orig = data['dens'], data['dens_min'], data['dens_max'], data['dens_orig']
if 'temperatures' in [hdul[1].header[x] for x in hdul[1].header.keys()]:
string = "{:.0e}".format(data['temperatures'][0]).split("e+")
temperature = "$T_e$ = " + "{}\\times 10^{}$K".format(string[0], round(int(string[1])))
ax.semilogx(dens_bins, dens_total_orig, color=clist(current))
if labels[i] == '':
ax.fill_between(dens_bins, dens_total_min, dens_total_max, label=temperature, color=clist(i), alpha=alphas[i])
else:
ax.fill_between(dens_bins, dens_total_min, dens_total_max, label=label, color=clist(i), alpha=alphas[i])
error = (abs(dens_total_max-dens_total_min)/dens_total_orig)/2
if max(error) > max_y_tick: max_y_tick = max(error)
ax2.semilogx(dens_bins, error, color=clist(i))
if dens_total_orig[-1] > dens_total_orig[0]: left = True
else: left = False
elif 'Te' in file:
ax2.set_xlabel('Temperature in K', fontsize=plot_settings['fontsize'])
with fits.open(file) as hdul:
data = hdul[1].data
temp_bins, Te_total_min, Te_total_max, Te_total_orig = data['temp'], data['Te_min'], data['Te_max'], data['Te_orig']
if 'density' in [hdul[1].header[x] for x in hdul[1].header.keys()]:
string = "{:.0e}".format(data['density'][0]).split("e+")
density = "$N_e = " + "{}\\times 10^{}".format(string[0], round(int(string[1]))) + " cm^{-3}$"
ax.semilogx(temp_bins, Te_total_orig)
if label == '':
ax.fill_between(temp_bins, Te_total_min, Te_total_max, label=density, color=clist(i), alpha=alphas[i])
else:
ax.fill_between(temp_bins, Te_total_min, Te_total_max, label=label, color=clist(i), alpha=alphas[i])
error = (abs(Te_total_max-Te_total_min)/Te_total_orig)/2
if max(error) > max_y_tick: max_y_tick = max(error)
ax2.semilogx(temp_bins, error, color=clist(i))
if Te_total_orig[-1] > Te_total_orig[0]: left = True
else: left = False
# set y ticks for error subplot if user didn't specify
if tickstep == {}:
if max_y_tick < 0.05: tickstep = 0.01
elif 0.05 < max_y_tick < 0.1: tickstep = 0.02
elif 0.1 < max_y_tick < 0.2: tickstep = 0.05
else: tickstep = 0.1
ticks = numpy.arange(0, max_y_tick + tickstep, tickstep)
if plot_settings['important_ticks'] != {}:
ticks += numpy.array(plot_settings['important_ticks'])
ax2.set_yticks(ticks)
if plot_settings['grid_kwargs'] != {}:
ax2.grid(plot_settings['grid_kwargs'])
fig.subplots_adjust(left=0.16, right=0.96, bottom=0.14, top=0.95)
if plot_settings['legendloc'] != 'best':
ax.legend(fontsize=plot_settings['legendsize'], loc=plot_settings['legendloc'])
else:
if left == True: ax.legend(fontsize=plot_settings['legendsize'], loc='upper left')
else: ax.legend(fontsize=plot_settings['legendsize'], loc='upper right')
fig.align_ylabels()
plt.savefig(name + ' blended ratio.pdf')
if show == True:
plt.show()
##update for better plotting
def run_line_diagnostics(Z, z1, up, lo, Te, dens, vary, delta_r, Te_range={}, dens_range={}, num={}, pop_fraction={}, show=True, makefiles=False):
""" Run line diagnostics for specified Z, z1 where up, lo are transition levels at
specified Te and dens. Vary is 'exc' rate or 'A' value, delta_r is fractional error.
Can specify range of Te and dens values with tuple of (min, max) values and number
of values to calculate at. Default Te_range is 20 values over (Te/10, Te*10)
and default dens_range is 10 values over (1, 1e16). Will plot if set to True.
Default is both temp and dens diagnostics if left blank. Can pick one type and use
default ranges by setting either Te_range or dens_range = -1."""
from timeit import default_timer as timer
#set default values
if num == {}: temp_num, dens_num = 20, 10
else: temp_num, dens_num = num, num
#set default ranges blank
if Te_range == -1: Te_range = (Te/10, Te*10)
if dens_range == -1: dens_range = (1, 1e16)
#check what type of diagnostics
if ((Te_range == {}) & (dens_range == {})) or ((Te_range == -1) & (dens_range == -1)): #run both
type, temperature, density = 'both', True, True
elif (Te_range == {}) & (dens_range != {}): #run dens diagnostics
type, temperature, density = 'dens', False, True
elif (Te_range != {}) & (dens_range == {}): #run temp diagnostics
type, temperature, density = 'temp', True, False
start = timer()
element, ion = pyatomdb.atomic.Ztoelsymb(Z), pyatomdb.atomic.int_to_roman(z1)
extras = {'process': vary, 'delta_r': delta_r, 'transition': (up, lo), 'transition_2': [],
'wavelen': (10, 20), 'Te_range': Te_range, 'dens_range': dens_range, 'corrthresh': 10e-5, 'e_signif': 0.0,
'pop_fraction': {}}
if temperature == True:
temp_bins = list(numpy.geomspace(Te_range[0], Te_range[1], num=temp_num)) # 20
Te_eps_orig, Te_eps_min, Te_eps_max =[], [], []
for counter, temp_Te in enumerate(temp_bins):
if vary == 'A':
Te_inputs, Te_values, transition = set_up(Z, z1, temp_Te, dens, extras=extras)
Te_new_inputs, Te_new_values = vary_a(Te_inputs, Te_values, (up, lo))
elif vary == 'exc':
extras.update({'transition': (lo, up)})
Te_inputs, Te_values, transition = set_up(Z, z1, temp_Te, dens, extras=extras)
Te_new_inputs, Te_new_values = vary_exc(Te_inputs, Te_values, (lo, up))
Te_table, Te_new_table, Te_inputs, Te_results = get_tables(Te_new_inputs, Te_new_values)
i = numpy.where((Te_table['Upper'] == up) & (Te_table['Lower'] == lo))[0]
for col, array in zip(['Epsilon_orig', 'Epsilon_min', 'Epsilon_max'], [Te_eps_orig, Te_eps_min, Te_eps_max]):
if Te_table[i][col] == 0: Te_table[i][col] = 1e-40
array.append(Te_table[i][col])
print(str(temp_num - counter), 'temperatures left\n')
if density == True:
dens_bins = list(numpy.geomspace(dens_range[0], dens_range[1], num=dens_num))
dens_eps_orig, dens_eps_min, dens_eps_max =[],[],[]
for counter, temp_dens in enumerate(dens_bins):
print("density is:", temp_dens)
if vary == 'A':
dens_inputs, dens_values, transition = set_up(Z, z1, Te, temp_dens, extras=extras)
dens_new_inputs, dens_new_values = vary_a(dens_inputs, dens_values, (up, lo))
elif vary == 'exc':
extras.update({'transition': (lo, up)})
dens_inputs, dens_values, transition = set_up(Z, z1, Te, temp_dens, extras=extras)
dens_new_inputs, dens_new_values = vary_exc(dens_inputs, dens_values, (lo, up))
dens_table, dens_new_table, dens_inputs, dens_results = get_tables(dens_new_inputs, dens_new_values)
i = numpy.where((dens_table['Upper'] == up) & (dens_table['Lower'] == lo))[0]
for col, array in zip(['Epsilon_orig', 'Epsilon_min', 'Epsilon_max'],
[dens_eps_orig, dens_eps_min, dens_eps_max]):
if dens_table[i][col] == 0: dens_table[i][col] = 1e-40
array.append(dens_table[i][col])
print(str(dens_num-counter), 'densities left\n')
if type == 'temp':
line_diagnostics = {'type': 'temp', 'temps': list(temp_bins),'orig': list(Te_eps_orig),
'min': list(Te_eps_min),'max': list(Te_eps_max), 'density': [dens]*len(temp_bins)}
table = Table([temp_bins, Te_eps_orig, Te_eps_min, Te_eps_max, [dens] * len(temp_bins)],
names=('temps', 'orig', 'min', 'max', 'density'))
elif type == 'dens':
line_diagnostics = {'type': 'dens', 'dens': list(dens_bins),'orig': list(dens_eps_orig),
'min': list(dens_eps_min),'max': list(dens_eps_max), 'temperature': [Te]*len(dens_bins)}
table = Table([dens_bins, dens_eps_orig, dens_eps_min, dens_eps_max, [Te]*len(dens_bins)], names=('dens', 'orig', 'min', 'max', 'temperature'))
elif type == 'both':
line_diagnostics = {'type': 'both', 'temps': list(temp_bins), 'dens': list(dens_bins),
'Te_orig': list(Te_eps_orig), 'Te_min': list(Te_eps_min),
'Te_max': list(Te_eps_max), 'dens_orig': list(dens_eps_orig),
'dens_min': list(dens_eps_min), 'dens_max': list(dens_eps_max)}
table = Table([dens_bins, dens_eps_orig, dens_eps_min, dens_eps_max, [Te] * len(dens_bins).
temp_bins, Te_eps_orig, Te_eps_min, Te_eps_max, [dens]*len(temp_bins)],
names=('dens', 'dens_orig', 'dens_min', 'dens_max', 'temperature',
'temps', 'Te_orig', 'Te_min', 'Te_max', 'density'))