-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpowerspectraldensity.py
executable file
·2902 lines (2473 loc) · 110 KB
/
powerspectraldensity.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script for estimating the power spectral density (PSD) of a blazar light
curve.
"""
from datetime import datetime
from math import ceil, floor, log10, sqrt
import os.path
import sys
import numpy as np
from scipy.signal import periodogram
from scipy.interpolate import splrep, splev
from scipy.stats import kstest
from statsmodels.distributions import ECDF
from matplotlib import pyplot as plt
from matplotlib import cm
import matplotlib.gridspec as gs
import tables as tb
import warnings
warnings.simplefilter('ignore', np.RankWarning)
__author__ = "Sebastian Kiehlmann"
__copyright__ = "Copyright 2023, Sebastian Kiehlmann"
__credits__ = ["Sebastian Kiehlmann"]
__license__ = "BSD 3"
__version__ = "4.1"
__maintainer__ = "Sebastian Kiehlmann"
__email__ = "skiehlmann@mail.de"
__status__ = "Production"
#==============================================================================
# Matplotlib configuration
#==============================================================================
cmap = cm.Spectral
plt.rcParams.update({'axes.labelsize': 16.,
'axes.titlesize': 16.,
'figure.figsize': [12, 7.5],
'legend.fontsize': 16.,
'legend.numpoints': 1,
'legend.scatterpoints': 1,
'lines.marker': 'None',
'lines.linestyle': '-',
'xtick.labelsize': 14.,
'ytick.labelsize': 14.})
#==============================================================================
# FUNCTIONS
#==============================================================================
def create_file_dir(filename):
"""
Extracts a path name if part of the file name, checks whether that path
exists and if not creates this path.
Parameters
-----
filename : sting
A path and filename.
Returns
-----
None
"""
#find dir name, if any:
filename_rev = filename[::-1]
try:
ind = filename_rev.index('/')
except:
return False
#extract dir name:
ind = len(filename) - ind
dirname = filename[:ind]
#check dir and create if not there:
path = os.path.dirname(dirname)
if not os.path.exists(path):
os.makedirs(path)
#==============================================================================
def powerlaw(frequencies, index=1., amplitude=10., frequency=0.1):
"""Returns an array of amplitudes following a power-law over the input
frequencies.
Parameters
-----
frequencies : 1darray
Frequencies for which to calculate the power-law in arbitrary units.
index : float, default=1.
Power-law index.
amplitude : float, default=10.
Power-law amplitude at 'frequency' in arbitrary unit.
frequency : float, default=0.1
Frequency for the given 'amplitude' in same unit as 'frequencies'.
Returns
-----
out : 1darray
Array of same length as input 'frequencies'.
"""
return amplitude * np.power(frequencies / frequency, -index)
#==============================================================================
def kneemodel(frequencies, index=1., amplitude=10., frequency=0.1):
"""Returns an array of amplitudes following a constant profile that changes
into a power-law around a given frequency.
Parameters
-----
frequencies : 1darray
Frequencies for which to calculate the power-law in arbitrary units.
index : float, default=1.
Power-law index.
amplitude : float, default=10.
Constant amplitude at frequencies below 'frequency' in arbitrary unit.
frequency : float, default=0.1
Frequency in same unit as 'frequencies' at which profile changes
into a power-law.
Returns
-----
out : 1darray
Array of same length as input 'frequencies'.
"""
return amplitude * np.power(
1 + np.power(frequencies / frequency, 2), -index / 2.)
#==============================================================================
def brokenpowerlaw(
frequencies, index_lo=1., index_hi=2., amplitude=10., frequency=0.1):
"""Returns an array of amplitudes following a broken power-law.
Parameters
-----
frequencies : array
Frequencies for which to calculate the power-law in arbitrary units.
index_hi : float, default=2.
Power-law index at frequencies lower than 'frequency'.
index_lo : float, default=1.
Power-law index at frequencies higher than 'frequency'.
frequency : float, default=0.1
Frequency of the power-law break in same unit as 'frequencies'.
amplitude : float, default=10.
Amplitude at 'frequency' in arbitrary unit.
Returns
-----
Array of same length as input 'frequencies'.
"""
return np.where(
frequencies>frequency,
amplitude * np.power(frequencies / frequency, -index_hi),
amplitude * np.power(frequencies / frequency, -index_lo))
#==============================================================================
def sampling(time, average='median', factor=0.1):
"""Prints out the total time and the min, max, median and mean sampling
of a time series. Returns the total time and a suggested upper limit for
the simulation sampling.
Parameters
-----
time : 1darray
Time series.
average : string, default='median'
Choose average type ('median' or 'mean') for suggested sampling.
factor : float, default=0.1
The suggested sampling is the average sampling times this factor.
Returns
-----
out, out : float, float
Total time and suggested sampling rate (upper limit).
"""
total_time = time[-1] - time[0]
deltat =time[1:] - time[:-1]
sampling_median = np.median(deltat)
sampling_mean = np.mean(deltat)
sampling_min = np.min(deltat)
sampling_max = np.max(deltat)
if average=='median':
sampling_sim = sampling_median * factor
elif average=='mean':
sampling_sim = sampling_mean * factor
print(f'Total time: {total_time:.3f}')
print(f'Min. sampling: {sampling_min:.3f}')
print(f'Max. sampling: {sampling_max:.3f}')
print(f'Mean sampling: {sampling_mean:.3f}')
print(f'Median sampling: {sampling_median:.3f}')
print(f'Suggested simulation sampling: <{sampling_sim:.3f}')
return total_time, sampling_sim
#==============================================================================
def create_timesteps(time, sampling):
"""Create equally sampled time steps.
Parameters
----------
time : float
Total time.
sampling : float
Time interval between adjacent time steps.
Returns
-------
np.ndarray
Time steps.
"""
# get number of data points and adjust total time:
N = int(ceil(time / sampling)) + 1
time = sampling * (N - 1)
return np.linspace(0, time, N)
#==============================================================================
def simulate_lightcurve_tk(time, sampling, spec_shape, spec_args, seed=False):
"""Create an equally sampled, simulated random light curve following a
noise process given a spectral shape of the power density spectrum.
Parameters
-----
time : float
Length of the simulation in arbitrary time unit.
sampling : float
Length of the sampling interval in same unit as 'time'.
spec_shape : func
Function that takes an array of frequencies and 'spec_args' as input
and calculates a spectrum for those frequencies.
spec_args : list
Function arguments to 'spec_shape'.
seed : bool, default:False
Sets a seed for the random generator to get a reproducable result.
For testing only.
Returns
-----
out : np.ndarray
The simulated red noise light curve.
Notes
-----
This is an implemention of the algorithm described in [1].
References
-----
[1] Timmer and Koenig, 1995, 'On generating power law noise', A&A, 300, 707
"""
# get number of data points and adjust total time:
N = int(ceil(time / sampling)) + 1
# set spectrum:
freq = np.fft.rfftfreq(N, sampling)
freq[0] = 1
spectrum = spec_shape(freq[1:], *spec_args)
spectrum[0] = 0
del freq
# random (complex) Fourier coefficients for inverse Fourier transform:
if seed:
np.random.seed(seed)
coef = np.random.normal(size=(2, spectrum.shape[0]))
# if N is even the Nyquist frequency is real:
if N%2==0:
coef[-1,1] = 0.
coef = coef[0] +1j * coef[1]
coef *= np.sqrt(0.5 *spectrum * N / sampling)
# inverse Fourier transform:
lightcurve = np.fft.irfft(coef, N)
return lightcurve
#==============================================================================
def simulate_lightcurves_tk(
time, sampling, spec_shape, spec_args, nlcs=1, seed=False):
"""Simulate multiple light curves with the T&K algorithm.
Parameters
----------
time : float
Length of the simulation in arbitrary time unit.
sampling : float
Length of the sampling interval in same unit as 'time'.
spec_shape : func
Function that takes an array of frequencies and 'spec_args' as input
and calculates a spectrum for those frequencies.
spec_args : list
Function arguments to 'spec_shape'.
nlcs : int, default:1
Number of light curves to be simulated.
seed : bool, default:False
Sets a seed for the random generator to get a reproducable result.
For testing only.
Returns
-------
lightcurves : np.ndarray
Two dimensional array of simulated red noise light curves. Each row
along the first dimension contains one light curve.
Notes
-----
The light curves will be initially created as one long light curve and then
are split into seperate light curves. Therefore, 'nlcs' does not only
control the number of final light curves. It also affects to what extend
lower power frequencies are included in the final light curves, which is
relevant for taking rednoise leakage into account in the PSD estimation.
A value of nlcs=10 is recommendable.
"""
# get number of data points per light curve:
N = int(ceil(time / sampling)) + 1
# simulate long lightcurve:
lightcurves = simulate_lightcurve_tk(
sampling*N*nlcs, sampling, spec_shape, spec_args, seed=seed)[:-1]
# reshape to short light curves and normalize each to zero mean:
if nlcs>1:
shape = (nlcs, N)
lightcurves = lightcurves[:N*nlcs].reshape(shape)
lightcurves -= np.repeat(
np.mean(lightcurves, axis=1), shape[1]).reshape(shape)
return lightcurves
#==============================================================================
def adjust_lightcurve_pdf(lightcurve, ecdf, iterations=100, verbose=0):
"""Interatively adjust a simulated red noise light curve to match a target
probability density function (PDF).
Parameters
----------
lightcurve : np.ndarray
The input light curve to adjust.
ecdf : statsmodels.distributions.ECDF
Target ECDF as an empirical description of the target PDF.
iterations : int, default: 100
Number of iterations.
verbose : int, default=0
Controls the amount of information printed.
Returns
-------
lc_sim : np.ndarray
The adjusted simulated light curve.
Notes
-----
This is an implemention of the algorithm described in [1].
References
-----
[1] Emmanoulopoulos et al., 2013, 'Generating artificial light curves:
revisited and updated', MNRAS, 433, 2, 907
"""
# calculate discrete Fourier transform:
dft_norm = np.fft.rfft(lightcurve)
#---Emmanoulopoulos-et-al-algorithm----------------------------------------
# calculate amplitudes based on the random Fourier coefficients:
N = len(lightcurve)
ampl_adj = np.absolute(dft_norm)
# create artificial light curve based on ECDF:
lc_sim = np.interp(
np.random.uniform(ecdf.y[1], 1., size=N), ecdf.y, ecdf.x)
# iteration:
for i in range(iterations):
# calculate DFT, amplitudes:
dft_sim = np.fft.rfft(lc_sim)
ampl_sim = np.absolute(dft_sim)
# spectral adjustment:
dft_adj = dft_sim / ampl_sim * ampl_adj
lc_adj = np.fft.irfft(dft_adj, n=N)
# amplitude adjustment:
a = np.argsort(lc_adj)
s = np.argsort(lc_sim)
lc_adj[a] = lc_sim[s]
if np.max(np.absolute(lc_adj - lc_sim) / lc_sim) < 0.01:
if verbose:
print(f'Convergence reached after {i+1} iterations.')
break
else:
lc_sim = lc_adj
else:
if verbose:
print(f'No convergence reached within {iterations} iterations.')
return lc_sim
#==============================================================================
def simulate_lightcurve_emp(
time, sampling, spec_shape, spec_args, ecdf, iterations=100,
seed=False):
"""Create an equally sampled, simulated random light curve following a
noise process given a spectral shape of the power density spectrum and
a target probability density function expressed by an ECDF.
Parameters
-----
time : float
Length of the simulation in arbitrary time unit.
sampling : float
Length of the sampling interval in same unit as 'time'.
spec_shape : func
Function that takes an array of frequencies and 'spec_args' as input
and calculates a spectrum for those frequencies.
spec_args : list
Function arguments to 'spec_shape'
ecdf : statsmodels.distributions.ECDF
Target ECDF as an empirical description of the target PDF.
iterations : int, default: 100
Number of iterations for the Emmanoulopoulos et al. algorithm.
seed : bool, default: False
Sets a seed for the random generator to get a reproducable result.
For testing only.
Returns
-------
lc_sim : np.ndarray
The simulated light curve following a target PSD and PDF.
Notes
-----
This is an implemention of the algorithm described in [1].
References
-----
[1] Emmanoulopoulos et al., 2013, 'Generating artificial light curves:
revisited and updated', MNRAS, 433, 2, 907
"""
#---check input and set arguments for spectral shape functions-------------
if spec_shape == powerlaw:
try:
float(spec_args)
except:
print("Input error: When spec_shape is 'powerlaw', spec_args " \
"needs to be a float (spectral index)!")
return False
spec_args = [spec_args, 10., 0.1]
elif spec_shape == kneemodel:
try:
spec_args[0] = float(spec_args[0])
spec_args[1] = float(spec_args[1])
except:
print("Input error: When spec_shape is 'kneemodel', spec_args " \
"needs to be a list or tuple of two floats (spectral index" \
", knee frequency)!")
return False
spec_args = [spec_args[0], 10., spec_args[1]]
elif spec_shape == brokenpowerlaw:
try:
spec_args[0] = float(spec_args[0])
spec_args[1] = float(spec_args[1])
spec_args[2] = float(spec_args[2])
except:
print("Input error: When spec_shape is 'brokenpowerlaw', " \
"spec_args needs to be a list or tuple of three floats " \
"(spectral index low, spectral index high, break " \
"frequency)!")
return False
spec_args = [spec_args[0], spec_args[1], 10., spec_args[2]]
#---Timmer-Koenig-algorithm------------------------------------------------
print('Step 1: TK algorithm')
# get number of data points and adjust total time:
N = int(ceil(time / sampling)) + 1
# set spectrum:
freq = np.fft.rfftfreq(N, sampling)
freq[0] = 1
spectrum = spec_shape(freq, *spec_args)
spectrum[0] = 0
del freq
# random (complex) Fourier coefficients for inverse Fourier transform:
if seed:
np.random.seed(seed)
dft_norm = np.random.normal(size=(2, spectrum.shape[0]))
# if N is even the Nyquist frequency is real:
if N % 2 == 0:
dft_norm[-1,1] = 0.
dft_norm = dft_norm[0] + 1j * dft_norm[1]
dft_norm *= np.sqrt(0.5 * spectrum * N / sampling)
#---Emmanoulopoulos-et-al-algorithm----------------------------------------
print('Step 2: ECDF based sim. light curve')
# calculate amplitudes based on the random Fourier coefficients:
ampl_adj = np.absolute(dft_norm)
del dft_norm
# create artificial light curve based on ECDF:
lc_sim = np.interp(
np.random.uniform(ecdf.y[1], 1., size=N), ecdf.y, ecdf.x)
# iteration:
print('Step 3: iterative spectral and amplitude adjustment...')
for i in range(iterations):
sys.stdout.write('\r Progress: {0:.0f} %'.format(
(i+1) * 100. / iterations))
sys.stdout.flush()
# calculate DFT, amplitudes:
dft_sim = np.fft.rfft(lc_sim)
ampl_sim = np.absolute(dft_sim)
# spectral adjustment:
dft_adj = dft_sim /ampl_sim *ampl_adj
lc_adj = np.fft.irfft(dft_adj, n=N)
# amplitude adjustment:
a = np.argsort(lc_adj)
s = np.argsort(lc_sim)
lc_adj[a] = lc_sim[s]
if np.max(np.absolute(lc_adj -lc_sim) /lc_sim) < 0.01:
print(f'\r Convergence reached after {i+1} iterations.')
break
else:
lc_sim = lc_adj
else:
print('\n No convergence reached.')
return lc_sim
#==============================================================================
def simulate_lightcurves_emp(
time, sampling, spec_shape, spec_args, ecdf, nlcs=1, adjust_iter=100,
verbose=0, seed=False):
"""Simulate multiple light curves with the Emmanoulpopoulous et al.
algorithm.
Parameters
----------
time : float
Length of the simulation in arbitrary time unit.
sampling : float
Length of the sampling interval in same unit as 'time'.
spec_shape : func
Function that takes an array of frequencies and 'spec_args' as input
and calculates a spectrum for those frequencies.
spec_args : list
Function arguments to 'spec_shape'.
ecdf : statsmodels.distributions.ECDF
Target ECDF as an empirical description of the target PDF.
nlcs : int, default: 1
Number of light curves to be simulated.
adjust_iter : int, default: 100
Number of iterations for the Emmanoulopoulos et al. algorithm.
verbose : int, default=0
Controls the amount of information printed.
seed : bool, default:False
Sets a seed for the random generator to get a reproducable result.
For testing only.
Returns
-------
lightcurves : np.ndarray
Two dimensional array of simulated red noise light curves. Each row
along the first dimension contains one light curve.
Notes
-----
* This is an implemention of the algorithm described in [1].
* The light curves will be initially created as one long light curve and
then are split into seperate light curves. Therefore, 'nlcs' does not
only control the number of final light curves. It also affects to what
extend lower power frequencies are included in the final light curves,
which is relevant for taking rednoise leakage into account in the PSD
estimation. A value of nlcs=10 is recommendable.
References
-----
[1] Emmanoulopoulos et al., 2013, 'Generating artificial light curves:
revisited and updated', MNRAS, 433, 2, 907
"""
#---check input and set arguments for spectral shape functions-------------
if spec_shape == powerlaw:
try:
float(spec_args)
except:
print("Input error: When spec_shape is 'powerlaw', spec_args " \
"needs to be a float (spectral index)!")
return False
spec_args = [spec_args, 10., 0.1]
elif spec_shape == kneemodel:
try:
spec_args[0] = float(spec_args[0])
spec_args[1] = float(spec_args[1])
except:
print("Input error: When spec_shape is 'kneemodel', spec_args " \
"needs to be a list or tuple of two floats (spectral index" \
", knee frequency)!")
return False
spec_args = [spec_args[0], 10., spec_args[1]]
elif spec_shape == brokenpowerlaw:
try:
spec_args[0] = float(spec_args[0])
spec_args[1] = float(spec_args[1])
spec_args[2] = float(spec_args[2])
except:
print("Input error: When spec_shape is 'brokenpowerlaw', " \
"spec_args needs to be a list or tuple of three floats " \
"(spectral index low, spectral index high, break " \
"frequency)!")
return False
spec_args = [spec_args[0], spec_args[1], 10., spec_args[2]]
#---create light curve: TK algorithm---------------------------------------
if verbose:
print(f'Create long light curve of total time: {time*nlcs:.1f}.')
# simulate light curves:
lightcurves = simulate_lightcurves_tk(
time, sampling, spec_shape, spec_args, nlcs=nlcs, seed=seed)
#---iterate through light curves-------------------------------------------
for i in range(nlcs):
# shell feedback:
if verbose:
sys.stdout.write(
'\rAdjust amplitudes of short light curves: ' \
'{0:.0f} %'.format(i*100./nlcs))
sys.stdout.flush()
# adjust amplitude PDF: EMP algorithm:
lightcurves[i] = adjust_lightcurve_pdf(lightcurves[i], ecdf,
iterations=adjust_iter)
else:
if verbose:
print('\rAdjust amplitudes of short light curves: done.')
return lightcurves
#==============================================================================
def resample(time, lightcurve, sampling, resample_n=1):
"""Resample a evenly binned light curve.
Parameters
----------
time : np.ndarray
Time steps of the original light curve.
lightcurve : np.ndarray
Flux density of the original light curve.
sampling : float or np.ndarray
Provide a float to resample to even time steps, where the time interval
is given by this float. Provide the target times in a np.ndarray to
resample the original data to specific times.
resample_n : int, default: 1
If larger than 1 the light curve will be resampled multiple times with
different zero points.
Returns
-------
time_res : np.ndarray
The resampled time steps.
lc_res : np.ndarray
The resampled flux densities.
"""
#---check input------------------------------------------------------------
shape = lightcurve.shape
resample_n = 1 if resample_n<1 else int(resample_n)
if resample_n>1 and not isinstance(sampling, float):
print("WARNING: Multiple resampling of a light curve only possible " \
"for even sampling. 'resample_n' in resample() set to 1.")
resample_n = 1
elif resample_n>1 and len(shape)>1:
print("WARNING: Multiple light curves will each be resampled only " \
" once. 'resample_n' in resample() set to 1.")
resample_n = 1
#---even sampling----------------------------------------------------------
if isinstance(sampling, float):
# create new time steps:
N = int(floor((time[-1] - time[0]) / sampling))
time_res = np.linspace(time[0], time[0]+sampling*N, N+1)
#---uneven sampling--------------------------------------------------------
elif isinstance(sampling, np.ndarray):
# sampling interval is not within time interval:
if sampling[-1]<time[0] or sampling[0]>time[-1]:
print("WARNING: New time steps are not within given time interval"\
". Cannot resample light curve. Aborted!")
return False
# limit resampling time steps to within time (no extrapolation):
if sampling[0]<time[0] or sampling[-1]>time[-1]:
i = np.min(np.where(sampling>=time[0])[0])
j = np.max(np.where(sampling<=time[-1])[0]) + 1
time_res = sampling[i:j]
del i, j
# sampling interval is within time interval:
else:
time_res = sampling
N = len(time_res)
#---invalid input----------------------------------------------------------
else:
print(f"WARNING: type '{type(sampling)}' for input 'sampling' in " \
"resample() is invalid. Give float or np.1darray. Aborted!")
return False
#---resample single light curve once---------------------------------------
if len(shape)==1 and resample_n==1:
lc_res = np.interp(time_res, time, lightcurve)
#---resample single light curve multiple times-----------------------------
elif len(shape)==1:
# create time zero point offsets:
time_offset = np.linspace(0, sampling, resample_n, endpoint=False)
# delete last last time step, if out of time limit with largest offset:
if time_res[-1]+time_offset[-1]>time[-1]:
time_res = time_res[:-1]
# iterate through resamples:
lc_res = np.zeros((resample_n, len(time_res)))
for i, off in enumerate(time_offset):
lc_res[i] = np.interp(time_res+off, time, lightcurve)
#---resample multiple light curves-----------------------------------------
else:
lc_res = np.zeros((shape[0], N))
#iterate through light curves:
for i in range(shape[0]):
lc_res[i] = np.interp(time_res, time, lightcurve[i])
return time_res, lc_res
#==============================================================================
def rebin(time, lightcurve, bins, bincenters=None, binlimits='lower'):
"""Bins and averages a light curve according to its time steps.
Parameters
-----
time : np.1darray
Time steps of the light curve, the light curve is bined according to
these time stamps.
lightcurve : np.ndarray
The signal that is bined and averaged. If 'lightcurve' is a 2darray
each row is treated as a single light curve, binned and averaged.
bins : float or array-like
Defines the lower or upper or two sided bin limits (when 'bincenters'
is not set) or the bin spread (when 'bincenters' is set).
When 'bincenters' is not set, there are 3 options:
1) If 'bins' is a float equally sized bins are created, starting at
the first time stamp.
2) If bins is a 1darray it defines the lower of upper bin limits
depending on 'binlimts'.
3) If 'bins' is a list of two arrays, the first array defines the
lower bin limits, the second array the upper limits.
bincenters : np.1darray, default=None
When bin centers are given, 'bins' defines the spread of each bin,
with 3 options:
1) If 'bins' is a float the bin limits are given by bincenters-/+bins,
yielding constant bin sizes of 2 times 'bins'.
2) If 'bins' is a 1darray of the same size as 'bincenters' the bin
limits are given as in (1) for each bin.
3) If 'bins' is a list of two 1darrays, the first array defines the
lower bin spreads, the second array the upper bin spreads from the
center value.
binlimits : str, default='lower'
If 'bincenters' is not set and 'bins' is a 1darray, 'binlimits' sets
wheather 'bins' are lower or upper bin limits. 'bincenters' overwrites
'binlimits'.
Returns
-----
out : 1daraay
"""
time = np.array(time)
lightcurve = np.array(lightcurve)
bins = np.array(bins)
#---create bin limits------------------------------------------------------
# bin centers and spread given:
if bincenters is not None:
bincenters = np.array(bincenters)
if len(bins.shape)<=1:
bins = np.array([bincenters-bins, bincenters+bins])
else:
bins = np.array([bincenters-bins[0], bincenters+bins[1]])
# fixed bin size:
elif len(bins.shape)==0:
binsize = bins
bins = np.arange(time[0], time[-1]+binsize, binsize)
bins = np.array([bins, bins+binsize])
del binsize
# lower or upper limits:
elif len(bins.shape)==1:
if binlimits=='lower':
binlimits = bins
bins = np.zeros((2, len(binlimits)))
bins[0,:] = binlimits
bins[1,:-1] = binlimits[1:]
bins[1,-1] = np.inf
else:
binlimits = bins
bins = np.zeros((2, len(binlimits)))
bins[1,:] = binlimits
bins[0,1:] = binlimits[:-1]
bins[0,0] = -np.inf
# upper and lower limits given:
else:
pass
bins = bins.T
#---bin data---------------------------------------------------------------
# iterate through bins to get data binning:
selections = []
for limlo, limhi in bins:
sel = np.where(np.logical_and(limlo<=time, time<limhi))[0]
selections.append(sel)
# create bined data array:
shape = lightcurve.shape
if len(shape)==1:
lightcurve_binned = np.ones(len(bins)) *np.nan
# iterate through bins:
for i, sel in enumerate(selections):
if len(sel)>0:
lightcurve_binned[i] = np.mean(lightcurve[sel])
else:
lightcurve_binned = np.ones((shape[0], len(bins))) *np.nan
# iterate through light curves:
for i, lc in enumerate(lightcurve):
# iterate through bins:
for j, sel in enumerate(selections):
if len(sel)>0:
lightcurve_binned[i,j] = np.mean(lc[sel])
return lightcurve_binned
#==============================================================================
def add_errors(lightcurve, errors):
"""Add Gaussian errors to a light curve.
Parameters
----------
lightcurve : np.ndarray
The light curve(s).
errors : float or np.ndarray
If a float is given, random errors are drawn from a Gaussian
distribution with zero mean and a standard deviation given by this
float.
If a np.array is given that matches the input lightcurve in length,
the values are randomly shuffled. Then errors are drawn from a Gaussian
distribution with zero mean and the standard deviation corresponding to
each individual data point given by the shuffled values
If a np.array is given that does not match the input lightcurve in
length, random uncertainties are drawn from the ECDF of 'errors'. Then
errors are drawn from a Gaussian distribution with zero mean and the
standard deviation corresponding to each individual data point given by
random draws from the ECDF.
Returns
-------
np.ndarray
The input light curve plus randomly drawn errors.
"""
shape = lightcurve.shape
#---constant error scale---------------------------------------------------
if isinstance(errors, float):
errors = np.random.normal(scale=errors, size=shape)
#---observed errors: shuffle-----------------------------------------------
# shuffle observed error, if as many errors are given as light curve points
elif isinstance(errors, np.ndarray) and len(shape)==1 \
and errors.shape[0]==shape[0]:
errors = np.random.shuffle(errors)
errors = np.random.normal(size=shape) *errors
elif isinstance(errors, np.ndarray) and len(shape)==2 \
and errors.shape[0]==shape[1]:
errors = np.tile(errors, shape[0]).reshape(shape)
map(np.random.shuffle, errors)
errors = np.random.normal(size=shape) *errors
#---observed errors: draw from ECDF----------------------------------------
# draw random error scales from the error ECDF, if the number of light
# curve data points differs from the number of given errors
elif isinstance(errors, np.ndarray):
ecdf = ECDF(errors)
errors = np.interp(np.random.uniform(low=ecdf.y[1], size=shape),
ecdf.y, ecdf.x)
errors = np.random.normal(scale=errors, size=shape)
#---invalid input for errors-----------------------------------------------
else:
print(f"WARNING: Data type '{type(errors)}' for input variable " \
"'errors' in add_errors() is not supported. Give float or " \
"np.ndarray. Aborted!")
return False
return lightcurve + errors
#==============================================================================
def smooth_pg(freq, pg, bins_per_order=10, interpolate=False, verbose=0):
"""Smooth periodogram.
Parameters
----------
freq : np.ndarray
Frequencies of the periodogram.
pg : np.ndarray
Powers of the periodogram.
bins_per_order : int, default: 10
Number of bins per order of magnitude in the covered frequency space.
interpolate : bool, default: False
If True, linearly interpolate empty frequency bins. Otherwise, empty
frequency bins will contain np.nan.
verbose : int, default=0
Controls the amount of information printed.
Returns
-------
freq_bin : np.ndarray
Center frequencies of the binned periodogram.
pg_bin : np.ndarray
Power of the binned periodogram.
pg_uncert : np.ndarray
Uncertainties of the power of the binned periodogram.
"""
# set frequency bins:
order_low = floor(log10(np.min(freq)))
order_high = ceil(log10(np.max(freq)))
bins = np.logspace(order_low, order_high,
bins_per_order*(order_high-order_low)+1)
i = np.where(bins<np.min(freq))[0]
i = i[-1] if len(i)>0 else 0
j = np.where(bins>np.max(freq))[0]
j = j[0] +1 if len(j)>0 else len(bins)
bins = bins[i:j]
# prepare arrays for bined periodogram:
freq_bin = np.zeros((3, len(bins)-1))
freq_bin[0] *= np.nan
freq_bin[1] = bins[:-1]
freq_bin[2] = bins[1:]
pg_bin = np.zeros(len(bins)-1) * np.nan
pg_uncert = np.zeros(len(bins)-1) * np.nan
# average bins: