-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNorm_and_Fit.py
1595 lines (1493 loc) · 74.7 KB
/
Norm_and_Fit.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
import numpy as np
from astropy.io import fits
from scipy.optimize import curve_fit, fsolve, leastsq
import scipy.stats as stat
import scipy.integrate as integrate
from statsmodels.stats.diagnostic import lilliefors
import matplotlib.pyplot as plt
from matplotlib import gridspec
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.colors as mcl
import matplotlib.patches as mpt
from astropy.time import Time
import astropy.units as unit
from astropy.cosmology import Planck15 as cosmo
class Normalisation:
"""Contains functions to normalise the input data (line and continuum fluxes) to the the epoch of highest continuum state"""
def __init__(self,namelist=[],spec_namelist=[],exclude=[],fits_name=None,SN_limit=None,deltat_limit=None):
if len(exclude)!=0: exclude = np.loadtxt(exclude,dtype='str')
try:
fin = np.loadtxt(namelist,dtype={'names':('name','obj','ra','dec','z','dt','airmass','S/N','A_v_sf','A_v_sdss'),'formats':('S30','S30','float','float','float','float','float','float','float','float')})
self.namelist,self.sdss_namelist,self.zdt_list = [],[],[]
#This line is to account for an idiosyncrasy in the data format, where the same object is listed under different names
self.simlist = []
ii=0
while ii < len(fin['obj']):
if fin['name'][ii] in exclude:
if ii%2==1:
del self.namelist[-1]
del self.sdss_namelist[-1]
del self.zdt_list[-1]
ii+=1
else:
ii+=2
continue
if deltat_limit:
if fin['dt'][ii]<deltat_limit:
ii+=2
continue
else:
if SN_limit:
if fin['S/N'][ii]<SN_limit:
if ii%2==1:
del self.namelist[-1]
del self.sdss_namelist[-1]
del self.zdt_list[-1]
ii+=1
else:
ii+=2
continue
else:
if ii%2==1 and fin['obj'][ii]!=self.namelist[-1][:len(fin['obj'][ii])]:
if fin['z'][ii]==self.zdt_list[-1][0] and fin['dt'][ii]==self.zdt_list[-1][1]:
self.simlist += [fin['obj'][ii][:9]]
self.zdt_list += [[ fin['z'][ii],fin['dt'][ii],fin['S/N'][ii] ]]
self.sdss_namelist += [fin['name'][ii]]
if fin['name'][0]=='/':
self.namelist += [fin['obj'][ii]+'_'+fin['name'][ii][12:17]]
else:
self.namelist += [fin['obj'][ii]+'_'+fin['name'][ii][10:15]]
ii+=1
continue
if SN_limit:
if fin['S/N'][ii]<SN_limit:
if ii%2==1:
del self.namelist[-1]
del self.sdss_namelist[-1]
del self.zdt_list[-1]
ii+=1
else:
ii+=2
continue
else:
if ii%2==1 and fin['obj'][ii]!=self.namelist[-1][:len(fin['obj'][ii])]:
if fin['z'][ii]==self.zdt_list[-1][0] and fin['dt'][ii]==self.zdt_list[-1][1]:
self.simlist += [fin['obj'][ii][:9]]
self.zdt_list += [[ fin['z'][ii],fin['dt'][ii],fin['S/N'][ii] ]]
self.sdss_namelist += [fin['name'][ii]]
if fin['name'][0]=='/':
self.namelist += [fin['obj'][ii]+'_'+fin['name'][ii][12:17]]
else:
self.namelist += [fin['obj'][ii]+'_'+fin['name'][ii][10:15]]
ii+=1
continue
#Inclusion in case no delta_t limit or S/N limit is set
if ii%2==1 and fin['obj'][ii]!=self.namelist[-1][:len(fin['obj'][ii])]:
if fin['z'][ii]==self.zdt_list[-1][0] and fin['dt'][ii]==self.zdt_list[-1][1]:
self.simlist += [fin['obj'][ii][:9]]
self.zdt_list += [[ fin['z'][ii],fin['dt'][ii],fin['S/N'][ii] ]]
self.sdss_namelist += [fin['name'][ii]]
if fin['name'][0]=='/':
self.namelist += [fin['obj'][ii]+'_'+fin['name'][ii][12:17]]
else:
self.namelist += [fin['obj'][ii]+'_'+fin['name'][ii][10:15]]
ii+=1
self.namelist = np.array(self.namelist)
self.sdss_namelist = np.array(self.sdss_namelist)
self.zdt_list = np.array(self.zdt_list)
except:
print 'Loading filename only list'
self.namelist = np.loadtxt(namelist,dtype='str')
self.simlist = []; self.zdt_list = len(self.namelist)*[[0,0,0]]; self.sdss_namelist=np.loadtxt(spec_namelist,dtype='str')
for ii in range(len(self.namelist)):
if self.namelist[ii] in exclude: np.delete(self.namelist,ii)
self.fits_name = fits_name
self.normalised = 0
self.data = None
@staticmethod
def date_converter(array_in):
'''search through a given array of dates and convert non MJD-dates to MJD. Assumed format for non-MJD dates is YYYYMMDD'''
for ii in range(len(array_in)):
if len(str(array_in[ii]))!=5:
d = str(array_in[ii])
d = d[:4]+'-'+d[4:6]+'-'+d[6:]
t = Time(d,format='iso')
array_in[ii] = int(t.mjd)
return np.array(array_in)
def load_data(self,data_path='./',conf_columns=[21,22,29,30],linef_columns=[19,20,27,28],distance_col = 31,inc_double_sig=False):
'''load and organize the data appropriately. Order for columns: flux1, flux1_err, flux2, flux2_err. This function is very specific to the data format.'''
cc,lc,dc = conf_columns,linef_columns,distance_col
Line, Line_err = [],[]
C, C_err = [],[]
SDSS_List, Name_List, Date_List, Z_List,Sigma_List,Sigma_err = [],[],[],[],[],[]
Z_Est, DT, SN = [],[],[]
#Load data from lmfit results, over multiple objects
if len(self.namelist)!=0:
line_, line_err = [],[]
c,c_err = [],[]
sdss_list,name_list,date_list,z_list,sigma_list,sigma_err = [],[],[],[],[],[]
namelen = self.namelist[0].find('_')
name = self.namelist[0][:namelen]; date = self.namelist[0][namelen+1:]
self.nobj = 0
for ii in range(len(self.namelist)):
spec = self.namelist[ii]
namelen = spec.find('_')
date = spec[namelen+1:]
if spec[:namelen]!=name: #Group together spectra for the same object
if spec[:9] in self.simlist and len(name_list)==1: #Account for two names being used for the same object
pass
else:
name = spec[:namelen]
Line+=[line_]; Line_err+=[line_err]
C+=[c]; C_err+=[c_err]
Name_List+=[name_list]
SDSS_List+=[sdss_list]
Date_List += [date_list]
Z_List += [z_list]
Z_Est += [len(z_list)*[self.zdt_list[ii-1][0]]]
Sigma_List += [sigma_list]
Sigma_err+=[sigma_err]
if self.zdt_list[ii-1][2]!=0:
DT += [len(z_list)*[self.zdt_list[ii-1][1]]]
SN += [[self.zdt_list[ii-1][2],self.zdt_list[ii][2]]]
else:
date_list = self.date_converter(date_list)
dt = []
for jj in range(len(date_list)-1):
dt += [abs(int(date_list[jj])-int(date_list[jj+1]))]
dt+=[dt[-1]]
DT += [dt]
SN += [len(z_list)*[0]]
line_, line_err = [],[]
c, c_err = [],[]
sdss_list,name_list,date_list,z_list,sigma_list,sigma_err = [],[],[],[],[],[]
self.nobj+=1
#Load fitting results
if spec.find('+')!=-1: spec_load = spec.replace('+','_')
else: spec_load = spec.replace('-','_')
fi = np.loadtxt(data_path+spec_load,dtype={'names':('par','val'),'formats':('S20','S30')})
ampb,ampb_e = 0,0
sigw=0
for row in fi:
if row[1]=='None':
val=0
else:
val = float(row[1])
if row[0]=='powUVamp': amp=val
elif row[0]=='powUVampErr': ampErr=val
elif row[0]=='powUVexp': exp=val
elif row[0]=='powUVexpErr': expErr=val
elif row[0]=='MgIIamplitude': ampb+=val
elif row[0]=='MgIIamplitudeErr': ampb_e+=val*val
elif row[0]=='MgIIcenter': centb=val
elif row[0]=='MgIIsigma': sigb=val
elif row[0]=='MgIIsigmaErr': sigb_e=val
elif row[0]=='MgIIwamplitude': ampb+=val
elif row[0]=='MgIIwamplitudeErr': ampb_e+=val*val
elif row[0]=='MgIIwsigma': sigw=val
elif row[0]=='MgIIwsigmaErr': sigw_e=val
c+= [amp*np.power(centb/5100.,exp)]
c_err+= [np.power((centb/5100.0),exp)*np.sqrt(np.power(ampErr,2) + np.power((amp*np.log(centb/5100.0)*expErr),2))]
line_+= [ampb]
line_err += [np.sqrt(ampb_e)]
name_list += [name]
sdss_list += [self.sdss_namelist[ii]]
date_list += [date]
if sigw!=0:
if inc_double_sig==True:
# print name, date
sigma_list += [np.maximum(sigb,sigw)]
sigma_err += [ (sigb_e,sigw_e)[np.argmax((sigb,sigw))] ]
else: sigma_list+=[0]; sigma_err+=[0]
else:
sigma_list += [sigb]; sigma_err+=[sigb_e]
z_list += [centb/2798. - 1.]
if spec==self.namelist[-1]:#Include last spectrum in the list
Line+=[line_]; Line_err+=[line_err]
C+=[c]; C_err+=[c_err]
Name_List+=[name_list]
SDSS_List+=[sdss_list]
Date_List += [date_list]
Z_List += [z_list]
Z_Est += [len(z_list)*[self.zdt_list[ii][0]]]
if self.zdt_list[ii-1][2]!=0:
DT += [len(z_list)*[self.zdt_list[ii-1][1]]]
SN += [[self.zdt_list[ii-1][2],self.zdt_list[ii][2]]]
else:
date_list = self.date_converter(date_list)
dt = []
for jj in range(len(date_list)-1):
dt += [abs(int(date_list[jj])-int(date_list[jj+1]))]
dt+=[dt[-1]]
DT += [dt]
SN += [len(z_list)*[0]]
Sigma_List+=[sigma_list]
Sigma_err+=[sigma_err]
self.nobj+=1
self.data = np.array([SDSS_List,Name_List,Date_List,C,C_err,Line,Line_err,Z_List,Z_Est,DT,SN,Sigma_List,Sigma_err])
#Load data from the fits file (QSFit data)
elif self.fits_name!=None:
hdulist = fits.open(self.fits_name)
tb = hdulist[1].data
for row in tb:
if row[lc[0]]!=0:
C += [[row[cc[0]],row[cc[2]]]]
C_err += [[row[cc[1]],row[cc[3]]]]
Line += [[row[lc[0]],row[lc[2]]]]
Line_err += [[row[lc[1]],row[lc[3]]]]
Name_List += [[row[0],row[0]]]
if val[5:8]=='wht' or val[5:8]=='mmt':
Date_List += [[0,int(val[9:17])]]
elif val[5:8]=='mag':
Date_List += [[0,int('20'+val[16:22])]]
self.data = [Name_List,Date_List,C,C_err,Line,Line_err]
else: print 'No data file specified'; return
def load_mc_errors(self,data_path='\.',nmc=100,inc_double_sig=False,ew=False):
'''Replace the errors in the data attribute with an average of the errors from a Monte Carlo simulation (N=nmc)'''
C_err,Line_err,Sigma_err,EW_err = [],[],[],[]
#Load data from lmfit results, over multiple objects
if len(self.namelist)!=0:
c_err,line_err,sigma_err,ew_err = [],[],[],[]
namelen = self.namelist[0].find('_')
name = self.namelist[0][:namelen]; date = self.namelist[0][namelen+1:]
for ii in range(len(self.namelist)):
spec = self.namelist[ii]
namelen = spec.find('_')
if spec[:namelen]!=name: #Group together spectra for the same object
if spec[:9] in self.simlist and len(name_list)==1: #Account for two names being used for the same object
pass
else:
name = spec[:namelen]
Line_err+=[line_err]
C_err+=[c_err]
Sigma_err += [sigma_err]
c_err,line_err,sigma_err = [],[],[]
#Load fitting results
if spec.find('+')!=-1: spec_load = spec.replace('+','_')
else: spec_load = spec.replace('-','_')
c_mc,l_mc,sig_mc,ew_mc=[],[],[],[]
for mm in range(nmc):
try:
fi = np.loadtxt(data_path+spec_load+'_'+str(mm),dtype={'names':('par','val'),'formats':('S20','S30')})
except IOError: continue
ampb,ampb_e = 0,0
sigw=0; G2=0
for row in fi:
if row[1]=='None':
val=0
else:
val = float(row[1])
if row[0]=='powUVamp': amp=val
elif row[0]=='powUVexp': exp=val
elif row[0]=='MgIIamplitude': ampb+=val
elif row[0]=='MgIIcenter': cb=val
elif row[0]=='MgIIsigma': sb=val
elif row[0]=='MgIIwamplitude': G2=1; ampw=val; ampb+=val
elif row[0]=='MgIIwcenter': cw=val
elif row[0]=='MgIIwsigma': sw=val
c_mc+= [amp*np.power(cb/5100.,exp)]
l_mc+= [ampb]
if sigw!=0:
if inc_double_sig==True:
sig_mc += [np.average(sb,sw)]
else: sig_mc+=[0]
else:
sig_mc += [sb]
if ew==True:
if G2 != 0:
I = integrate.quad(self.p_EqW2,cb-8*sb,cb+8*sb,args=(ampb,cb,sb,ampw,cw,sw,amp,exp))
ew_mc+=[I[0]]
else:
I = integrate.quad(self.p_EqW1,cb-8*sb,cb+8*sb,args=(ampb,cb,sb,amp,exp))
ew_mc+=[I[0]]
else:
ew_mc+=[0]
c_err+=[np.std(c_mc)]; line_err+=[np.std(l_mc)]; sigma_err+=[np.std(sig_mc)]; ew_err+=[np.std(ew_mc)]
if spec==self.namelist[-1]:#Include last spectrum in the list
C_err+=[c_err]; Line_err+=[line_err]; Sigma_err+=[sigma_err]; EW_err+=[ew_err]
#Replace the errors in the data attribute
if ew==True:
self.data[4]=C_err; self.data[6]=Line_err; self.data[8]=EW_err
else:
self.data[4]=C_err; self.data[6]=Line_err; self.data[12]=Sigma_err
def Gaussian(self,x,amp,mu,sigma):
'''needed in the EW calculation'''
return amp/(sigma*np.sqrt(2*np.pi))*np.exp(-.5*np.power((x-mu)/sigma,2))
def PL(self,x,amp,ind):
'''needed in the EW calculation'''
return amp*np.power(x/5100.,ind)
def p_EqW1(self,x,Ga,Gm,Gs,PLa,PLi):
'''needed in the EW calculation'''
return self.Gaussian(x,Ga,Gm,Gs)/self.PL(x,PLa,PLi)
def p_EqW2(self,x,G1a,G1m,G1s,G2a,G2m,G2s,PLa,PLi):
'''needed in the EW calculation'''
return (self.Gaussian(x,G1a,G1m,G1s)+self.Gaussian(x,G2a,G2m,G2s))/self.PL(x,PLa,PLi)
def load_data_ew(self,data_path='./'):
'''Load data from the spectral fit output files, and calculate the equivalent widths and associated errors'''
Line, Line_err = [],[]
C, C_err = [],[]
EW, EW_err = [],[]
SDSS_List, Name_List, Date_List, Z_List = [],[],[],[]
#Load data from lmfit results, over multiple objects
if len(self.namelist)!=0:
line_, line_err = [],[]
c, c_err = [],[]
ew, ew_err = [],[]
sdss_list,name_list,date_list,z_list = [],[],[],[]
namelen = self.namelist[0].find('_')
name = self.namelist[0][:namelen]; date = self.namelist[0][namelen+1:]
self.nobj = 0
for ii in range(len(self.namelist)):
spec = self.namelist[ii]
namelen = spec.find('_')
date = spec[namelen+1:]
if spec[:namelen]!=name: #Group together spectra for the same object
if spec[:9] in self.simlist and len(name_list)==1: #Account for two names being used for the same object
pass
else:
name = spec[:namelen]
Line+=[line_]; Line_err+=[line_err]
C+=[c]; C_err+=[c_err]
EW+=[ew]; EW_err+=[ew_err]
Name_List+=[name_list]
SDSS_List+=[sdss_list]
Date_List += [date_list]
Z_List += [z_list]
line_, line_err = [],[]
c, c_err = [],[]
ew, ew_err = [],[]
sdss_list,name_list,date_list,z_list = [],[],[],[]
self.nobj+=1
#Load fitting results
if spec.find('+')!=-1: spec_load = spec.replace('+','_')
else: spec_load = spec.replace('-','_')
fi = np.loadtxt(data_path+spec_load,dtype={'names':('par','val'),'formats':('S20','S30')})
lf, lfe = 0,0
G2 = 0
for row in fi:
if row[1]=='None':
val=0
else:
val = float(row[1])
if row[0]=='powUVamp': amp=val
elif row[0]=='powUVampErr': ampErr=val
elif row[0]=='powUVexp': exp=val
elif row[0]=='powUVexpErr': expErr=val
elif row[0]=='MgIIamplitude':
lf+=val; ampb=val
elif row[0]=='MgIIamplitudeErr':
lfe+=np.power(val,2); ampb_err=val
elif row[0]=='MgIIcenter': cb=val
elif row[0]=='MgIIsigma': sb=val
elif row[0]=='MgIIwamplitude':
G2 = 1 #Marker that a second Gaussian was used in the fitting
lf+=val; ampw=val
elif row[0]=='MgIIwamplitudeErr':
lfe+=np.power(val,2); ampw_err=val
elif row[0]=='MgIIwcenter': cw=val
elif row[0]=='MgIIwsigma': sw=val
c+= [amp*np.power(cb*(3000./2798.)/5100.0,exp)]
c_err+= [np.power((cb*(3000./2798.)/5100.0),exp)*np.sqrt(np.power(ampErr,2) + np.power((amp*np.log(cb*(3000./2798.)/5100.0)*expErr),2))]
line_+= [lf]
line_err+= [np.sqrt(lfe)]
pl_tmp = self.PL(cb,amp,exp)
pl_err_tmp = np.power((cb/5100.0),exp)*np.sqrt(np.power(amp,2) + np.power((amp*np.log(cb/5100.0)*exp),2))
if G2 != 0:
I = integrate.quad(self.p_EqW2,cb-8*sb,cb+8*sb,args=(ampb,cb,sb,ampw,cw,sw,amp,exp))
ew+=[I[0]]
ampb_err = np.sqrt(ampb_err*ampb_err + ampw_err+ampw_err)
else:
I = integrate.quad(self.p_EqW1,cb-8*sb,cb+8*sb,args=(ampb,cb,sb,amp,exp))
ew+=[I[0]]
ew_err += [np.sqrt( np.power(ampb_err/pl_tmp,2) + np.power(ampb_err*pl_err_tmp,2)/np.power(pl_tmp,4) )]
name_list += [name]
sdss_list += [self.sdss_namelist[ii]]
date_list += [date]
z_list += [cb/2798. - 1.]
if spec==self.namelist[-1]:#Include last spectrum in the list
Line+=[line_]; Line_err+=[line_err]
C+=[c]; C_err+=[c_err]
EW += [ew]; EW_err+=[ew_err]
Name_List+=[name_list]
SDSS_List+=[sdss_list]
Date_List += [date_list]
Z_List += [z_list]
self.nobj+=1
self.data = np.array([SDSS_List,Name_List,Date_List,C,C_err,Line,Line_err,EW,EW_err,Z_List])
def add_sdss_dates(self,datefile='sdssnames.txt'):
'''Find the dates for sdss spectra (to be used in combination with data from fits file)'''
indata = np.loadtxt(datefile,dtype={'names':('a','name','c','spec'),'formats':(int,'S7',float,'S25')})
for ii in range(len(self.data[0])):
name = self.data[0][ii,0]
if name in indata['name']:
self.data[1][ii,0] = int(indata['spec'][np.argwhere(indata['name']==name)][0][0][10:15])
def normalise(self,n='cmax'):
'''Normalise the flux data, as descibed in the paper. Setting n='cmax' normalises to the date of maximum continuum, and n='cmin' to the date of minimum continuum'''
DS_List, DC_List,DL_List = [],[],[]
DSe_List, DCe_List,DLe_List = [],[],[]
for ii in range(len(self.data[0])):
cpc,cpl,cps = np.array(self.data[3][ii]).astype('float'),np.array(self.data[5][ii]).astype('float'),np.array(self.data[11][ii]).astype('float')
cpce,cple,cpse = np.array(self.data[4][ii]).astype('float'),np.array(self.data[6][ii]).astype('float'),np.array(self.data[12][ii]).astype('float')
if n=='cmax':
nc = np.amax(cpc); nl = cpl[np.argmax(cpc)]
elif n=='cmin':
nc = np.amin(cpc); nl= cpl[np.argmin(cpc)]
DS,DC,DL = [],[],[]
DSe,DCe,DLe = [],[],[]
for jj in range(len(cpc)-1):
DC += [(float(cpc[jj])-float(cpc[jj+1]))/cpc[jj]]
DCe+= [np.sqrt(np.power(cpce[jj+1]/cpc[jj],2)+np.power(cpc[jj+1]*cpce[jj]/(cpc[jj]*cpc[jj]),2))]
DL += [(float(cpl[jj])-float(cpl[jj+1]))/cpl[jj]]
DLe+= [np.sqrt(np.power(cple[jj+1]/cpl[jj],2)+np.power(cpl[jj+1]*cple[jj]/(cpl[jj]*cpl[jj]),2))]
if cps[jj]==0 or cps[jj+1]==0: DS+=[0]; DSe+=[0]
else: DS += [(cps[jj]-cps[jj+1])/cps[jj]]; DSe+=[np.sqrt(np.power(cpse[jj+1]/cps[jj],2)+np.power(cps[jj+1]*cpse[jj]/(cps[jj]*cps[jj]),2))] #Normalise del_sigma to oldest epoch, assuming all epochs are in chr. order
DS += [DS[-1]]; DC += [DC[-1]]; DL+=[DL[-1]]
DSe += [DSe[-1]]; DCe += [DCe[-1]]; DLe+=[DLe[-1]]
DS_List += [DS]; DC_List += [DC]; DL_List += [DL]
DSe_List += [DSe]; DCe_List += [DCe]; DLe_List += [DLe]
self.data[3][ii] = cpc/nc; self.data[5][ii] = cpl/nl
self.data[4][ii] = np.array(self.data[4][ii]).astype('float')/nc; self.data[6][ii] = np.array(self.data[6][ii]).astype('float')/nl
DC_List = np.array([DS_List,DSe_List,DC_List,DCe_List,DL_List,DLe_List])
self.data = np.concatenate((self.data,DC_List),axis=0)
self.normalised=True
def create_flux_list(self,name_add=''):
'''Write the normalised fluxes and previously data into a single file \n
format of input data: np.array([SDSS_List 0,Name_List 1,Date_List 2,C 3,C_err 4,Line 5,Line_err 6,Z_List 7,Z_Est 8,DT 9,SN 10,Sigma_List 11, Sigma_err 12])'''
if self.normalised:
outfile='Named_MgII_norm_flux'+name_add
with open(outfile,'w') as of:
of.write( '#{:>30} {:>35} {:>23} {:>25} {:>23} {:>24} {:>20} {:>20} {:>11} {:>15} {:>18} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25}\n'.format('SpecName','Name','Continuum','Continuum_err','Line','Line_err','z_fit','z_sdss','Delta_t','S/N_sdss','Sigma','Sigma_err','Delta_S','Delta_S_err','Delta_C','Delta_C_err','Delta_L','Delta_L_err') )
for ii in range(len(self.data[0])):
for jj in range(len(self.data[0][ii])):
of.write( ' {:>30} {:>35} {:>23} {:>25} {:>28} {:>24} {:>20} {:>20} {:>11} {:>15} {:>18} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25}\n'.format( self.data[0][ii][jj],self.data[1][ii][jj]+'_'+str(self.data[2][ii][jj]),self.data[3][ii][jj],self.data[4][ii][jj],self.data[5][ii][jj],self.data[6][ii][jj],self.data[7][ii][jj],self.data[8][ii][jj],self.data[9][ii][jj],str(round(float(self.data[10][ii][jj]),2)),self.data[11][ii][jj],self.data[12][ii][jj],self.data[13][ii][jj],self.data[14][ii][jj],self.data[15][ii][jj],self.data[16][ii][jj],self.data[17][ii][jj],self.data[18][ii][jj] ) )
outfile='MgII_norm_flux'+name_add
with open(outfile,'w') as of:
of.write( '#{:>23} {:>25} {:>23} {:>24} {:>20} {:>20} {:>16} {:>15} {:>18} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25}\n'.format('Continuum','Continuum_err','Line','Line_err','z_fit','z_sdss','Delta_t','S/N_sdss','Sigma','Sigma_err','Delta_S','Delta_S_err','Delta_C','Delta_C_err','Delta_L','Delta_L_err') )
for ii in range(len(self.data[0])):
for jj in range(len(self.data[0][ii])):
of.write( ' {:>23} {:>25} {:>23} {:>24} {:>20} {:>20} {:>16} {:>15} {:>18} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25}\n'.format( str(self.data[3][ii][jj]),str(self.data[4][ii][jj]),str(self.data[5][ii][jj]),str(self.data[6][ii][jj]),str(self.data[7][ii][jj]),str(self.data[8][ii][jj]),str(self.data[9][ii][jj]),str(self.data[10][ii][jj]),str(self.data[11][ii][jj]),str(self.data[12][ii][jj]),self.data[13][ii][jj],self.data[14][ii][jj],self.data[15][ii][jj],self.data[16][ii][jj],self.data[17][ii][jj],self.data[18][ii][jj] ) )
else:
DC_List,DCe_List,DL_List,DLe_List,DS_List,DSe_List = [],[],[],[],[],[]
for ii in range(len(self.data[0])):
cpc,cpce,cpl,cple = np.array(self.data[3][ii]).astype('float'),np.array(self.data[4][ii]).astype('float'),np.array(self.data[5][ii]).astype('float'),np.array(self.data[6][ii]).astype('float')
cps,cpse = np.array(self.data[11][ii]).astype('float'),np.array(self.data[12][ii]).astype('float')
DC,DCe,DL,DLe,DS,DSe=[],[],[],[],[],[]
for jj in range(len(cpc)-1):
DC += [float(cpc[jj])-float(cpc[jj+1])]; DCe += [np.sqrt(cpce[jj]*cpce[jj]+cpce[jj+1]*cpce[jj+1])]
DL += [float(cpl[jj])-float(cpl[jj+1])]; DLe += [np.sqrt(cple[jj]*cple[jj]+cple[jj+1]*cple[jj+1])]
if cps[jj]==0 or cps[jj+1]==0: DS+=[0]; DSe+=[0]
else: DS += [cps[jj]-cps[jj+1]]; DSe+=[np.sqrt(cpse[jj]*cpse[jj]+cpse[jj+1]*cpse[jj+1])]
DC+=[DC[-1]]; DCe+=[DCe[-1]]; DL+=[DL[-1]]; DLe+=[DLe[-1]]; DS+=[DS[-1]]; DSe+=[DSe[-1]]
DC_List += [DC]; DCe_List+=[DCe]; DL_List += [DL]; DLe_List+=[DLe]; DS_List+=[DS]; DSe_List+=[DSe]
DC_List = np.array([DS_List,DSe_List,DC_List,DCe_List,DL_List,DLe_List])
self.data = np.concatenate((self.data,DC_List),axis=0)
outfile='Named_MgII_flux'+name_add
with open(outfile,'w') as of:
of.write( '#{:>30} {:>18} {:>25} {:>23} {:>20} {:>24} {:>16} {:>20} {:>10} {:>15} {:>25} {:>23} {:>25} {:>23} {:>25} {:>23} {:>25} {:>23}\n'.format('SpecName','Name','Continuum','Continuum_err','Line','Line_err','z_fit','z_sdss','Delta_t','S/N_sdss','Sigma','Sigma_err','Delta_S','Delta_S_err','Delta_C','Delta_C_err','Delta_L','Delta_L_err') )
for ii in range(len(self.data[0])):
for jj in range(len(self.data[0][ii])):
of.write( ' {:>30} {:>18} {:>25} {:>23} {:>20} {:>24} {:>16} {:>20} {:>10} {:>15} {:>25} {:>23} {:>25} {:>23} {:>25} {:>23} {:>25} {:>23}\n'.format( self.data[0][ii][jj],self.data[1][ii][jj]+'_'+str(self.data[2][ii][jj]),str(self.data[3][ii][jj]),str(self.data[4][ii][jj]),str(self.data[5][ii][jj]),str(self.data[6][ii][jj]),str(self.data[7][ii][jj]),str(self.data[8][ii][jj]),str(self.data[9][ii][jj]),str(self.data[10][ii][jj]),str(self.data[11][ii][jj]),str(self.data[12][ii][jj]),str(self.data[13][ii][jj]),str(self.data[14][ii][jj]),str(self.data[15][ii][jj]),str(self.data[16][ii][jj]),str(self.data[17][ii][jj]),str(self.data[18][ii][jj]) ) )
outfile='MgII_flux'+name_add
with open(outfile,'w') as of:
of.write( '#{:>25} {:>23} {:>20} {:>24} {:>16} {:>20} {:>10} {:>15} {:>25} {:>23} {:>25} {:>23} {:>25} {:>23} {:>25} {:>23}\n'.format('Continuum','Continuum_err','Line','Line_err','z_fit','z_sdss','Delta_t','S/N_sdss','Sigma','Sigma_err','Delta_S','Delta_S_err','Delta_C','Delta_C_err','Delta_L','Delta_L_err') )
for ii in range(len(self.data[0])):
for jj in range(len(self.data[0][ii])):
of.write( ' {:>25} {:>23} {:>20} {:>24} {:>16} {:>20} {:>10} {:>15} {:>25} {:>23} {:>25} {:>23} {:>25} {:>23} {:>25} {:>23}\n'.format( str(self.data[3][ii][jj]),str(self.data[4][ii][jj]),str(self.data[5][ii][jj]),str(self.data[6][ii][jj]),str(self.data[7][ii][jj]),str(self.data[8][ii][jj]),str(self.data[9][ii][jj]),str(self.data[10][ii][jj]),str(self.data[11][ii][jj]),str(self.data[12][ii][jj]),str(self.data[13][ii][jj]),str(self.data[14][ii][jj]),str(self.data[15][ii][jj]),str(self.data[16][ii][jj]),str(self.data[17][ii][jj]),str(self.data[18][ii][jj]) ) )
def create_ew_list(self,name_add=''):
'''Write the equivalent widths into a single file'''
outfile='MgII_EW'+name_add
with open(outfile,'w') as of:
of.write( '#{:>25} {:>23} {:>20} {:>24} {:>25} {:>23} {:>23}\n'.format('Continuum','Continuum_err','Line','Line_err','EW','EW_err','z_est') )
for ii in range(len(self.data[0])):
for jj in range(len(self.data[0][ii])):
of.write( ' {:>25} {:>23} {:>20} {:>24} {:>25} {:>23} {:>23}\n'.format(str(self.data[3][ii][jj]),str(self.data[4][ii][jj]),str(self.data[5][ii][jj]),str(self.data[6][ii][jj]),str(self.data[7][ii][jj]),str(self.data[8][ii][jj]),str(self.data[9][ii][jj]) ))
outfile='Named_MgII_EW'+name_add
with open(outfile,'w') as of:
of.write( '#{:>30} {:>25} {:>23} {:>20} {:>24} {:>25} {:>23} {:>23}\n'.format('Name','Continuum','Continuum_err','Line','Line_err','EW','EW_err','z_est') )
for ii in range(len(self.data[0])):
for jj in range(len(self.data[0][ii])):
of.write( ' {:>30} {:>25} {:>23} {:>20} {:>24} {:>25} {:>23} {:>23}\n'.format(self.data[1][ii][jj],str(self.data[3][ii][jj]),str(self.data[4][ii][jj]),str(self.data[5][ii][jj]),str(self.data[6][ii][jj]),str(self.data[7][ii][jj]),str(self.data[8][ii][jj]),str(self.data[9][ii][jj]) ))
#$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$#
class Fit:
"""Contains models to be used in fitting, as well as the chi2 calculation, a method to produce errors on the fits, and methods to create figures"""
def __init__(self,fname='fit_flat_inv'):
self.fname=fname
self.fit_func = None
self.data = None
self.namelist=''
self.func= None
self.npars = None
self.par = None
self.pcov = None
self.Nspec = None
self.residuals = None
self.cor_coeff = None
self.chi2 = None
self.red_chi2 = None
##################################################################################
##Define possible functions to be used in fits
def fit_line(x,*p):
a = p
return np.array(a*x)
def fit_line_offset(x,*p):
a,b = p
return np.array(b+a*x)
def fit_pl4(x,*p):
x_k,a,b,c = p
xt = x/x_k
return np.power(xt,b)/(1+np.power(xt,a)) + np.power(xt,a+c)/(1+np.power(xt,a))
def fit_pl3(x,*p):
x_k,b,s = p
xt = x/x_k
return (xt+np.power(xt,b+s))/(1+np.power(xt,s))
def fit_pl2(x,*p):
x_k,b = p
xt = x/x_k
s = 4.
return (xt+np.power(xt,b+s))/(1+np.power(xt,s))
def fit_lin3(x,*p):
if len(p) != 1:
x_k,a,b = p
else:
x_k,a,b = p[0]
if type(x) == np.ndarray:
f = []
for el in x:
if el<x_k:
f+=[el*a]
else:
f+=[a*x_k+(el-x_k)*b]
else:
if x<x_k:
f=[x*a]
else:
f=[a*x_k+(x-x_k)*b]
return np.array(f)
def fit_lin2(x,*p):
if len(p) != 1: #This statement is required to properly deal with a difference in data format for the parameters when passed through different functions.
x_k,b=p
else:
x_k,b = p[0]
if type(x) == np.ndarray:
f = []
for el in x:
if el<x_k:
f+=[np.float(el)]
else:
f+=[np.float(x_k+(el-x_k)*b)]
else:
if x<x_k:
f=[np.float(x)]
else:
f=[np.float(x_k+(x-x_k)*b)]
return np.array(f)
def fit_pl_slopes(x,*p):
x_k, a, b, s = p
xt = x/x_k
return (np.power(xt,a)+np.power(xt,b+s))/(1+np.power(x,s))
def fit_flat(x,*p):
if len(p)!=1:
x_k,a = p
else:
x_k,a = p[0]
if type(x) == np.ndarray:
f = []
for el in x:
if el<x_k:
f+=[np.float(el*a)]
else:
f+=[np.float(x_k*a)]
else:
if x<x_k:
f = [np.float(x*a)]
else:
f = [np.float(x_k*a)]
return np.array(f)
def fit_flat_inv(x,*p):
if len(p)!=1:
y_s,a = p
else:
y_s,a = p[0]
if type(x) == np.ndarray:
f = []
for el in x:
if y_s > el*a:
f+=[np.float(el*a)]
else:
f+=[np.float(y_s)]
else:
if y_s > x*a:
f = [np.float(x*a)]
else:
f = [np.float(y_s)]
return np.array(f)
def fit_knee(x,x_k):
f = []
if type(x) == np.ndarray:
for el in x:
if el<x_k:
f+=[np.float(el)]
else:
f+=[np.float(x_k)]
else:
if x<x_k:
f+=[np.float(x)]
else:
f+=[np.float(x_k)]
return np.array(f)
##Dictionary containing the fitting functions, and the number of parameters required for each
func_list = dict([('fit_line',[fit_line,1]),('fit_line_offset',[fit_line_offset,2]),('fit_pl2',[fit_pl2,2]),('fit_pl3',[fit_pl3,3]),('fit_pl4',[fit_pl4,4]),('fit_lin2',[fit_lin2,2]),('fit_lin3',[fit_lin3,3]),('fit_pl_slopes',[fit_pl_slopes,4]),('fit_flat',[fit_flat,2]),('fit_flat_inv',[fit_flat_inv,2]),('fit_knee',[fit_knee,1])])
###################################################################################
def load_data(self,path_to_data,names=None):
"""Load data to be fitted. Argument of the function should be the full path to the data. If a list on names is included, it must have the same ordering as the columns of the data file"""
self.data = np.loadtxt(path_to_data)
if names:
self.namelist = np.loadtxt(names,usecols=0,dtype='str')
for ii in range(len(self.namelist)):
if self.namelist[ii][0]=='/': self.namelist[ii]=self.namelist[ii][1:]
for ii in reversed(range(len(self.data))):
if np.isnan(self.data[ii][2]) or np.isinf(self.data[ii][2]) or np.isnan(self.data[ii][3]) or np.isinf(self.data[ii][3]):
self.data = np.delete(self.data,ii,0)
if names: self.namelist=np.delete(self.namelist,ii,0)
self.Nspec = len(self.data)
self.data = self.data.T
def make_catalogue_file(self,catalogue,outfile='sample_catalogue_data',use_sdss_name=False):
'''Load the data from a quasar catalog file (format Shen et al. DR7), and store in a file. Note that all objects come in pairs, so one set of characteristics is required per pair of spectra.'''
try: hdu = fits.open(catalogue); T=hdu[1].data;
except: print 'Please specify the catalogue file (Shen et al DR7)'; return
spec_list = []
for ii in range(len(self.namelist)):
sp = self.namelist[ii].split('-')
spec_list += [(self.namelist[ii],sp[1],sp[2],sp[3][:-5],self.data[4][ii])]
spec_list = np.array(spec_list,dtype=[('name','S25'),('plate','int'),('mjd','int'),('fiber','int'),('z',float)])
D = []
m = 0
if use_sdss_name==False:
spec_list = np.sort(spec_list,order=['plate','mjd','fiber'])
print 'starting with copy'
for ii in range(len(T['plate'])):
D += [(T['plate'][ii],T['mjd'][ii],T['fiber'][ii],T['sdss_name'][ii],T['logl3000'][ii],T['loglbol'][ii],T['logbh'][ii],T['logedd_ratio'][ii],T['r_6cm_2500a'][ii],T['ew_mgii'][ii])]
print 'copied relevant columns'
T = np.array(D,dtype=[('plate','int'),('mjd','int'),('fiber','int'),('sdss_name','S25'),('logl3000',float),('loglbol',float),('logbh',float),('logedd_ratio',float),('r_6cm_2500a',float),('ew_mgii',float)])
del D; hdu.close()
print 'sorting rows'
T = np.sort(T,order=['plate','mjd','fiber'])
print 'sorted'
lc = []
start,jj=0,0
for obj in spec_list:
if jj%100==0:
print jj, obj['name']
jj+=1
if obj['mjd']>55000: continue
for ii in range(start,len(T['plate'])):
if T['plate'][ii]==obj['plate'] and T['fiber'][ii]==obj['fiber'] and T['mjd'][ii]==obj['mjd']:
start = ii
lc +=[[obj['name'],T['sdss_name'][ii],obj['z'],T['logl3000'][ii],T['loglbol'][ii],T['logbh'][ii],T['logedd_ratio'][ii],T['r_6cm_2500a'][ii],T['ew_mgii'][ii]]]
break
with open(outfile,'w') as of:
of.write('#{:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25}\n'.format('spec_name','sdss_name','z','logl3000','loglbol','logbh','logEdd','r_loud','ew_mgii'))
for r in lc:
of.write(' {:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25} {:>25}\n'.format(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8]))
def filter_data(self,delta=False,name_pair=False,norm_clean_max=False,norm_clean_min=False,rm_delsig=False):
"""Remove spectra with NaN values in their normalised fit results, as well as the spectra used for normalisation. Different keywords are used for different normalisations."""
self.data = self.data.T
N_spec = len(self.data)
nan_count = 0; del_lst =[]
if name_pair==True:
for ii in range(0,len(self.namelist)-1,2):
if int(self.namelist[ii].split('-')[2])<int(self.namelist[ii+1].split('-')[2]):
self.namelist[ii+1]=self.namelist[ii]
else:
self.namelist[ii]=self.namelist[ii+1]
#remove Nan
for ii in reversed(range(N_spec)):
if np.count_nonzero(np.isnan(self.data[ii]))!=0:
nan_count += 1
del_lst += [ii]
#Clean normalised data
if norm_clean_max==True:
for ii in range(len(self.data)):
if np.count_nonzero(np.isinf(self.data[ii]))!=0 or self.data[ii][0]<0.01 or self.data[ii][0]>1 or self.data[ii][2]<0 or self.data[ii][2]>2:
del_lst+=[ii]
elif norm_clean_min==True:
for ii in range(len(self.data)):
if np.count_nonzero(np.isinf(self.data[ii]))!=0 or self.data[ii][0]<1 or self.data[ii][0]>20 or self.data[ii][2]<0.0 or self.data[ii][2]>15:
del_lst+=[ii]
print 'Number of quality-removed spectra = {} out of {}'.format(nan_count,N_spec)
if rm_delsig==True:
for ii in range(len(self.data)):
if self.data[ii][8]==0: del_lst+=[ii]
#Remove objects with the same value of delta_t, and all entries normalised to one
if delta==True:
delta = self.data[0][6]
for ii in reversed(range(N_spec)):
if self.data[ii][6] == delta or self.data[ii][0]==1: del_lst+=[ii]
else: delta = self.data[ii][6]
else:
for ii in reversed(range(N_spec)):
if self.data[ii][0]==1.: del_lst+=[ii]
del_lst=np.unique(del_lst)
self.data = np.delete(self.data,del_lst,axis=0)
if len(self.namelist)!=0: self.namelist=np.delete(self.namelist,del_lst,axis=0)
self.Nspec = len(self.data)
print 'Number of spectra in final data-set = {}'.format(self.Nspec)
self.data = self.data.T
def find_spearman(self,prnt=False):
'''Calculate the p-value for t-statistic derived from the Spearman correlation coefficient'''
r1 = stat.rankdata(self.data[0])
r2 = stat.rankdata(self.data[2])
bn = len(self.data[0])
self.scc = 1 - 6./(bn*(bn*bn-1))*sum(np.power(r2-r1,2))
if prnt:
print 'Spearman correlation coefficient = {}'.format(self.scc)
def find_pearson_pval(self,prnt=False,in1=[],in2=[]):
'''Calculate the p-value for t-statistic derived from the Spearman correlation coefficient'''
if len(in1)==0: in1=self.data[0]
if len(in2)!=len(in1): in2=self.data[2]
a1 = np.average(in1); s1 = np.std(in1)
a2 = np.average(in2); s2 = np.std(in2)
cov = np.sum((in1-a1)*(in2-a2))/len(in1)
self.pcc = cov/(s1*s2)
TPcc = self.pcc*np.sqrt((len(in1)-2)/(1-self.pcc*self.pcc))
self.pcc_p = 2*stat.t.sf(TPcc, len(in1)-2)
if prnt:
print 'Pearson correlation coefficient = {}, with a p-value for the associated t-statistic of {}'.format(self.pcc,self.pcc_p)
def do_fit(self,**kwargs):
"""Call the scipy.optimize.curve_fit function, in combination with the preset fitting function and the loaded data to perform a fit on the data"""
self.fit_func, self.npars = self.func_list[self.fname]
self.par, self.pcov = [],[]
if 'fit_data' in kwargs:
fit_data = kwargs['fit_data']
else:
fit_data = self.data
if 'sig' in kwargs: sig=kwargs['sig']
else: sig = np.full(len(fit_data[0]),1)
if 'bnds' in kwargs:
self.par, self.pcov = curve_fit(self.fit_func,fit_data[0],fit_data[2],p0=np.full(self.npars,1),sigma=sig,bounds=kwargs['bnds'])
else: self.par, self.pcov = curve_fit(self.fit_func,fit_data[0],fit_data[2],p0=np.full(self.npars,1),sigma=sig)
def find_residuals(self,fit_data=[]):
'''Find the residuals with respect to the defined fitting function'''
if len(fit_data)==0: fit_data = self.data
self.residuals = fit_data[2]-self.fit_func(fit_data[0],*self.par)
def find_chi2(self,sig):
'''return chi^2 using the residuals of the fit. Requires the array of errors as input'''
try: len(self.residuals)
except: self.find_residuals()
self.chi2 = np.sum(np.power(self.residuals/sig,2))
self.red_chi2 = np.sum(np.power(self.residuals/sig,2))/(len(self.data[0])-len(self.par))
def sequence_test(self,inp_array=[],prnt=True):
if len(inp_array)==0: inp_array=self.residuals
S,D = 0,0
for ii in range(1,len(inp_array)):
if inp_array[ii-1]*inp_array[ii]>0:
S+=1
else: D+=1
pval=1-stat.binom_test([S,D],p=0.5)
if prnt==True: print 'Number of sequential data points = {}, number of different points = {}, with a p-value of {}'.format(S,D,pval)
return float(S),pval
def compare_models(self,fit_data=[],fname=['fit_line','fit_flat_inv'],prnt=True):
'''Fit two models to the data (iteratively) and calculate comparative goodness of fit statistics (delta chi2 and sequence test)\n
Note that for the initial fit, using the lmfit errors, all zeros are filtered out and replaced with an average error
NOTE: different use of 'sig' in fitting algorithm, to ensure the fits to be compared use the same errors (CHECK THIS)\n
fname needs to be an iterable containing the name(s) of the function(s) to be fitted'''
if len(fit_data)==0: fit_data=self.data
a = np.average(fit_data[3][np.where(fit_data[3]!=0)])
for jj in range(len(fit_data[3])):
if fit_data[3][jj]==0: fit_data[3][jj]=a
chi2,red_chi2,seq,residuals,pars,errs = [],[],[],[],[],[]
for ii in range(len(fname)):
self.fname = fname[ii]
self.do_fit(fit_data=fit_data,sig=fit_data[3])
self.find_residuals(fit_data=fit_data)
if 'sig' not in locals():
sig = np.full(len(self.residuals),np.std(self.residuals))
self.do_fit(fit_data=fit_data,sig=sig)
self.find_residuals(fit_data=fit_data)
self.find_chi2(sig=sig)
chi2 += [self.chi2]; red_chi2 += [self.red_chi2]
seq += [self.sequence_test(prnt=False)]
residuals += [self.residuals]; pars += [self.par]; errs += [np.sqrt(np.diag(self.pcov))]
if len(fname)!=1: d_chi2 = abs(chi2[0]-chi2[1])
else: d_chi2=0
if prnt==True:
print 'For the models {} and {}, the following test statistics apply:'.format(fname[0],fname[1])
print 'For {}, chi2 = {}; for {}, chi2 = {}'.format(fname[0],round(chi2[0],5),fname[1],round(chi2[1],5))
print 'Delta_chi2 = {}, with an associated p-value of {}'.format(round(d_chi2,5),round(stat.chi2.sf(d_chi2,1),3))
print 'For {}, p_s = {}; for {}, p_s = {}'.format(fname[0],round(seq[0][1],5),fname[1],round(seq[1][1],5))
for ii in range(len(seq)): seq[ii]=seq[ii][0]
return dict([('fname',fname),('d_chi2',d_chi2),('red_chi2',tuple(red_chi2)),('seq',tuple(seq)),('residuals',residuals),('parameters',pars),('fit_err',errs)])
def bootstrap_mc_cmp(self,fname=['fit_line','fit_flat_inv'],Nmc=10):
'''Repeat the model comparison on a bootstrapped sample of the data, repeating this Nmc times in a Monte Carlo experiment'''
indx = np.random.randint(0,len(self.data[0]),size=Nmc)
outp = []
for ii in range(Nmc):
masked_data = np.delete(self.data.T,indx[ii],axis=0).T
cm = self.compare_models(fit_data=masked_data,fname=fname,prnt=False)
outp_row = [cm['d_chi2']]
for jj in range(len(fname)): outp_row+=[cm['seq'][jj]]
outp += [outp_row]
outp = np.array(outp).T
a_chi2 = np.average(outp[0])
print 'Average Delta chi2 = {} (+-{}), giving a p-value of {}'.format(round(a_chi2,3),round(np.std(outp[1]),3),round(stat.chi2.sf(a_chi2,1),3))
for ii in range(len(fname)):
print 'For {}, average S={}+/-{}'.format(fname[ii],round(np.average(outp[1+ii]),2),round(np.std(outp[1+ii])))
def linregress_lvsc(self,val='con_line',sample='fps',lim=5):
'''Linear regression of either the log10(line) on the log10(continuum) fluxes, or of the log10(sigma) on the log10(continuum).'''
d_corr = 4*np.pi*np.power(cosmo.comoving_distance(self.data[4]).cgs.value*(1.+self.data[4]),2)
if val=='con_line':
X=np.log10(self.data[0]*d_corr*2798)#; Xerr=self.data[13]*d_corr*2798*np.log10(np.e)/self.data[0]
Y=np.log10(self.data[2]*d_corr); Yerr=self.data[15]*d_corr*np.log10(np.e)/self.data[2]
elif val=='con_sig':
X=np.log10(self.data[0]*d_corr*2798)#; Xerr=self.data[13]*d_corr*2798*np.log10(np.e)/self.data[0]
Y=np.log10(self.data[8]/(1+self.data[4])); Yerr=self.data[15]/(1+self.data[4])*np.log10(np.e)/self.data[8]
dX,dY,dYerr=[],[],[]
if sample=='fps':#Full Population sample data format
print 'sample=fps: assuming all objects come in pairs'
for ii in range(0,len(self.data[0]),2):
dx=X[ii+1]-X[ii]
if abs(dx)>lim: continue
dy=Y[ii+1]-Y[ii]
if abs(dy)>lim: continue
dX+=[dx]; dY+=[dy]; dYerr+=[np.sqrt(Yerr[ii]*Yerr[ii]+Yerr[ii+1]*Yerr[ii+1])]
elif sample=='svs':#Supervariable sample data format
for ii in reversed(range(1,len(self.namelist))):
if self.namelist[ii]==self.namelist[ii-1]:
dx=X[ii+1]-X[ii]
if abs(dx)>lim: continue
dy=Y[ii+1]-Y[ii]
if abs(dy)>lim: continue
dX+=[dx]; dY+=[dy]; dYerr+=[np.sqrt(Yerr[ii]*Yerr[ii]+Yerr[ii+1]*Yerr[ii+1])]
else: print 'please select a correct sample name'; return
dx=X[1]-X[0]; dy=Y[1]-Y[0]
if abs(dx)>lim and abs(dy)>lim: dX+=[dx]; dY+=[dy]; dYerr+=[np.sqrt(Yerr[0]*Yerr[0]+Yerr[1]*Yerr[1])]
dX=np.array(dX); dY=np.array(dY); dYerr=np.array(dYerr)
dY=dY[np.isnan(dX)==0]
dYerr=dYerr[np.isnan(dX)==0]
dX=dX[np.isnan(dX)==0]
dX=dX[np.isnan(dY)==0]
dYerr=dYerr[np.isnan(dY)==0]
dY=dY[np.isnan(dY)==0]
dY=dY[np.isinf(dX)==0]
dYerr=dYerr[np.isinf(dX)==0]
dX=dX[np.isinf(dX)==0]
dX=dX[np.isinf(dY)==0]
dYerr=dYerr[np.isinf(dY)==0]
dY=dY[np.isinf(dY)==0]
print len(X),len(Y),len(Yerr)
print len(dX),len(dY),len(dYerr)
print np.amin(dX),np.amax(dX)
print np.amin(dY),np.amax(dY)
a = stat.linregress(dX,dY)
self.fname='fit_line'
self.fit_func, self.npars = self.func_list[self.fname]
self.par, self.pcov = curve_fit(self.fit_func,dX,dY,p0=np.full(self.npars,1))
print a
print self.par,self.pcov
def create_figure(self,fig_type='residuals',saveloc='Figures/',name='MgII_figure.pdf',s7_data='False',catalogue_file=None,cat_cmp='',fit_data=[],mod_cmp=[],lims=[0,1.05,0,1.75],nbins=30,nbins_sub=10,zbins=[.5,1,1.5,5],dtbins=[3,5,7,9],levels_pct=[.25,.5,.75,.9,.95],dt_rng=None,boxs=None,additional_data=[],contours=False,xlog=False,ylog=False,log_counts=False,rm_lims=((-100,100),),lum=None,cmap='RdBu',absval=False,rm_cat=False, clq_namelist=None ):
'''Create the figures; the figure type is selected with the keyword 'fig_type'. The following is list of the available types.\n
-1- residuals: linear fits to the data (of the Supervariable sample) and the residuals (F5&6)\n
-2- lum_overview: change in line luminosity plotted against change in continuum luminosity. Required file format: C Ce L Le z z_sdss dt S/N dC dCe dL dL, where the Continuum (C) is measured at 2798 AA (F4)\n
-3- dt_histogram: histogram of the Delta t values in the sample(s) (F1)\n
-3- colourmap: 2D histogram of normalised line and continuum fluxes (F5&6)\n
-4- dtbin_colourmap: four panels containing the same histograms as 'colourmap', split by Delta t (F12)\n
-5- subsample_catalogue: sample distribution of Lbol,Mbh, and Eddington ratio, based on subsections in normalised flux space (F20)\n
-6- response_catalogue: sample distribution of Lbol,Mbh, and Eddington ratio, based on the values of alpha_rm (F21)\n
-7- flux_vs_dt: create subsamples based on Delta t of the relative change in flux (F13)\n
-8- continuum_vs_dt: as flux_vs_dt for continuum flux levels\n
-9- response_metric_hist: histogram of alpha_rm (F7)\n
-10- cmp_clq: compare CLQ and non-CLQ identifications in the Supervariable sample (F8)\n
-11- del_sigma_hist: histogram of Delta sigma (F14)\n
-12- sig_vs_con: plot sigma against the continuum flux in a 2D histogram\n
-13- delsig_vs_delcon: plot Delta sigma against Delta f_c in a 2D histogram\n
-14- sig_vs_line: plot sigma against the line flux (F16)\n
-15- delsig_vs_delline: plot Delta sigma against Delta f_MgII (F15)\n
-16- cvsf_individual: plot the normalised line flux against the normalised continuum for J022556 (F10)\n
-17- ew_histogram: histogram of Equivalent Widths (F11)\n
-18- lzedd: Lbol plotted against redshift, colour-coded by Eddinton ratio (F19)\n
'''