-
Notifications
You must be signed in to change notification settings - Fork 19
/
pptoas.py
executable file
·1629 lines (1579 loc) · 83.5 KB
/
pptoas.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
##########
# pptoas #
##########
#pptoas is a command-line program used to simultaneously fit for phases
# (phis/TOAs), dispersion measures (DMs), frequency**-4 delays (GMs),
# scattering timescales (taus), and scattering indices (alphas). Mean flux
# densities can also be estimated from the fitted model. Full-functionality
# is obtained when using pptoas within an interactive python environment.
#Written by Timothy T. Pennucci (TTP; [email protected]).
#Contributions by Scott M. Ransom (SMR) and Paul B. Demorest (PBD).
from pptoaslib import *
#cfitsio defines a maximum number of files (NMAXFILES) that can be opened in
#the header file fitsio2.h. Without calling unload() with PSRCHIVE, which
#touches the archive, I am not sure how to close the files. So, to avoid the
#loop crashing, set a maximum number of archives for pptoas. Modern machines
#should be able to handle almost 1000.
max_nfile = 999
#See F0_fact in pplib.py
if F0_fact:
rm_baseline = True
else:
rm_baseline = False
class TOA:
"""
TOA class bundles common TOA attributes together with useful functions.
"""
def __init__(self, archive, frequency, MJD, TOA_error, telescope,
telescope_code, DM=None, DM_error=None, flags={}):
"""
Form a TOA.
archive is the string name of the TOA's archive.
frequency is the reference frequency [MHz] of the TOA.
MJD is a PSRCHIVE MJD object (the TOA, topocentric).
TOA_error is the TOA uncertainty [us].
telescope is the name of the observatory.
telescope_code is the string written on the TOA line.
DM is the full DM [cm**-3 pc] associated with the TOA.
DM_error is the DM uncertainty [cm**-3 pc].
flags is a dictionary of arbitrary TOA flags
(e.g. {'subint':0, 'be':'GUPPI'}).
"""
self.archive = archive
self.frequency = frequency
self.MJD = MJD
self.TOA_error = TOA_error
self.telescope = telescope
self.telescope_code = telescope_code
self.DM = DM
self.DM_error = DM_error
self.flags = flags
for flag in flags.keys():
exec('self.%s = flags["%s"]'%(flag, flag))
def write_TOA(self, inf_is_zero=True, outfile=None):
"""
Print a loosely IPTA-formatted TOA to standard output or to file.
inf_is_zero=True follows the TEMPO/2 convention of writing 0.0 MHz as
the frequency for infinite-frequency TOAs.
outfile is the output file name; if None, will print to standard
output.
"""
write_TOAs(self, inf_is_zero=inf_is_zero, outfile=outfile, append=True)
class GetTOAs:
"""
GetTOAs is a class with methods to measure TOAs and DMs from data.
"""
def __init__(self, datafiles, modelfile, quiet=False):
"""
Unpack all of the data and set initial attributes.
datafiles is either a single PSRCHIVE file name, or a name of a
metafile containing a list of archive names.
modelfile is a ppgauss or ppspline model file. modelfile can also be
an arbitrary PSRCHIVE archive, although this feature is
*not*quite*implemented*yet*.
quiet=True suppresses output.
"""
if file_is_type(datafiles, "ASCII"):
self.datafiles = [datafile[:-1] for datafile in \
open(datafiles, "r").readlines()]
else:
self.datafiles = [datafiles]
if len(self.datafiles) > max_nfile:
print "Too many archives. See/change max_nfile(=%d) in pptoas.py."%max_nfile
sys.exit()
self.is_FITS_model = file_is_type(modelfile, "FITS")
self.modelfile = modelfile # the model file in use
self.obs = [] # observatories from the observations
self.doppler_fs = [] # PSRCHIVE Doppler factors from Earth's motion
self.nu0s = [] # PSRCHIVE center frequency
self.nu_fits = [] # reference frequencies for the fit
self.nu_refs = [] # reference frequencies for the output
self.ok_idatafiles = [] # list of indices for good/examined datafiles
self.ok_isubs = [] # list of indices for the good subintegrations
self.epochs = [] # PSRCHIVE midpoints of the subintegrations
self.MJDs = [] # same as epochs, in days
self.Ps = [] # PSRCHIVE spin period at each epoch
self.phis = [] # the fitted phase shifts / phi parameter
self.phi_errs = [] # their uncertainties
self.TOAs = [] # the fitted TOA
self.TOA_errs = [] # their uncertainties
self.DM0s = [] # the stored PSRCHIVE header DMs
self.DMs = [] # the fitted DMs (may include the Doppler correction)
self.DM_errs = [] # their uncertainties
self.DeltaDM_means = [] # fitted single mean DM-DM0
self.DeltaDM_errs = [] # their uncertainties
self.GMs = [] # fitted "GM" parameter, from delays that go as nu**-4
self.GM_errs = [] # their uncertainties
self.taus = [] # fitted scattering timescales
self.tau_errs = [] # their uncertainties
self.alphas = [] # fitted scattering indices
self.alpha_errs = [] # their uncertainties
self.scales = [] # fitted per-channel scaling parameters
self.scale_errs = [] # their uncertainties
self.snrs = [] # signal-to-noise ratios (S/N)
self.channel_snrs = [] # per-channel S/Ns
self.profile_fluxes = [] # estimated per-channel fluxes
self.profile_flux_errs = [] # their uncertainties
self.fluxes = [] # estimated overall fluxes
self.flux_errs = [] # their uncertainties
self.flux_freqs = [] # their reference frequencies
self.red_chi2s = [] # reduced chi2 values of the fit
self.channel_red_chi2s = [] # per-channel reduced chi2 values
self.covariances = [] # full covariance matrices
self.nfevals = [] # number of likelihood function evaluations
self.rcs = [] # return codes from the fit
self.fit_durations = [] # durations of the fit
self.order = [] # order that datafiles are examined (deprecated)
self.TOA_list = [] # complete, single list of TOAs
self.zap_channels = [] # proposed channels to be zapped
# dictionary of instrumental response characteristics
self.instrumental_response_dict = self.ird = \
{'DM':0.0, 'wids':[], 'irf_types':[]}
self.quiet = quiet # be quiet?
def get_TOAs(self, datafile=None, tscrunch=False, nu_refs=None, DM0=None,
bary=True, fit_DM=True, fit_GM=False, fit_scat=False,
log10_tau=True, scat_guess=None, fix_alpha=False,
print_phase=False, print_flux=False, print_parangle=False,
add_instrumental_response=False, addtnl_toa_flags={},
method='trust-ncg', bounds=None, nu_fits=None, show_plot=False,
quiet=None):
"""
Measure TOAs from wideband data accounting for numerous ISM effects.
datafile defaults to self.datafiles, otherwise it is a single
PSRCHIVE archive name
tscrunch=True tscrunches archive before fitting (i.e. make one set of
measurements per archive)
nu_refs is a tuple containing two output reference frequencies [MHz],
one for the TOAs, and the other for the scattering timescales;
defaults to the zero-covariance frequency between the TOA and DM,
and the scattering timescale and index, respectively.
DM0 is the baseline dispersion measure [cm**-3 pc]; defaults to what is
stored in each datafile.
bary=True corrects the measured DMs, GMs, taus, and nu_ref_taus based
on the Doppler motion of the observatory with respect to the solar
system barycenter.
fit_DM=False will not fit for DM; if this is the case, you might want
to set bary to False.
fit_GM=True will fit for a parameter ('GM') characterizing a delay term
for each TOA that scales as nu**-4. Will be highly covariant with
DM.
fit_scat=True will fit the scattering timescale and index for each TOA.
log10_tau=True does the scattering fit with log10(scattering timescale)
as the parameter.
scat_guess can be a list of three numbers: a guess of the scattering
timescale tau [s], its reference frequency [MHz], and a guess of
the scattering index alpha. Will be used for all archives;
supercedes other initial values.
fix_alpha=True will hold the scattering index fixed, in the case that
fit_scat==True. alpha is fixed to the value specified in the
.gmodel file, or scattering_alpha in pplib.py if no .gmodel is
provided.
print_phase=True will print the fitted parameter phi and its
uncertainty on the TOA line with the flags -phs and -phs_err.
print_flux=True will print an estimate of the overall flux density and
its uncertainty on the TOA line.
print_parangle=True will print the parallactic angle on the TOA line.
add_instrumental_response=True will account for the instrumental
response according to the dictionary instrumental_response_dict.
addtnl_toa_flags are pairs making up TOA flags to be written uniformly
to all IPTA-formatted TOAs. e.g. ('pta','NANOGrav','version',0.1)
method is the scipy.optimize.minimize method; currently can be 'TNC',
'Newton-CG', or 'trust-cng', which are all Newton
Conjugate-Gradient algorithms.
bounds is a list of five 2-tuples, giving the lower and upper bounds on
the phase, dispersion measure, GM, tau, and alpha parameters,
respectively. NB: this is only used if method=='TNC'.
nu_fits is a tuple, analogous to nu_ref, where these reference
frequencies [MHz] are used in the fit; defaults to a guess at the
zero-covariance frequency based on signal-to-noise ratios.
show_plot=True will show a plot of the fitted model, data, and
residuals at the end of the fitting. If set to "save" will
save plots to files.
quiet=True suppresses output.
"""
if quiet is None: quiet = self.quiet
already_warned = False
warning_message = \
"You are using an experimental functionality of pptoas!"
self.nfit = 1
if fit_DM: self.nfit += 1
if fit_GM: self.nfit += 1
if fit_scat: self.nfit += 2
if fix_alpha: self.nfit -= 1
self.fit_phi = True
self.fit_DM = fit_DM
self.fit_GM = fit_GM
self.fit_tau = self.fit_alpha = fit_scat
if fit_scat: self.fit_alpha = not fix_alpha
self.fit_flags = [int(self.fit_phi), int(self.fit_DM),
int(self.fit_GM), int(self.fit_tau), int(self.fit_alpha)]
self.log10_tau = log10_tau
if not fit_scat:
self.log10_tau = log10_tau = False
if self.fit_GM or fit_scat or self.fit_tau or self.fit_alpha:
print warning_message
already_warned = True
self.scat_guess = scat_guess
nu_ref_tuple = nu_refs
nu_fit_tuple = nu_fits
self.DM0 = DM0
self.bary = bary
start = time.time()
tot_duration = 0.0
if datafile is None:
datafiles = self.datafiles
else:
datafiles = [datafile]
self.tscrunch = tscrunch
self.add_instrumental_response = add_instrumental_response
for iarch, datafile in enumerate(datafiles):
fit_duration = 0.0
#Load data
try:
data = load_data(datafile, dedisperse=False,
dededisperse=False, tscrunch=tscrunch,
pscrunch=True, fscrunch=False, rm_baseline=rm_baseline,
flux_prof=False, refresh_arch=False, return_arch=False,
quiet=quiet)
if data.dmc:
if not quiet:
print "%s is dedispersed (dmc = 1). Reloading it."%\
datafile
#continue
data = load_data(datafile, dedisperse=False,
dededisperse=True, tscrunch=tscrunch,
pscrunch=True, fscrunch=False,
rm_baseline=rm_baseline, flux_prof=False,
refresh_arch=False, return_arch=False, quiet=quiet)
if not len(data.ok_isubs):
if not quiet:
print "No subints to fit for %s. Skipping it."%\
datafile
continue
else: self.ok_idatafiles.append(iarch)
except RuntimeError:
if not quiet:
print "Cannot load_data(%s). Skipping it."%datafile
continue
#Unpack the data dictionary into the local namespace; see load_data
#for dictionary keys.
for key in data.keys():
exec(key + " = data['" + key + "']")
if source is None: source = "noname"
#Observation info
obs = DataBunch(telescope=telescope, backend=backend,
frontend=frontend)
nu_fits = list(np.zeros([nsub, 3], dtype=np.float64))
nu_refs = list(np.zeros([nsub, 3], dtype=np.float64))
phis = np.zeros(nsub, dtype=np.double)
phi_errs = np.zeros(nsub, dtype=np.double)
TOAs = np.zeros(nsub, dtype="object")
TOA_errs = np.zeros(nsub, dtype="object")
DMs = np.zeros(nsub, dtype=np.float64)
DM_errs = np.zeros(nsub, dtype=np.float64)
GMs = np.zeros(nsub, dtype=np.float64)
GM_errs = np.zeros(nsub, dtype=np.float64)
taus = np.zeros(nsub, dtype=np.float64)
tau_errs = np.zeros(nsub, dtype=np.float64)
alphas = np.zeros(nsub, dtype=np.float64)
alpha_errs = np.zeros(nsub, dtype=np.float64)
scales = np.zeros([nsub, nchan], dtype=np.float64)
scale_errs = np.zeros([nsub, nchan], dtype=np.float64)
snrs = np.zeros(nsub, dtype=np.float64)
channel_snrs = np.zeros([nsub, nchan], dtype=np.float64)
profile_fluxes = np.zeros([nsub, nchan], dtype=np.float64)
profile_flux_errs = np.zeros([nsub, nchan], dtype=np.float64)
fluxes = np.zeros(nsub, dtype=np.float64)
flux_errs = np.zeros(nsub, dtype=np.float64)
flux_freqs = np.zeros(nsub, dtype=np.float64)
red_chi2s = np.zeros(nsub, dtype=np.float64)
covariances = np.zeros([nsub, self.nfit, self.nfit],
dtype=np.float64)
nfevals = np.zeros(nsub, dtype="int")
rcs = np.zeros(nsub, dtype="int")
#PSRCHIVE epochs are *midpoint* of the integration
MJDs = np.array([epochs[isub].in_days() \
for isub in range(nsub)], dtype=np.double)
DM_stored = DM # same as = arch.get_dispersion_measure()
if self.DM0 is None:
DM0 = DM_stored
else:
DM0 = self.DM0
if self.is_FITS_model:
if not already_warned:
print warning_message
already_warned = True
model_data = load_data(self.modelfile, dedisperse=False,
dededisperse=False, tscrunch=True, pscrunch=True,
fscrunch=False, rm_baseline=True, flux_prof=False,
#fscrunch=False, rm_baseline=False, flux_prof=False,
refresh_arch=False, return_arch=False, quiet=True)
model = (model_data.masks * model_data.subints)[0,0]
if model_data.nbin != nbin:
print "Model nbin %d != data nbin %d for %s; skipping it."\
%(model_data.nbin, nbin, datafile)
continue
if model_data.nchan == 1:
model = np.tile(model[0], len(freqs[0])).reshape(
len(freqs[0]), nbin)
if model_data.nchan != nchan:
print "Model nchan %d != data nchan %d for %s; skipping it."%(model_data.nchan, nchan, datafile)
continue
if not quiet:
print "\nEach of the %d TOAs is approximately %.2f s"%(
len(ok_isubs), integration_length / nsub)
itoa = 1
for isub in ok_isubs:
if self.is_FITS_model and \
np.any(model_data.freqs[0] - freqs[isub]): # tscrunched
print "Frequency mismatch between template and data!"
sub_id = datafile + "_%d"%isub
epoch = epochs[isub]
MJD = MJDs[isub]
P = Ps[isub]
if not self.is_FITS_model:
#Read model
try:
if not fit_scat:
self.model_name, self.ngauss, model = read_model(
self.modelfile, phases, freqs[isub],
Ps[isub],
quiet=bool(quiet+(itoa-1)))
else:
self.model_name, self.ngauss, full_model = \
read_model(self.modelfile, phases,
freqs[isub], Ps[isub],
quiet=bool(quiet+(itoa-1)))
self.model_name, self.model_code, \
self.model_nu_ref, self.ngauss, \
self.gparams, model_fit_flags, self.alpha,\
model_fit_alpha = read_model(
self.modelfile,
quiet=bool(quiet+(itoa-1)))
unscat_params = np.copy(self.gparams)
unscat_params[1] = 0.0
model = unscat_model = gen_gaussian_portrait(
self.model_code, unscat_params, 0.0,
phases, freqs[isub], self.model_nu_ref)
except UnboundLocalError:
self.model_name, model = read_spline_model(
self.modelfile, freqs[isub], nbin,
quiet=True) #bool(quiet+(itoa-1)))
#else:
##THESE FREQUENCIES WILL BE OFF IF AVERAGED CHANNELS##
# print model_data.freqs[0, ok_ichans[isub]] - \
# freqs[isub,ok_ichans[isub]]
freqsx = freqs[isub,ok_ichans[isub]]
weightsx = weights[isub,ok_ichans[isub]]
portx = subints[isub,0,ok_ichans[isub]]
modelx = model[ok_ichans[isub]]
if add_instrumental_response and \
(self.ird['DM'] or len(self.ird['wids'])):
inst_resp_port_FT = instrumental_response_port_FT(
nbin, freqsx, self.ird['DM'], P,
self.ird['wids'], self.ird['irf_types'])
modelx = fft.irfft(inst_resp_port_FT * \
fft.rfft(modelx, axis=-1), axis=-1)
SNRsx = SNRs[isub,0,ok_ichans[isub]]
#NB: Time-domain uncertainties below
errs = noise_stds[isub,0,ok_ichans[isub]]
#nu_fit is the reference frequency for parameters in the fit
nu_mean = freqsx.mean()
if nu_fit_tuple is None:
#NB: the subints are dedispersed at different nu_fit.
nu_fit = guess_fit_freq(freqsx, SNRsx)
nu_fit_DM = nu_fit_GM = nu_fit_tau = nu_fit
else:
nu_fit_DM = nu_fit_GM = nu_fit_tuple[0]
nu_fit_tau = nu_fit_tuple[-1]
nu_fits[isub] = [nu_fit_DM, nu_fit_GM, nu_fit_tau]
if nu_ref_tuple is None:
nu_ref = None
nu_ref_DM = nu_ref_GM = nu_ref_tau = nu_ref
else:
nu_ref_DM = nu_ref_GM = nu_ref_tuple[0]
nu_ref_tau = nu_ref_tuple[-1]
if bary and nu_ref_tau: # from bary to topo below
nu_ref_tau /= doppler_factors[isub]
nu_refs[isub] = [nu_ref_DM, nu_ref_GM, nu_ref_tau]
###################
# INITIAL GUESSES #
###################
DM_guess = DM_stored
rot_port = rotate_data(portx, 0.0, DM_guess, P, freqsx,
nu_mean) # why not nu_fit?
rot_prof = np.average(rot_port, axis=0, weights=weightsx)
GM_guess = 0.0
tau_guess = 0.0
alpha_guess = 0.0
if fit_scat:
if self.scat_guess is not None:
tau_guess_s,tau_guess_ref,alpha_guess = self.scat_guess
tau_guess = (tau_guess_s / P) * \
(nu_fit_tau / tau_guess_ref)**alpha_guess
else:
if hasattr(self, 'alpha'): alpha_guess = self.alpha
else: alpha_guess = scattering_alpha
if hasattr(self, 'gparams'):
tau_guess = (self.gparams[1] / P) * \
(nu_fit_tau/self.model_nu_ref)**alpha_guess
else:
tau_guess = 0.0 # nbin**-1?
#tau_guess = guess_tau(...)
model_prof_scat = fft.irfft(scattering_portrait_FT(
np.array([scattering_times(tau_guess, alpha_guess,
nu_fit_tau, nu_fit_tau)]), nbin)[0] * fft.rfft(
modelx.mean(axis=0)))
phi_guess = fit_phase_shift(rot_prof,
model_prof_scat, Ns=100).phase
if self.log10_tau:
if tau_guess == 0.0: tau_guess = nbin**-1
tau_guess = np.log10(tau_guess)
else:
#NB: Ns should be larger than nbin for very low S/N data,
#especially in the case of noisy models...
phi_guess = fit_phase_shift(rot_prof, modelx.mean(axis=0),
Ns=100).phase
phi_guess = phase_transform(phi_guess, DM_guess, nu_mean,
nu_fit_DM, P, mod=True) # why not use nu_fit at first?
#Need a status bar?
param_guesses = [phi_guess, DM_guess, GM_guess, tau_guess,
alpha_guess]
if bounds is None and method == 'TNC':
phi_bounds = (None, None)
DM_bounds = (None, None)
GM_bounds = (None, None)
if not self.log10_tau: tau_bounds = (0.0, None)
else: tau_bounds = (np.log10((10*nbin)**-1), None)
alpha_bounds = (-10.0, 10.0)
bounds = [phi_bounds, DM_bounds, GM_bounds, tau_bounds,
alpha_bounds]
###########
# THE FIT #
###########
if not quiet: print "Fitting for TOA #%d"%(itoa)
if len(freqsx) == 1:
fit_flags = [1,0,0,0,0]
if not quiet:
print "TOA #%d only has 1 frequency channel...fitting for phase only..."%(itoa)
elif len(freqsx) == 2 and self.fit_DM and self.fit_GM:
# prioritize DM fit
fit_flags[2] = 0
if not quiet:
print "TOA #%d only has 2 frequency channels...fitting for phase and DM only..."%(itoa)
else:
fit_flags = list(np.copy(self.fit_flags))
results = fit_portrait_full(portx, modelx, param_guesses, P,
freqsx, nu_fits[isub], nu_refs[isub], errs, fit_flags,
bounds, self.log10_tau, option=0, sub_id=sub_id,
method=method, is_toa=True, quiet=quiet)
# Old code
#results = fit_portrait(portx, modelx,
# np.array([phi_guess, DM_guess]), P, freqsx,
# nu_fit_DM, nu_ref_DM, errs, bounds=bounds, id=sub_id,
# quiet=quiet)
#results.phi = results.phase
#results.phi_err = results.phase_err
#results.GM = results.GM_err = None
#results.tau = results.tau_err = None
#results.alpha = results.alpha_err = None
#results.covariance_matrix = np.zeros([2,2])
#results.nu_DM = results.nu_GM = results.nu_tau =results.nu_ref
# Old code for fitting just phase...
#else: #1-channel hack
# if not quiet:
# print "TOA only has %d frequency channel!..."%len(
# freqsx)
# print "...using Fourier phase gradient routine to fit phase only..."
# results = fit_phase_shift(portx[0], modelx[0], errs[0],
# Ns=nbin)
# results.phi = results.phase
# results.phi_err = results.phase_err
# results.DM = results.DM_err = None
# results.GM = results.GM_err = None
# results.tau = results.tau_err = None
# results.alpha = results.alpha_err = None
# results.nu_DM, results.nu_GM, results.nu_tau = \
# [freqsx[0], freqsx[0], freqsx[0]]
# results.nfeval = 0
# results.return_code = -2
# results.scales = np.array([results.scale])
# results.scale_errs = np.array([results.scale_err])
# results.covariance_matrix = np.identity(self.nfit)
fit_duration += results.duration
####################
# CALCULATE TOA #
####################
results.TOA = epoch + pr.MJD(
((results.phi * P) + backend_delay) /
(3600 * 24.))
results.TOA_err = results.phi_err * P * 1e6 # [us]
######################
# DOPPLER CORRECTION #
######################
# This correction should fix Doppler-induced annual variations
# to DM(t), but will not fix Doppler-induced /orbital/
# variations to DM(t).
if self.bary: #Default is True
df = doppler_factors[isub]
if fit_flags[1]:
# NB: The following eqution was incorrectly reversed in
# the original paper Pennucci et al. (2014),
# printed as DM_bary = DM_topo / df.
results.DM *= df #NB: No longer the *fitted* value!
if fit_flags[2]:
results.GM *= df**3 #NB: No longer the *fitted* value!
else:
df = 1.0
#################
# ESTIMATE FLUX #
#################
if print_flux:
if results.tau != 0.0:
if self.log10_tau: tau = 10**results.tau
else: tau = results.tau
alpha = results.alpha
scat_model = fft.irfft(scattering_portrait_FT(
scattering_times(tau, alpha, freqsx,
results.nu_tau), data.nbin) * \
fft.rfft(modelx, axis=1), axis=1)
else: scat_model = np.copy(modelx)
scat_model_means = scat_model.mean(axis=1)
profile_fluxes[isub, ok_ichans[isub]] = scat_model_means *\
results.scales
profile_flux_errs[isub, ok_ichans[isub]] = abs(
scat_model_means) * results.scale_errs
flux, flux_err = weighted_mean(profile_fluxes[isub,
ok_ichans[isub]], profile_flux_errs[isub,
ok_ichans[isub]])
flux_freq, flux_freq_err = weighted_mean(freqsx,
profile_flux_errs[isub, ok_ichans[isub]])
fluxes[isub] = flux
flux_errs[isub] = flux_err
flux_freqs[isub] = flux_freq
nu_refs[isub] = [results.nu_DM, results.nu_GM, results.nu_tau]
phis[isub] = results.phi
phi_errs[isub] = results.phi_err
TOAs[isub] = results.TOA
TOA_errs[isub] = results.TOA_err
DMs[isub] = results.DM
DM_errs[isub] = results.DM_err
GMs[isub] = results.GM
GM_errs[isub] = results.GM_err
taus[isub] = results.tau
tau_errs[isub] = results.tau_err
alphas[isub] = results.alpha
alpha_errs[isub] = results.alpha_err
nfevals[isub] = results.nfeval
rcs[isub] = results.return_code
scales[isub, ok_ichans[isub]] = results.scales
scale_errs[isub, ok_ichans[isub]] = results.scale_errs
snrs[isub] = results.snr
channel_snrs[isub, ok_ichans[isub]] = results.channel_snrs
try:
covariances[isub] = results.covariance_matrix
except ValueError:
for ii,ifit in enumerate(np.where(fit_flags)[0]):
for jj,jfit in enumerate(np.where(fit_flags)[0]):
covariances[isub][ifit,jfit] = \
results.covariance_matrix[ii,jj]
red_chi2s[isub] = results.red_chi2
#Compile useful TOA flags
# Add doppler_factor?
toa_flags = {}
if not fit_flags[1]:
results.DM = None
results.DM_err = None
if fit_flags[2]:
toa_flags['gm'] = results.GM
toa_flags['gm_err'] = results.GM_err
if fit_flags[3]:
if self.log10_tau:
toa_flags['scat_time'] = 10**results.tau * P / df * 1e6
# usec, w/ df
toa_flags['log10_scat_time'] = results.tau + \
np.log10(P / df) # w/ df
toa_flags['log10_scat_time_err'] = results.tau_err
else:
toa_flags['scat_time'] = results.tau * P / df * 1e6
# usec, w/ df
toa_flags['scat_time_err'] = results.tau_err * P / df \
* 1e6 # usec, w/ df
toa_flags['scat_ref_freq'] = results.nu_tau * df # w/ df
toa_flags['scat_ind'] = results.alpha
if fit_flags[4]:
toa_flags['scat_ind_err'] = results.alpha_err
toa_flags['be'] = backend
toa_flags['fe'] = frontend
toa_flags['f'] = frontend + "_" + backend
toa_flags['nbin'] = nbin
toa_flags['nch'] = nchan
toa_flags['nchx'] = len(freqsx)
toa_flags['bw'] = freqsx.max() - freqsx.min()
toa_flags['chbw'] = abs(bw) / nchan
toa_flags['subint'] = isub
toa_flags['tobs'] = subtimes[isub]
toa_flags['fratio'] = freqsx.max() / freqsx.min()
toa_flags['tmplt'] = self.modelfile
toa_flags['snr'] = results.snr
if (nu_ref_DM is not None and np.all(fit_flags[:2])):
toa_flags['phi_DM_cov'] = \
results.covariance_matrix[0,1]
toa_flags['gof'] = results.red_chi2
if print_phase:
toa_flags['phs'] = results.phi
toa_flags['phs_err'] = results.phi_err
if print_flux:
toa_flags['flux'] = fluxes[isub]
# consistent with pat / psrflux
toa_flags['flux_err'] = flux_errs[isub]
#toa_flags['fluxe'] = flux_errs[isub]
toa_flags['flux_ref_freq'] = flux_freqs[isub]
if print_parangle:
toa_flags['par_angle'] = parallactic_angles[isub]
for k,v in addtnl_toa_flags.iteritems():
toa_flags[k] = v
self.TOA_list.append(TOA(datafile, results.nu_DM, results.TOA,
results.TOA_err, telescope, telescope_code, results.DM,
results.DM_err, toa_flags))
itoa += 1
DeltaDMs = DMs - DM0
#The below returns the weighted mean and the sum of the weights,
#but needs to do better in the case of small-error outliers from
#RFI, etc. Also, last TOA may mess things up...use median...?
if np.all(DM_errs[ok_isubs]):
DM_weights = DM_errs[ok_isubs]**-2
else:
DM_weights = np.ones(len(DM_errs[ok_isubs]))
DeltaDM_mean, DeltaDM_var = np.average(DeltaDMs[ok_isubs],
weights=DM_weights, returned=True)
DeltaDM_var = DeltaDM_var**-1
if len(ok_isubs) > 1:
#The below multiply by the red. chi-squared to inflate the
#errors.
DeltaDM_var *= np.sum(
((DeltaDMs[ok_isubs] - DeltaDM_mean)**2) * DM_weights)\
/ (len(DeltaDMs[ok_isubs]) - 1)
DeltaDM_err = DeltaDM_var**0.5
self.order.append(datafile)
self.obs.append(obs)
self.doppler_fs.append(doppler_factors)
self.nu0s.append(nu0)
self.nu_fits.append(nu_fits)
self.nu_refs.append(nu_refs)
self.ok_isubs.append(ok_isubs)
self.epochs.append(epochs)
self.MJDs.append(MJDs)
self.Ps.append(Ps)
self.phis.append(phis) #NB: phis are w.r.t. nu_ref_DM
self.phi_errs.append(phi_errs)
self.TOAs.append(TOAs) #NB: TOAs are w.r.t. nu_ref_DM
self.TOA_errs.append(TOA_errs)
self.DM0s.append(DM0)
self.DMs.append(DMs)
self.DM_errs.append(DM_errs)
self.DeltaDM_means.append(DeltaDM_mean)
self.DeltaDM_errs.append(DeltaDM_err)
self.GMs.append(GMs)
self.GM_errs.append(GM_errs)
self.taus.append(taus) #NB: taus are w.r.t. nu_ref_tau
self.tau_errs.append(tau_errs)
self.alphas.append(alphas)
self.alpha_errs.append(alpha_errs)
self.scales.append(scales)
self.scale_errs.append(scale_errs)
self.snrs.append(snrs)
self.channel_snrs.append(channel_snrs)
self.profile_fluxes.append(profile_fluxes)
self.profile_flux_errs.append(profile_flux_errs)
self.fluxes.append(fluxes)
self.flux_errs.append(flux_errs)
self.flux_freqs.append(flux_freqs)
self.covariances.append(covariances)
self.red_chi2s.append(red_chi2s)
self.nfevals.append(nfevals)
self.rcs.append(rcs)
self.fit_durations.append(fit_duration)
if not quiet:
print "--------------------------"
print datafile
print "~%.4f sec/TOA"%(fit_duration / len(ok_isubs))
print "Med. TOA error is %.3f us"%(np.median(
phi_errs[ok_isubs]) * Ps.mean() * 1e6)
if show_plot:
stop = time.time()
tot_duration += stop - start
for isub in ok_isubs:
if show_plot=="save":
savefig = datafile + '.%d.pptoas.png' % isub
else:
savefig = False
self.show_fit(datafile, isub, savefig=savefig)
start = time.time()
if not show_plot:
tot_duration = time.time() - start
if not quiet and len(self.ok_isubs):
print "--------------------------"
print "Total time: %.2f sec, ~%.4f sec/TOA"%(tot_duration,
tot_duration / (np.array(map(len, self.ok_isubs)).sum()))
def get_narrowband_TOAs(self, datafile=None, tscrunch=False,
fit_scat=False, log10_tau=True, scat_guess=None, print_phase=False,
print_flux=False, print_parangle=False,
add_instrumental_response=False, addtnl_toa_flags={},
method='trust-ncg', bounds=None, show_plot=False, quiet=None):
"""
Measure narrowband TOAs using internal algorithm.
datafile defaults to self.datafiles, otherwise it is a single
PSRCHIVE archive name
tscrunch=True tscrunches archive before fitting (i.e. make one set of
measurements per archive)
fit_scat=True will fit the scattering timescale for each TOA. [NOT YET
IMPLEMENTED]
log10_tau=True does the scattering fit with log10(scattering timescale)
as the parameter.
scat_guess can be a list of three numbers: a guess of the scattering
timescale tau [s], its reference frequency [MHz], and a guess of
the scattering index alpha. Will be used for all archives;
supercedes other initial values.
print_phase=True will print the fitted parameter phi and its
uncertainty on the TOA line with the flags -phs and -phs_err.
print_flux=True will print an estimate of the flux density and its
uncertainty on the TOA line.
print_parangle=True will print the parallactic angle on the TOA line.
add_instrumental_response=True will account for the instrumental
response according to the dictionary instrumental_response_dict.
addtnl_toa_flags are pairs making up TOA flags to be written uniformly
to all IPTA-formatted TOAs. e.g. ('pta','NANOGrav','version',0.1)
method is the scipy.optimize.minimize method; currently can be 'TNC',
'Newton-CG', or 'trust-cng', which are all Newton
Conjugate-Gradient algorithms.
bounds is a list of two 2-tuples, giving the lower and upper bounds on
the phase and tau parameters,
respectively. NB: this is only used if method=='TNC'.
show_plot=True will show a plot of the fitted model, data, and
residuals at the end of the fitting. [NOT YET IMPLEMENTED]
quiet=True suppresses output.
"""
if quiet is None: quiet = self.quiet
already_warned = False
warning_message = \
"You are using an experimental functionality of pptoas!"
self.nfit = 1
if fit_scat: self.nfit += 2
self.fit_phi = True
self.fit_tau = fit_scat
self.fit_flags = [int(self.fit_phi), int(self.fit_tau)]
self.log10_tau = log10_tau
if not fit_scat:
self.log10_tau = log10_tau = False
if True:#fit_scat or self.fit_tau:
print warning_message
already_warned = True
self.scat_guess = scat_guess
start = time.time()
tot_duration = 0.0
if datafile is None:
datafiles = self.datafiles
else:
datafiles = [datafile]
self.tscrunch = tscrunch
self.add_instrumental_response = add_instrumental_response
for iarch, datafile in enumerate(datafiles):
fit_duration = 0.0
#Load data
try:
data = load_data(datafile, dedisperse=False,
dededisperse=False, tscrunch=tscrunch,
pscrunch=True, fscrunch=False, rm_baseline=rm_baseline,
flux_prof=False, refresh_arch=False, return_arch=False,
quiet=quiet)
if data.dmc:
if not quiet:
print "%s is dedispersed (dmc = 1). Reloading it."%\
datafile
#continue
data = load_data(datafile, dedisperse=False,
dededisperse=True, tscrunch=tscrunch,
pscrunch=True, fscrunch=False,
rm_baseline=rm_baseline, flux_prof=False,
refresh_arch=False, return_arch=False, quiet=quiet)
if not len(data.ok_isubs):
if not quiet:
print "No subints to fit for %s. Skipping it."%\
datafile
continue
else: self.ok_idatafiles.append(iarch)
except RuntimeError:
if not quiet:
print "Cannot load_data(%s). Skipping it."%datafile
continue
#Unpack the data dictionary into the local namespace; see load_data
#for dictionary keys.
for key in data.keys():
exec(key + " = data['" + key + "']")
if source is None: source = "noname"
#Observation info
obs = DataBunch(telescope=telescope, backend=backend,
frontend=frontend)
phis = np.zeros([nsub, nchan], dtype=np.double)
phi_errs = np.zeros([nsub, nchan], dtype=np.double)
TOAs = np.zeros([nsub, nchan], dtype="object")
TOA_errs = np.zeros([nsub, nchan], dtype="object")
taus = np.zeros([nsub, nchan], dtype=np.float64)
tau_errs = np.zeros([nsub, nchan], dtype=np.float64)
scales = np.zeros([nsub, nchan], dtype=np.float64)
scale_errs = np.zeros([nsub, nchan], dtype=np.float64)
channel_snrs = np.zeros([nsub, nchan], dtype=np.float64)
profile_fluxes = np.zeros([nsub, nchan], dtype=np.float64)
profile_flux_errs = np.zeros([nsub, nchan], dtype=np.float64)
channel_red_chi2s = np.zeros([nsub, nchan], dtype=np.float64)
covariances = np.zeros([nsub, nchan, self.nfit, self.nfit],
dtype=np.float64)
nfevals = np.zeros([nsub, nchan], dtype="int")
rcs = np.zeros([nsub, nchan], dtype="int")
#PSRCHIVE epochs are *midpoint* of the integration
MJDs = np.array([epochs[isub].in_days() \
for isub in range(nsub)], dtype=np.double)
if self.is_FITS_model:
if not already_warned:
print warning_message
already_warned = True
model_data = load_data(self.modelfile, dedisperse=False,
dededisperse=False, tscrunch=True, pscrunch=True,
fscrunch=False, rm_baseline=True, flux_prof=False,
#fscrunch=False, rm_baseline=False, flux_prof=False,
refresh_arch=False, return_arch=False, quiet=True)
model = (model_data.masks * model_data.subints)[0,0]
if model_data.nbin != nbin:
print "Model nbin %d != data nbin %d for %s; skipping it."\
%(model_data.nbin, nbin, datafile)
continue
if model_data.nchan == 1:
model = np.tile(model[0], len(freqs[0])).reshape(
len(freqs[0]), nbin)
if model_data.nchan != nchan:
print "Model nchan %d != data nchan %d for %s; skipping it."%(model_data.nchan, nchan, datafile)
continue
icount = 1
for isub in ok_isubs:
if self.is_FITS_model and \
np.any(model_data.freqs[0] - freqs[isub]): # tscrunched
print "Frequency mismatch between template and data!"
sub_id = datafile + "_%d"%isub
epoch = epochs[isub]
MJD = MJDs[isub]
P = Ps[isub]
if not self.is_FITS_model:
#Read model
try:
if not fit_scat:
self.model_name, self.ngauss, model = read_model(
self.modelfile, phases, freqs[isub],
Ps[isub],
quiet=bool(quiet+(icount-1)))
else:
self.model_name, self.ngauss, full_model = \
read_model(self.modelfile, phases,
freqs[isub], Ps[isub],
quiet=bool(quiet+(icount-1)))
self.model_name, self.model_code, \
self.model_nu_ref, self.ngauss, \
self.gparams, model_fit_flags, self.alpha,\
model_fit_alpha = read_model(
self.modelfile,
quiet=bool(quiet+(icount-1)))
unscat_params = np.copy(self.gparams)
unscat_params[1] = 0.0
model = unscat_model = gen_gaussian_portrait(
self.model_code, unscat_params, 0.0,
phases, freqs[isub], self.model_nu_ref)
except UnboundLocalError:
self.model_name, model = read_spline_model(
self.modelfile, freqs[isub], nbin,
quiet=True) #bool(quiet+(icount-1)))
freqsx = freqs[isub,ok_ichans[isub]]
weightsx = weights[isub,ok_ichans[isub]]
portx = subints[isub,0,ok_ichans[isub]]
modelx = model[ok_ichans[isub]]
if add_instrumental_response and \
(self.ird['DM'] or len(self.ird['wids'])):
inst_resp_port_FT = instrumental_response_port_FT(
nbin, freqsx, self.ird['DM'], P,
self.ird['wids'], self.ird['irf_types'])
modelx = fft.irfft(inst_resp_port_FT * \
fft.rfft(modelx, axis=-1), axis=-1)
#NB: Time-domain uncertainties below
errs = noise_stds[isub,0,ok_ichans[isub]]
###################
# INITIAL GUESSES #
###################
tau_guess = 0.0
alpha_guess = 0.0
if fit_scat:
if self.scat_guess is not None:
tau_guess_s,tau_guess_ref,alpha_guess = self.scat_guess
tau_guess = (tau_guess_s / P) * \
(nu_fit_tau / tau_guess_ref)**alpha_guess
else:
if hasattr(self, 'alpha'): alpha_guess = self.alpha
else: alpha_guess = scattering_alpha
if hasattr(self, 'gparams'):
tau_guess = (self.gparams[1] / P) * \
(nu_fit_tau/self.model_nu_ref)**alpha_guess
else:
tau_guess = 0.0 # nbin**-1?
#tau_guess = guess_tau(...)
model_prof_scat = fft.irfft(scattering_portrait_FT(
np.array([scattering_times(tau_guess, alpha_guess,
nu_fit_tau, nu_fit_tau)]), nbin)[0] * fft.rfft(
modelx.mean(axis=0)))
phi_guess = fit_phase_shift(rot_prof,
model_prof_scat, Ns=100).phase
if self.log10_tau:
if tau_guess == 0.0: tau_guess = nbin**-1
tau_guess = np.log10(tau_guess)
else:
#NB: Ns should be larger than nbin for very low S/N data,
#especially in the case of noisy models...
#phi_guess = fit_phase_shift(rot_prof, modelx.mean(axis=0),
# Ns=100).phase
phi_guess = 0.0
#Need a status bar?
param_guesses = [phi_guess, tau_guess]
if bounds is None and method == 'TNC':
phi_bounds = (None, None)
if not self.log10_tau: tau_bounds = (0.0, None)
else: tau_bounds = (np.log10((10*nbin)**-1), None)
bounds = [phi_bounds, tau_bounds]
###########
# THE FIT #
###########
fit_flags = list(np.copy(self.fit_flags))
for ichanx in range(len(ok_ichans[isub])):
ichan = ok_ichans[isub][ichanx]
if self.is_FITS_model:
if model_data.weights[isub,ichan] == 0: continue
prof = portx[ichanx]
model_prof = modelx[ichanx]
err = errs[ichanx]
#results = fit_phase_shift_scat(prof, model_prof,
# param_guesses, P, err, fit_flags, bounds,
# self.log10_tau, option=0, sub_id=sub_id,
# method=method, is_toa=True, quiet=quiet)
results = fit_phase_shift(prof, model_prof, err,
bounds=[-0.5,0.5], Ns=100)
results.tau = results.tau_err = 0.0
fit_duration += results.duration
####################
# CALCULATE TOA #
####################
results.TOA = epoch + pr.MJD(