-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspectra_results.py
executable file
·1645 lines (1312 loc) · 73.3 KB
/
spectra_results.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
#! /usr/bin/env python
#Author: Kari A. Frank
#Date: June 25, 2014
#Purpose: Plot and fit the light curve and other spectral results of SN1987A.
#Usage: spectra_results.py [--infile_a infile_a] [--clean clean] [--ylog ylog] [--plotfit plotfit] [--dofit dofit] [--helder helder] [--xmm xmm] [--caldb459 caldb459] [--piled piled] [--rosat rosat] [--early early] [--soft soft] [--soft12 soft12] [--hard hard] [--soft13 soft13] [--soft23 soft23] [--broad broad] [--skip462] [--clobber clobber] [--lateonly lateonly] [--agemin agemin] [--agemax agemax] [--instcolor instcolor] [--fluxmax fluxmax] [--ignorechippos ignorechippos] [--official official] [--quadcounts quadcounts]
#
#Input:
#
# infile_b: optionally specify file with observation and spectra data
# default is infile_a =
# '/export/bulk/rice1/kaf33/main/Chandra_Observations/SN1987A/comparison_dir/spectra459/spectra_fits.txt'
# infile_s: optionally specify second file with observation and spectra data
# default is infile_b =
# '/export/bulk/rice1/kaf33/main/Chandra_Observations/SN1987A/comparison_dir/spectra462/spectra_fits462.txt'
#
# clean: optional switch to change the axes labels and ticks to even
# years and ages (default = 'yes')
#
# ylog: switch to plot the light curve with log y-axis (default='no')
#
# dofit: do linear fit of light curve
#
# plotfit: plot best fit(s) on the contamination absorption plot
#
# helder: plot flux measurements from Helder2012 (default='no')
#
# xmm: plot flux measurements from XMM (default='yes')]
#
# rosat: plot flux measurements from ROSAT (default='no')
#
# caldb459: plot flux measurements from Chandra CALDB 4.5.9 (default='no')
#
# piled: plot non-pileup corrected flux measurements (default='no')
#
# early: plot non-pileup corrected flux measurements for observations
# 1387 and 122 (default='yes')
#
# lateonly: plot only the late-time observations on the light curve
# (day 8000+)
#
# soft/soft12/soft13/soft23/broad/hard: plot the corresponding band's
# light curve and/or ratios (default='yes')
#
# official: switch to only include observations in the official list,
# $sna/comparison_dir/official_obsid_list.txt (default='no')
#
# agemin/agemax: set the minimum and maximum age (in day) to plot
#
# fluxmax: optionally set the maximum of flux axis in light curve
# (in 10^-13 erg/cm^2/s)
#
# instcolor: plot different instruments by color and different bands by symbol.
# only applies to the xmm and chandra (4.6.2) soft and hard bands.
# (default = 'no')
#
# quadcounts: plot the fraction of counts in each quadrant over time
#
# plotextras: optionally plot information from other wavelengths: optical hot spots,
# Plait1995 ring size/location, Ng2013 radio break (default=None)
# options are: 'plait1995','ng2013','larsson2013','hotspots','sugarman2002','all'
#
# clobber: specifies whether files should be overwritten
# if they already exist (same as in ciao tools,
# default = 'no')
#
#Output:
# - pdf file of the expansion curve plot
#
#Usage Notes:
#---------------------------------------
# Import Modules
#---------------------------------------
import argparse,os,sys
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import numpy as np
from numpy.lib.recfunctions import append_fields
from sn1987a_time import *
import fitting
#sys.path.append('/astro/research/kaf33/Dropbox/Research/Python_Programs/')
sys.path.append('/Users/kafrank/Dropbox/Research/Python_Programs/')
from fancy_plot import fancy_plot
from scipy.optimize import curve_fit
import analytical_functions as af
import pandas as pd
from sn1987a_plot_helpers import plot_extras
#---------------------------------------
# Define Helper Functions
#---------------------------------------
def plot_a(ax,age,flux,low=None,high=None,syms='o',colors='b',sizes=4,alphas=1.0,mecs='black',mews=0.5,line='',errorband=False,label='_nolegend_'):
if low is not None:
elow,ehigh = ebars(flux,low,high)
else:
elow = None
ehigh = None
# fancy_plot(age,flux,yerror=elow,yerror_high=ehigh,syms=syms,colors=colors,sizes=sizes,alphas=alphas,mecs=mecs,errorband=errorband,line=line,mews=mews)
fancy_plot(age,flux,yerror=np.array(flux-low),yerror_high=np.array(high-flux),syms=syms,colors=colors,sizes=sizes,alphas=alphas,mecs=mecs,errorband=errorband,line=line,mews=mews)
# ax.errorbar(age,flux,yerr=[elow,ehigh],fmt='.',color=colors[0],markersize=0,markeredgewidth=0)
# ax.plot(age,flux,syms[0],markersize=4,markeredgewidth=0.5,color=colors[0])
def plot_b(ax,age,flux,flux_low,flux_high,sym='o',color='b',alpha=1):
ax.errorbar(age,flux,yerr=[flux-flux_low,flux_high-flux],fmt='.',markersize=0,color=color,markeredgewidth=0)
ax.plot(age,flux,sym,markersize=4,color=color,markeredgewidth=0.5,alpha=alpha)
def ebars(x,x_low,x_high):
#function to convert error intervals intor error bars
errlow = x-x_low
errhigh = x_high - x
return errlow,errhigh
#-function to derive vectors of errors on ratios-
def ratio_err(top,bottom,top_low,top_high,bottom_low,bottom_high):
#uses simple propagation of errors (partial derivatives)
#note it returns error interval
#-make sure input is numpy arrays-
top = np.array(top).astype(float)
top_low = np.array(top_low)
top_high = np.array(top_high)
bottom = np.array(bottom).astype(float)
bottom_low = np.array(bottom_low)
bottom_high = np.array(bottom_high)
#-calculate errorbars-
top_errlow = np.subtract(top,top_low)
top_errhigh = np.subtract(top_high,top)
bottom_errlow = np.subtract(bottom,bottom_low)
bottom_errhigh = np.subtract(bottom_high,bottom)
#-calculate ratio_low-
ratio_low = top/bottom - ( (top_errlow/bottom)**2.0 + (top/(bottom)**2.0*bottom_errlow)**2.0 )**0.5
# ratio_low = np.divide(top,bottom) - ( np.divide(top_errlow,bottom)**2.0 + (np.divide(top,bottom**2.0)*bottom_errlow)**2.0 )**0.5
#-calculate ratio_high-
ratio_high = ( (top_errhigh/bottom)**2.0 + (top/(bottom)**2.0*bottom_errhigh)**2.0 )**0.5 + top/bottom
# return two vectors, err_low and err_high
return ratio_low,ratio_high
def set_axis(ax,x=None,twin=False,title=None,xlab=None,grid=False,
clean='yes'):
# font_size = 10
font_size = 13
# fontangle = 50
fontangle = 40
if (twin == False) and (clean == 'yes'):
fontangle = 0
if clean == 'no':
font_size = 9
if twin == False:
ax0 = ax
ax0.xaxis.grid(grid,which='major')
if x is not None:
ax0.set_xticks(x,minor=False)
else:
ax0 = ax.twiny()
# x_min,x_max = plt.xlim()
ax0.set_xlim(ax.get_xlim())
if x is not None:
ax0.set_xticks(x,minor=False)
if xlab is not None:
ax0.set_xticklabels(xlab)
if title is not None:
ax0.set_xlabel(title)
for tick in ax0.xaxis.get_major_ticks():
if twin == False:
tick.label.set_fontsize(font_size)
tick.label.set_rotation(fontangle)
if twin == True:
tick.label2.set_fontsize(font_size)
tick.label2.set_rotation(fontangle)
#ax.set_yscale('log')
def start_plot(xtitle='',ytitle='',xmin=None,xmax=None,ymin=None,ymax=None,
ylog=False,clean='yes'):
#-initialize main plot-
fig,ax1=plt.subplots()
#-set axis titles-
plt.xlabel(xtitle)
plt.ylabel(ytitle)
#-set bottom axis-
if ylog == True: plt.yscale('log')
set_axis(ax1,x=botx,grid=mgrid,clean=clean)
if xmin is not None or xmax is not None:
ax1.set_xlim(xmin,xmax)
if ymin is not None or ymax is not None:
ax1.set_ylim(ymin,ymax)
#-add extra space on bottom-
plt.subplots_adjust(bottom=bott,top=topp)
return ax1
#---------------------------------------
# Parse arguments and set defaults
#---------------------------------------
parser = argparse.ArgumentParser(description='Plot and fit SN1987A light curve and other spectral results.')
pwd = os.getcwd()
#parser.add_argument('required_arg',help='Description and usage for required_arg.',default='default for required_arg')
#rice
sn1987a_dir = '/data/nasdrive/main/kaf33/sn1987a_monitoring/'
#brevis
#sn1987a_dir = '/Users/kafrank/Research/SN1987A/'
parser.add_argument('--infile_b',help='File containing observation and spectra data.',default='')
parser.add_argument('--infile_a',help='File containing observation and spectra data.',default=sn1987a_dir+'comparison_dir/spectra_current/spectra465_frank2015a_fits_official.txt')
parser.add_argument('--clean',help='Determines x-axis ticks and labels.',default='yes')
parser.add_argument('--ylog',help='Plot light curve with log scale y-axis.',default='no')
parser.add_argument('--plotfit',help='Plot best fit contamination.',default='no')
parser.add_argument('--dofit',help='Run mcmc on contamination absorption.',default='no')
parser.add_argument('--helder',help='Plot fluxes from Helder2012',default='no')
parser.add_argument('--xmm',help='Plot fluxes from XMM EPIC-pn',default='yes')
parser.add_argument('--rosat',help='Plot fluxes from ROSAT',default='no')
parser.add_argument('--caldb459',help='Plot fluxes from Chandra CALDB 4.5.9',default='no')
parser.add_argument('--piled',help='Plot non-pileup corrected fluxes.',default='no')
parser.add_argument('--early',help='Plot (non-pileup corrected) fluxes of observations 1387 and 122.',default='yes')
parser.add_argument('--lateonly',help='Plot only day 8000+ on light curve.',default='no')
parser.add_argument('--soft',help='Plot 0.5-2.0 keV band light curve.',default='yes')
parser.add_argument('--soft12',help='Plot 1.0-2.0 keV band light curve.',default='yes')
parser.add_argument('--soft13',help='Plot 1.0-3.0 keV band light curve.',default='no')
parser.add_argument('--hard',help='Plot 3.0-8.0 keV band light curve.',default='yes')
parser.add_argument('--broad',help='Plot 0.5-8.0 keV band light curve.',default='yes')
parser.add_argument('--soft23',help='Plot 2.0-3.0 keV band light curve.',default='no')
parser.add_argument('--skip462',help='Do not plot the caldb462 light curve.',default='no')
parser.add_argument('--official',help='Include only obsids in the official list.',default='no')
parser.add_argument('--agemin',help='Minimum age for x-axes.',default=0)
parser.add_argument('--agemax',help='Maximum age for x-axes.',default=0)
parser.add_argument('--fluxmax',help='Maximum flux for light curve y-axis.',default=0)
parser.add_argument('--instcolor',help='Switch meaning of symbols and colors.',default='no')
parser.add_argument('--quadcounts',help='Plot fraction of counts per quadrant.',default='yes')
parser.add_argument('--ignorechippos',help='Plot normal borders for observations with offset chip positions.',default='no')
parser.add_argument('--plotextras',help='Overplot information from other wavelengths.',default=None)
#not currently implemented!
parser.add_argument('--clobber',help='Overwrite existing files.',default='no')
args = parser.parse_args()
#----Set dependent arguments----
args.agemin = int(args.agemin)
args.agemax = int(args.agemax)
args.fluxmax = float(args.fluxmax)
if args.ylog == 'yes':
args.ylog = True
else:
args.ylog = False
#-check if all chandra is skipped-
skipchandra = 'no'
if args.skip462 == 'yes' and args.caldb459 == 'no' and args.helder == 'no': skipchandra = 'yes'
#-if rosat and/or xmm only, only plot soft band-
#(will prevent adding extraneous bands to legends)
if skipchandra == 'yes':
args.broad = 'no'
args.soft12 = 'no'
args.soft13 = 'no'
args.soft23 = 'no'
if args.xmm == 'no': args.hard = 'no'
#----Set file paths----
helderfile = '/astro/research/kaf33/Dropbox/Research/SN1987A/Helder_table1.txt'
#helderfile = '/Users/kafrank/Dropbox/Research/SN1987A/Helder_table1.txt'
#plotfile = sn1987a_dir+'comparison_dir/spectra_results.pdf'
plotfile = './spectra465_frank2015a_results.pdf'
posteriorfile = sn1987a_dir+'comparison_dir/posteriors.pdf'
mcmcfile = sn1987a_dir+'comparison_dir/mcmc_contamfit.txt'
countratefile = sn1987a_dir+'comparison_dir/countrate_ratios.txt'
xmmfile = sn1987a_dir+'comparison_dir/xmm_results.txt'
rosatfile = sn1987a_dir+'comparison_dir/rosat_results.txt'
earlyfile = sn1987a_dir+'comparison_dir/chandra_early_fluxes.txt'
obsfile = sn1987a_dir+'comparison_dir/chandra_observations.txt'
radiusfile =sn1987a_dir+'comparison_dir/imaging/sn1987a_radii_fits.txt'
radiusfitfile = sn1987a_dir+'comparison_dir/imaging/expansion_fits/sn1987a_mpfit_radii_fits.txt'
expansionfitfile = sn1987a_dir+'comparison_dir/imaging/expansion_fits_sept2014/mpfit_results_3.txt'
#expansionfitfile = sn1987a_dir+'/comparison_dir/imaging/expansion_fits/expansion_mcmc_three_2000000-10000000_results.txt'
officialfile = sn1987a_dir+'comparison_dir/official_obsid_list.txt'
quadcountfile_front = sn1987a_dir+'comparison_dir/spectra_current/sn1987a_'
quadcountfile_back = '_counts.txt'
nwcountsfile = quadcountfile_front+'nw'+quadcountfile_back
necountsfile = quadcountfile_front+'ne'+quadcountfile_back
swcountsfile = quadcountfile_front+'sw'+quadcountfile_back
secountsfile = quadcountfile_front+'se'+quadcountfile_back
totalcountsfile = quadcountfile_front+'total'+quadcountfile_back
#---------------------------------------
# Read and Convert Data
#---------------------------------------
#----Read CALDB4.6.2 Results from File----
a_data = np.genfromtxt(args.infile_a,skip_header=0,names=True,comments='#',dtype=None)
if args.infile_b != '':
b_data = np.genfromtxt(args.infile_b,skip_header=0,names=True,comments='#',dtype=None)
else:
b_data = np.genfromtxt(args.infile_a,skip_header=0,names=True,comments='#',dtype=None)
#columns names:
#obsid date age grating caldb model pcounts psoft psoftlow psofthigh phard phardlow phardhigh pbroad pbroadlow pbroadhigh psoft12 psoft12low psoft12high Counts soft softlow softhigh hard hardlow hardhigh broad broadlow broadhigh soft12 soft12low soft12high soft23 soft23low soft23high soft13 soft13low soft13high kTcool kTcoollow kTcoolhigh kThot kThotlow kThothigh Taucool Taucoolerr tauhot tauhotlow tauhothigh normcool normcoollow normcoolhigh normhot normhotlow normhothigh chi2 dof redchi2 csoft12 csoft12low csoft12high csoft csoftlow csofthigh csoft23 csoft23low csoft23high csoft13 csoft13low csoft13high chard chardlow chardhigh
#----Read Radius Measurements----
if False:
# r_data = np.genfromtxt(radiusfile,skip_header=0,names=True,comments='#',dtype=None)
#columsn:
#obsid age radius radiuslow radiushigh counts deconcounts
#--calculate errors--
r_data['radiuslow'] = np.sqrt(r_data['radiuslow']**2.0 + r_data['radius']**2.0/r_data['counts'])
r_data['radiushigh'] = np.sqrt(r_data['radiushigh']**2.0 + r_data['radius']**2.0/r_data['counts'])
#--convert errorbars to error intervals--
r_data['radiuslow'] = r_data['radius'] - r_data['radiuslow']
r_data['radiushigh'] = r_data['radius'] + r_data['radiushigh']
#--convert values to arcsec--
r_data['radius'] = convert_units(r_data['radius'],'r','arcsec')
r_data['radiuslow'] = convert_units(r_data['radiuslow'],'r','arcsec')
r_data['radiushigh'] = convert_units(r_data['radiushigh'],'r','arcsec')
#-read radius fit results-
rfit_data = np.genfromtxt(expansionfitfile,skip_header=0,names=True,dtype=None)
#columns:
#stat v_early v_late intercept changepoint
#rows:
#median, mean, standard deviation
#-read fitted radius data points-
rmodel_data = np.genfromtxt(radiusfitfile,skip_header=0,names=True,comments='#',dtype=None)
#--convert errorbars to error intervals--
rmodel_data['radiuslow'] = rmodel_data['radius'] - rmodel_data['radiuslow']
rmodel_data['radiushigh'] = rmodel_data['radius'] + rmodel_data['radiushigh']
#----Get Observation Info----
#--Get Observation Years (and ages if necessary)--
a_obsyears = [str(get_obs_time(int(obs),get='year')) for obs in a_data['obsid']]
a_data = append_fields(a_data,names='year',data=a_obsyears)
if 'age' not in a_data.dtype.names:
a_age = [get_obs_time(obs) for obs in a_data['obsid']]
a_data = append_fields(a_data,names='age',data=a_age)
b_obsyears = [str(get_obs_time(int(obs),get='year')) for obs in b_data['obsid']]
b_data = append_fields(b_data,names='year',data=b_obsyears)
if 'age' not in b_data.dtype.names:
b_age = [get_obs_time(obs) for obs in b_data['obsid']]
b_data = append_fields(b_data,names='age',data=b_age)
#r_obsyears = [str(get_obs_time(int(obs),get='year')) for obs in r_data['obsid']]
#r_data = append_fields(r_data,names='year',data=r_obsyears)
#if 'age' not in r_data.dtype.names:
# r_age = [get_obs_time(obs) for obs in r_data['obsid']]
# r_data = append_fields(r_data,names='age',data=r_age)
#--Read Main Info File--
obs_info = np.genfromtxt(obsfile,skip_header=0,names=True,comments='#',dtype=None)
#column names:
#obsid date age pi configuration grating exposure frametime simoffset yoffset zoffset
#-get years-
obsyears = [str(get_obs_time(int(obs),get='year')) for obs in obs_info['obsid']]
obs_info = append_fields(obs_info,names='year',data=obsyears)
#--Get FrameTimes--
a_frames = [obs_info['frametime'][np.where(obs_info['obsid'] == obs)] for obs in a_data['obsid']]
a_data = append_fields(a_data,names='frametime',data=np.array(a_frames)[:,0])
b_frames = [obs_info['frametime'][np.where(obs_info['obsid'] == obs)] for obs in b_data['obsid']]
b_data = append_fields(b_data,names='frametime',data=np.array(b_frames)[:,0])
#r_frames = [obs_info['frametime'][np.where(obs_info['obsid'] == obs)] for obs in r_data['obsid']]
#r_data = append_fields(r_data,names='frametime',data=np.array(r_frames)[:,0])
#--Get SimZ--
#-convert 'default' to '0.0'-
obs_info['simoffset'][np.where(obs_info['simoffset'] == 'default')] = '0.0'
#print i_sim,i_obsid
#-associate with a,b,r data-
a_sims = [obs_info['simoffset'][np.where(obs_info['obsid'] == obs)] for obs in a_data['obsid']]
a_data = append_fields(a_data,names='sim',data=np.array(a_sims)[:,0])
b_sims = [obs_info['simoffset'][np.where(obs_info['obsid'] == obs)] for obs in b_data['obsid']]
b_data = append_fields(b_data,names='sim',data=np.array(b_sims)[:,0])
#r_sims = [obs_info['simoffset'][np.where(obs_info['obsid'] == obs)] for obs in r_data['obsid']]
#r_data = append_fields(r_data,names='sim',data=np.array(r_sims)[:,0])
#--get gratings for radius observations--
#r_gratings = [obs_info['grating'][np.where(obs_info['obsid'] == obs)] for obs in r_data['obsid']]
#r_data = append_fields(r_data,names='grating',data=np.array(r_gratings)[:,0])
#----Calculate Contamination Abssorption and Append to Data Structure----
#unabsorbed/absorbed flux
#(without contamination models / with contamination models)
#--save light curve data to text file for easy reference--
lightcurve = pd.DataFrame(np.ma.filled(a_data,fill_value=-9999))
lightcurve.to_csv(args.infile_a+'_fluxes.txt',sep='\t',columns=['obsid','age','grating','counts','soft','softlow','softhigh','soft12','soft12low','soft12high','hard','hardlow','hardhigh','broad','broadlow','broadhigh'],index=False)
if args.infile_a == sn1987a_dir+'comparison_dir/spectra462/spectra_fits462.txt':
abs_soft = np.divide(a_data['csoft'],a_data['soft'])
abs_soft12 = np.divide(a_data['csoft12'],a_data['soft12'])
abs_soft23 = np.divide(a_data['csoft23'],a_data['soft23'])
abs_soft13 = np.divide(a_data['csoft13'],a_data['soft13'])
abs_hard = np.divide(a_data['chard'],a_data['hard'])
abs_soft_low,abs_soft_high = ratio_err(a_data['csoft'],a_data['soft'],a_data['csoftlow'],a_data['csofthigh'],a_data['softlow'],a_data['softhigh'])
abs_soft12_low,abs_soft12_high = ratio_err(a_data['csoft12'],a_data['soft12'],a_data['csoft12low'],a_data['csoft12high'],a_data['soft12low'],a_data['soft12high'])
abs_soft23_low,abs_soft23_high = ratio_err(a_data['csoft23'],a_data['soft23'],a_data['csoft23low'],a_data['csoft23high'],a_data['soft23low'],a_data['soft23high'])
abs_soft13_low,abs_soft13_high = ratio_err(a_data['csoft13'],a_data['soft13'],a_data['csoft13low'],a_data['csoft13high'],a_data['soft13low'],a_data['soft13high'])
abs_hard_low,abs_hard_high = ratio_err(a_data['chard'],a_data['hard'],a_data['chardlow'],a_data['chardhigh'],a_data['hardlow'],a_data['hardhigh'])
a_data = append_fields(a_data,names=['abssoft','abssoft12','abssoft23','abssoft13','abshard'],data=[abs_soft,abs_soft12,abs_soft23,abs_soft13,abs_hard])
a_data = append_fields(a_data,names=['abssoftlow','abssoft12low','abssoft23low','abssoft13low','abshardlow'],data=[abs_soft_low,abs_soft12_low,abs_soft23_low,abs_soft13_low,abs_hard_low])
a_data = append_fields(a_data,names=['abssofthigh','abssoft12high','abssoft23high','abssoft13high','abshardhigh'],data=[abs_soft_high,abs_soft12_high,abs_soft23_high,abs_soft13_high,abs_hard_high])
#----Calculate Optical Depth and Append to Data Structure----
#errors are error intervals
depth_soft = -1.0*np.log(abs_soft)
depth_soft_low = -1.0*np.log(abs_soft_low)
depth_soft_high = -1.0*np.log(abs_soft_high)
depth_soft12 = -1.0*np.log(abs_soft12)
depth_soft12_low = -1.0*np.log(abs_soft12_low)
depth_soft12_high = -1.0*np.log(abs_soft12_high)
depth_soft13 = -1.0*np.log(abs_soft13)
depth_soft13_low = -1.0*np.log(abs_soft13_low)
depth_soft13_high = -1.0*np.log(abs_soft13_high)
depth_soft23 = -1.0*np.log(abs_soft23)
depth_soft23_low = -1.0*np.log(abs_soft23_low)
depth_soft23_high = -1.0*np.log(abs_soft23_high)
depth_hard = -1.0*np.log(abs_hard)
depth_hard_low = -1.0*np.log(abs_hard_low)
depth_hard_high = -1.0*np.log(abs_hard_high)
a_data = append_fields(a_data,names=['depthsoft','depthsoftlow','depthsofthigh','depthsoft12','depthsoft12low','depthsoft12high','depthsoft13','depthsoft13low','depthsoft13high','depthsoft23','depthsoft23low','depthsoft23high','depthhard','depthhardlow','depthhardhigh'],data=[depth_soft,depth_soft_low,depth_soft_high,depth_soft12,depth_soft12_low,depth_soft12_high,depth_soft13,depth_soft13_low,depth_soft13_high,depth_soft23,depth_soft23_low,depth_soft23_high,depth_hard,depth_hard_low,depth_hard_high])
#----Calculate Pileup Fractions and Append to Data----
if 'psoft' in a_data.dtype.names:
ratiosoft = a_data['soft']/a_data['psoft']
ratiohard = a_data['hard']/a_data['phard']
ratiobroad = a_data['broad']/a_data['pbroad']
a_data = append_fields(a_data,names=['softpileup','hardpileup','broadpileup'],data=[ratiosoft,ratiohard,ratiobroad])
soft_err_low,soft_err_high = ratio_err(a_data['soft'],a_data['psoft'],a_data['softlow'],a_data['softhigh'],a_data['psoftlow'],a_data['psofthigh'])
hard_err_low,hard_err_high = ratio_err(a_data['hard'],a_data['phard'],a_data['hardlow'],a_data['hardhigh'],a_data['phardlow'],a_data['phardhigh'])
broad_err_low,broad_err_high = ratio_err(a_data['broad'],a_data['pbroad'],a_data['broadlow'],a_data['broadhigh'],a_data['pbroadlow'],a_data['pbroadhigh'])
a_data = append_fields(a_data,names=['softpileuplow','softpileuphigh','hardpileuplow','hardpileuphigh','broadpileuplow','broadpileuphigh'],data=[soft_err_low,soft_err_high,hard_err_low,hard_err_high,broad_err_low,broad_err_high])
#----Read Helder2012 Results----
if args.helder == 'yes':
h_data = np.genfromtxt(helderfile,names=True,dtype=None,comments='#')
#columnn names:
#obsid configuration soft softlow softhigh frametimes softpileup hard hardlow hardhigh hardpileup
#-convert errorbars to error intervals for consistency with other data-
h_data['softlow']=h_data['soft']-h_data['softlow']
h_data['softhigh']=h_data['softhigh']+h_data['soft']
h_data['hardlow']=h_data['hard']-h_data['hardlow']
h_data['hardhigh']=h_data['hardhigh']+h_data['hard']
#--get associated ages--
h_age = [get_obs_time(obs) for obs in h_data['obsid']]
h_data = append_fields(h_data,names='age',data=h_age)
#--get chip position--
h_sims = [obs_info['simoffset'][np.where(obs_info['obsid'] == obs)] for obs in h_data['obsid']]
h_data = append_fields(h_data,names='sim',data=np.array(h_sims)[:,0])
#----Read CountRates and Calculate Ratios----
#(estimate of contamination absorption)
count_data = np.genfromtxt(countratefile,names=True,dtype=None,comments='#')
#column names: (em=emitted flux, meas=measured (contamination absorbed) flux)
#obsid date age grating caldb model emsoft emsoft12 emsoft13 emhard meassoft meassoft12 meassoft13 meashard
count_ratio_soft = count_data['meassoft']/count_data['emsoft']
count_ratio_soft12 = count_data['meassoft12']/count_data['emsoft12']
count_ratio_soft13 = count_data['meassoft13']/count_data['emsoft13']
count_ratio_hard = count_data['meashard']/count_data['emhard']
a_data = append_fields(a_data,names=['ratiosoft','ratiosoft12','ratiosoft13','ratiohard'],data=[count_ratio_soft,count_ratio_soft12,count_ratio_soft13,count_ratio_hard])
#----Read XMM Results----
#notes:
# the hard flux is 3-10 keV
# obsids are read as numbers, not strings, so leading zeros are stripped
xmm_data = np.genfromtxt(xmmfile,names=True,comments='#',dtype=None)
#column names:
#obsid date age filter totalexp filtexp soft softlow softhigh hard hardlow hardhigh
#fluxes are 10^-13 ergs/s/cm^2
#errors are lower and upper errorbars
#-convert errorbars to error intervals for consistency with other data-
xmm_data['softlow']=xmm_data['soft']-xmm_data['softlow']
xmm_data['softhigh']=xmm_data['softhigh']+xmm_data['soft']
xmm_data['hardlow']=xmm_data['hard']-xmm_data['hardlow']
xmm_data['hardhigh']=xmm_data['hardhigh']+xmm_data['hard']
#----Read ROSAT Results----
#notes:
rosat_data = np.genfromtxt(rosatfile,names=True,comments='#',dtype=None)
#column names:
#age configuration soft softlow softhigh
#fluxes are 10^-13 ergs/s/cm^2
#errors are lower and upper errorbars
#-convert errorbars to error intervals for consistency with other data-
rosat_data['softlow']=rosat_data['soft']-rosat_data['softlow']
rosat_data['softhigh']=rosat_data['softhigh']+rosat_data['soft']
#fluxes are all in units of 10^-13 ergs/s/cm^2
#errors are 68%
#norms in units of 10^-3
#pileup flux ratios are unpiled/piled
#----Read Early Chandra Fluxes----
#notes:
early_data = np.genfromtxt(earlyfile,names=True,comments='#',dtype=None)
#column names:
#obsid data age grating caldb model counts soft softlow softhigh hard hardlow hardhigh broad broadlow broadhigh soft12 soft12low soft12high
#fluxes are 10^-13 ergs/s/cm^2
#errors are error interval limits
#----Read Quadrant Counts Files----
if args.quadcounts == 'yes':
nwcounts = pd.read_table('sn1987a_nw_counts.txt',index_col=0,comment='#',header=None,names=['obsid','nwcounts'])
necounts = pd.read_table('sn1987a_ne_counts.txt',index_col=0,comment='#',header=None,names=['obsid','necounts'])
swcounts = pd.read_table('sn1987a_sw_counts.txt',index_col=0,comment='#',header=None,names=['obsid','swcounts'])
secounts = pd.read_table('sn1987a_se_counts.txt',index_col=0,comment='#',header=None,names=['obsid','secounts'])
# combine into one table
ctable = pd.merge(nwcounts,necounts,left_index=True,right_index=True)
ctable = pd.merge(ctable,secounts,left_index=True,right_index=True)
ctable = pd.merge(ctable,swcounts,left_index=True,right_index=True)
# add total counts columns
ctable['counts'] = ctable['nwcounts']+ctable['necounts']+ctable['swcounts']+ctable['secounts']
# remove HETG observations for epochs with both HETG and bare
# ACIS (bare ACIS had more counts, and we don't care about pileup here)
# ctable.drop([14698,9144])
# ctable = ctable[ctable.index != 10855]
# ctable = ctable[ctable.index != 9144]
# print ctable
# calculate count fractions
ctable['nwfraction']=ctable['nwcounts']/ctable['counts']
ctable['nefraction']=ctable['necounts']/ctable['counts']
ctable['sefraction']=ctable['secounts']/ctable['counts']
ctable['swfraction']=ctable['swcounts']/ctable['counts']
# sum count fractions
ctable['fractionsum'] = ctable['nwfraction']+ctable['nefraction']+ctable['swfraction']+ctable['sefraction']
# calculate fraction errors (poisson)
ctable['nwfraction_errlow'],ctable['nwfraction_errhigh'] = ratio_err(ctable['nwcounts'],ctable['counts'],(ctable['nwcounts']-np.sqrt(ctable['nwcounts'])),ctable['nwcounts']+np.sqrt(ctable['nwcounts']),ctable['counts']-np.sqrt(ctable['counts']),ctable['counts']+np.sqrt(ctable['counts']))
ctable['nefraction_errlow'],ctable['nefraction_errhigh'] = ratio_err(ctable['necounts'],ctable['counts'],ctable['necounts']-np.sqrt(ctable['necounts']),ctable['necounts']+np.sqrt(ctable['necounts']),ctable['counts']-np.sqrt(ctable['counts']),ctable['counts']+np.sqrt(ctable['counts']))
ctable['swfraction_errlow'],ctable['swfraction_errhigh'] = ratio_err(ctable['swcounts'],ctable['counts'],ctable['swcounts']-np.sqrt(ctable['swcounts']),ctable['swcounts']+np.sqrt(ctable['swcounts']),ctable['counts']-np.sqrt(ctable['counts']),ctable['counts']+np.sqrt(ctable['counts']))
ctable['sefraction_errlow'],ctable['sefraction_errhigh'] = ratio_err(ctable['secounts'],ctable['counts'],ctable['secounts']-np.sqrt(ctable['secounts']),ctable['secounts']+np.sqrt(ctable['secounts']),ctable['counts']-np.sqrt(ctable['counts']),ctable['counts']+np.sqrt(ctable['counts']))
# add observation age
obsyears = [str(get_obs_time(int(obs),get='year')) for obs in ctable.index]
age = [get_obs_time(obs) for obs in ctable.index]
ctable['age'] = age
#--get gratings for radius observations--
cgratings = [obs_info['grating'][np.where(obs_info['obsid'] == obs)] for
obs in ctable.index]
ctable['grating'] = cgratings
#--sort by observation age--
ctable.sort_values('age',inplace=True)
#---------------------------------------
#---------------------------------------
# PLOTS
#---------------------------------------
#---------------------------------------
#---------------------------------------
# Global Plot Properties
#---------------------------------------
#--Set whitespace on bottom, top--
bott = 0.13
topp = 0.87
#--Initialize Plot and Set Axes--
if args.agemin == 0:
if args.rosat == 'yes':
args.agemin = 1000
else:
args.agemin = 5000
if args.lateonly == 'yes':
args.agemin = 7800
if args.early == 'yes' and args.rosat == 'no':
args.agemin = 4500
if skipchandra == 'yes' and args.xmm == 'no' and args.rosat == 'yes':
if args.agemax == 0: args.agemax = 4500
fluxmax = 1.5
else:
if args.agemax == 0: args.agemax = 11000
if args.fluxmax == 0:
if min(a_data['age']) <= args.agemax:
if args.broad == 'yes':
#fluxmax = 120
fluxmax = 1.1*max(a_data['broad'][np.where(a_data['age']<=args.agemax)])
else:
# fluxmax = 100
fluxmax = 1.1*max(a_data['soft'][np.where(a_data['age']<=args.agemax)])
else: #before main chandra, use xmm or rosat
if min(xmm_data['age']) <= args.agemax:
fluxmax = 1.1*max(xmm_data['soft'][np.where(xmm_data['age']<=args.agemax)])
else:
fluxmax = 1.1*max(rosat_data['soft'][np.where(rosat_data['age']<=args.agemax)])
else: fluxmax = args.fluxmax
if args.ylog == True:
if args.rosat == 'yes':
fluxmin = 0.07
else:
fluxmin = 0.3
else:
fluxmin = 0.0
#----Set Axis Labels and Ticks----
#-calculate required top axis labels automatically based on agemin/agemax-
#print 'agemin = ',args.agemin
years = range(convert_time(args.agemin,get='year')+1,convert_time(args.agemax,get='year')+1)
year_ticks = [str(yr) for yr in years]
regular_ages = [convert_time(yr+'-01-01',get='age',informat='date') for yr in year_ticks]
#print 'yeartick = ',year_ticks
#print 'regular ages = ',regular_ages
#radyears = range(1999,2016)
#radius_year_ticks = [str(yr) for yr in radyears]
#radius_regular_ages = [convert_time(yr+'-01-01',get='age') for yr in radius_year_ticks]
spectrayears = ['2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014']
spectra_year_ticks = [str(yr) for yr in spectrayears]
spectra_regular_ages = [convert_time(yr+'-01-01',get='age',informat='date') for yr in spectra_year_ticks]
if args.clean == 'yes':
lightcurve_topx = regular_ages
lightcurve_toplab = year_ticks
topx = spectra_regular_ages
toplab = spectra_year_ticks
# ext_topx = radius_regular_ages
# ext_toplab = radius_year_ticks
botx = None
toptitle = 'Year'
mgrid = False
# frame = False
frame = True #but sets edge and facecolor to white
else:
topx = obs_info['age']#a_data['age']
toplab = obs_info['year']#a_data['year']
lightcurve_topx = topx
lightcurve_toplab = toplab
ext_topx = topx
ext_toplab = toplab
toptitle = 'Observation Year'
botx = obs_info['age']#a_data['age']
mgrid = True
frame = True
#-set fonts-
font = {'family':'serif','weight':'normal','size':15}
matplotlib.rc('font',**font)
matplotlib.rcParams['text.latex.preamble'] = [r"\boldmath"]
plt.rc('text',usetex=True)
#----Set Symbols and Colors----
#--find indices--
#-detector position-
a_offz_i = np.where(a_data['sim'] == '-8.42')
b_offz_i = np.where(b_data['sim'] == '-8.42')
#r_offz_i = np.where(r_data['sim'] == '-8.42')
if args.helder == 'yes': h_offz_i = np.where(h_data['sim'] == '-8.42')
#-ACIS grating-
a_hetg_i = np.where(a_data['grating'] == 'HETG')
a_bare_i = np.where(a_data['grating'] == 'NONE')
b_hetg_i = np.where(b_data['grating'] == 'HETG')
b_bare_i = np.where(b_data['grating'] == 'NONE')
#r_hetg_i = np.where(r_data['grating'] == 'HETG')
#r_bare_i = np.where(r_data['grating'] == 'NONE')
if args.helder == 'yes':
h_hetg_i = np.where(h_data['configuration'] == 'HETG')
h_bare_i = np.where(h_data['configuration'] == 'S3')
a_letg_i = np.where(a_data['grating'] == 'LETG')
b_letg_i = np.where(b_data['grating'] == 'LETG')
#--make lists for each--
#-colors = energy band-
softcolor = 'green'#'red'
soft12color = 'purple'#'green'
soft13color = 'blue'
soft23color = 'magenta'
hardcolor = 'cyan'
broadcolor = 'black'#'purple'
#--colors = instrument,symbols = band--
#(used only for chandra and xmm, soft and hard bands, if instcolor='yes')
#(supersedes the bandcolor and instrument symbols)
xmmsoftcolor = 'red'
chandrasoftcolor = 'royalblue'
xmmsoftsym = '^'
chandrasoftsym = 'o'
xmmhardcolor = 'red'
chandrahardcolor = 'royalblue'
xmmhardsym = 'd'
chandrahardsym = 's'
#-number of observations-
a_nobs = a_data.shape[0]
b_nobs = b_data.shape[0]
#r_nobs = r_data.shape[0]
xmm_nobs = xmm_data.shape[0]
rosat_nobs = rosat_data.shape[0]
if args.helder == 'yes': h_nobs = h_data.shape[0]
print 'nobs = ',a_nobs
#print 'xmm_nobs = ',xmm_nobs
#-symbol = instrument (ACIS-HETG,ACIS-NONE,XMM-EPIC-pn)-
hetg_sym = 'o' #HETG = circle
bare_sym = 'd' #bare acis = thin diamond
letg_sym = 'p' #LETG = pentagon
a_syms = [hetg_sym]*a_nobs
for i in list(a_bare_i[:][0]):
a_syms[i] = bare_sym
for i in list(a_letg_i[:][0]):
a_syms[i] = letg_sym
b_syms = [hetg_sym]*b_nobs
for i in list(b_bare_i[:][0]):
b_syms[i] = bare_sym
for i in list(b_letg_i[:][0]):
b_syms[i] = letg_sym
#r_syms = [hetg_sym]*r_nobs
#for i in list(r_bare_i[:][0]):
# r_syms[i] = bare_sym
if args.helder == 'yes':
h_syms = [hetg_sym]*h_nobs
for i in list(h_bare_i[:][0]):
h_syms[i] = bare_sym
xmm_syms = '^' #xmm = triangle
rosat_syms = 'x' #rosat = x
early_syms = [hetg_sym,bare_sym]
chandrahardsyms = ['s']*a_nobs
chandrasoftsyms = ['o']*a_nobs
#for i in list(a_bare_i[:][0]):
# chandrahardsyms[i] = 'H'
# chandrasoftsyms[i] = 'p'
chandrahardcolors = ['royalblue']*a_nobs
chandrasoftcolors = ['royalblue']*a_nobs
for i in list(a_bare_i[:][0]):
chandrahardcolors[i] = 'navy'
chandrasoftcolors[i] = 'navy'
#-markeredgecolor = simz (detector z)-
if args.instcolor == 'no':
offcolor = 'gray'
else:
offcolor = 'black'
a_mecs = ['black']*a_nobs
b_mecs = ['black']*b_nobs
#r_mecs = ['black']*r_nobs
if args.helder == 'yes': h_mecs = ['black']*h_nobs
if args.ignorechippos == 'no':
for i in list(a_offz_i[:][0]):
a_mecs[i] = offcolor #offset observations have offcolor outline
for i in list(b_offz_i[:][0]):
b_mecs[i] = offcolor #offset observations have offcolor outline
# for i in list(r_offz_i[:][0]):
# r_mecs[i] = offcolor #offset observations have offcolor outline
if args.helder == 'yes':
for i in list(h_offz_i[:][0]):
h_mecs[i] = offcolor #offset observations have offcolor outline
xmm_mecs = 'black'
rosat_mecs = softcolor
early_mecs = 'black'
#-markeredgewidth = simz (detector z)-
offmew = 1.5
a_mews = [0.5]*a_nobs
b_mews = [0.5]*b_nobs
#r_mews = [0.5]*r_nobs
if args.helder == 'yes': h_mews = [0.5]*h_nobs
if args.ignorechippos == 'no':
for i in list(a_offz_i[:][0]):
a_mews[i] = offmew #offset observations have different outline
for i in list(b_offz_i[:][0]):
b_mews[i] = offmew #offset observations have different outline
# for i in list(r_offz_i[:][0]):
# r_mews[i] = offmew #offset observations have different outline
if args.helder == 'yes':
for i in list(h_offz_i[:][0]):
h_mews[i] = offmew #offset observations have different outline
#h_mews = 0.5
xmm_mews = 1.0
rosat_mews = 0.7
early_mews = 0.5
#-markersize - # = frametime-
xmm_sizes = 8
#a_sizes = [f*3 for f in a_data['frametime']]
#b_sizes = [f*3 for f in b_data['frametime']]
a_sizes = 8
b_sizes = 4
#r_sizes = 4
rosat_sizes = 8
early_sizes = 8
#-alpha (transparency) = caldb-
a_alpha = 1.0
if args.skip462 == 'no':
b_alpha = 0.6
else:
b_alpha = 1.0
#r_alpha = 1.0
xmm_alpha = [1.0]*xmm_nobs
xmm_alpha[-1] = 0.7 #set last point to different alpha (since reduced myself)
if args.skip462 == 'no':
h_alpha = 0.6
else:
if args.caldb459 == 'yes':
h_alpha = 0.6
else:
h_alpha = 1.0
rosat_alpha = 1.0
early_alpha = 1.0
piled_alpha = 0.1
#---------------------------------------
# Light Curve(s)
#---------------------------------------
#----Set Up Plot----
pdffile = PdfPages(plotfile)
#fig = plt.figure()
#-initialize main plot-
#fig,ax1=plt.subplots()
#ax1.set_xlim(xmin,xmax)
#ax1.set_ylim(ymin,ymax)
#-set axis titles-
#plt.xlabel('SN1987A Age [days]')
#plt.ylabel('Flux [10$^{-13}$ erg cm$^{-2}$ s$^{-1}$]')
#-set bottom axis-
#set_axis(ax1,x=botx,grid=mgrid)
#-add extra space on bottom-
#plt.subplots_adjust(bottom=bott,top=topp)
#--Initialize Plot--
ax1 = start_plot(xtitle='SN1987A Age [days]',ytitle='Flux [10$^{-13}$ erg cm$^{-2}$ s$^{-1}$]',xmin=args.agemin,xmax=args.agemax,ymin=fluxmin,ymax=fluxmax,ylog=args.ylog,clean=args.clean)
if args.skip462 == 'no':
if args.soft == 'yes':
#--Soft Flux--
if args.instcolor == 'yes': #color=instrument,symbol=band (effects xmm and chandra, soft and hard only)
plot_a(ax1,a_data['age'],a_data['soft'],low=a_data['softlow'],high=a_data['softhigh'],syms=chandrasoftsyms,colors=chandrasoftcolors,alphas=a_alpha,mecs=a_mecs,mews=a_mews,sizes=a_sizes)
else:
plot_a(ax1,a_data['age'],a_data['soft'],low=a_data['softlow'],high=a_data['softhigh'],syms=a_syms,colors=softcolor,alphas=a_alpha,mecs=a_mecs,mews=a_mews,sizes=a_sizes)
# if args.dofit == 'yes': #do linear fit to light curve
# lc_fit = np.polyfit(a_data['age'],a_data['soft'],1)
# fit_fn = np.poly1d(lc_fit) #make function out of best fit
# plt.plot(a_data['age'],fit_fn(a_data['age']),'-')#plot best fit
if args.dofit == 'yes': #do powerlaw fit to light curve
fit_i = np.array([-11,-10,-9,-8,-7,-6,-4,-3,-2,-1])
# fit_i = range(3,a_nobs-1)
fit_params, fit_covars = curve_fit(af.powerlaw,a_data['age'][fit_i],a_data['soft'][fit_i],p0=[1.0,0.5,-8000.0])
sigmas = [np.sqrt(fit_covars[0,0]),np.sqrt(fit_covars[1,1]),np.sqrt(fit_covars[2,2])]
print 'fit_params = ',fit_params
print 'fit_covars = ',fit_covars
fitx=np.linspace(min(a_data['age'][fit_i]),11000.0)
plt.plot(fitx,af.powerlaw(fitx,fit_params[0],fit_params[1],fit_params[2]),'--',color=softcolor)
plt.plot(fitx,af.powerlaw(fitx,fit_params[0]+sigmas[0],fit_params[1]+sigmas[1],fit_params[2]+sigmas[1]),'--',color=softcolor,alpha=0.5)
plt.plot(fitx,af.powerlaw(fitx,fit_params[0]-sigmas[0],fit_params[1]-sigmas[1],fit_params[2]-sigmas[1]),'--',color=softcolor,alpha=0.5)
future_ages = np.array([10257,10441,10623,10807])
print 'fit(future_ages) = ',af.powerlaw(future_ages,fit_params[0],fit_params[1],fit_params[2])
plt.plot(future_ages,af.powerlaw(future_ages,fit_params[0],fit_params[1],fit_params[2]),'*',color=softcolor)
# plt.plot(future_ages,af.powerlaw(future_ages,fit_params[0]+sigmas[0],fit_params[1]+sigmas[1],fit_params[2]+sigmas[1]),'*',color=softcolor,alpha=0.6)
# plt.plot(future_ages,af.powerlaw(future_ages,fit_params[0]-sigmas[0],fit_params[1]-sigmas[1],fit_params[2]-sigmas[1]),'*',color=softcolor,alpha=0.6)
if args.soft12 == 'yes':
#--Soft12 Flux (1.0-2.0keV)--
plot_a(ax1,a_data['age'],a_data['soft12'],low=a_data['soft12low'],high=a_data['soft12high'],syms=a_syms,colors=soft12color,alphas=a_alpha,mecs=a_mecs,mews=a_mews,sizes=a_sizes)
if args.soft13 == 'yes':
#--Soft13 Flux (1.0-3.0keV)--
plot_a(ax1,a_data['age'],a_data['soft13'],low=a_data['soft13low'],high=a_data['soft13high'],syms=a_syms,colors=soft13color,alphas=a_alpha,mecs=a_mecs,mews=a_mews,sizes=a_sizes)
if args.hard == 'yes':
#--Hard Flux--
if args.instcolor == 'yes':
plot_a(ax1,a_data['age'],a_data['hard'],low=a_data['hardlow'],high=a_data['hardhigh'],syms=chandrahardsyms,colors=chandrahardcolors,alphas=a_alpha,mecs=a_mecs,mews=a_mews,sizes=a_sizes)
else:
plot_a(ax1,a_data['age'],a_data['hard'],low=a_data['hardlow'],high=a_data['hardhigh'],syms=a_syms,colors=hardcolor,alphas=a_alpha,mecs=a_mecs,mews=a_mews,sizes=a_sizes)
#print 'hard fluxes = ',a_data['hard']
if args.broad == 'yes':
#--Broad Flux--
plot_a(ax1,a_data['age'],a_data['broad'],low=a_data['broadlow'],high=a_data['broadhigh'],syms=a_syms,colors=broadcolor,alphas=a_alpha,mecs=a_mecs,mews=a_mews,sizes=a_sizes)
#--CALDB4.5.9--
if args.caldb459 == 'yes':
#--Soft Flux--
if args.soft == 'yes': plot_a(ax1,b_data['age'],b_data['soft'],low=b_data['softlow'],high=b_data['softhigh'],syms=b_syms,colors=softcolor,alphas=b_alpha,mecs=b_mecs,mews=b_mews,sizes=b_sizes)
#--Soft12 Flux (1.0-2.0keV)--
if args.soft12 == 'yes': plot_a(ax1,b_data['age'],b_data['soft12'],low=b_data['soft12low'],high=b_data['soft12high'],syms=b_syms,colors=soft12color,alphas=b_alpha,mecs=b_mecs,mews=b_mews,sizes=b_sizes)
#--Soft13 Flux (1.0-3.0keV)--
if args.soft13 == 'yes': plot_a(ax1,b_data['age'],b_data['soft13'],low=b_data['soft13low'],high=b_data['soft13high'],syms=b_syms,colors=soft13color,alphas=b_alpha,mecs=b_mecs,mews=b_mews,sizes=b_sizes)
#--Hard Flux--
if args.hard == 'yes': plot_a(ax1,b_data['age'],b_data['hard'],low=b_data['hardlow'],high=b_data['hardhigh'],syms=b_syms,colors=hardcolor,alphas=b_alpha,mecs=b_mecs,mews=b_mews,sizes=b_sizes)
#--Broad Flux--