forked from samconnolly/DELightcurveSimulation
-
Notifications
You must be signed in to change notification settings - Fork 1
/
DELCgen.py
executable file
·1698 lines (1448 loc) · 66.5 KB
/
DELCgen.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
"""
LCgenerationDE.py
Created on Fri Nov 7 16:18:50 2014
Author: Sam Connolly
Python version of the light curve simulation algorithm from
Emmanoulopoulos et al., 2013, Monthly Notices of the Royal
Astronomical Society, 433, 907.
Uses 'Lightcurve' objects to allow easy interactive use and
easy plotting.
The PSD and PDF can be supplied, or a given model can be fitted
Both best fitting models from fits to data and theoretical models can be used.
requires:
numpy, pylab, scipy, pickle
"""
import numpy as np
import pylab as plt
import scipy.integrate as itg
import scipy.stats as st
import numpy.fft as ft
import numpy.random as rnd
import scipy.optimize as op
import scipy.special as sp
from astropy.io import fits
#__all__ = ['Mixture_Dist', 'BendingPL', 'RandAnyDist', 'Min_PDF','OptBins',
# 'PSD_Prob','SD_estimate','TimmerKoenig','EmmanLC','Lightcurve',
# 'Comparison_Plots','Load_Lightcurve','Simulate_TK_Lightcurve',
# 'Simulate_DE_Lightcurve']
# ------ Distribution Functions ------------------------------------------------
class Mixture_Dist(object):
'''
Create a mixture distribution using a weighted combination of the functions
in the array 'funcs'. The resultant object can both calculate a value
for the function and be randomly sampled.
inputs:
functions (array of functions)
- list of all of the functions to mix
n_args (2-D array)
- numerical array of the parameters of each function
frozen (list, [int,int], optional)
- list of the indices of parameters which which should be frozen
in the resultant function and their values, e.g. [[1,0.5]]
will freeze the parameter at position 1 to be 0.5
force_scipy (bool, optional)
- If the code will not recognise scipy distributions (or is giving
parsing errors), this flag will force it to do so. Can occur
due to old scipy versions.
functions:
Sample(params,length)
- produce a random sample of length 'length' from the function for
a given set of paramaters.
Value(x, params)
- calculate the value of the function at the value(s) x, for
the paramters given.
'''
def __init__(self,functions,n_args,frozen=None, force_scipy=False):
self.functions = functions
self.n_args = n_args
self.frozen = frozen
self.__name__ = 'Mixture_Dist'
self.default = False
if functions[0].__module__ == 'scipy.stats._continuous_distns' or \
force_scipy == True:
self.scipy = True
else:
self.scipy = False
def Sample(self,params,length=1):
'''
Use inverse transform sampling to randomly sample a mixture of any set
of scipy contiunous (random variate) distributions.
inputs:
params (array) - list of free parameters in each function
followed by the weights - e.g.:
[f1_p1,f1_p2,f2_p1,f2_p2,f2+p3,w1,w2]
length (int) - Length of the random sample
outputs:
sample (array, float) - The random sample
'''
if self.scipy == True:
cumWeights = np.cumsum(params[-len(self.functions):])
# random sample for function choice
mix = np.random.random(size=length)*cumWeights[-1]
sample = np.array([])
args = []
if self.frozen:
n = self.n_args[0] - len(self.frozen[0][0])
par = params[:n]
if len(self.frozen[0]) > 0:
for f in range(len(self.frozen[0][0])):
par = np.insert(par,self.frozen[0][0][f]-1,
self.frozen[0][1][f])
else:
n = self.n_args[0]
par = params[:n]
args.append(par)
for i in range(1,len(self.functions)):
if self.frozen:
if len(self.frozen[i]) > 0:
n_next = n + self.n_args[i] - len(self.frozen[i][0])
par = params[n:n_next]
if len(self.frozen[i]) > 0:
for f in range(len(self.frozen[i][0])):
par = np.insert(par,
self.frozen[i][0][f]-1,self.frozen[i][1][f])
else:
n_next = n+self.n_args[i]
par = params[n:n_next]
else:
n_next = n+self.n_args[i]
par = params[n:n_next]
args.append(par)
# cycle through each distribution according to probability weights
for i in range(len(self.functions)):
if i > 0:
sample = np.append(sample, self.functions[i].rvs(args[i][0],
loc=args[i][1], scale=args[i][2],
size=len(np.where((mix>cumWeights[i-1])*
(mix<=cumWeights[i]))[0])))
else:
sample = np.append(sample, self.functions[i].rvs(args[i][0],
loc=args[i][1],scale=args[i][2],
size=len(np.where((mix<=cumWeights[i]))[0])))
# randomly mix sample
np.random.shuffle(sample)
# return single values as floats, not arrays
if len(sample) == 1:
sample = sample[0]
return sample
def Value(self,x,params):
'''
Returns value or array of values from mixture distribution function.
inputs:
x (array or float) - numerical array to which the mixture function
will be applied
params (array) - list of free parameters in each function
followed by the weights - e.g.:
[f1_p1,f1_p2,f2_p1,f2_p2,f2_p3,w1,w2]
outputs:
data (array) - output data array
'''
if self.scipy == True:
functions = []
for f in self.functions:
functions.append(f.pdf)
else:
functions = self.functions
n = self.n_args[0]
if self.frozen:
n = self.n_args[0] - len(self.frozen[0][0])
par = params[:n]
if len(self.frozen[0]) > 0:
for f in range(len(self.frozen[0][0])):
par = np.insert(par,self.frozen[0][0][f]-1,
self.frozen[0][1][f])
else:
n = self.n_args[0]
par = params[:n]
data = np.array(functions[0](x,*par))*params[-len(functions)]
for i in range(1,len(functions)):
if self.frozen:
if len(self.frozen[i]) > 0:
n_next = n + self.n_args[i] - len(self.frozen[i][0])
par = params[n:n_next]
if len(self.frozen[i]) > 0:
for f in range(len(self.frozen[i][0])):
par = np.insert(par,self.frozen[i][0][f]-1,
self.frozen[i][1][f])
else:
n_next = n+self.n_args[i]
par = params[n:n_next]
else:
n_next = n+self.n_args[i]
par = params[n:n_next]
data += np.array(functions[i](x,*par))*params[-len(functions)+i]
n = n_next
data /= np.sum(params[-len(functions):])
return data
def BendingPL(v,A,v_bend,a_low,a_high,c):
'''
Bending power law function - returns power at each value of v,
where v is an array (e.g. of frequencies)
inputs:
v (array) - input values
A (float) - normalisation
v_bend (float) - bending frequency
a_low ((float) - low frequency index
a_high float) - high frequency index
c (float) - intercept/offset
output:
out (array) - output powers
'''
numer = v**-a_low
denom = 1 + (v/v_bend)**(a_high-a_low)
out = A * (numer/denom) + c
return out
def RandAnyDist(f,args,a,b,size=1):
'''
Generate random numbers from any distribution. Slow.
inputs:
f (function f(x,**args)) - The distribution from which numbers are drawn
args (tuple) - The arguments of f (excluding the x input array)
a,b (float) - The range of values for x
size (int, optional) - The size of the resultant array of random values,
returns a single value as default
outputs:
out (array) - List of random values drawn from the input distribution
'''
out = []
while len(out) < size:
x = rnd.rand()*(b-a) + a # random value in x range
v = f(x,*args) # equivalent probability
p = rnd.rand() # random number
if p <= v:
out.append(x) # add to value sample if random number < probability
if size == 1:
return out[0]
else:
return out
def PDF_Sample(lc):
'''
Generate random sample the flux histogram of a lightcurve by sampling the
piecewise distribution consisting of the box functions forming the
histogram of the lightcurve's flux.
inputs:
lc (Lightcurve)
- Lightcurve whose histogram will be sample
outputs:
sample (array, float)
- Array of data sampled from the lightcurve's flux histogram
'''
if lc.bins == None:
lc.bins = OptBins(lc.flux)
pdf = np.histogram(lc.flux,bins=lc.bins)
chances = pdf[0]/float(sum(pdf[0]))
nNumbers = len(lc.flux)
sample = np.random.choice(len(chances), nNumbers, p=chances)
sample = np.random.uniform(pdf[1][:-1][sample],pdf[1][1:][sample])
return sample
#-------- PDF Fitting ---------------------------------------------------------
def Min_PDF(params,hist,model,force_scipy=False):
'''
PDF chi squared function allowing the fitting of a mixture distribution
using a log normal distribution and a gamma distribution
to a histogram of a data set.
inputs:
params (array) - function variables - kappa, theta, lnmu,lnsig,weight
hist (array) - histogram of data set (using numpy.hist)
force_scipt (bool,optional) - force the function to assume a scipy model
outputs:
chi (float) - chi squared
'''
# pdf(x,shape,loc,scale)
# gamma - shape = kappa,loc = 0, scale = theta
# lognorm - shape = sigma, loc = 0, scale = exp(mu)
mids = (hist[1][:-1]+hist[1][1:])/2.0
try:
if model.__name__ == 'Mixture_Dist':
model = model.Value
m = model(mids,params)
elif model.__module__ == 'scipy.stats.distributions' or \
model.__module__ == 'scipy.stats._continuous_distns' or \
force_scipy == True:
m = model.pdf
else:
m = model(mids,*params)
except AttributeError:
m = model(mids,*params)
chi = (hist[0] - m)**2.0
return np.sum(chi)
def OptBins(data,maxM=100):
'''
Python version of the 'optBINS' algorithm by Knuth et al. (2006) - finds
the optimal number of bins for a one-dimensional data set using the
posterior probability for the number of bins. WARNING sometimes doesn't
seem to produce a high enough number by some way...
inputs:
data (array) - The data set to be binned
maxM (int, optional) - The maximum number of bins to consider
outputs:
maximum (int) - The optimum number of bins
Ref: K.H. Knuth. 2012. Optimal data-based binning for histograms
and histogram-based probability density models, Entropy.
'''
N = len(data)
# loop through the different numbers of bins
# and compute the posterior probability for each.
logp = np.zeros(maxM)
for M in range(1,maxM+1):
n = np.histogram(data,bins=M)[0] # Bin the data (equal width bins)
# calculate posterior probability
part1 = N * np.log(M) + sp.gammaln(M/2.0)
part2 = - M * sp.gammaln(0.5) - sp.gammaln(N + M/2.0)
part3 = np.sum(sp.gammaln(n+0.5))
logp[M-1] = part1 + part2 + part3 # add to array of posteriors
maximum = np.argmax(logp) + 1 # find bin number of maximum probability
return maximum + 10
#--------- PSD fitting --------------------------------------------------------
def PSD_Prob(params,periodogram,model):
'''
Calculate the log-likelihood (-2ln(L) ) of obtaining a given periodogram
for a given PSD, described by a given model.
inputs:
periodogram (array, 2-column) - lightcurve periodogram and equivalent
frequencies - [frequncies, periodogram]
params (array, length 5) - list of params of the PSD -
[A,v_bend,a_low,a_high,c]
model (function, optional) - model PSD function to use
outputs:
p (float) - probability
'''
psd = model(periodogram[0],*params) # calculate the psd
even = True
# calculate the likelihoods for each value THESE LINES CAUSE RUNTIME ERRORS
if even:
p = 2.0 * np.sum( np.log(psd[:-1]) + (periodogram[1][:-1]/psd[:-1]) )
p_nq = np.log(np.pi * periodogram[1][-1]*psd[-1]) \
+ 2.0 * (periodogram[1][-1]/psd[-1])
p += p_nq
else:
p = 2.0 * np.sum( np.log(psd) + (periodogram[1]/psd) )
return p
#--------- Standard Deviation estimate ----------------------------------------
def SD_estimate(mean,v_low,v_high,PSDdist,PSDdistArgs):
'''
Estimate the standard deviation from a PSD model, by integrating between
frequencies of interest, giving RMS squared variability, and multiplying
by the mean squared. And square rooting.
inputs:
mean (float) - mean of the data
v_low (float) - lower frequency bound of integration
v_high (float) - upper frequency bound of integration
PSDdist (function) - PSD distribution function
PSDdistargs (var) - PSD distribution best fit parameters
outputs:
out (float) - the estimated standard deviation
'''
i = itg.quad(PSDdist,v_low,v_high,tuple(PSDdistArgs))
out = [np.sqrt(mean**2.0 * i[0]),np.sqrt(mean**2.0 * i[1])]
return out
#------------------ Lightcurve Simulation Functions ---------------------------
def TimmerKoenig(RedNoiseL, aliasTbin, randomSeed, tbin, LClength,\
PSDmodel, PSDparams,std=1.0, mean=0.0):
'''
Generates an artificial lightcurve with the a given power spectral
density in frequency space, using the method from Timmer & Koenig, 1995,
Astronomy & Astrophysics, 300, 707.
inputs:
RedNoiseL (int) - multiple by which simulated LC is lengthened
compared to data LC to avoid red noise leakage
aliasTbin (int) - divisor to avoid aliasing
randomSeed (int) - Random number seed
tbin (int) - Sample rate of output lightcurve
LClength (int) - Length of simulated LC
std (float) - standard deviation of lightcurve to generate
mean (float) - mean amplitude of lightcurve to generate
PSDmodel (function) - Function for model used to fit PSD
PSDparams (various) - Arguments/parameters of best-fitting PSD model
outputs:
lightcurve (array) - array of amplitude values (cnts/flux) with the
same timing properties as entered, length 1024
seconds, sampled once per second.
fft (array) - Fourier transform of the output lightcurve
shortPeriodogram (array, 2 columns) - periodogram of the output
lightcurve [freq, power]
'''
# --- create freq array up to the Nyquist freq & equivalent PSD ------------
frequency = np.arange(1.0, (RedNoiseL*LClength)/2 +1)/ \
(RedNoiseL*LClength*tbin*aliasTbin)
powerlaw = PSDmodel(frequency,*PSDparams)
# -------- Add complex Gaussian noise to PL --------------------------------
rnd.seed(randomSeed)
real = (np.sqrt(powerlaw*0.5))*rnd.normal(0,1,((RedNoiseL*LClength)/2))
imag = (np.sqrt(powerlaw*0.5))*rnd.normal(0,1,((RedNoiseL*LClength)/2))
positive = np.vectorize(complex)(real,imag) # array of +ve, complex nos
noisypowerlaw = np.append(positive,positive.conjugate()[::-1])
znoisypowerlaw = np.insert(noisypowerlaw,0,complex(0.0,0.0)) # add 0
# --------- Fourier transform the noisy power law --------------------------
inversefourier = np.fft.ifft(znoisypowerlaw) # should be ONLY real numbers
longlightcurve = inversefourier.real # take real part of the transform
# extract random cut and normalise output lightcurve,
# produce fft & periodogram
if RedNoiseL == 1:
lightcurve = longlightcurve
else:
extract = rnd.randint(LClength-1,RedNoiseL*LClength - LClength)
lightcurve = np.take(longlightcurve,range(extract,extract + LClength))
if mean:
lightcurve = lightcurve-np.mean(lightcurve)
if std:
lightcurve = (lightcurve/np.std(lightcurve))*std
if mean:
lightcurve += mean
fft = ft.fft(lightcurve)
periodogram = np.absolute(fft)**2.0 * ((2.0*tbin*aliasTbin*RedNoiseL)/\
(LClength*(np.mean(lightcurve)**2)))
shortPeriodogram = np.take(periodogram,range(1,LClength/2 +1))
#shortFreq = np.take(frequency,range(1,LClength/2 +1))
shortFreq = np.arange(1.0, (LClength)/2 +1)/ (LClength*tbin)
shortPeriodogram = [shortFreq,shortPeriodogram]
return lightcurve, fft, shortPeriodogram
# The Emmanoulopoulos Loop
def EmmanLC(time,RedNoiseL,aliasTbin,RandomSeed,tbin,
PSDmodel, PSDparams, PDFmodel=None, PDFparams=None,maxFlux=None,
maxIterations=1000,verbose=False, LClength=None, \
force_scipy=False,histSample=None):
'''
Produces a simulated lightcurve with the same power spectral density, mean,
standard deviation and probability density function as those supplied.
Uses the method from Emmanoulopoulos et al., 2013, Monthly Notices of the
Royal Astronomical Society, 433, 907. Starts from a lightcurve using the
Timmer & Koenig (1995, Astronomy & Astrophysics, 300, 707) method, then
adjusts a random set of values ordered according to this lightcurve,
such that it has the correct PDF and PSD. Using a scipy.stats distribution
recommended for speed.
inputs:
time (array)
- Times from data lightcurve
flux (array)
- Fluxes from data lightcurve
RedNoiseL (int)
- multiple by which simulated LC is lengthened compared to the data
LC to avoid red noise leakage
aliasTbin (int)
- divisor to avoid aliasing
RandomSeed (int)
- random number generation seed, for repeatability
tbin (int)
- lightcurve bin size
PSDmodel (fn)
- Function for model used to fit PSD
PSDparams (tuple,var)
- parameters of best-fitting PSD model
PDFmodel (fn,optional)
- Function for model used to fit PDF if not scipy
PDFparams (tuple,var)
- Distributions/params of best-fit PDF model(s). If a scipy random
variate is used, this must be in the form:
([distributions],[[shape,loc,scale]],[weights])
maxIterations (int,optional)
- The maximum number of iterations before the routine gives up
(default = 1000)
verbose (bool, optional)
- If true, will give you some idea what it's doing, by telling you
(default = False)
LClength (int)
- Length of simulated LC
histSample (Lightcurve, optional)
- If
outputs:
surrogate (array, 2 column)
- simulated lightcurve [time,flux]
PSDlast (array, 2 column)
- simulated lighturve PSD [freq,power]
shortLC (array, 2 column)
- T&K lightcurve [time,flux]
periodogram (array, 2 column)
- T&K lighturve PSD [freq,power]
ffti (array)
- Fourier transform of surrogate LC
LClength (int)
- length of resultant LC if not same as input
'''
if LClength != None:
length = LClength
time = np.arange(0,tbin*LClength,tbin)
else:
length = len(time)
ampAdj = None
# Produce Timmer & Koenig simulated LC
if verbose:
print "Running Timmer & Koening..."
tries = 0
success = False
if histSample:
mean = np.mean(histSample.mean)
else:
mean = 1.0
while success == False and tries < 5:
try:
if LClength:
shortLC, fft, periodogram = \
TimmerKoenig(RedNoiseL,aliasTbin,RandomSeed,tbin,LClength,
PSDmodel,PSDparams,mean=1.0)
success = True
else:
shortLC, fft, periodogram = \
TimmerKoenig(RedNoiseL,aliasTbin,RandomSeed,tbin,len(time),
PSDmodel,PSDparams,mean=1.0)
success = True
# This has been fixed and should never happen now in theory...
except IndexError:
tries += 1
print "Simulation failed for some reason (IndexError) - restarting..."
shortLC = [np.arange(len(shortLC))*tbin, shortLC]
# Produce random distrubtion from PDF, up to max flux of data LC
# use inverse transform sampling if a scipy dist
if histSample:
dist = PDF_Sample(histSample)
else:
mix = False
scipy = False
try:
if PDFmodel.__name__ == "Mixture_Dist":
mix = True
except AttributeError:
mix = False
try:
if PDFmodel.__module__ == 'scipy.stats.distributions' or \
PDFmodel.__module__ == 'scipy.stats._continuous_distns' or \
force_scipy == True:
scipy = True
except AttributeError:
scipy = False
if mix:
if verbose:
print "Inverse tranform sampling..."
dist = PDFmodel.Sample(PDFparams,length)
elif scipy:
if verbose:
print "Inverse tranform sampling..."
dist = PDFmodel.rvs(*PDFparams,size=length)
else: # else use rejection
if verbose:
print "Rejection sampling... (slow!)"
if maxFlux == None:
maxFlux = 1
dist = RandAnyDist(PDFmodel,PDFparams,0,max(maxFlux)*1.2,length)
dist = np.array(dist)
if verbose:
print "mean:",np.mean(dist)
sortdist = dist[np.argsort(dist)] # sort!
# Iterate over the random sample until its PSD (and PDF) match the data
if verbose:
print "Iterating..."
i = 0
oldSurrogate = np.array([-1])
surrogate = np.array([1])
while i < maxIterations and np.array_equal(surrogate,oldSurrogate) == False:
oldSurrogate = surrogate
if i == 0:
surrogate = [time, dist] # start with random distribution from PDF
else:
surrogate = [time,ampAdj]#
ffti = ft.fft(surrogate[1])
PSDlast = ((2.0*tbin)/(length*(mean**2))) *np.absolute(ffti)**2
PSDlast = [periodogram[0],np.take(PSDlast,range(1,length/2 +1))]
fftAdj = np.absolute(fft)*(np.cos(np.angle(ffti)) \
+ 1j*np.sin(np.angle(ffti))) #adjust fft
LCadj = ft.ifft(fftAdj)
LCadj = [time/tbin,LCadj]
PSDLCAdj = ((2.0*tbin)/(length*np.mean(LCadj)**2.0)) \
* np.absolute(ft.fft(LCadj))**2
PSDLCAdj = [periodogram[0],np.take(PSDLCAdj, range(1,length/2 +1))]
sortIndices = np.argsort(LCadj[1])
sortPos = np.argsort(sortIndices)
ampAdj = sortdist[sortPos]
i += 1
if verbose:
print "Converged in {} iterations".format(i)
return surrogate, PSDlast, shortLC, periodogram, ffti
#--------- Lightcurve Class & associated functions -----------------------------
class Lightcurve(object):
'''
Light curve class - contains all data, models and fits associated
with a lightcurve. Possesses functions allowing
plotting, saving and simulation of new lightcurves
with the same statistical properties (PSD and PDF).
inputs:
time (array) - Array of times for lightcurve
flux (array) - Array of fluxes for lightcurve
errors (array,optional) - Array of flux errors for lightcurve
tbin (int,optional) - width of time bin of lightcurve
functions:
STD_Estimate()
- Estimate and set the standard deviation of the lightcurve from a
PSD model.
Fourier_Transform()
- Calculate and set the Fourier Transform of the lightcurve.
Periodogram()
- Calculate and set the periodogram of the lightcurve.
Fit_PSD(initial_params= [1, 0.001, 1.5, 2.5, 0], model = BendingPL,
fit_method='Nelder-Mead',n_iter=1000, verbose=True)
- Fit the lightcurve's periodogram with a given PSD model.
Fit_PDF(initial_params=[6,6, 0.3,7.4,0.8,0.2], model= None,
fit_method = 'BFGS', nbins=None,verbose=True)
- Fit the lightcurve with a given PDF model
Simulate_DE_Lightcurve(self,PSDmodel=None,PSDinitialParams=None,
PSD_fit_method='Nelder-Mead',n_iter=1000,
PDFmodel=None,PDFinitialParams=None,
PDF_fit_method = 'BFGS',nbins=None,
RedNoiseL=100, aliasTbin=1,randomSeed=None,
maxIterations=1000,verbose=False,size=1)
- Simulate a lightcurve with the same PSD and PDF as this one,
using the Emmanoulopoulos method.
Plot_Periodogram()
- Plot the lightcurve's periodogram (calculated if necessary)
Plot_Lightcurve()
- Plot the lightcurve
Plot_PDF(bins=None,norm=True)
- Plot the lightcurve's PDF
Plot_Stats(bins=None,norm=True)
- Plot the lightcurve and its PSD and periodogram (calculated if
necessary)
Save_Periodogram()
- Save the lightcurve's periodogram to a txt file.
Save_Lightcurve()
- Save the lightcurve to a txt file.
'''
def __init__(self,time,flux,tbin,errors=None):
self.time = time
self.flux = flux
self.errors = errors
self.length = len(time)
self.freq = np.arange(1, self.length/2.0 + 1)/(self.length*tbin)
self.psd = None
self.mean = np.mean(flux)
self.std_est = None
self.std = np.std(flux)
self.tbin = tbin
self.fft = None
self.periodogram = None
self.pdfFit = None
self.psdFit = None
self.psdModel = None
self.pdfModel = None
self.bins = None
def STD_Estimate(self,PSDdist=None,PSDdistArgs=None):
'''
Set and return standard deviation estimate from a given PSD, using the
frequency range of the lightcurve.
inputs:
PSDdist (function,optional)
- PSD model to use to estimate SD. If not geven and a model has
been fitted this is used, otherwise the default is fitted
and used.
PSDdistArgs (var,optional)
- Arguments/parameters of PSD model, if a model is provided.
outputs:
std_est (float) - The estimate of the standard deviation
'''
if PSDdist == None:
if self.psdModel == None:
print "Fitting PSD for standard deviation estimation..."
self.Fit_PSD(verbose=False)
PSDdist = self.psdModel
PSDdistArgs = self.psdFit['x']
self.std_est = SD_estimate(self.mean,self.freq[0],self.freq[-1],PSDdist,PSDdistArgs)[0]
return self.std_est
def PSD(self,PSDdist,PSDdistArgs):
'''
DEPRECATED
Set and return the power spectral density from a given model, using the
frequency range of the lightcurve
inputs:
PSDdist (function) - The PSD model (e.g. bending power law etc.)
PSDArgs (array) - Array of parameters taken by model function
outputs:
psd (array) - The calculated PSD
'''
self.psd = PSDdist(self.freq,*PSDdistArgs)
return self.psd
def Fourier_Transform(self):
'''
Calculate and return the Fourier transform of the lightcurve
outputs:
fft (array) - The Fourier transform of the lightcurve
'''
self.fft = ft.fft(self.flux) # 1D Fourier Transform (as time-binned)
return self.fft
def Periodogram(self):
'''
Calculate, set and return the Periodogram of the lightcurve. Does the
Fourier transform if not previously carried out.
output:
periodogram (array) - The periodogram of the lightcurve
'''
if self.fft == None:
self.Fourier_Transform()
periodogram = ((2.0*self.tbin)/(self.length*(self.mean**2)))\
* np.absolute(np.real(self.fft))**2
freq = np.arange(1, self.length/2 + 1).astype(float)/\
(self.length*self.tbin)
shortPeriodogram = np.take(periodogram,np.arange(1,self.length/2 +1))
self.periodogram = [freq,shortPeriodogram]
return self.periodogram
def Set_PSD_Fit(self, model, params):
self.psdModel = model
self.psdFit = dict([('x',np.array(params))])
def Set_PDF_Fit(self, model, params=None):
if model == None:
self.pdfModel = None
self.pdfFit = None
else:
self.pdfModel = model
if params:
self.pdfFit = dict([('x',np.array(params))])
def Fit_PSD(self, initial_params= [1, 0.001, 1.5, 2.5, 0],
model = BendingPL, fit_method='Nelder-Mead',n_iter=1000,
verbose=True):
'''
Fit the PSD of the lightcurve with a given model. The result
is then stored in the lightcurve object as 'psdFit' (if successful).
The fit is obtained by finding the parameters of maximum likelihood
using a Basin-Hopping algorithm and the specified minimisation
algorithm.
inputs:
initial_params (array, optional) -
array of parameters for the PSD model. For the default model
this is an array of FIVE parameters:
[A,v_bend,a_low,a_high,c]
where A is the normalisation, v_bend is the bend frequency,
a_low and a_high is the power law indexes at the low
and high frequencies, respectively, and c is the offset.
model (function, optional) -
PSD model to fit to the periodogram. Default is a bending
power law.
fit_method (string) -
fitting algorithm - must be a scipy.optimize.minimize method.
default is Nelder-Mead.
n_iter (int) -
The number of iterations of the Basing-Hopping algorithm
to carry out. Each iteration restarts the minimisation in
a different location, in order to ensure that the actual
minimum is found.
verbose (bool, optional) -
Sets whether output text showing fit parameters is displayed.
Fit failure text if always displayed.
'''
if self.periodogram == None:
self.Periodogram()
minimizer_kwargs = {"args":(self.periodogram,model),"method":fit_method}
m = op.basinhopping(PSD_Prob, initial_params,
minimizer_kwargs=minimizer_kwargs,niter=n_iter)
if m['message'][0] == \
'requested number of basinhopping iterations completed successfully':
if verbose:
print "\n### Fit successful: ###"
#A,v_bend,a_low,a_high,c
if model == BendingPL:
print "Normalisation: {}".format(m['x'][0])
print "Bend frequency: {}".format(m['x'][1])
print "Low frequency index: {}".format(m['x'][2])
print "high frequency index: {}".format(m['x'][3])
print "Offset: {}".format(m['x'][4])
else:
for p in range(len(m['x'])):
print "Parameter {}: {}".format(p+1,m['x'][p])
self.psdFit = m
self.psdModel = model
else:
print "#### FIT FAILED ####"
print "Fit parameters not assigned."
print "Try different initial parameters with the 'initial_params' keyword argument"
def Fit_PDF(self, initial_params=[6,6, 0.3,7.4,0.8,0.2],
model= None, fit_method = 'BFGS', nbins=None,verbose=True):
'''
Fit the PDF of the flux with a given model - teh default is a mixture
distribution consisting of a gamma distribution and a lognormal
distribution. The result is then stored in the lightcurve object as
'pdfFit' (if successful).
The function is fitted to a histogram of the data using the
optimum number of bins as calculated using the 'optBins' algorithm
described in Knuth et al. 2006 (see notes on the 'OptBin function).
inputs:
initial_params (array, optional) -
array of FIVE parameters:
[kappa,theta,ln(mu),ln(sigma),weight]
where kappa and theta are the parameters of the gamma
distribution (using the standard notation) and ln(mu) and
ln(sigma) are the parameters of the lognormal distribution
(i.e. the natural log of the mean and standard deviation)
model (function, optional) -
Model used to fit the PDF and subsequently to draw samples
from when simulating light curves.
fit_method (str, optional) -
Method used to minimise PDF fit. Must be a scipy minimisation
algorithm.
nbins (int, optional)
- Number of bins used when fitting the PSD. If not given,
an optimum number is automatically calculated using
'OptBins'.
verbose (bool, optional) -
Sets whether output text showing fit parameters is displayed.
Fit failure text if always displayed.
'''
if model == None:
model = Mixture_Dist([st.gamma,st.lognorm],
[3,3],[[[2],[0]],[[2],[0],]])
model.default = True
if nbins == None:
nbins = OptBins(self.flux)
self.bins = nbins
hist = np.array(np.histogram(self.flux,bins=nbins,normed=True))
m = op.minimize(Min_PDF, initial_params,
args=(hist,model),method=fit_method)
if m['success'] == True:
if verbose:
print "\n### Fit successful: ###"
mix = False
try:
if model.__name__ == "Mixture_Dist":
mix = True
except AttributeError:
mix = False
if mix:
if model.default == True:
#kappa,theta,lnmu,lnsig,weight
print "\nGamma Function:"
print "kappa: {}".format(m['x'][0])
print "theta: {}".format(m['x'][1])
print "weight: {}".format(m['x'][4])
print "\nLognormal Function:"
print "exp(ln(mu)): {}".format(m['x'][2])
print "ln(sigma): {}".format(m['x'][3])
print "weight: {}".format(1.0 - m['x'][4])
else:
for p in range(len(m['x'])):
print "Parameter {}: {}".format(p+1,m['x'][p])
else:
for p in range(len(m['x'])):
print "Parameter {}: {}".format(p+1,m['x'][p])
self.pdfFit = m
self.pdfModel = model
else:
print "#### FIT FAILED ####"
print "Fit parameters not assigned."
print "Try different initial parameters with the 'initial_params' keyword argument"
def Simulate_DE_Lightcurve(self,PSDmodel=None,PSDinitialParams=None,
PSD_fit_method='Nelder-Mead',n_iter=1000,
PDFmodel=None,PDFinitialParams=None,
PDF_fit_method = 'BFGS',nbins=None,
RedNoiseL=100, aliasTbin=1,randomSeed=None,
maxIterations=1000,verbose=False,size=1,LClength=None,histSample=False):
'''
Simulate a lightcurve using the PSD and PDF models fitted to the
lightcurve, with the Emmanoulopoulos algorithm. If PSD and PDF fits
have not been carried out, they are automatically carried out using
keyword parameters, or default parameters if keyword parameters are not