-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmesaplot.py
More file actions
1419 lines (1122 loc) · 66.4 KB
/
mesaplot.py
File metadata and controls
1419 lines (1122 loc) · 66.4 KB
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
#!/usr/bin/env python
import matplotlib
#matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.colors as colors
import matplotlib.cm as cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import numpy.lib.recfunctions
from astropy import units as u
from astropy import constants as const
from multiprocessing import Pool,cpu_count
from scipy.interpolate import interp1d
from math import atan2,degrees
#Label line with line2D label data
def labelLine(line,x,label=None,align=True,**kwargs):
ax = line.get_axes()
xdata = line.get_xdata()
ydata = line.get_ydata()
if (x < xdata[0]) or (x > xdata[-1]):
print('x label location is outside data range!')
return
#Find corresponding y co-ordinate and angle of the
ip = 1
for i in range(len(xdata)):
if x < xdata[i]:
ip = i
break
y = ydata[ip-1] + (ydata[ip]-ydata[ip-1])*(x-xdata[ip-1])/(xdata[ip]-xdata[ip-1])
if not label:
label = line.get_label()
if align:
#Compute the slope
dx = xdata[ip] - xdata[ip-1]
dy = ydata[ip] - ydata[ip-1]
ang = degrees(atan2(dy,dx))
#Transform to screen co-ordinates
pt = np.array([x,y]).reshape((1,2))
trans_angle = ax.transData.transform_angles(np.array((ang,)),pt)[0]
else:
trans_angle = 0
#Set a bunch of keyword arguments
if 'color' not in kwargs:
kwargs['color'] = line.get_color()
if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs):
kwargs['ha'] = 'center'
if ('verticalalignment' not in kwargs) and ('va' not in kwargs):
kwargs['va'] = 'center'
if 'backgroundcolor' not in kwargs:
kwargs['backgroundcolor'] = ax.get_axis_bgcolor()
if 'clip_on' not in kwargs:
kwargs['clip_on'] = True
if 'zorder' not in kwargs:
kwargs['zorder'] = 2.5
t = ax.text(x,y,label,rotation=trans_angle, **kwargs)
t.set_bbox(dict(color='white', alpha=0.0))
def labelLines(lines,align=True,xvals=None,**kwargs):
ax = lines[0].get_axes()
labLines = []
labels = []
#Take only the lines which have labels other than the default ones
for line in lines:
label = line.get_label()
if "_line" not in label:
labLines.append(line)
labels.append(label)
if xvals is None:
xmin,xmax = ax.get_xlim()
xvals = np.linspace(xmin,xmax,len(labLines)+2)[1:-1]
else:
xmin,xmax = ax.get_xlim()
xvals = np.asarray(xvals)*(xmax-xmin)+xmin
for line,x,label in zip(labLines,xvals,labels):
labelLine(line,x,label,align,**kwargs)
def LoadOneProfile(filename):
"""Load one profile.
Use numpy's genfromtxt to read input file. Top 5 lines are skipped.
Args:
filename (str) -- name of the file to be loaded
Returns:
data stored as a numpy array
"""
# This function needs to be outside the class, otherwise it is not picklable and it does nto work with pool.async
data_from_file=np.genfromtxt(filename, skip_header=5, names=True)
return data_from_file
def InterpolateOneProfile(profile, NY, Yaxis, Ymin, Ymax, Variable):
"""Interpolate along a stellar profile.
Args:
profile (ndarray) -- the data structure holding a stellar profile
NY (int) -- the number of data points to interpolate
Yaxis (str) -- the independent variable along which to interpolate.
Possible values: mass, radius, q, log_mass, log_radius, log_q
Ymin (flt) -- the minimum independent variable value
Ymax (flt) -- the maximum independent variable value
Variable (str) -- the variable to be interpolated
Possible values: eps_nuc, velocity, entropy, total_energy, j_rot,
eps_recombination, ionization_energy, energy, potential_plus_kinetic,
extra_heat, v_div_vesc, v_div_csound, pressure, temperature, density,
tau, opacity, gamma1, gamma3, dq, L_div_Ledd, Lrad_div_Ledd. t_thermal, t_dynamical,
t_dynamical_down, t_thermal_div_t_dynamical, omega_div_omega_crit, omega
super_ad, vconv, vconv_div_vesc, conv_vel_div_csound, total_energy_plus_vconv2
t_thermal_div_t_expansion, E_kinetic_div_E_thermal
Returns:
data interpolated along profile as a 1-D numpy array of length NY
"""
# This function needs to be outside the class, otherwise it is not picklable and it does nto work with pool.async
# Add the fields log_mass, log_q and log_radius, in case they are not stored in the profile files
if (not "log_mass" in profile.dtype.names):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'log_mass',
data = np.log10(profile['mass']), asrecarray=True)
except Exception:
raise ValueError("Column 'mass' is missing from the profile files")
if (not "log_q" in profile.dtype.names):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'log_q',
data = np.log10(profile['q']), asrecarray=True)
except Exception:
try:
profile = numpy.lib.recfunctions.append_fields(profile,'log_q',
data = np.log10(profile['mass']/profile['mass'][0]), asrecarray=True)
except Exception:
raise ValueError("Column 'q' is missing from the profile files")
if (not "log_radius" in profile.dtype.names):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'log_radius',
data = np.log10(profile['radius']), asrecarray=True)
except Exception:
try:
profile = numpy.lib.recfunctions.append_fields(profile,'log_radius',
data = profile['logR'], asrecarray=True)
except Exception:
raise ValueError("Column 'logR' or 'log_radius' or 'radius' is missing from the profile files")
if (not "radius" in profile.dtype.names):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'radius',
data = 10.**profile['log_radius'], asrecarray=True)
except Exception:
try:
profile = numpy.lib.recfunctions.append_fields(profile,'radius',
data = 10.**profile['logR'], asrecarray=True)
except Exception:
raise ValueError("Column 'logR' or 'log_radius' or 'radius' is missing from the profile files")
if (not "j_rot" in profile.dtype.names and (Variable == 'log_j_rot' or Variable == 'j_rot')):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'j_rot',
data = 10.**profile['log_j_rot'], asrecarray=True)
except Exception:
raise ValueError("Column 'log_j_rot' is missing from the profile files")
if (not "potential_plus_kinetic" in profile.dtype.names and (Variable == 'potential_plus_kinetic' )):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'potential_plus_kinetic',
data = profile['total_energy'] - profile['energy'], asrecarray=True)
except Exception:
raise ValueError("Column 'total_energy' and/or 'energy' is missing from the profile files")
if (not "v_div_vesc" in profile.dtype.names and (Variable == 'v_div_vesc' )):
G = const.G.to('cm3/(g s2)').value
Msun = const.M_sun.to('g').value
Rsun = const.R_sun.to('cm').value
try:
profile = numpy.lib.recfunctions.append_fields(profile,'v_div_vesc',
data = profile['velocity']/np.sqrt(2.*G*(profile['mass']*Msun)/(profile['radius']*Rsun)), asrecarray=True)
except Exception:
raise ValueError("Column 'radius' and/or 'velocity' is missing from the profile files")
if Variable == 'temperature' :
try:
profile = numpy.lib.recfunctions.append_fields(profile,'temperature',
data = 10.**profile['logT'], asrecarray=True)
except Exception:
raise ValueError("Column 'logT' is missing from the profile files")
if Variable == 'pressure' :
try:
profile = numpy.lib.recfunctions.append_fields(profile,'pressure',
data = 10.**profile['logP'], asrecarray=True)
except Exception:
raise ValueError("Column 'logP' is missing from the profile files")
if Variable == 'density' :
try:
profile = numpy.lib.recfunctions.append_fields(profile,'density',
data = 10.**profile['logRho'], asrecarray=True)
except Exception:
raise ValueError("Column 'logRho' is missing from the profile files")
if Variable == 'gamma1' :
try:
profile['gamma1'] = 4./3.-profile['gamma1']
except Exception:
raise ValueError("Column 'gamma1' is missing from the profile files")
if Variable == 'tau' :
try:
profile = numpy.lib.recfunctions.append_fields(profile,'tau',
data = 10.**profile['logtau'], asrecarray=True)
except Exception:
raise ValueError("Column 'logtau' is missing from the profile files")
if (not "opacity" in profile.dtype.names and (Variable == 'opacity' )):
raise ValueError("Column 'opacity' is missing from the profile files")
if (not "v_div_csound" in profile.dtype.names and (Variable == 'v_div_csound' )):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'v_div_csound',
data = profile['velocity']/profile['csound'], asrecarray=True)
except Exception:
raise ValueError("Column 'v_div_csound' is missing from the profile files")
if (not "dq" in profile.dtype.names and (Variable == 'dq' )):
raise ValueError("Column 'dq' is missing from the profile files")
if (Variable == 'L_div_Ledd'):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'L_div_Ledd',
data = 10.**profile['log_L_div_Ledd'], asrecarray=True)
except Exception:
raise ValueError("Column 'log_L_div_Ledd' is missing from the profile files")
if (Variable == 'Lrad_div_Ledd'):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'Lrad_div_Ledd',
data = 10.**profile['log_Lrad_div_Ledd'], asrecarray=True)
except Exception:
raise ValueError("Column 'log_Lrad_div_Ledd' is missing from the profile files")
if (Variable == 't_thermal'):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'t_thermal',
data = 10.**profile['log_thermal_time_to_surface'], asrecarray=True)
except Exception:
raise ValueError("Column 'log_thermal_time_to_surface' is missing from the profile files")
if (Variable == 't_dynamical'):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'t_dynamical',
data = 10.**profile['log_acoustic_depth'], asrecarray=True)
except Exception:
raise ValueError("Column 'log_acoustic_depth' is missing from the profile files")
if (Variable == 't_dynamical_down'):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'t_dynamical_down',
data = 10.**profile['log_acoustic_radius'], asrecarray=True)
except Exception:
raise ValueError("Column 'log_acoustic_radius' is missing from the profile files")
if (Variable == 't_thermal_div_t_dynamical'):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'t_thermal_div_t_dynamical',
data = 10.**profile['log_thermal_time_to_surface']/10.**profile['log_acoustic_depth'], asrecarray=True)
except Exception:
raise ValueError("Column 'log_thermal_time_to_surface' and/or 'log_acoustic_depth' are missing from the profile files")
if (not "omega_div_omega_crit" in profile.dtype.names and (Variable == 'omega_div_omega_crit' )):
raise ValueError("Column 'omega_div_omega_crit' is missing from the profile files")
if (not "omega" in profile.dtype.names and (Variable == 'omega' )):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'omega',
data = 10.**profile['log_omega'], asrecarray=True)
except Exception:
raise ValueError("Column 'omega' and 'log_omega' are missing from the profile files")
if (not "super_ad" in profile.dtype.names and (Variable == 'super_ad' )):
raise ValueError("Column 'super_ad' is missing from the profile files")
if (not "vconv" in profile.dtype.names and (Variable == 'vconv' )):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'vconv',
data = profile['conv_vel'], asrecarray=True)
except Exception:
raise ValueError("Column 'conv_vel' is missing from the profile files")
if (not "vconv_div_vesc" in profile.dtype.names and (Variable == 'vconv_div_vesc' )):
G = const.G.to('cm3/(g s2)').value
Msun = const.M_sun.to('g').value
Rsun = const.R_sun.to('cm').value
try:
profile = numpy.lib.recfunctions.append_fields(profile,'vconv_div_vesc',
data = profile['conv_vel']/np.sqrt(2.*G*(profile['mass']*Msun)/(profile['radius']*Rsun)), asrecarray=True)
except Exception:
raise ValueError("Column 'radius' and/or 'conv_vel' is missing from the profile files")
if (not "conv_vel_div_csound" in profile.dtype.names and (Variable == 'conv_vel_div_csound' )):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'conv_vel_div_csound',
data = profile['conv_vel']/profile['csound'], asrecarray=True)
except Exception:
raise ValueError("Column 'csound' and/or 'conv_vel' is missing from the profile files")
if (not "total_energy_plus_vconv2" in profile.dtype.names and (Variable == 'total_energy_plus_vconv2' )):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'total_energy_plus_vconv2',
data = profile['total_energy'] + 0.5*np.power(profile['conv_vel'],2), asrecarray=True)
except Exception:
raise ValueError("Column 'total_energy' and/or 'conv_vel' is missing from the profile files")
if (not "t_thermal_div_t_expansion" in profile.dtype.names and (Variable == 't_thermal_div_t_expansion' )):
try:
Rsun = const.R_sun.to('cm').value
profile = numpy.lib.recfunctions.append_fields(profile,'t_thermal_div_t_expansion',
data = 10.**profile['log_thermal_time_to_surface']/(10.**profile['logR']*Rsun/profile["velocity"]), asrecarray=True)
except Exception:
raise ValueError("Column 'log_thermal_time_to_surface' and/or 'velocity' is missing from the profile files")
if (not "E_kinetic_div_E_thermal" in profile.dtype.names and (Variable == 'E_kinetic_div_E_thermal' )):
try:
profile = numpy.lib.recfunctions.append_fields(profile,'E_kinetic_div_E_thermal',
data = 0.5*profile["velocity"]*profile["velocity"]/(profile["energy"]-profile["ionization_energy"]), asrecarray=True)
except Exception:
raise ValueError("Column 'ionization_energy' and/or 'velocity' is missing from the profile files")
#Define the values that we want to itnerpolate along the Y axis
Y_to_interp = (np.arange(1,NY+1).astype(float))/float(NY+2) * (Ymax-Ymin) + Ymin
# Find the elements of Y_to_iterp that are valid for the specific profile data file.
valid_points = np.where((Y_to_interp < np.max(profile[Yaxis])) &
(Y_to_interp > np.min(profile[Yaxis])))
invalid_points = np.where((Y_to_interp > np.max(profile[Yaxis])) &
(Y_to_interp < np.min(profile[Yaxis])))
interp_func = interp1d(profile[Yaxis], profile[Variable])
data1 = np.zeros(NY)
data1[:] = float('nan')
data1[valid_points] = interp_func(Y_to_interp[valid_points])
return data1
class mesaplot(object):
def __init__(self, **kwargs):
"""An object containing the output data from a MESA run.
Upon initialization, class loads data, interpolates along axes, and
stores interpolated data in instance of class.
Args:
data_path (str) -- file path of data directory (default "./")
NX (int) -- number of data points on the x-axis (default 1024)
NY (int) -- number of data points on the y-axis (default 1024)
Yaxis (str) -- y-axis plotting variable (default 'mass')
Xaxis (str) -- x-axis plotting variable (default 'star_age')
Variable (str) -- z-axis (color) plotting variable (default 'eps_nuc')
cmap (str) -- color scheme (default 'coolwarm')
cmap_dynamic_range (flt) -- range in decades for cmap (default 10)
Xaxis_dynamic_range (flt) -- x-axis range (default float('Inf'))
Yaxis_dynamic_range (flt) -- y-axis range (default 4)
Xaxis_min (flt) -- minimum of x-axis range (default undefined which results to auto)
Xaxis_max (flt) -- maximum of x-axis range (default undefined which results to auto)
Yaxis_min (flt) -- minimum of y-axis range (default undefined which results to auto)
Yaxis_max (flt) -- maximum of y-axis range (default undefined which results to auto)
figure_format (str) -- figure output format (default "eps")
font_small (int) -- figure small font size (default 16)
font_large (int) -- figure large font size (default 20)
file_out (str) -- output figure name (default 'figure')
onscreen (bool) -- plot figure on screen (default False)
parallel (bool) -- create object using multiple processors (default True)
abundances (bool) -- include abundance data in object (default False)
log_abundances (bool) -- abudance data stored as logs (default True)
czones (bool) - include convective zone data (default False)
signed_log_cmap (bool) - use absolute value for color map (default True)
orbit (bool) -- include secondary's position, for profile plots (default False)
tau10 (bool) -- include optical depth of 10 in plot (default True)
tau100 (bool) -- include optical depth of 100 in plot (default False)
Nprofiles_to_plot (int) -- number of profiles to plot (default 10)
profiles_to_plot (list[int]) -- profile numbers to be plotted (default [])
masses_TML (list[float]) -- mass locations (in Msun) to trace in radius (default [])
xvals_TML (list[float]) -- xvals, between 0 and 1, where labels of lines that trace constant mass are places.
Must be same size as masses_TML. If left empty, labels are placed automatically (default [])
"""
self._param = {'data_path':"./", 'NX':1024, 'NY':1024, 'Yaxis':'mass', 'Xaxis':'star_age',
'Variable':'eps_nuc', 'cmap':'coolwarm', 'cmap_dynamic_range':10, 'Xaxis_dynamic_range':float('Inf'),
'Yaxis_dynamic_range':4, 'figure_format':"eps", 'font_small':16, 'font_large':20, 'file_out':'figure',
'onscreen':False, 'parallel':True, 'abundances':False, 'log_abundances':True, 'czones':False,
'signed_log_cmap':True, 'orbit':False, 'tau10':True, 'tau100':False, 'Nprofiles_to_plot':10,
'profiles_to_plot':[], 'masses_TML':[], 'xvals_TML':[], 'Xaxis_min':None, 'Xaxis_max':None, 'Xaxis_label':None,
'Yaxis_label':None, 'Yaxis_min':None, 'Yaxis_max':None, 'cmap_min':None, 'cmap_max':None, 'cmap_label':None}
for key in kwargs:
if (key in self._param):
self._param[key] = kwargs[key]
else:
raise ValueError(key+" is not a valid parameter name")
self.CheckParameters()
self.LoadData()
self.InterpolateData()
@property
def data_path(self):
return self._param['data_path']
@property
def NY(self):
return self._param['NY']
@property
def NX(self):
return self._param['NX']
@property
def Yaxis(self):
return self._param['Yaxis']
@property
def Xaxis(self):
return self._param['Xaxis']
@property
def Variable(self):
return self._param['Variable']
@property
def cmap(self):
return self._param['cmap']
@property
def cmap_dynamic_range(self):
return self._param['cmap_dynamic_range']
@property
def Xaxis_dynamic_range(self):
return self._param['Xaxis_dynamic_range']
@property
def Yaxis_dynamic_range(self):
return self._param['Yaxis_dynamic_range']
@property
def figure_format(self):
return self._param['figure_format']
@property
def font_small(self):
return self._param['font_small']
@property
def font_large(self):
return self._param['font_large']
@property
def file_out(self):
return self._param['file_out']
@property
def onscreen(self):
return self._param['onscreen']
@property
def parallel(self):
return self._param['parallel']
@property
def abundances(self):
return self._param['abundances']
@property
def abundances(self):
return self._param['log_abundances']
@property
def czones(self):
return self._param['czones']
@property
def signed_log_cmap(self):
return self._param['signed_log_cmap']
@property
def orbit(self):
return self._param['orbit']
@property
def tau10(self):
return self._param['tau10']
@property
def signed_log_cmap(self):
return self._param['tau100']
@property
def Nprofiles_to_plot(self):
return self._param['Nprofiles_to_plot']
@property
def profiles_to_plot(self):
return self._param['profiles_to_plot']
@property
def masses_TML(self):
return self._param['masses_TML']
@property
def xvals_TML(self):
return self._param['xvals_TML']
@property
def Xaxis_min(self):
return self._param['Xaxis_min']
@property
def Xaxis_max(self):
return self._param['Xaxis_max']
@property
def Xaxis_label(self):
return self._param['Xaxis_label']
@property
def Yaxis_min(self):
return self._param['Yaxis_min']
@property
def Yaxis_max(self):
return self._param['Yaxis_max']
@property
def Yaxis_label(self):
return self._param['Yaxis_label']
@property
def cmap_min(self):
return self._param['cmap_min']
@property
def cmap_max(self):
return self._param['cmap_max']
@property
def cmap_label(self):
return self._param['cmap_label']
def help(self):
#TODO: add a list of all parameters, the default values and the possible option, add a list of functions, and an example
pass
def CheckParameters(self):
"""Check parameters to make sure valid options have been assigned.
Possible values:
Xaxis -- model_number, star_age, inv_star_age, log_model_number,
log_star_age, log_inv_star_age
Yaxis -- mass, radius, q, log_mass, log_radius, log_q
Variable -- eps_nuc, velocity, entropy, total_energy, j_rot,
eps_recombination, ionization_energy, energy, potential_plus_kinetic,
extra_heat, v_div_vesc, v_div_csound, pressure, temperature, density,
tau, opacity, gamma1, dq,L_div_Ledd, Lrad_div_Ledd, t_thermal, t_dynamical,
t_dynamical_down, t_thermal_div_t_dynamical, omega_div_omega_crit, omega
cmap -- colors allowed by colormap module in matplotlib
"""
cmaps=[m for m in cm.datad]
if not (self._param['cmap'] in cmaps):
raise ValueError(self._param['cmap']+"not a valid option for parameter cmap")
if not (self._param['Yaxis'] in ['mass', 'radius', 'q', 'log_mass', 'log_radius', 'log_q']):
raise ValueError(self._param['Yaxis']+"not a valid option for parameter Yaxis")
if not (self._param['Xaxis'] in ['model_number', 'star_age', 'inv_star_age', 'log_model_number', 'log_star_age',
'log_inv_star_age']):
raise ValueError(self._param['Xaxis']+"not a valid option for parameter Xaxis")
if not (self._param['Variable'] in ['eps_nuc', 'velocity', 'entropy', 'total_energy', 'j_rot', 'eps_recombination'
, 'ionization_energy', 'energy', 'potential_plus_kinetic', 'extra_heat', 'v_div_vesc',
'v_div_csound', 'pressure', 'temperature', 'density', 'tau', 'opacity', 'gamma1', 'gamma3', 'dq',
'L_div_Ledd', 'Lrad_div_Ledd', 't_thermal', 't_dynamical', 't_dynamical_down', 't_thermal_div_t_dynamical',
'omega_div_omega_crit', 'omega','super_ad', 'vconv', 'vconv_div_vesc', 'conv_vel_div_csound',
't_thermal_div_t_expansion','E_kinetic_div_E_thermal','total_energy_plus_vconv2']):
raise ValueError(self._param['Variable']+"not a valid option for parameter Variable")
return
def SetParameters(self,**kwargs):
"""Change the value of a parameter held by instance of mesa class"""
for key in kwargs:
if (key in self._param):
self._param[key] = kwargs[key]
else:
raise ValueError(key+" is not a valid parameter name")
#Check if any of the parameters that changed require reloading and reinterrpolating the data
for key in kwargs:
if key in ['data_path','NX','NY','Xaxis','Yaxis','Variable','Xaxis_dynamic_range','Yaxis_dynamic_range']:
self.InterpolateData()
break
self.CheckParameters()
return
def LoadData(self):
"""Load data from mesa outputs.
Data is loaded from both history.data and individual
profile*.data files. 'profiles.index' is used.
"""
# Read history with numpy so that we keep the column names and then convert then convert to a record array
self.history = np.genfromtxt(self._param['data_path']+"history.data", skip_header=5, names=True)
# Read list of available profile files
self._profile_index = np.genfromtxt(self._param['data_path']+"profiles.index",skip_header=1,usecols=(0,2),
dtype=[('model_number',int),('file_index',int)])
if not len(self._profile_index["file_index"]):
raise(self._param['data_path']+"profiles.index"+" does not contain information about enough profiles files")
#Create an array fromt eh history data that gives you the age of each model for wich you have output a profile
model_age_from_history = interp1d(self.history["model_number"], self.history["star_age"])
self.profile_age = model_age_from_history(self._profile_index["model_number"])
#Check that the age is increasing in consecutive profiles. If not, then MESA ma have done a back up in which
#case we should remove these profiles
idx_profiles_to_keep = np.where(self.profile_age[:-1] < self.profile_age[1:])[0]
self._profile_index = self._profile_index[:][idx_profiles_to_keep]
self.profile_age = self.profile_age[idx_profiles_to_keep]
#Check that the age is increasing in lines of history.data. If not, then MESA ma have done a back up in which
#case we should remove these profiles
idx_history_lines_to_keep = np.where(self.history['star_age'][:-1] < self.history['star_age'][1:])[0]
self.history = self.history[:][idx_history_lines_to_keep]
self.Nprofile = len(self._profile_index["file_index"])
self.profiles=[]
#Load the profile files and interpolate along the Y axis
if self._param['parallel'] :
# Creates jobserver with ncpus workers
pool = Pool(processes=cpu_count())
print("Process running in parallel on ", cpu_count(), " cores")
filenames = [self._param['data_path']+"profile"+str(self._profile_index["file_index"][i])+".data" for i in range(self.Nprofile)]
results = [pool.apply_async(LoadOneProfile, args = (filename,)) for filename in filenames]
Nresults=len(results)
for i in range(0,Nresults):
self.profiles.append(results[i].get())
pool.close()
else:
print("Process running serially")
for i in range(self.Nprofile):
filename = self._param['data_path']+"profile"+str(self._profile_index["file_index"][i])+".data"
self.profiles.append(LoadOneProfile(filename))
def InterpolateData(self):
"""Data is interpolated
Interpolations are performed in 1D, across
the defined x-axis.
"""
# Set the maximum and the minimum of the X axis
if (self._param['Xaxis_min'] is None) != (self._param['Xaxis_max'] is None):
raise("Both Xaxis_min and Xaxis_max need to be provided")
elif self._param['Xaxis_min'] is not None and self._param['Xaxis_max'] is not None:
self._Xaxis_min = self._param['Xaxis_min']
self._Xaxis_max = self._param['Xaxis_max']
elif self._param['Xaxis'] == "model_number":
self._Xaxis_max = np.max(self._profile_index["model_number"])
self._Xaxis_min = np.min(self._profile_index["model_number"])
elif self._param['Xaxis'] == "star_age":
self._Xaxis_max = np.max(self.profile_age)
self._Xaxis_min = np.min(self.profile_age)
elif self._param['Xaxis'] == "inv_star_age":
self._Xaxis_max = np.min(self.profile_age[-1] - self.profile_age)
self._Xaxis_min = np.max(self.profile_age[-1] - self.profile_age)
elif self._param['Xaxis'] == "log_model_number":
self._Xaxis_max = np.max(np.log10(self._profile_index["model_number"]))
self._Xaxis_min = max([np.min(np.log10(self._profile_index["model_number"])),
self._Xaxis_max-self._param['Xaxis_dynamic_range']])
elif self._param['Xaxis'] == "log_star_age":
self._Xaxis_max = np.max(np.log10(self.profile_age))
self._Xaxis_min = max([np.min(np.log10(self.profile_age)), self._Xaxis_max-self._param['Xaxis_dynamic_range']])
elif self._param['Xaxis'] == "log_inv_star_age":
self._Xaxis_min = np.max(np.log10(2.*self.profile_age[-1] - self.profile_age[-2] - self.profile_age))
self._Xaxis_max = max([np.min(np.log10(2.*self.profile_age[-1] - self.profile_age[-2] - self.profile_age)),
self._Xaxis_min-self._param['Xaxis_dynamic_range']])
else:
raise(self._param['Xaxis']+" is not a valid option for Xaxis")
# Set the maximum and the minimum of the Y axis
if (self._param['Yaxis_min'] is None) != (self._param['Yaxis_max'] is None):
raise("Both Yaxis_min and Yaxis_max need to be provided")
elif self._param['Yaxis_min'] is not None and self._param['Yaxis_max'] is not None:
self._Yaxis_min = self._param['Yaxis_min']
self._Yaxis_max = self._param['Yaxis_max']
elif self._param['Yaxis'] == "mass":
self._Yaxis_max = np.max(self.history["star_mass"])
self._Yaxis_min = 0.
elif self._param['Yaxis'] == "radius":
self._Yaxis_max = 10.**np.max(self.history["log_R"])
self._Yaxis_min = 0.
elif self._param['Yaxis'] == "q":
self._Yaxis_max = 1.
self._Yaxis_min = 0.
elif self._param['Yaxis'] == "log_mass":
self._Yaxis_max = np.max(np.log10(self.history["star_mass"]))
self._Yaxis_min = np.max(np.log10(self.history["star_mass"])) - self._param['Yaxis_dynamic_range']
elif self._param['Yaxis'] == "log_radius":
self._Yaxis_max = np.max(self.history["log_R"])
self._Yaxis_min = np.max(self.history["log_R"]) - self._param['Yaxis_dynamic_range']
elif self._param['Yaxis'] == "log_q":
self._Yaxis_max = 0.
self._Yaxis_min = -self._param['Yaxis_dynamic_range']
else:
raise(self._param['Yaxis']+" is not a valid option for Yaxis")
#Define the values that we want to itnerpolate along the the X and Y axis
X_to_interp = (np.arange(1,self._param['NX']+1).astype(float))/float(self._param['NX']+2) * (self._Xaxis_max-self._Xaxis_min) + self._Xaxis_min
self._data = np.zeros((self._param['NX'],self._param['NY']))
data_all = np.zeros((self.Nprofile,self._param['NY']))
data_all[:,:] = float('nan')
#Load the profile files and interpolate along the Y axis
if self._param['parallel'] :
# Creates jobserver with ncpus workers
pool = Pool(processes=cpu_count())
print("Process running in parallel on ", cpu_count(), " cores")
results = [pool.apply_async(InterpolateOneProfile, args = (profile, self._param['NY'], self._param['Yaxis'],
self._Yaxis_min, self._Yaxis_max, self._param['Variable'],)) for profile in self.profiles]
Nresults=len(results)
for i in range(0,Nresults):
data_all[i,:] = results[i].get()
pool.close()
else:
print("Process running serially")
for i in range(self.Nprofile):
data_all[i,:] = InterpolateOneProfile(self.profiles[i], self._param['NY'], self._param['Yaxis'], self._Yaxis_min,
self._Yaxis_max, self._param['Variable'])
for i in range(self._param['NY']):
if self._param['Xaxis'] == "model_number":
Xaxis_values = interp1d(self._profile_index["model_number"].astype(float), data_all[:,i])
elif self._param['Xaxis'] == "star_age":
Xaxis_values = interp1d(self.profile_age, data_all[:,i])
elif self._param['Xaxis'] == "inv_star_age":
Xaxis_values = interp1d(self.profile_age[-1]-self.profile_age, data_all[:,i])
elif self._param['Xaxis'] == "log_model_number":
Xaxis_values = interp1d(np.log10(self._profile_index["model_number"].astype(float)), data_all[:,i])
elif self._param['Xaxis'] == "log_star_age":
Xaxis_values = interp1d(np.log10(self.profile_age), data_all[:,i])
elif self._param['Xaxis'] == "log_inv_star_age":
Xaxis_values = interp1d(np.log10(2.*self.profile_age[-1]-self.profile_age[-2]-self.profile_age), data_all[:,i])
self._data[:,i] = Xaxis_values(X_to_interp)
def TraceMassLocations(self):
masses_TML = np.asarray(self._param['masses_TML'])
radii_of_masses_TML = np.zeros((masses_TML.shape[0],self.Nprofile))
for i in range(self.Nprofile):
inter_TML = interp1d(self.profiles[i]["mass"],10.**self.profiles[i]["logR"])
valid_points = np.where(masses_TML < np.max(self.profiles[i]["mass"]))
radii_of_masses_TML[:,i] = float('nan')
radii_of_masses_TML[valid_points,i] = inter_TML(masses_TML[valid_points])
return radii_of_masses_TML
def Kippenhahn(self, ax=None):
"""Generate a Kippenhahn diagram
Resulting plot is created and outputed.
"""
######################################################################
# Set the labels of the two axis
if self._param["Yaxis_label"] is not None:
Ylabel = self._param["Yaxis_label"]
elif self._param['Yaxis'] == "mass":
Ylabel = "Mass Coordinate [$M_{\odot}$]"
elif self._param['Yaxis'] == "radius":
Ylabel = "Radius Coordinate [$R_{\odot}$]"
elif self._param['Yaxis'] == "q":
Ylabel = "Dimentionless Mass Coordinate q"
elif self._param['Yaxis'] == "log_mass":
Ylabel = "log(Mass Coordinate [$M_{\odot}$])"
elif self._param['Yaxis'] == "log_radius":
Ylabel = "log(Radius Coordinate [$R_{\odot}$])"
elif self._param['Yaxis'] == "log_q":
Ylabel = "log(Dimentionless Mass Coordinate q)"
if self._param["Xaxis_label"] is not None:
Xlabel = self._param["Xaxis_label"]
elif self._param['Xaxis'] == "model_number":
Xlabel = "Model Number"
elif self._param['Xaxis'] == "star_age":
Xlabel = "Star Age [yr]"
elif self._param['Xaxis'] == "inv_star_age":
Xlabel = "Time since the end of evolution [yr]"
elif self._param['Xaxis'] == "log_model_number":
Xlabel = "log(Model Number)"
elif self._param['Xaxis'] == "log_star_age":
Xlabel = "log(Star Age [yr])"
elif self._param['Xaxis'] == "log_inv_star_age":
Xlabel = "log(Time since the end of evolution [yr])"
if self._param["cmap_label"] is not None:
cmap_label = self._param["cmap_label"]
elif self._param['Variable'] == "eps_nuc":
cmap_label = "log($\epsilon_{nuclear}$ [erg/s/gr])"
elif self._param['Variable'] == "velocity":
cmap_label = "log(radial velocity [cm/s])"
elif self._param['Variable'] == "entropy":
cmap_label = "log(specific entropy [erg/K/gr])"
elif self._param['Variable'] == "total_energy":
cmap_label = "log(specific total energy [erg/gr])"
elif self._param['Variable'] == "j_rot":
cmap_label = "log(specific angular momentum [cm$^2$/s])"
elif self._param['Variable'] == "eps_recombination":
cmap_label = "log($\epsilon_{recombination}$ [erg/s/gr])"
elif self._param['Variable'] == "ionization_energy":
cmap_label = "log(specific ionization energy [erg/gr])"
elif self._param['Variable'] == "dq":
cmap_label = "Cell Mass Fraction"
elif self._param['Variable'] == "energy":
cmap_label = "log(specific internal energy [erg/gr])"
elif self._param['Variable'] == "potential_plus_kinetic":
cmap_label = "log(specific potential+kinetic energy [erg/gr])"
elif self._param['Variable'] == "extra_heat":
cmap_label = "log(specific injected energy rate [erg/s/gr])"
elif self._param['Variable'] == "v_div_vesc":
cmap_label = "log($v/v_{esc}$)"
elif self._param['Variable'] == "v_div_csound":
cmap_label = "log($v/v_{sound}$)"
elif self._param['Variable'] == "gamma1":
cmap_label = "log($4/3-\Gamma_{1}$)"
elif self._param['Variable'] == "gamma3":
cmap_label = "log($\Gamma_{3}$)"
elif self._param['Variable'] == "opacity":
cmap_label = "log(Opacity [cm$^2$/gr])"
elif self._param['Variable'] == "pressure":
cmap_label = "log(Pressure [gr/(cm s$^2$)])"
elif self._param['Variable'] == "density":
cmap_label = "log(Density [gr/cm$^3$])"
elif self._param['Variable'] == "temperature":
cmap_label = "log(Temperature [K])"
elif self._param['Variable'] == "tau":
cmap_label = "log(optical depth)"
elif self._param['Variable'] == "dq":
cmap_label = "log(dq)"
elif self._param['Variable'] == "L_div_Ledd":
cmap_label = "log(L/L$_{Edd}$)"
elif self._param['Variable'] == "Lrad_div_Ledd":
cmap_label = "log(L$_{rad}$/L$_{Edd}$)"
elif self._param['Variable'] == "t_thermal":
cmap_label = "log($\\tau_{thermal}$ [s])"
elif self._param['Variable'] == "t_dynamical":
cmap_label = "log($\\tau_{s.cr.,out}$ [s])"
elif self._param['Variable'] == "t_dynamical_down":
cmap_label = "log($\\tau_{s.cr.,in}$ [s])"
elif self._param['Variable'] == "t_thermal_div_t_dynamical":
cmap_label = "log($\\tau_{thermal}/\\tau_{s.cr.}$)"
elif self._param['Variable'] == "omega_div_omega_crit":
cmap_label = "log($\Omega/\Omega_{crit}$)"
elif self._param['Variable'] == "omega":
cmap_label = "log($\Omega [rad/s]$)"
elif self._param['Variable'] == "super_ad":
cmap_label = "log($\\nabla - \\nabla_{ad}$)"
elif self._param['Variable'] == "vconv":
cmap_label = "log($v_{conv}$ [cm/s])"
elif self._param['Variable'] == "vconv_div_vesc":
cmap_label = "log($v_{conv}/v_{esc}$)"
elif self._param['Variable'] == "conv_vel_div_csound":
cmap_label = "log($v_{conv}/v_{sound}$)"
elif self._param['Variable'] == "total_energy_plus_vconv2":
cmap_label = "log(specific total energy + $1/2v_{conv}^2$ [erg/gr])"
elif self._param['Variable'] == "t_thermal_div_t_expansion":
cmap_label = r"log($\tau_{thermal}/\tau_{expansion}$)"
elif self._param['Variable'] == "E_kinetic_div_E_thermal":
cmap_label = r"log($E_{kinetic}/E_{thermal}$)"
if self._param['signed_log_cmap'] and (self._cmap_label is not None):
cmap_label = "sign x log(max(1,abs(" + cmap_label[4:]+"))"
if ax is None:
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
fig1.subplots_adjust(top=0.80, left=0.12, right=0.9, bottom=0.12)
else:
ax1 = ax
ax1.set_xlabel(Xlabel,fontsize=self._param['font_large'])
ax1.set_ylabel(Ylabel,fontsize=self._param['font_large'])
ax1.xaxis.set_tick_params(labelsize = self._param['font_small'])
ax1.yaxis.set_tick_params(labelsize = self._param['font_small'])
ax1.set_xlim([self._Xaxis_min,self._Xaxis_max])
ax1.set_ylim([self._Yaxis_min,self._Yaxis_max])
if self._param['signed_log_cmap']:
data_to_plot = np.sign(np.transpose(self._data)) * np.log10(np.maximum(1.,np.abs(np.transpose(self._data))))
else:
data_to_plot = np.log10(np.transpose(self._data))
#Define the minimum and maximum of the color scale
# When using signed_log_cmap, ignore cmap_dynamic_range
if (self._param['cmap_min'] is None) != (self._param['cmap_max'] is None):
raise("Both cmap_min and cmap_max need to be provided")
elif self._param['cmap_min'] is not None and self._param['cmap_max'] is not None:
cmap_min = self._param['cmap_min']
cmap_max = self._param['cmap_max']
elif self._param['signed_log_cmap']:
self._param['cmap_dynamic_range'] = np.nanmax(data_to_plot) - np.nanmin(data_to_plot)
cmap_min = np.nanmax(data_to_plot)-self._param['cmap_dynamic_range']
cmap_max = np.nanmax(data_to_plot)