-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlatent_SDE.py
5900 lines (4918 loc) · 309 KB
/
latent_SDE.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
# Author: Joshua Fagin
import os
import multiprocessing
import gc
import shutil
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.ticker import FormatStrFormatter
import numpy as np
import torch
from torch import nn, optim
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
import torch.nn.functional as F
from tqdm import tqdm
from torch.utils.data import DataLoader, Dataset
from torch.distributions import Normal
from torch.distributions.multivariate_normal import MultivariateNormal
from torch.distributions import Categorical
from model.model import LatentSDE, RNN_baseline
from model.TF import generate_tf
from model.TF_numpy_with_brightness import generate_tf_numpy
import datetime
import torchsde
from glob import glob
import astropy
from astropy.io import fits
from astropy.cosmology import FlatLambdaCDM
import astropy.units as u
import corner
from scipy.fft import ifft
from scipy.optimize import curve_fit
from scipy.interpolate import interp1d
from scipy.signal import convolve, welch, sawtooth, square
from scipy.constants import c
import scipy.stats as stats
from speclite import filters
import pickle
import time
from sys import platform
# This is all for the GPR baseline
import gpytorch
from gpytorch.kernels import MaternKernel, ScaleKernel
from gpytorch.mlls import ExactMarginalLogLikelihood
from botorch.models.multitask import FixedNoiseMultiTaskGP
from botorch.fit import fit_gpytorch_model
import linear_operator.settings as linop_settings
linop_settings._fast_covar_root_decomposition._default = True
linop_settings._fast_log_prob._default = True
linop_settings._fast_solves._default = True
linop_settings.cholesky_max_tries._global_value = 6
linop_settings.max_cholesky_size._global_value = 800
# I didn't end up using this because it leads to NaN in the gradients
from torch.cuda.amp import GradScaler, autocast
torch.backends.cudnn.benchmark = True
import warnings
warnings.filterwarnings("ignore")
np.seterr(divide='ignore', invalid='ignore')
# For debugging
#torch.autograd.set_detect_anomaly(True)
import torch.distributed as dist
import torch.nn.parallel as parallel
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.distributed import DistributedSampler
# So that we have the same validation set each time
np.random.seed(0)
# Plotting settings
size = 13
plt.rc('font', size=size)
plt.rc('axes', titlesize=size)
plt.rc('axes', labelsize=size)
plt.rc('xtick', labelsize=size)
plt.rc('ytick', labelsize=size)
plt.rc('legend', fontsize=size)
plt.rc('figure', titlesize=size)
tick_length_major = 7
tick_length_minor = 3
tick_width = 1
#If plot then display the plots. Otherwise they are only saved
plot = False
#What type of file to save figures as e.g pdf, eps, png, etc.
save_file_format = 'pdf'
#Path to directory where to save the results
save_path = 'results'
#make directory to save results
os.makedirs(save_path, exist_ok=True)
os.makedirs(f'{save_path}/recovery', exist_ok=True)
#The different parameters to predict
parameters_keys = ['spin','log_edd','f_lamp','height','theta_inc','redshift','beta','log_mass', 'log_nu_b', 'alpha_L', 'alpha_H_minus_L', 'standard_deviation']
# Give redshift must be set to False. I never added this to the model.
# NOT USED
give_redshift = False
if give_redshift:
# Redshift is not a parameter to predict since we are giving it to the model
if 'redshift' in parameters_keys:
parameters_keys.remove('redshift')
n_params = len(parameters_keys)
# parameters of the driving variability
parameters_keys_driving = ['log_nu_b', 'alpha_L', 'alpha_H_minus_L', 'standard_deviation']
n_params = len(parameters_keys)
n_params_variability = len(parameters_keys_driving)
n_params_accretion = n_params-n_params_variability
assert(n_params_variability > 0), "Must have at least one variability parameter"
assert(n_params_accretion > 0), "Must have at least one accretion parameter"
#This is used for plotting. Variables with units for axis plotting.
plotting_labels = dict()
plotting_labels['spin'] = r'$a$'
plotting_labels['log_edd'] = r'$\log_{10}(\lambda_{\mathrm{Edd}})$'
plotting_labels['f_lamp'] = r'$f_{\mathrm{Lamp}}$'
plotting_labels['theta_inc'] = r'$\theta_{\mathrm{inc}}$ [deg]'
plotting_labels['height'] = r'$(H-R_{\mathrm{in}})/R_g$'
plotting_labels['redshift'] = r'$z$'
plotting_labels['beta'] = r'$\beta$'
plotting_labels['log_mass'] = r"$\log_{10}\left(M/M_\odot\right)$"
plotting_labels['log_nu_b'] = r'$\log_{10}(\nu_b/\mathrm{day}^{-1})$'
plotting_labels['alpha_L'] = r'$\alpha_L$'
plotting_labels['alpha_H_minus_L'] = r'$\alpha_H - \alpha_L$'
plotting_labels['standard_deviation'] = r'$\sigma$ [mag]'
#This is used for plotting. Variables without units.
plotting_labels_no_units = dict()
plotting_labels_no_units['spin'] = r'$a$'
plotting_labels_no_units['log_edd'] = r'$\log_{10}(\lambda_{\mathrm{Edd}})$'
plotting_labels_no_units['f_lamp'] = r'$f_{\mathrm{Lamp}}$'
plotting_labels_no_units['theta_inc'] = r'$\theta_{\mathrm{inc}}$'
plotting_labels_no_units['height'] = r'$(H-R_{\mathrm{in}})/R_g$'
plotting_labels_no_units['redshift'] = r'$z$'
plotting_labels_no_units['beta'] = r'$\beta$'
plotting_labels_no_units['log_mass'] = r"$\log_{10}\left(M/M_\odot\right)$"
plotting_labels_no_units['log_nu_b'] = r'$\log_{10}(\nu_b)$'
plotting_labels_no_units['alpha_L'] = r'$\alpha_L$'
plotting_labels_no_units['alpha_H_minus_L'] = r'$\alpha_H - \alpha_L$'
plotting_labels_no_units['standard_deviation'] = r'$\sigma$'
#Define the max and min ranges of the parameter space
min_max_dict = dict()
min_max_dict['log_mass'] = (7.0,10.0)
min_max_dict['spin'] = (-1.0,1.0)
min_max_dict['log_edd'] = (-2.0,0.0)
min_max_dict['f_lamp'] = (0.002,0.007)
min_max_dict['theta_inc'] = (0.0,70.0)
min_max_dict['height'] = (0.0,40.0)
min_max_dict['redshift'] = (0.1,5.0)
min_max_dict['beta'] = (0.5,1.0)
min_max_dict['log_nu_b'] = (-3.5,0.0)
min_max_dict['alpha_L'] = (0.25,1.5)
min_max_dict['alpha_H_minus_L'] = (0.75, 2.75)
min_max_dict['standard_deviation'] = (0.0,0.5)
min_max_array = np.array([min_max_dict[key] for key in parameters_keys])
days_per_year = 365
hours_per_day = 24
# This is the size of the light curve. The LSST cadences last for 10 years but we can make predictions for times before or after.
num_years = 10.5
# LSST filters
bandpasses=list('ugrizy')
#effective frequency of LSST bands
lambda_effective_Angstrom = np.array([3671, 4827, 6223, 7546, 8691, 9712]) #in Angstrom
lambda_effective = 1e-10*lambda_effective_Angstrom #in meter
freq_effective = c/lambda_effective #in Hz
lambda_min_LSST = 3000 #in Angstrom
lambda_max_LSST = 11000 #in Angstrom
# Should be set to True. Actually models the spectrum and integrates across the LSST response filters.
model_spectrum = True
# Not used if model_spectrum = True.
mag_mean = [21.52,21.06,20.80,20.64,20.49,20.41]
mag_std = [1.29,1.08,1.01,0.98,0.95,0.94]
min_magnitude = 13.0
max_magnitude = 27.0
# Define the cosmology. We assume a flat universe with H0 = 70 km/s/Mpc and Omega_m = 0.3.
cosmo = FlatLambdaCDM(H0=70 * u.km / u.s / u.Mpc, Om0=0.3)
# For our spectrum model
# Taken from https://github.com/MJTemple/qsogen
f1 = 'model/qsogen_files/qsosed_emlines_20210625.dat'
# wav, median_emlines, continuum, peaky_line, windy_lines, narrow_lines
emline_template = np.genfromtxt(f1, unpack=True)
# S0 galaxy template from SWIRE
# https://ui.adsabs.harvard.edu/abs/2008MNRAS.386..697R/
f2 = 'model/qsogen_files/S0_template_norm.sed'
galaxy_template = np.genfromtxt(f2, unpack=True)
# Extinction curve, format: [lambda, E(lambda-V)/E(B-V)]
# Recall flux_reddened(lambda) = flux(lambda)*10^(-A(lambda)/2.5)
# where A(lambda) = E(B-V)*[E(lambda-V)/E(B-V) + R]
# so taking R=3.1, A(lambda) = E(B-V)*[Col#2 + 3.1]
f3 = 'model/qsogen_files/pl_ext_comp_03.sph'
reddening_curve = np.genfromtxt(f3, unpack=True)
mag_mean = float(np.array(mag_mean).mean())
mag_std = float(np.array(mag_std).mean())
# CHANGE THIS TO THE PATH TO THE DATA!
local = True if platform != 'linux' else False
if local:
# If local, just use a few examples for testing.
file_name_for_cadence = "../../cadence"
num_training_LC = 50
validation_rate = 0.1
else:
# Cadence files generated from: rubin_sim, https://github.com/lsst/rubin_sim
file_name_for_cadence = "../rubin/cadence_100000"
num_training_LC = 100_000
validation_rate = 0.1
assert num_training_LC > 0, "Must have at least one training light curve"
#Fraction of the total data set used as validation set.
num_validation_LC = max(int(validation_rate*num_training_LC),1) # We must have at least one validation light curve
# This
seed_list_train = np.random.randint(0, 99999999, num_training_LC)
seed_list_val = np.random.randint(0, 99999999, num_validation_LC)
#seed_list_train = seed_list_train[:100]
#seed_list_val = seed_list_val[:100]
# Time spacing of data set in days. Ideally this would be smaller but would take up too much memory.
cadence = 1.0
n_params = len(parameters_keys)
output_dim = 2*len(bandpasses) #num bands and uncertainty
num_bands = len(bandpasses) #num bands
# This is an array of the days included in the light curves
days = cadence*np.arange(int(num_years*days_per_year/cadence)+1)
# Get the LSST cadence files
cadence_files = glob(f'{file_name_for_cadence}/*.dat')
num_cadences = len(cadence_files)//len(bandpasses)
del cadence_files
def generate_variability(N, dt, mean_mag, standard_deviation, log_nu_b, alpha_L, alpha_H_minus_L, redshift, extra_time_factor = 8, plot=False):
"""
Function to generate the driving variability from a bended broken power-law PSD.
N: int, number of time steps in the driving signal.
dt: float, time step in days.
mean_mag: float, mean magnitude of the driving signal.
standard_deviation: float, standard deviation of the driving signal.
log_nu_b: float, log10 of the break frequency in days.
alpha_L: float, power law index of the low frequency part of the power spectral density.
alpha_H_minus_L: float, difference between the power law index of the high frequency part and the low frequency part of the power spectral density.
redshift: float, redshift of the driving signal.
extra_time_factor: float, extra time to add to the driving signal to avoid periodic boundary conditions.
plot: bool, if True, plot the driving signal. For debugging purposes.
return: numpy array, driving signal.
"""
# get alpha_H from alpha_H_minus_L and alpha_L
alpha_H = alpha_H_minus_L + alpha_L
# get nu_b from log10(nu_b), this is the rest frame frequency
nu_b_rest = 10.0**log_nu_b
# get nu_b_rest from nu_b and redshift
nu_b = nu_b_rest / (1.0+redshift) # observed frame break frequency
# Apply the extra time to avoid the periodicity of generating a signal
duration = extra_time_factor*N*dt
# Frequency range from 1/duration to the Nyquist frequency
frequencies = np.linspace(1.0/duration, 1.0/(2.0*dt), int(duration//2/dt)+1)
psd = (frequencies**-alpha_L)*(1.0+(frequencies/nu_b)**(alpha_H-alpha_L))**-1
if plot:
plt.figure(figsize=(6, 6))
plt.loglog(frequencies, psd, label='PSD')
plt.loglog(frequencies[frequencies<=nu_b],psd[0]*(frequencies[frequencies<=nu_b]/frequencies[0])**-alpha_L,
linestyle='--', label = f'$P(\\nu) \\propto \\nu^{{-{alpha_L}}}$')
plt.loglog(frequencies[frequencies>nu_b],psd[-1]*(frequencies[frequencies>nu_b]/frequencies[-1])**-alpha_H,
linestyle='--', label = f'$P(\\nu) \\propto \\nu^{{-{alpha_H}}}$')
plt.axvline(nu_b, color='black', linestyle='--', label=r'$\nu = \nu_b$') # This is the observed frame break frequency
plt.xlim(frequencies[0],frequencies[-1])
plt.xlabel('freq [1/days]')
plt.ylabel(r'$P(\nu)$')
plt.legend()
plt.minorticks_on()
plt.tick_params(which='major',direction='in',top=True, right=True,length=tick_length_major,width=tick_width)
plt.tick_params(which='minor',direction='in',top=True, right=True,length=tick_length_minor,width=tick_width)
plt.savefig("Example_PSD_labeled.pdf", bbox_inches='tight')
plt.show()
## Now generate the light curve from the PSD ##
# Generate random phase shifts uniformly distributed in range [0, 2pi]
random_phases = 2.0 * np.pi * np.random.random(size=frequencies.size)
# Generate complex-valued function of frequency
fourier_transform = np.sqrt(psd) * np.exp(1j*random_phases)
# Make sure the function of frequency is Hermitian
fourier_transform = np.concatenate((fourier_transform, fourier_transform[-2:0:-1].conjugate()))
# Generate time series using inverse Fourier transform, drop the imaginary part (should be ~0)
timeseries = ifft(fourier_transform).real
# Normalize flux to have mean zero and variance one
timeseries = timeseries - timeseries.mean()
timeseries = timeseries / timeseries.std()
# Now set to the desired mean magnitude and stdev
timeseries = timeseries * standard_deviation
timeseries = timeseries + mean_mag
# Time array
time = np.linspace(0, duration, int(duration/dt))
# get rid of the extra time to not include the periodic boundary condition and to use unbiased mean_mag and standard_deviation
timeseries = timeseries[N: 2*N] # Take out an N time step section
time = time[:N]
if plot:
# Plot time series
plt.figure(figsize=(12, 4))
plt.plot(time, timeseries)
plt.ylim(mean_mag-4*standard_deviation,mean_mag+4*standard_deviation)
plt.xlim(time[0],time[-1])
plt.gca().invert_yaxis()
plt.xlabel('time [days]')
plt.ylabel('magnitude')
plt.minorticks_on()
plt.tick_params(which='major',direction='in',top=True, right=True,length=tick_length_major,width=tick_width)
plt.tick_params(which='minor',direction='in',top=True, right=True,length=tick_length_minor,width=tick_width)
plt.savefig("Example_xray_variability.pdf", bbox_inches='tight')
plt.show()
if plot:
# The PSD cannot be recovered at very low frequency due to red noise leak from not having long enough light curve and alliasing
frac_sep = 0.5
frequencies_measured, psd_measured = welch(timeseries, fs=1/dt, nperseg=frac_sep*duration/extra_time_factor)
psd_measured = psd_measured/psd_measured[int(0.5*len(psd_measured))] # normalize by point 90% through measured PSD
# Theoretical PSD
psd = psd/psd[int(0.5*len(psd))] # normalize by point 90% through the PSD. This is just for plotting purposes.
plt.figure(figsize=(6, 6))
plt.loglog(frequencies, psd, label='theoretical PSD')
plt.loglog(frequencies_measured, psd_measured, label='measured PSD')
plt.loglog(frequencies[frequencies<=nu_b],psd[0]*(frequencies[frequencies<=nu_b]/frequencies[0])**-alpha_L,
linestyle='--', label = f'$P(\\nu) \\propto \\nu^{{-{alpha_L}}}$')
plt.loglog(frequencies[frequencies>nu_b],psd[-1]*(frequencies[frequencies>nu_b]/frequencies[-1])**-alpha_H,
linestyle='--', label = f'$P(\\nu) \\propto \\nu^{{-{alpha_H}}}$')
plt.axvline(nu_b, color='black', linestyle='--', label=r'$\nu = \nu_b$')
plt.title("Example Recovered PSD")
plt.xlim(1.0/(duration/extra_time_factor),frequencies[-1])
plt.xlabel('frequency [1/day]')
plt.ylabel('PSD')
plt.legend()
plt.minorticks_on()
plt.tick_params(which='major',direction='in',top=True, right=True,length=tick_length_major,width=tick_width)
plt.tick_params(which='minor',direction='in',top=True, right=True,length=tick_length_minor,width=tick_width)
plt.savefig("Example_PSD_recovery.pdf", bbox_inches='tight')
plt.show()
return timeseries
def generate_driving_variability_torch(N, dt, mean_mag, standard_deviation, log_nu_b, alpha_L, alpha_H_minus_L, phases, redshift, device, dtype=torch.float32, extra_time_factor = 8, plot=False):
"""
Not used in this work but included for completeness.
This function generates a driving signal using PyTorch to work on GPU and with auto-differentiation.
N: int, number of time steps in the driving signal.
dt: float, time step in days.
mean_mag: float, mean magnitude of the driving signal.
standard_deviation: float, standard deviation of the driving signal.
log_nu_b: float, log10 of the break frequency in days.
alpha_L: float, power law index of the low frequency part of the power spectral density.
alpha_H_minus_L: float, difference between the power law index of the high frequency part and the low frequency part of the power spectral density.
phases: Either None, or torch tensor, random phases uniformly distributed in range [0, 1]. If none then the phases are generated randomly.
redshift: float, redshift of the driving signal.
device: torch device, device to use for the computation.
dtype: torch dtype, data type to use for the computation.
extra_time_factor: float, extra time to add to the driving signal to avoid periodic boundary conditions.
plot: bool, if True, plot the driving signal. For debugging purposes.
return: torch tensor of shape (N, 1), driving signal.
"""
# get alpha_H from alpha_H_minus_L and alpha_L
alpha_H = alpha_H_minus_L + alpha_L
# get nu_b from log10(nu_b)
nu_b = 10.0**log_nu_b
# apply the redshift to the time domain
dt = dt*(1.0+redshift) # We could have applied the redshift to the frequency domain instead
# Apply the extra time to avoid the periodicity of generating a signal
duration = extra_time_factor*N*dt
# Frequency range from 1/duration to the Nyquist frequency
frequencies = torch.linspace(1.0/duration, 1.0/(2.0*dt), int(duration//2/dt)+1, dtype=dtype, device=device)
psd = (frequencies**-alpha_L)*(1.0+(frequencies/nu_b)**(alpha_H-alpha_L))**-1
if plot:
plt.figure(figsize=(6, 6))
plt.loglog(frequencies, psd, label='PSD')
plt.loglog(frequencies[frequencies<=nu_b],psd[0]*(frequencies[frequencies<=nu_b]/frequencies[0])**-alpha_L,
linestyle='--', label = f'$P(\\nu) \\propto \\nu^{{-{alpha_L}}}$')
plt.loglog(frequencies[frequencies>nu_b],psd[-1]*(frequencies[frequencies>nu_b]/frequencies[-1])**-alpha_H,
linestyle='--', label = f'$P(\\nu) \\propto \\nu^{{-{alpha_H}}}$')
plt.axvline(nu_b, color='black', linestyle='--', label=r'$\nu = \nu_b$')
plt.xlim(frequencies[0],frequencies[-1])
plt.xlabel('freq [1/days]')
plt.ylabel(r'$P(\nu)$')
plt.legend()
plt.minorticks_on()
plt.tick_params(which='major',direction='in',top=True, right=True,length=tick_length_major,width=tick_width)
plt.tick_params(which='minor',direction='in',top=True, right=True,length=tick_length_minor,width=tick_width)
plt.savefig("Example_PSD_labeled.pdf", bbox_inches='tight')
plt.show()
# Now generate the light curve from the PSD
# Generate random phase shifts uniformly distributed in range [0, 2pi]
if phases is None:
random_phases = 2.0 * np.pi * torch.rand(frequencies.shape, dtype=dtype, device=device)
else:
random_phases = 2.0 * np.pi * phases.type(dtype).to(device)
#random_phases = 2.0 * np.pi * phases
# Generate complex-valued function of frequency
fourier_transform = torch.sqrt(psd) * torch.exp(1j*random_phases)
# Make sure the function of frequency is Hermitian
#fourier_transform = torch.cat((fourier_transform, fourier_transform[-2:0:-1].conj()))
fourier_transform = torch.cat((fourier_transform, torch.flip(fourier_transform, dims=(0,))[1:-1]))
# Generate time series using inverse Fourier transform, drop the imaginary part (should be ~0)
timeseries = torch.fft.ifft(fourier_transform).real
# Normalize flux to have mean zero and variance one
timeseries = timeseries - timeseries.mean()
timeseries = timeseries / timeseries.std()
timeseries = timeseries.unsqueeze(1) * standard_deviation.unsqueeze(0)
timeseries = timeseries + mean_mag.unsqueeze(0)
# get rid of the extra time to not include the periodic boundary condition and to use unbiased mean_mag and standard_deviation
#timeseries = timeseries[N: 2*N]
timeseries = timeseries[N:2*N]
if plot:
# Time array
time = torch.linspace(0, duration, int(duration/dt)).type(dtype).to(device)
time = time[:N]
# Plot time series
plt.figure(figsize=(12, 4))
plt.plot(time.detach().cpu().numpy(), timeseries.detach().cpu().numpy())
plt.title("Normalized X-ray Flux")
plt.ylim(mean_mag-4*standard_deviation,mean_mag+4*standard_deviation)
plt.xlim(time[0],time[-1])
plt.xlabel('time [days]')
plt.ylabel('normalized flux')
plt.minorticks_on()
plt.tick_params(which='major',direction='in',top=True, right=True,length=tick_length_major,width=tick_width)
plt.tick_params(which='minor',direction='in',top=True, right=True,length=tick_length_minor,width=tick_width)
plt.savefig("Example_xray_variability.pdf", bbox_inches='tight')
plt.show()
return timeseries
def make_light_curve(transfer_function, log_nu_b, alpha_L , alpha_H_minus_L, standard_deviation, band_mean_mag, band_mean_mag_without_host_galaxy, redshift, kernel_num_days, kernel_resolution, reference_band, plot=False, custom_driving_signal=None):
"""
This function generated a light curve by convolving it with a transfer function.
transfer_function: numpy array of shape (length_t, num_bands), transfer function used as a kernel to convolve with DRW.
log_nu_b: float, log10 of the break frequency in days.
alpha_L: float, power law index of the low frequency part of the power spectral density.
alpha_H_minus_L: float, difference between the power law index of the high frequency part and the low frequency part of the power spectral density.
standard_deviation: float, sandard deviation of the driving signal.
band_mean_mag: numpy array of shape (num_bands), mean magnitude of each band.
band_mean_mag_without_host_galaxy: numpy array of shape (num_bands), mean magnitude of each band excluding the contribution of the driving signal.
redshift: float, redshift the spectrum into the observers frame to integrate across the LSST filters
kernel_num_days: int, number of dats in the transfer function kernels
kernel_resolution: float, resolution of the transfer function bins
reference_band: int, an arbitrary reference band to determine the normalization of the driving signal
plot: bool, if True, plot the light curve and DRW. For debugging purposes.
custom_driving_signal: function, a custom driving signal function to use instead of the default bended broken power-law
return: numpy array of shape (length_t, num_bands), light curve.
"""
# Extra time points to make sure the convolution is done correctly at the edges
extra_time = kernel_num_days
num_days = num_years*days_per_year
t = np.linspace(0,num_days,int(num_days/cadence)+1)
dt = kernel_resolution # time step in days
duration = num_days+extra_time
t_high_res = np.linspace(0,num_days,int(num_days/dt)+1)
N = int(extra_time/dt)+int(num_days/dt) # driving N time steps
### Figure out what to do here ###
# Generate the driving signal with zero mean
driving_mean_mag = 0.0
# Use redshift 0.0 so nu_b is in the observed frame
if custom_driving_signal is None:
driving = generate_variability(N, dt, driving_mean_mag, standard_deviation, log_nu_b, alpha_L, alpha_H_minus_L, redshift=0.0, extra_time_factor = 8, plot=False)
else:
# use some custom function instead of the broken power law
driving = custom_driving_signal(N, dt, driving_mean_mag, standard_deviation, log_nu_b, alpha_L, alpha_H_minus_L, extra_time_factor = 8) # We just use this to test other kinds of driving signals than the broken power law after training.
flux_without_host_galaxy = mag_to_flux(np.expand_dims(band_mean_mag_without_host_galaxy, axis=0) + np.expand_dims(driving, axis=1))
flux_from_host_galaxy = mag_to_flux(np.expand_dims(band_mean_mag, axis=0))-mag_to_flux(np.expand_dims(band_mean_mag_without_host_galaxy, axis=0))
assert np.min(flux_from_host_galaxy) >= 0.0, "Flux from host galaxy must be positive, the host galaxy must never take flux away from the quasar."
light_curve_high_res = flux_without_host_galaxy + flux_from_host_galaxy
driving_save = flux_to_mag(light_curve_high_res[:, reference_band])
# light curve at resolution of cadence.
light_curve = np.zeros((len(t),len(bandpasses)))
for i in range(len(bandpasses)):
conv = np.convolve(light_curve_high_res[:, i], transfer_function[:,i], mode='valid')
if cadence != dt:
light_curve[:,i] = np.interp(t, t_high_res, conv)
else:
light_curve[:,i] = conv
del conv, light_curve_high_res
# convert light curve from F_nu in units of erg/s/cm^2/Hz to magnitude
light_curve = flux_to_mag(light_curve)
# plot the DRW and then the convolved light curve for each band
if plot:
# plot the light curve
driving_norm = driving_save[transfer_function.shape[0]-1:]
light_curve_norm1 = light_curve[:,0]
light_curve_norm2 = light_curve[:,1]
light_curve_norm3 = light_curve[:,2]
driving_norm = driving_norm - driving_norm.mean()
driving_norm = driving_norm/driving_norm.std()
driving_norm = driving_norm*0.2+19.7
light_curve_norm1 = light_curve_norm1 - light_curve_norm1.mean()
light_curve_norm1 = light_curve_norm1/light_curve_norm1.std()
light_curve_norm1 = light_curve_norm1*0.2+19.9
light_curve_norm2 = light_curve_norm2 - light_curve_norm2.mean()
light_curve_norm2 = light_curve_norm2/light_curve_norm2.std()
light_curve_norm2 = light_curve_norm2*0.2+20.1
light_curve_norm3 = light_curve_norm3 - light_curve_norm3.mean()
light_curve_norm3 = light_curve_norm3/light_curve_norm3.std()
light_curve_norm3 = light_curve_norm3*0.2+20.3
# plot the time delays
zoom_time = 50 # days
plt.figure(figsize=(6, 4))
plt.plot(t, driving_norm, label='driving', color='black')
plt.plot(t,light_curve_norm1,label=bandpasses[0], color="blue")
plt.plot(t,light_curve_norm2,label=bandpasses[1], color="green")
plt.plot(t,light_curve_norm3,label=bandpasses[2], color="#F2D91A")
# get time delay
time_delay1 = np.sum(transfer_function[:,0]*np.arange(transfer_function.shape[0]))*dt
time_delay2 = np.sum(transfer_function[:,1]*np.arange(transfer_function.shape[0]))*dt
time_delay3 = np.sum(transfer_function[:,2]*np.arange(transfer_function.shape[0]))*dt
# plot the time delay arrow
start_time = 15 #np.argmax(np.abs(light_curve_norm1[:zoom_time]))
head_width = 0.05
head_length = 1.0
start_height = min(driving_norm[:int(zoom_time/dt)]-0.3)
plt.arrow(start_time, start_height, time_delay1, 0, head_width=head_width, head_length=head_length, fc='blue', ec='blue')
# arrow text
plt.text(start_time-9, start_height+0.025, f'{time_delay1:.1f} days', color='blue', fontsize=12)
plt.arrow(start_time, start_height+0.1, time_delay2, 0, head_width=head_width, head_length=head_length, fc='green', ec='green')
plt.text(start_time-9, start_height+0.1+0.025, f'{time_delay2:.1f} days', color='green', fontsize=12)
plt.arrow(start_time, start_height+0.2, time_delay3, 0, head_width=head_width, head_length=head_length, fc='#F2D91A', ec='#F2D91A')
plt.text(start_time-9, start_height+0.2+0.025, f'{time_delay3:.1f} days', color='#F2D91A', fontsize=12)
plt.ylim(start_height-0.1, np.max(light_curve_norm3[:int(zoom_time/dt)]+0.1))
plt.xlim(0, zoom_time)
plt.gca().invert_yaxis()
plt.minorticks_on()
plt.tick_params(which='major',direction='in',top=True, right=True,length=tick_length_major,width=tick_width)
plt.tick_params(which='minor',direction='in',top=True, right=True,length=tick_length_minor,width=tick_width)
#plt.xlim(t.min(),t.max())
plt.xlabel('time [days]')
plt.ylabel('magnitude')
plt.tight_layout()
plt.savefig("Example_time_delay.pdf", bbox_inches='tight')
plt.show()
if plot:
for i in range(len(bandpasses)):
plt.plot(transfer_function[:,i],label=bandpasses[i])
min_val = np.argmax((transfer_function[0,:]>0.0001)+np.array(range(transfer_function.shape[-1])) * 1e-5)
plt.minorticks_on()
plt.tick_params(which='major',direction='in',top=True, right=True,length=tick_length_major,width=tick_width)
plt.tick_params(which='minor',direction='in',top=True, right=True,length=tick_length_minor,width=tick_width)
#plt.xlim(0,min_val)
plt.legend()
plt.xlabel(f'time')
plt.ylabel('PD')
plt.savefig('transfer_function.pdf',bbox_inches='tight')
plt.show()
plt.figure(figsize=(12, 3))
for i in range(len(bandpasses)):
plt.plot(t,light_curve[:,i],label=bandpasses[i])
#DRW_mag = flux_to_mag(DRW/freq_effective.mean())
#DRW_mag = DRW_mag - DRW_mag.mean()+light_curve.max()+0.05
#plt.plot(t_hourly_extra,DRW_mag,color='black',label='DRW')
plt.gca().invert_yaxis()
plt.minorticks_on()
plt.tick_params(which='major',direction='in',top=True, right=True,length=tick_length_major,width=tick_width)
plt.tick_params(which='minor',direction='in',top=True, right=True,length=tick_length_minor,width=tick_width)
plt.xlim(t.min(),t.max())
plt.legend(loc='upper left')
plt.xlabel('time [days]')
plt.ylabel('magnitude')
plt.savefig('DRW_light_curve.pdf',bbox_inches='tight')
plt.tight_layout()
plt.show()
# linearly interpolate the driving_save so that it is at the same resolution as the light curve
if cadence != dt:
driving_save = np.interp(np.linspace(0,1,int(duration/cadence)), np.linspace(0,1,driving_save.shape[0]), driving_save)
return light_curve, transfer_function, driving_save
class Quasar_sed():
"""
@author: Matthew Temple
https://github.com/MJTemple/qsogen
# Modified by: Joshua Fagin for use in my project but original code by Matthew Temple. All credit to Matthew Temple.
# See his paper: https://arxiv.org/abs/2109.04472
Construct an instance of the quasar SED model.
Attributes
----------
flux : ndarray
Flux per unit wavelength from total SED, i.e. quasar plus host galaxy.
host_galaxy_flux : ndarray
Flux p.u.w. from host galaxy component of the model SED.
wavlen : ndarray
Wavelength array in the rest frame.
wavred : ndarray
Wavelength array in the observed frame.
Examples
--------
Create and plot quasar models using default params at redshifts z=2 and z=4
>>> Quasar2 = Quasar_sed(z=2)
>>> Quasar4 = Quasar_sed(z=4)
>>> import matplotlib.pyplot as plt
>>> plt.plot(Quasar2.wavred, Quasar2.flux, label='$z=2$ quasar model')
>>> plt.plot(Quasar4.wavred, Quasar4.flux, label='$z=4$ quasar model')
"""
def __init__(self,
params,
wavlen,
):
"""Initialises an instance of the Quasar SED model.
Parameters
----------
z : float, optional
Redshift. If `z` is less than 0.005 then 0.005 is used instead.
LogL3000 : float, optional
Monochromatic luminosity at 3000A of (unreddened) quasar model,
used to scale model flux such that synthetic magnitudes can be
computed.
wavlen : ndarray, optional
Rest-frame wavelength array. Default is log-spaced array covering
~890 to 30000 Angstroms. `wavlen` must be monotonically increasing,
and if gflag==True, `wavlen` must cover 4000-5000A to allow the
host galaxy component to be properly normalised.
ebv : float, optional
Extinction E(B-V) applied to quasar model. Not applied to galaxy
component. Default is zero.
zlum_lumval : array, optional
Redshift-luminosity relation used to control galaxy and emission-
line contributions. `zlum_lumval[0]` is an array of redshifts, and
`zlum_lumval[1]` is an array of the corresponding absolute i-band
magnitudes M_i. Default is the median M_i from SDSS DR16Q in the
apparent magnitude range 18.6<i<19.1.
M_i :float, optional
Absolute i-band magnitude (at z=2), as reported in SDSS DR16Q, used
to control scaling of emission-line and host-galaxy contributions.
Default is to use the relevant luminosity from `zlum_lumval`, which
gives a smooth scaling with redshift `z`.
params : dict, optional
Dictionary of additional parameters, including emission-line and
host-galaxy template SEDs, reddening curve. Default is to read in
from config.py file.
Other Parameters
----------------
tbb : float, optional
Temperature of hot dust blackbody in Kelvin.
bbnorm : float, optional
Normalisation, relative to power-law continuum at 2 micron, of the
hot dust blackbody.
scal_emline : float, optional
Overall scaling of emission line template. Negative values preserve
relative equivalent widths while positive values preserve relative
line fluxes. Default is -1.
emline_type : float, optional
Type of emission line template. Minimum allowed value is -2,
corresponding to weak, highly blueshifed lines. Maximum allowed is
+3, corresponding to strong, symmetric lines. Zero correspondes to
the average emission line template at z=2, and -1 and +1 map to the
high blueshift and high EW extrema observed at z=2. Default is
None, which uses `beslope` to scale `emline_type` as a smooth
function of `M_i`.
scal_halpha, scal_lya, scal_nlr : float, optional
Additional scalings for the H-alpha, Ly-alpha, and for the narrow
optical lines. Default is 1.
beslope : float, optional
Baldwin effect slope, which controls the relationship between
`emline_type` and luminosity `M_i`.
bcnorm : float, optional
Balmer continuum normalisation. Default is zero as default emission
line templates already include the Balmer Continuum.
lyForest : bool, optional
Flag to include Lyman absorption from IGM. Default is True.
lylim : float, optional
Wavelength of Lyman-limit system, below which all flux is
suppressed. Default is 912A.
gflag : bool, optional
Flag to include host-galaxy emission. Default is True.
fragal : float, optional
Fractional contribution of the host galaxy to the rest-frame 4000-
5000A region of the total SED, for a quasar with M_i = -23.
gplind : float, optional
Power-law index dependence of galaxy luminosity on M_i.
emline_template : array, optional
Emission line templates. Array must have structure
[wavelength, average lines, reference continuum,
high-EW lines, high-blueshift lines, narrow lines]
reddening_curve : array, optional
Quasar reddening law.
Array must have structure [wavelength lambda, E(lambda-V)/E(B-V)]
galaxy_template : array, optional
Host-galaxy SED template.
Array must have structure [lambda, f_lambda].
Default is an S0 galaxy template from the SWIRE library.
"""
_params = params.copy()
z = _params['z']
self.z = max(float(z), 0.005)
# avoid crazy flux normalisation at zero redshift
self.wavlen = wavlen
if np.any(self.wavlen[:-1] > self.wavlen[1:]):
raise Exception('wavlen must be monotonic')
self.flux = np.zeros_like(self.wavlen)
self.host_galaxy_flux = np.zeros_like(self.wavlen)
self.ebv = _params['ebv']
self.plslp1 = _params['plslp1']
self.plslp2 = _params['plslp2']
self.plstep = _params['plstep']
self.tbb = _params['tbb']
self.plbrk1 = _params['plbrk1']
self.plbrk3 = _params['plbrk3']
self.bbnorm = _params['bbnorm']
self.scal_emline = _params['scal_emline']
self.emline_type = _params['emline_type']
self.scal_halpha = _params['scal_halpha']
self.scal_lya = _params['scal_lya']
self.scal_nlr = _params['scal_nlr']
self.emline_template = _params['emline_template']
self.reddening_curve = _params['reddening_curve']
self.galaxy_template = _params['galaxy_template']
self.continuum = _params['continuum'] # We don't want to modify the original continuum outside of this class
self.beslope = _params['beslope']
self.benorm = _params['benorm']
self.bcnorm = _params['bcnorm']
self.fragal = _params['fragal']
self.gplind = _params['gplind']
self.zlum = _params['zlum_lumval'][0]
self.lumval = _params['zlum_lumval'][1]
if _params['M_i'] is not None:
self.M_i = _params['M_i']
else:
self.M_i = np.interp(self.z, self.zlum, self.lumval)
#######################################################
# READY, SET, GO!
#######################################################
'''
self.set_continuum() # We don't want to use this since we have our own continuum
self.add_blackbody() # We won't get any black body emission from the hot dust since it only emits after 10000 Angstroms
# We don't need this because it is included in the emission line templates
if self.bcnorm:
self.add_balmer_continuum()
# We don't need this because our continuum is already in f_lambda in physical units
if LogL3000 is not None:
self.f3000 = (10**(LogL3000 - four_pi_dL_sq(self.z))
/ (3000*(1 + self.z)))
self.convert_fnu_flambda(flxnrm=self.f3000, wavnrm=3000)
else:
self.convert_fnu_flambda()
'''
# Set the flux to our continuum
self.flux = self.continuum
self.add_emission_lines()
if _params['gflag']:
self.host_galaxy()
# creates self.host_galaxy_flux object
# need to create this before reddening qso to get correct normalisation
# redden spectrum if E(B-V) != 0
if self.ebv:
self.redden_spectrum()
# add in host galaxy flux
if _params['gflag']:
self.flux += self.host_galaxy_flux
# simulate the effect of a Lyman limit system at rest wavelength Lylim
# by setting flux equal to zero at wavelengths < Lylim angstroms
if _params['lyForest']:
lylim = self.wav2num(_params['lylim'])
self.flux[:lylim] = 0.0
self.host_galaxy_flux[:lylim] = 0.0
# Then add in Ly forest absorption at z>1.4
self.lyman_forest()
# redshift spectrum
#self.wavred = (self.z + 1)*self.wavlen
def wav2num(self, wav):
"""Convert a wavelength to an index."""
return np.argmin(np.abs(self.wavlen - wav))
def wav2flux(self, wav):
"""Convert a wavelength to a flux.
Different from self.flux[wav2num(wav)], as wav2flux interpolates in an
attempt to avoid problems when wavlen has gaps. This mitigation only
works before the emission lines are added to the model, and so wav2flux
should only be used with a reasonably dense wavelength array.
"""
return np.interp(wav, self.wavlen, self.flux)
@staticmethod
def pl(wavlen, plslp, const):
"""Define power-law in flux density per unit frequency."""
return const*wavlen**plslp
@staticmethod
def bb(tbb, wav):
"""Blackbody shape in flux per unit frequency.
Parameters
----------
tbb
Temperature in Kelvin.
wav : float or ndarray of floats
Wavelength in Angstroms.
Returns
-------
Flux : float or ndarray of floats
(Non-normalised) Blackbody flux density per unit frequency.
Notes
-----
h*c/k_b = 1.43877735e8 KelvinAngstrom
"""
return (wav**(-3))/(np.exp(1.43877735e8 / (tbb*wav)) - 1.0)
def set_continuum(self, flxnrm=1.0, wavnrm=5500):
"""Set multi-powerlaw continuum in flux density per unit frequency."""
# Flip signs of powerlaw slopes to enable calculation to be performed
# as a function of wavelength rather than frequency
sl1 = -self.plslp1
sl2 = -self.plslp2
wavbrk1 = self.plbrk1
# Define normalisation constant to ensure continuity at wavbrk
const2 = flxnrm/(wavnrm**sl2)
const1 = const2*(wavbrk1**sl2)/(wavbrk1**sl1)
# Define basic continuum using the specified normalisation fnorm at
# wavnrm and the two slopes - sl1 (<wavbrk) sl2 (>wavbrk)
fluxtemp = np.where(self.wavlen < wavbrk1,
self.pl(self.wavlen, sl1, const1),
self.pl(self.wavlen, sl2, const2))
# Also add steeper power-law component for sub-Lyman-alpha wavelengths
sl3 = sl1 - self.plstep
wavbrk3 = self.plbrk3
# Define normalisation constant to ensure continuity
const3 = const1*(wavbrk3**sl1)/(wavbrk3**sl3)
self.flux = np.where(self.wavlen < wavbrk3,
self.pl(self.wavlen, sl3, const3),
fluxtemp)
def add_blackbody(self, wnorm=20000.):
"""Add basic blackbody spectrum to the flux distribution."""
bbnorm = self.bbnorm # blackbody normalisation at wavelength wnorm
tbb = self.tbb
if bbnorm > 0:
bbval = self.bb(tbb, wnorm)
cmult = bbnorm / bbval
bb_flux = cmult*self.bb(tbb, self.wavlen)
self.flux += bb_flux
def convert_fnu_flambda(self, flxnrm=1.0, wavnrm=5100):
"""Convert f_nu to f_lamda, using c/lambda^2 conversion.
Normalise such that f_lambda(wavnrm) is equal to flxnrm.
"""
self.flux = self.flux*self.wavlen**(-2)
self.flux = self.flux*flxnrm/self.wav2flux(wavnrm)
def add_emission_lines(self, wavnrm=5500, wmin=6000, wmax=7000):
"""Add emission lines to the model SED.
Emission-lines are included via 4 emission-line templates, which are
packaged with a reference continuum. One of these templates gives the
average line emission for a M_i=-27 SDSS DR16 quasar at z~2. The narrow
optical lines have been isolated in a separate template to allow them
to be re-scaled if necesssary. Two templates represent the observed
extrema of the high-ionisation UV lines, with self.emline_type
controlling the balance between strong, peaky, systemic emission and
weak, highly skewed emission. Default is to let this vary as a function
of redshift using self.beslope, which represents the Baldwin effect.
The template scaling is specified by self.scal_emline, with positive
values producing a scaling by intensity, whereas negative values give a
scaling that preserves the equivalent-width of the lines relative
to the reference continuum template. The facility to scale the H-alpha
line by a multiple of the overall emission-line scaling is included
through the parameter scal_halpha, and the ability to rescale the
narrow [OIII], Hbeta, etc emission is included through scal_nlr.
"""
scalin = self.scal_emline
scahal = self.scal_halpha
scalya = self.scal_lya
scanlr = self.scal_nlr
beslp = self.beslope
benrm = self.benorm
if self.emline_type is None:
if beslp:
vallum = self.M_i
self.emline_type = (vallum - benrm)*beslp
else:
self.emline_type = 0. # default median emlines
varlin = self.emline_type
linwav, medval, conval, pkyval, wdyval, nlr = self.emline_template
if varlin == 0.:
# average emission line template for z~2 SDSS DR16Q-like things
linval = medval + (scanlr-1.)*nlr
elif varlin > 0:
# high EW emission line template