-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodel_analysis.py
executable file
·1508 lines (1275 loc) · 53.5 KB
/
model_analysis.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
"""
model_analysis.py
Author: Nathanael Lampe, Monash University
Date Created: 19/7/2013 (Anniversary of the moon landing, woohoo)
Purpose:
To recode old IDL routines that took KEPLER models and produced mean
lightcurves and burst parameters.
Changelog:
Modified in August 2016 by NL to
- Add compatibility with lmfit >v0.9
- Migrate to four space tabs and improve PEP8 compliance for code linters
Modified in July 2016 by LK to
- remove obsolete routines
- load from binary files
- add a 'qb' array to the keyTable
- refactored code to be object oriented
"""
from __future__ import division, unicode_literals, print_function
import numpy as np
from scipy.interpolate import interp1d
from copy import deepcopy
from lmfit import minimize, Parameters
import bottleneck as bn
import os
import logging
np.seterr(divide='raise', over='warn', under='warn', invalid='raise')
###############################################################################
###############################################################################
# #
# ANALYSIS SUBROUTINES #
# #
###############################################################################
###############################################################################
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~FITTING BURST TAILS~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def fitTail(time, lumin, dlumin, params, method='power'):
'''
Fit a function to the burst tail
params, fitData = fitTail(time, lumin, method='power')
=============================================================================
args:
-----
time: array of times in burst tail
lumin: array of luminositiws through burst tail
dlumin: array of luminosity uncertainties
params: lmfit.Parameters object specifying parameters [Note 1]
kwargs:
-----
method: type of function to fit, options are
'power': fit a power law like in [1]
'exp1': fit a single exponential [1]
'exp2': fit a double exponential (not implemented)
returns:
-----
params: lmfit.Parameters object with fit parameters
fitData: dictionary with fit statistics
=============================================================================
Notes:
1. The lmfit.Parameters class object specifies parameter values and bounds.
The parameters it needs to specify vary depending on the fitting
method,
-----
exp1 lmfit.parameters Object contains [F0, t0, tau, Fp]
F0 = initial flux
t0 = time shift
tau = time constant
Fp = persistent emission
-----
power lmfit.Parameters Object contains [F0, t0, ts, al, Fp]
F0 = initial flux
t0 = time shift (decay starts)
ts = time shift (burst starts)
al = power law exponent
Fp = persistent emission
-----
=============================================================================
Changelog:
Created 22-11-2013
26-11-2013: Added single tail and power law functions, work on chi-square
minimisation
18-02-2014: Added fit statistics to be returned as a dictionary
03-03-2014: Fit from 90% to 10% in the tail, rather than be adaptive.
=============================================================================
References:
[1] in't Zand et al., The cooling rate of neutron stars after thermonuclear
shell flashes, A&A (submitted 2013)
'''
# opening assertions
assert len(time) == len(lumin), 'time and lumin should be same length'
assert np.ndim(time) == 1, 'time & lumin should be 1-d'
assert method in ['power', 'exp1', 'exp2'], 'method kwarg invalid'
# copy arrays
time = deepcopy(np.asarray(time))
lumin = deepcopy(np.asarray(lumin))
dlumin = deepcopy(np.asarray(dlumin))
def exp1(t, p):
'''
Single Tail Exponential
exp1(t, params)
===========================================================================
args:
-----
t: 1-d array of burst times
p: lmfit.parameters Object [F0, t0, tau, Fp]
F0 = initial flux
t0 = time shift
tau = time constant
Fp = persistent emission
returns:
-----
1-D array of burst luminosities as predicted by a single tail
exponential with parameters set by params in p
'''
F0 = p['F0'].value
t0 = p['t0'].value
tau = p['tau'].value
Fp = p['Fp'].value
return F0*np.exp(-(t-t0)/tau) + Fp
def power(t, p):
'''
Power Law
power(t, params)
===========================================================================
args:
-----
t: 1-d array of burst times
p: lmfit.Parameters Object with [F0, t0, ts, al, Fp]
F0 = initial flux
t0 = time shift (decay starts)
ts = time shift (burst starts)
al = power law exponent
Fp = persistent emission
returns:
-----
1-D array of burst luminosities as predicted by a power law
with parameters set by params in p
'''
F0 = p['F0'].value
t0 = p['t0'].value
ts = p['ts'].value
al = p['al'].value
Fp = p['Fp'].value
return F0*((t-ts)/(t0-ts))**(-1.0*al) + Fp
msg = 'Two tail exponential not available yet'
if method == 'power':
f = power
elif method == 'exp1':
f = exp1
elif method == 'exp2':
raise NotImplementedError(msg)
else:
raise SystemError('Method kwarg incorrect')
def minFunc(p, t, l, dl, f):
'''
Minimisation Function
'''
lm = f(t, p)
csq = ((l - lm)/dl)
return csq
result = minimize(minFunc, params, args=(time, lumin, dlumin, f),
method='leastsq')
fitData = {'nfev': result.nfev, # number of function evaluations
'success': result.success, # boolean for fit success
'errorbars': result.errorbars, # boolean, errors were estimated
'message': result.message, # message about fit success.
'ier': result.ier, # int error value from sp.optimize.leastsq
'lmdif_message': result.lmdif_message, # from sp.opt.leastsq
'nvarys': result.nvarys, # number of variables in fit
'ndata': result.ndata, # number of data points
'nfree': result.nfree, # degrees of freedom in fit
'residual': result.residual, # residual array /return of func()
'chisqr': result.chisqr, # chi-square
'redchi': result.redchi} # reduced chi-square
return result.params, fitData
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Fitting routine ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def burstFits(mt, ml, pt, mdl=None):
'''
Conduct a least squares minimisation of a power law and single tail
exponential on a thermonuclear burst tail
pParams,pData,eParams,eData = burstFits(mt, ml, pt, mdl = None)
=============================================================================
args:
-----
mt: Tail time (since burst start, not from tail start)
ml: Tail luminosity
pt: Time of burst Peak
kwargs:
-----
mdl: Optionally weight the points by uncertainty (chi-square minimisation)
if None, assume uniform weights
returns:
-----
pParams: lmfit.Parameters object with power law fit final parameters
pData: dictionary with fit statistics for pLaw fit
eParams: lmfit.Parameters object with exponential fit final parameters
eData: dictionary with fit statistics for exp law fit
In both cases, pp['rcs']
=============================================================================
Notes:
Conducts fits to burst tails following In't Zand et al, A&A 562 A16 (2014),
except fit from 0.90Fpeak to 0.10Fpeak, rather than adaptively choose where
to start fitting.
'''
peakTime = bn.nanargmax(mt > pt)
peakLum = ml[peakTime]
persLum = ml[0]/peakLum # (scaled persLum)
# rescaling, by 1/peakLum, and set equal weights if mdl == None
if mdl is None:
t = mt[peakTime:]
l = ml[peakTime:]/peakLum
dl = np.ones_like(t)
else:
# remove artificially low uncertainties
ok = np.nonzero((mdl > 1e35) & (mt > 0))[0]
t = mt[ok]
l = ml[ok]/peakLum
dl = mdl[ok]/peakLum
# find t90, t10
n = len(l)
# last occurence crossing 0.1Lpeak (note >)
t10Ind = n - bn.nanargmax(l[::-1] > 0.1)
# find last point where we have 0.9Lpeak (note >=)
t90Ind = n - bn.nanargmax(l[::-1] >= 0.9)
t0 = t[t90Ind]
tFit = t[t90Ind:t10Ind]
lFit = l[t90Ind:t10Ind]
dlFit = dl[t90Ind:t10Ind]
p = Parameters()
p.add('F0', value=1., vary=True)
p.add('t0', value=t0, vary=False)
p.add('ts', value=-1, vary=True, min=-10, max=t0)
p.add('al', value=1.4, vary=True, min=0)
p.add('Fp', value=persLum, vary=True, min=0., max=1.)
pParams, pData = fitTail(tFit, lFit, dlFit, p, method='power')
p = Parameters()
p.add('F0', value=1., vary=True)
p.add('t0', value=t0, vary=False)
p.add('tau', value=10, vary=True, min=0)
p.add('Fp', value=persLum, vary=True, min=0., max=1.)
eParams, eData = fitTail(tFit, lFit, dlFit, p, method='exp1')
# rescale back
for i in (pParams['F0'], pParams['Fp'], eParams['F0'], eParams['Fp']):
if i.value != 0:
i.value = i.value*peakLum
if i.stderr != 0:
i.stderr = i.value*peakLum
return pParams, pData, eParams, eData
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~RISE TIMES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def findAtRiseFrac(time, lumin, peakLum, persLum, frac):
'''
findAtRiseFrac(time, lumin, peakLum, persLum, frac)
args:
time: 1-d array of burst rise times
lumin: 1-d array of burst rise luminosities
peakLum: peak luminosity
persLum: persistent luminosity
frac: fraction of peak luminsoity to find time at
return:
float, time at which burst reaches frac*(peakLum-persLum)
A function to find the time a burst reaches a certain luminosity as
a fraction of the peak luminosity, screening out spurious results from
convective shocks.
Created November 15, 2013
'''
time = np.asarray(deepcopy(time))
lumin = np.asarray(deepcopy(lumin))
lumin -= persLum
peakLum -= persLum
fracLum = frac*peakLum
# find candidates where we cross the required Lumfrac
greater = lumin > fracLum
cross = greater - np.roll(greater, 1)
cands = np.nonzero(cross[1:])[0] + 1 # candidates to cross fracLum
avgBurstGrad = (lumin[-1]-lumin[0])/(time[-1]-time[0])
grads = (lumin[cands]-lumin[cands-1])/(time[cands]-time[cands-1])
# exclude -ve gradients (added apr-03-2014)
for ii in xrange(len(grads)):
if grads[ii] < 0:
grads[ii] = np.Inf
# calculate gradient by back-step FD, rather than central diff
candGrads = zip(cands, grads)
candGrads.sort(key=lambda x: x[1]) # sort by gradient
best = candGrads[0][0] # Most likely candidate has lowest gradient
# Now interpolate for more precision
interpTimes = np.linspace(time[best-1], time[best+1], 2**6)
lumInterp = interp1d(time, lumin, kind='linear', copy=True)
interpLums = lumInterp(interpTimes)
interpBest = bn.nanargmax(interpLums > fracLum)
return interpTimes[interpBest]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~SMOOTHING LIGHTCURVES~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def smooth(t, f, r, tmin):
'''
newt, newf, newr = smooth(t,f,r,tmin)
args:
t = 1-D array of times
f = 1-D array of fluxes
r = 1-D array of radii
tmin = float, new minimum time bin size
returns:
newt = smoothed t values
newf = smoothed f values
newr = smoothed r values
A routine to take a lightcurve and return a new lightcurve that averages
over variations that last less than tmin.
Specifically designed to be used on lightcurves that show large shocks e.g.
model a6. In these cases, a number of millisecond shocks cause large
increases in stellar luminosity due to a convective layer reaching the
stellar surface. These are too small to typically be observed, and boggle
the analysis routine that tries to identify peak luminosities
'''
# some simple asseritons
assert len(t) == len(r) and len(t) == len(f),\
'''t,r,f should be the same shape'''
assert len(np.shape(t)) == 1, '''t should be 1-D'''
# set up lists, loops
ii = 0
newt = []
newf = []
newr = []
dt = t - np.roll(t, 1)
n = len(t)
while ii < n:
if dt[ii] > tmin:
# case 1: bigger timestep than tmin
newt.append(t[ii])
newf.append(f[ii])
newr.append(r[ii])
ii += 1
elif dt[ii] < 0:
# case 2: first timestep will have dt<0
newt.append(t[ii])
newf.append(f[ii])
newr.append(r[ii])
ii += 1
else:
# case 3: smaller timesteps than tmin
tStart = ii
tStop = max(tStart, np.argmax(t > (t[ii] + tmin)))
if (tStop != tStart) and tStop != n:
# 3a: not at the EOF
newt.append(t[ii]+tmin/2.)
avgf = sum(f[tStart:tStop]*dt[tStart+1:tStop+1])/(t[tStop]-t[tStart]) # NOQA
avgr = sum(r[tStart:tStop]*dt[tStart+1:tStop+1])/(t[tStop]-t[tStart]) # NOQA
newf.append(avgf)
newr.append(avgr)
ii = tStop
elif (tStop != tStart):
# 3b found the EOF, average to EOF
tStop = n-1
newt.append((t[tStart] + t[tStop]) / 2.)
avgf = sum(f[tStart:tStop]*dt[tStart+1:tStop+1])/(t[tStop]-t[tStart]) # NOQA
avgr = sum(r[tStart:tStop]*dt[tStart+1:tStop+1])/(t[tStop]-t[tStart]) # NOQA
newf.append(avgf)
newr.append(avgr)
ii = n
else:
ii = n # Forget about the last lonely point
return np.array(newt), np.array(newf), np.array(newr)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Shock Checking~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def isShock(times, fluxes, index):
'''
isShock(times, fluxes, index)
args:
times = 1-d array of times
fluxes = 1-d array of fluxes
index = int, index to check
returns:
True if index is a shock
False if index is not a shock
used to identify shocks in the burst rise, so they are not treated as a
maximum by the analysis routine
shocks appear in the rise due to a convective zone hitting the surface of
the neutron star atmosphere, causing a swelling in luminosity. They are
not usually observable as burning as not usually spherically symmetric, and
they have a very short duration
'''
# some assertions
assert len(np.shape(times)) == 1, ''' times should be 1-d'''
assert index == np.int_(index), '''index should be type int'''
assert np.shape(times) == np.shape(fluxes), '''times and fluxes should have
the same shape'''
# shocks do not change the luminosity much either side of the shock, but
# are vastly different to the shock
# get indices for +/- 0.05s from shock
justPrev = bn.nanargmax(times > (times[index] - 0.02))
if justPrev == index:
justPrev -= 1
justAfter = bn.nanargmax(times > (times[index] + 0.02))
if justAfter == index:
justAfter += 1
if ((fluxes[justPrev]/fluxes[index] > 0.8) or
(fluxes[justAfter]/fluxes[index] > 0.8)):
# we have no shock, as the values either side of this point suggest
# a flat top, or is a step
if fluxes[index+1] < 0.95*fluxes[index]:
# extra little routine to pick up shocks near the burst peak
shock = True
else:
shock = False
else:
shock = True
return shock
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Simpson's Rule~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def simprule(a, b, c, dt):
'''
simprule(a,b,c,dt)
evaluate the area underneath three points by Simpson's Rule
the three points ought to be equally spaced, with b being the midpoint
the inputs a,b,and c are f(start), f(mid) and f(end) respectively,
dt is the spacing
Thus, Simpson's rule becomes here: area=([c-a]/6)(f(a)+4f(b)+f(c))
'''
return (a + 4.0*b + c)*dt/6.0
# ~~~~~~~~~~~~~~~~~~~~~~~~~~Check Local Maximum~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def isMaximum(a, b, c):
'''
Small routine to check if point b is a local maximum
'''
if b > a and b > c:
return True
else:
return False
###############################################################################
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Convexity~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
###############################################################################
def convexity(time, lumin, peakLum, persLum):
'''
convexity(time, lumin, peakLum, persLum)
args:
time: 1-d array of times (burst rise)
lumin: 1-d array of luminosities
peakLum: peak luminosity of the burst
persLum: persistent luminosity of the burst
returns:
convexity parameter according to [1] as a float
calculate the convexity of a thermonuclear burst from the burst rise
This algorithm will flip out if you use a whole burst.
References:
[1] Maurer and Watts (2008), MNRAS, 383, p387
'''
time = np.asarray(deepcopy(time))
lumin = np.asarray(deepcopy(lumin))
lumin -= persLum
peakLum -= persLum # correct for persistent luminosity
n = len(lumin)
gt10 = lumin > 0.1*peakLum
ten = (n) - bn.nanargmin(gt10[::-1])
gt90 = lumin > 0.9*peakLum
ninety = (n) - bn.nanargmin(gt90[::-1])
# for 10%
fa = 0.1*peakLum
m = (lumin[ten] - lumin[ten-1])/(time[ten] - time[ten-1])
ta = time[ten-1] + (fa - lumin[ten-1])/m
# for 90%
fb = 0.9*peakLum
m = (lumin[ninety] - lumin[ninety-1])/(time[ninety] - time[ninety-1])
tb = time[ninety-1] + (fb - lumin[ninety-1])/m
t = np.concatenate(([ta], time[ten:ninety], [tb]))
l = np.concatenate(([fa], lumin[ten:ninety], [fb]))
lRange = np.max(l) - np.min(l)
if lRange != 0:
t -= t[0]
l -= l[0]
lastl = l[-1]
lastt = t[-1]
t *= (10./lastt)
l *= (10./lastl)
c = 0
for ii in xrange(1, len(t)):
c += 0.5*((l[ii] + l[ii-1]) - (t[ii] + t[ii-1]))*(t[ii] - t[ii-1])
return c
else:
return 0
###############################################################################
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~LC Averaging~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
###############################################################################
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Average to key burst~~~~~~~~~~~~~~~~~~~~~~~~~~ #
def avgParams(times, lums, rads):
'''
sumParams(times, lums, rads)
each paramater is a list of arrays to be averaged
Arrays are averaged to the burst with the latest finishing time
'''
n = len(times)
if n == 1:
dl = np.zeros(len(times[0]))
dr = np.zeros(len(times[0]))
t = times[0]
l = lums[0]
r = rads[0]
elif n == 2:
lens = map(max, times)
if lens[1] > lens[0]:
# Average using longer array
times.reverse()
lums.reverse()
rads.reverse()
t = times[0]
# l = 0.5*lums[0]
# r = 0.5*rads[0]
interpLum = interp1d(times[1], lums[1], fill_value=np.nan,
bounds_error=False)
interpRad = interp1d(times[1], rads[1], fill_value=np.nan,
bounds_error=False)
l = np.nanmean([lums[0], interpLum(t)], axis=0) # 0.5*interpLum(t)
r = np.nanmean([rads[0], interpRad(t)], axis=0) # 0.5*interpRad(t)
dl = np.zeros(len(t))
dr = np.zeros(len(t))
elif n >= 3:
# exclude first burst, interpolate along 2, then average
times = times[1:]
lums = lums[1:]
rads = rads[1:]
lengths = map(max, times[1:])
longest = np.argmax(lengths) + 1
t = times[longest]
interpolatedLums = [lums[longest]]
interpolatedRads = [rads[longest]]
for ii in range(0, n-1):
if ii != longest:
interpLum = interp1d(times[ii], lums[ii], fill_value=np.nan,
bounds_error=False)
interpRad = interp1d(times[ii], rads[ii], fill_value=np.nan,
bounds_error=False)
interpolatedLums.append(interpLum(t))
interpolatedRads.append(interpRad(t))
interpolatedLums = np.asarray(interpolatedLums, dtype=np.float64)
interpolatedRads = np.asarray(interpolatedRads, dtype=np.float64)
# can we do some outlier analysis here to remove shocks in the rise?
# a question for later analyses.
l = np.nanmean(interpolatedLums, axis=0)
r = np.nanmean(interpolatedRads, axis=0)
dl = np.nanstd(interpolatedLums, axis=0, ddof=0)
dr = np.nanstd(interpolatedRads, axis=0, ddof=0)
# now remove any sneaky NaN's that have gotten through
# shouldn't have to do this, but apparently I do.
# NaN's may arise from every column in interpolatedLums being NaN, but
# we shouldn't interpolate here
bad_dl = np.isnan(dl)
bad_dr = np.isnan(dr)
ok = np.logical_not(np.logical_or(bad_dl, bad_dr))
t = t[ok]
l = l[ok]
r = r[ok]
dl = dl[ok]
dr = dr[ok]
# There will still be spots where dl=0 (std of one value) but now
# there are no NaN's!!
return t, l, r, dl, dr
# ~~~~~~~~~~~~~~~~~~~~~~~~~Average to fixed interval~~~~~~~~~~~~~~~~~~~~~~~~~ #
def intervalAvg(times, lums, rads, interval=0.125):
'''
Average burst LC's onto a grid with a fixed observation interval
sumParams(times, lums, rads, interval = 0.125)
=============================================================================
args
-----
times: list containing times for each burst
lums: list containing luiminosities for each burst
rads: list containing radii for each burst
kwargs:
-----
interval: time resolution
returns:
-----
t, l, r, dl, dr
t: time
l: mean luminosity
r: mean radius
dl: 1-sigma error in luminosity
dr: 1-sigma error in radius
============================================================================
Notes:
This routine considers that observations integrate across 0.125s intervals
in x-ray detectors.
Hence, rather than binning to the model resolution, we consider integrating
the observed flux in fixed width bins. This defaults to 0.125s, as this is
the finest bin-width commonly encountered
============================================================================
Changelog:
Created 25-11-2013 from avgParams
'''
def interp(times, lums, rads, interval):
'''
Call this routine in multi-burst averaging
'''
# make new time array
minTime = min([t[0] for t in times])
maxTime = max([t[-1] for t in times])
posTime = np.arange(0, maxTime, interval)
negTime = np.arange(-1*interval, minTime, -1*interval)
newTime = np.concatenate((negTime[::-1], posTime))
# now we integrate across each bin
newL = []
newR = []
for (t, l, r) in zip(times, lums, rads):
newl = [] # define lists for new burst
newr = []
for tBin in newTime:
# tbin is the bin midpoint for integration
mint = tBin - interval/2
maxt = tBin + interval/2
goodIndex = np.nonzero(np.logical_and(t > mint, t < maxt))[0]
if len(goodIndex) > 1:
mni = goodIndex[0]
mxi = goodIndex[-1]
try:
# if the points all exist, integrate
# startpoints
l0 = l[mni-1] + (l[mni]-l[mni-1])/(t[mni]-t[mni-1])*(mint-t[mni-1]) # NOQA
r0 = r[mni-1] + (r[mni]-r[mni-1])/(t[mni]-t[mni-1])*(mint-t[mni-1]) # NOQA
# first trapezoid
ll = 0.5*(l[mni]+l0)*(t[mni]-mint)
rr = 0.5*(r[mni]+r0)*(t[mni]-mint)
# middle trapezoids
for ind in goodIndex[1:]:
ll += 0.5*(l[ind]+l[ind-1])*(t[ind]-t[ind-1])
rr += 0.5*(r[ind]+r[ind-1])*(t[ind]-t[ind-1])
# endpoints
lf = l[mxi] + (l[mxi+1]-l[mxi])/(t[mxi+1]-t[mxi])*(maxt-t[mxi]) # NOQA
rf = r[mxi] + (r[mxi+1]-r[mxi])/(t[mxi+1]-t[mxi])*(maxt-t[mxi]) # NOQA
# last trapezoid
ll += 0.5*(l[mxi+1]+lf)*(maxt-t[mxi])
rr += 0.5*(r[mxi+1]+rf)*(maxt-t[mxi])
# normalise
ll /= interval
rr /= interval
except IndexError:
ll = np.NaN
rr = np.NaN
elif len(goodIndex) in [1]:
ll = l[goodIndex[0]]
rr = r[goodIndex[0]]
else:
idx = bn.nanargmax(t > tBin)
if idx != 0:
ll = l[idx-1] + (l[idx]-l[idx-1])/(t[idx]-t[idx-1])*(tBin-t[idx-1]) # NOQA
rr = r[idx-1] + (r[idx]-r[idx-1])/(t[idx]-t[idx-1])*(tBin-t[idx-1]) # NOQA
else:
ll = np.NaN
rr = np.NaN
newl.append(ll)
newr.append(rr)
newL.append(np.array(newl))
newR.append(np.array(newr))
# and now take averages. Hooray
t = newTime
l = np.nanmean(np.asarray(newL), axis=0)
r = np.nanmean(np.asarray(newR), axis=0)
dl = np.nanstd(np.asarray(newL), axis=0, ddof=0)
dr = np.nanstd(np.asarray(newR), axis=0, ddof=0)
# now remove any sneaky NaN's that have gotten through
# NaN's may arise from every column in interpolatedLums being NaN, but
# we shouldn't interpolate here
bad_dl = np.isnan(dl)
bad_dr = np.isnan(dr)
ok = np.logical_not(np.logical_or(bad_dl, bad_dr))
t = t[ok]
l = l[ok]
r = r[ok]
dl = dl[ok]
dr = dr[ok]
# There will still be spots where dl=0 (std of one value) but now there
# are no NaN's!!
return t, l, r, dl, dr
# Commence routine
n = len(times)
if n == 1:
# cannot really perform an average
dl = np.zeros(len(times[0]))
dr = np.zeros(len(times[0]))
t = times[0]
l = lums[0]
r = rads[0]
elif n == 2:
# Average second burst with first
t, l, r, dl, dr = interp(times, lums, rads, interval)
elif n >= 3:
# average bursts from second onwards
t, l, r, dl, dr = interp(times[1:], lums[1:], rads[1:], interval)
return t, l, r, dl, dr
###############################################################################
###############################################################################
# #
# INDIVIDUAL BURST SEPARATION #
# #
###############################################################################
###############################################################################
def separate(burstTime, burstLum, burstRad, modelID, outputDirectory):
'''
separate(bursttime, burstflux, burstrad, modelID, outputDirectory)
This program is designed to separate the bursts in the models into
individual burst files for subsequent analysis. It will take the delta t
value's for each burst
Individual burst files do not have the persistent luminosity subtracted
'''
print('SEPARATING '+str(modelID))
beginTimeBackJump = 20 # seconds before burst to start recording
peakTimeBackLook = 0.3 # look for the peak in a 5 second range
peakTimeForwardLook = 5.0 # look forward 5s, and back less
tim = np.asarray(burstTime, dtype=np.float64)
lum = np.asarray(burstLum, dtype=np.float64)
rad = np.asarray(burstRad, dtype=np.float64)
minFlux = 1.e36
# ANALYSIS
jj = bn.nanargmax(tim > beginTimeBackJump) + 1
startTime = np.argmax(tim > peakTimeBackLook)
tDel = [0]
alpha = [0]
peakTime = []
peakLum = []
peakIndex = []
persLum = []
startIndex = []
endIndex = []
startTimes = []
endTimes = []
fluences = []
convexities = []
t10 = []
t25 = []
t90 = []
tBurst = []
burstLums = []
burstTims = []
burstRads = []
fitAlpha = []
fitDecay = []
upTurns = []
while jj < len(tim)-200:
# There should be a burst if point is a maximum in +/- peakTimeWindow
# seconds and is 10 times more luminous than 20s ago
minTimeIndex = bn.nanargmax(tim > (tim[jj]-peakTimeBackLook))
maxTimeIndex = bn.nanargmax(tim > (tim[jj]+peakTimeForwardLook))
if maxTimeIndex == 0:
break # near end of file
nbhd = lum[minTimeIndex:maxTimeIndex+1]
tnbhd = tim[minTimeIndex:maxTimeIndex+1]
endBurst = False
if (lum[jj] > minFlux) & (lum[jj] == max(nbhd)):
midIndex = jj - minTimeIndex
persLumCompare =\
lum[bn.nanargmax(tim > (tim[jj]-beginTimeBackJump))]
if lum[jj] > 10*persLumCompare and not isShock(tnbhd, nbhd, midIndex): # NOQA
# We have identified a burst now
# conditions to screen for weird bursts
if jj >= len(tim):
break
if lum[jj] > 10*lum[jj-1] and lum[jj] > 10*lum[jj+1]:
break
beginIndex = jj
recordStartIndex = np.argmax(tim > (tim[beginIndex] -
beginTimeBackJump)) - 1
currentPersLum = lum[recordStartIndex]
endFlux = currentPersLum + 0.02*(lum[jj]-currentPersLum)
jj = bn.nanargmax(tim > (tim[beginIndex] + 10))
# minimum burst duration is 10 seconds
critGrad = 0.01*(lum[jj] - currentPersLum)/10
upTurn = False
while lum[jj] >= endFlux:
if jj < len(tim)-1:
jj += 1
else:
print('<seperate> Beware: peak at end of data set')
print('<seperate> not analysing this peak, as it is' +
' incomplete')
print(
'<seperate> %s other peak(s) found' % len(peakLum))
jj = -1
endBurst = True
break
if (tim[jj] - tim[beginIndex]) > 20:
# on long bursts, consider ending at local minima
tenSecAgo = bn.nanargmax(tim > (tim[jj] - 10))
if (lum[jj] - lum[tenSecAgo])/10. > critGrad:
# Check we aren't in a persistent rise
# This essentially checks we can fit a decay curve
# But also, if the burst is crazy bright still,
# probably not
# in the upturn
if lum[jj] < 0.8*lum[beginIndex]:
# check for +ve gradient
upTurn = True
print('UpTurn has occurred at' +
'{0:.2f}'.format(tim[jj]))
break
if endBurst is True:
break
stopIndex = jj
currentPeakLum = lum[beginIndex]
currentPersLum = lum[recordStartIndex]
# store the time of the peak in structure
peakTime.append(tim[beginIndex])
peakIndex.append(beginIndex)
startIndex.append(recordStartIndex)
startTimes.append(tim[recordStartIndex])
peakLum.append(currentPeakLum)
persLum.append(currentPersLum)
endIndex.append(stopIndex)
endTimes.append(tim[stopIndex])
burstRiseTimes = tim[recordStartIndex:beginIndex+2]
burstRiseLums = lum[recordStartIndex:beginIndex+2]
t10.append(findAtRiseFrac(burstRiseTimes, burstRiseLums,
currentPeakLum, currentPersLum, .10) - peakTime[-1])
t25.append(findAtRiseFrac(burstRiseTimes, burstRiseLums,
currentPeakLum, currentPersLum, .25) - peakTime[-1])
t90.append(findAtRiseFrac(burstRiseTimes, burstRiseLums,
currentPeakLum, currentPersLum, .90) - peakTime[-1])
burstLum = np.array(lum[recordStartIndex:stopIndex])
burstTim = np.array(tim[recordStartIndex:stopIndex] -
tim[beginIndex])
burstRad = np.array(rad[recordStartIndex:stopIndex])
burstLums.append(burstLum)
burstTims.append(burstTim)
burstRads.append(burstRad)
upTurns.append(upTurn)
tBurst.append(max(burstTim) - t25[-1])
convexities.append(
convexity(burstRiseTimes, burstRiseLums, currentPeakLum,
currentPersLum))
# Tail Fits
# PeakTime is 0 at the moment
pParams, pData, eParams, eData =\
burstFits(burstTim, burstLum, 0, mdl=None)
fitAlpha.append(pParams['al'].value)
fitDecay.append(eParams['tau'].value)
# Now it is time to find fluence