forked from stevertaylor/NX01
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NX01_singlePsr.py
executable file
·732 lines (579 loc) · 27.1 KB
/
NX01_singlePsr.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
#!/usr/bin/env python
"""
Created by stevertaylor
Copyright (c) 2014 Stephen R. Taylor
Code contributions by Rutger van Haasteren (piccard) and Justin Ellis (PAL/PAL2).
"""
from __future__ import division
import os, math, optparse, time, cProfile
import json, sys
import cPickle as pickle
from time import gmtime, strftime
from collections import OrderedDict
import h5py as h5
import numpy as np
from numpy import *
from numpy import random
from scipy import integrate
from scipy import optimize
from scipy import constants as sc
from scipy import special as ss
from scipy import linalg as sl
from scipy.interpolate import interp1d
import numexpr as ne
import ephem
from ephem import *
import libstempo as T2
import NX01_AnisCoefficients as anis
import NX01_utils as utils
import NX01_psr
try:
import NX01_jitter as jitter
except ImportError:
print "You do not have NX01_jitter.so. " \
"Trying to make the .so file now..."
import pyximport
pyximport.install(setup_args={"include_dirs":np.get_include()},
reload_support=True)
try:
import NX01_jitter as jitter
except ImportError:
error_warning = """\
_____ __ __ _____ ____ _____ _______ ______ _____ _____ ____ _____ _ _
|_ _| \/ | __ \ / __ \| __ \__ __| | ____| __ \| __ \ / __ \| __ \| | |
| | | \ / | |__) | | | | |__) | | | | |__ | |__) | |__) | | | | |__) | | |
| | | |\/| | ___/| | | | _ / | | | __| | _ /| _ /| | | | _ /| | |
_| |_| | | | | | |__| | | \ \ | | | |____| | \ \| | \ \| |__| | | \ \|_|_|
|_____|_| |_|_| \____/|_| \_\ |_| |______|_| \_\_| \_\\____/|_| \_(_|_)
_____ ____ __ __ _____ _____ _ ______ _ _____ _______ _______ ______ _____
/ ____/ __ \| \/ | __ \_ _| | | ____| | |_ _|__ __|__ __| ____| __ \
| | | | | | \ / | |__) || | | | | |__ | | | | | | | | | |__ | |__) |
| | | | | | |\/| | ___/ | | | | | __| _ | | | | | | | | | __| | _ /
| |___| |__| | | | | | _| |_| |____| |____ | |__| |_| |_ | | | | | |____| | \ \
\_____\____/|_| |_|_| |_____|______|______| \____/|_____| |_| |_| |______|_| \_\
"""
print error_warning
print "You need to run: " \
"python setup-cython.py build_ext --inplace"
sys.exit()
try:
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
except ImportError:
print 'Do not have mpi4py package.'
import nompi4py as MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
parser = optparse.OptionParser(description = "NX01 - It's been a long road, getting from there to here")
############################
############################
parser.add_option('--sampler', dest='sampler', action='store', type=str, default='ptmcmc',
help='Which sampler do you want to use: PTMCMC (ptmcmc), MultiNest (mnest), or Polychord (pchord) (default = ptmcmc)')
parser.add_option('--ins', dest='ins', action='store_true', default=False,
help='Switch on importance nested sampling for MultiNest (default = False)')
parser.add_option('--nlive', dest='nlive', action='store', type=int, default=500,
help='Number of live points for MultiNest or Polychord (default = 500)')
parser.add_option('--sampleEff', dest='sampleEff', action='store', type=float, default=0.3,
help='Sampling efficiency for MultiNest (default = 0.3)')
parser.add_option('--constEff', dest='constEff', action='store_true', default=False,
help='Run MultiNest in constant efficiency mode? (default = False)')
parser.add_option('--resume', dest='resume', action='store_true', default=False,
help='Do you want to resume the sampler (default = False)')
parser.add_option('--nmodes', dest='nmodes', action='store', type=int,
help='Number of modes in low-rank time-frequency approximation')
parser.add_option('--cadence', dest='cadence', action='store', type=float, default=14.0,
help='Number days between successive observations (default = 14 days)')
parser.add_option('--parfile', dest='parfile', action='store', type=str,
help='Full path to parfile')
parser.add_option('--timfile', dest='timfile', action='store', type=str,
help='Full path to timfile')
parser.add_option('--efacequad-sysflag', dest='systarg', action='store', type=str, default='group',
help='Which system flag should the EFACs/EQUADs target? (default = \'group\')')
parser.add_option('--redPrior', dest='redPrior', action='store', type=str, default='loguniform',
help='What kind of prior to place on the red noise amplitude? (default = \'loguniform\')')
parser.add_option('--dmPrior', dest='dmPrior', action='store', type=str, default='loguniform',
help='What kind of prior to place on the DM variation amplitude? (default = \'loguniform\')')
parser.add_option('--incDM', dest='incDM', action='store_true', default=False,
help='Search for DM variations in the data (False)? (default=False)')
parser.add_option('--fullN', dest='fullN', action='store_true', default=False,
help='Search for EFAC/EQUAD/ECORR over all systems (True), or just apply a GEFAC (False)? (default=False)')
parser.add_option('--grab_planets', dest='grab_planets', action='store_true', default=False,
help='Grab the planet position vectors at the TOA timestamps? (default=False)')
parser.add_option('--incGlitch', dest='incGlitch', action='store_true', default=False,
help='Search for a glitch in the pulsar? (default=False)')
parser.add_option('--jitterbin', dest='jitterbin', action='store', type=float, default=1.0,
help='What time duration (in seconds) do you want a jitter bin to be? (default = 1.0)')
parser.add_option('--mnest', dest='mnest', action='store_true', default=False,
help='Do you want to sample using MultiNest? (default=False)')
parser.add_option('--writeHotChains', dest='writeHotChains', action='store_true', default=False,
help='Do you want to store hot PTMCMC chains? (default=False)')
parser.add_option('--hotChain', dest='hotChain', action='store_true', default=False,
help='Do you want to include a very hot chain? (default=False)')
parser.add_option('--dirExt', dest='dirExt', action='store', type=str, default='./chains_nanoAnalysis/',
help='What master directory name do you want to put this run into? (default = ./chains_nanoAnalysis/)')
(args, x) = parser.parse_args()
header = """\
/$$ /$$ /$$ /$$ /$$$$$$ /$$
| $$$ | $$| $$ / $$ /$$$_ $$ /$$$$ ________________ _
| $$$$| $$| $$/ $$/| $$$$\ $$|_ $$ \__(=======/_=_/____.--'-`--.___
| $$ $$ $$ \ $$$$/ | $$ $$ $$ | $$ \ \ `,--,-.___.----'
| $$ $$$$ >$$ $$ | $$\ $$$$ | $$ .--`\\--'../
| $$\ $$$ /$$/\ $$| $$ \ $$$ | $$ '---._____.|]
| $$ \ $$| $$ \ $$| $$$$$$/ /$$$$$$
|__/ \__/|__/ |__/ \______/ |______/
____ ____ ______ __ __ __ __ ___ ____ ____ _______
\ \ / / / __ \ | | | | | | | | / \ \ \ / / | ____|
\ \/ / | | | | | | | | | |__| | / ^ \ \ \/ / | |__
\_ _/ | | | | | | | | | __ | / /_\ \ \ / | __|
| | | `--' | | `--' | | | | | / _____ \ \ / | |____
|__| \______/ \______/ |__| |__| /__/ \__\ \__/ |_______|
.___________. __ __ _______ ______ ______ .__ __. .__ __.
| || | | | | ____| / | / __ \ | \ | | | \ | |
`---| |----`| |__| | | |__ | ,----'| | | | | \| | | \| |
| | | __ | | __| | | | | | | | . ` | | . ` |
| | | | | | | |____ | `----.| `--' | | |\ | | |\ |
|__| |__| |__| |_______| \______| \______/ |__| \__| |__| \__|
"""
if rank == 0:
print header
if args.nmodes:
print ("\n You've given me the number of frequencies",
"to include in the low-rank time-frequency approximation, got it?\n")
else:
print ("\n You've given me the sampling cadence for the observations,",
"which determines the upper frequency limit and the number of modes, got it?\n")
if args.sampler == 'mnest':
import pymultinest
elif args.sampler == 'ptmcmc':
import PTMCMCSampler
from PTMCMCSampler import PTMCMCSampler as ptmcmc
#####################################################################
# PASSING THROUGH TEMPO2 VIA libstempo
#####################################################################
t2psr = T2.tempopulsar(parfile=args.parfile, timfile=args.timfile)
t2psr.fit(iters=10)
if np.any(np.isfinite(t2psr.residuals())==False)==True:
t2psr = T2.tempopulsar(parfile=args.parfile,timfile=args.timfile)
psr = NX01_psr.PsrObj(t2psr)
psr.grab_all_vars(jitterbin=args.jitterbin, makeGmat=False,
fastDesign=True, planetssb=args.grab_planets)
#############################################################################
# GETTING MAXIMUM TIME, COMPUTING FOURIER DESIGN MATRICES, AND GETTING MODES
#############################################################################
Tmax = psr.toas.max() - psr.toas.min()
if args.nmodes:
psr.makeTe(args.nmodes, Tmax, makeDM=args.incDM)
# get GW frequencies
fqs = np.linspace(1/Tmax, args.nmodes/Tmax, args.nmodes)
nmode = args.nmodes
else:
nmode = int(round(Tmax/args.cadence))
psr.makeTe(nmode, Tmax, makeDM=args.incDM)
# get GW frequencies
fqs = np.linspace(1/Tmax, nmode/Tmax, nmode)
################################################################################################################################
# FORM A LIST COMPOSED OF NP ARRAYS CONTAINING THE INDEX POSITIONS WHERE EACH UNIQUE SYSTEM IS APPLIED
################################################################################################################################
if args.fullN:
systems = psr.sysflagdict[args.systarg]
else:
systems = OrderedDict.fromkeys([psr.name])
systems[psr.name] = np.arange(len(psr.toas))
################################################################################################################################
# SETTING UP PRIOR RANGES
################################################################################################################################
pmin = np.array([-20.0,0.0])
pmax = np.array([-11.0,7.0])
if args.incDM:
pmin = np.append(pmin,np.array([-20.0,0.0]))
pmax = np.append(pmax,np.array([-8.0,7.0]))
pmin = np.append(pmin,0.001*np.ones(len(systems)))
pmax = np.append(pmax,10.0*np.ones(len(systems)))
if args.fullN:
pmin = np.append(pmin,-10.0*np.ones(len(systems)))
pmax = np.append(pmax,-3.0*np.ones(len(systems)))
if 'pta' in t2psr.flags():
if 'NANOGrav' in list(set(t2psr.flagvals('pta'))):
if len(psr.sysflagdict['nano-f'].keys())>0:
pmin = np.append(pmin, -10.0*np.ones(len(psr.sysflagdict['nano-f'].keys())))
pmax = np.append(pmax, -3.0*np.ones(len(psr.sysflagdict['nano-f'].keys())))
if args.incGlitch:
pmin = np.append(pmin,[np.min(psr.toas),-18.0])
pmax = np.append(pmax,[np.max(psr.toas),-11.0])
################################################################################################################################
# PRIOR AND LIKELIHOOD
################################################################################################################################
def my_prior(xx):
logp = 0.
if np.all(xx <= pmax) and np.all(xx >= pmin):
logp = np.sum(np.log(1/(pmax-pmin)))
else:
logp = -np.inf
return logp
def ln_prob(xx):
Ared = 10.0**xx[0]
gam_red = xx[1]
ct = 2
if args.incDM:
Adm = 10.0**xx[ct]
gam_dm = xx[ct+1]
ct = 4
EFAC = xx[ct:ct+len(systems)]
ct += len(systems)
if args.fullN:
EQUAD = 10.0**xx[ct:ct+len(systems)]
ct += len(systems)
ECORR = []
if 'pta' in t2psr.flags():
if 'NANOGrav' in list(set(t2psr.flagvals('pta'))):
if len(psr.sysflagdict['nano-f'].keys())>0:
ECORR = 10.0**xx[ct:ct+len(psr.sysflagdict['nano-f'].keys())]
ct += len(psr.sysflagdict['nano-f'].keys())
if args.incGlitch:
glitch_epoch = xx[ct]
glitch_lamp = xx[ct+1]
loglike1 = 0.
####################################
####################################
scaled_err = (psr.toaerrs).copy()
for jj,sysname in enumerate(systems):
scaled_err[systems[sysname]] *= EFAC[jj]
###
white_noise = np.zeros(len(scaled_err))
if args.fullN:
white_noise = np.ones(len(scaled_err))
for jj,sysname in enumerate(systems):
white_noise[systems[sysname]] *= EQUAD[jj]
new_err = np.sqrt( scaled_err**2.0 + white_noise**2.0 )
########
if args.incGlitch:
model_res = psr.res - utils.glitch_signal(psr, glitch_epoch, glitch_lamp)
elif not args.incGlitch:
model_res = psr.res
# compute ( T.T * N^-1 * T )
# & log determinant of N
if args.fullN:
if len(ECORR)>0:
Jamp = np.ones(len(psr.epflags))
for jj,nano_sysname in enumerate(psr.sysflagdict['nano-f'].keys()):
Jamp[np.where(psr.epflags==nano_sysname)] *= ECORR[jj]**2.0
Nx = jitter.cython_block_shermor_0D(model_res, new_err**2.,
Jamp, psr.Uinds)
d = np.dot(psr.Te.T, Nx)
logdet_N, TtNT = \
jitter.cython_block_shermor_2D(psr.Te, new_err**2.,
Jamp, psr.Uinds)
det_dummy, dtNdt = \
jitter.cython_block_shermor_1D(model_res, new_err**2.,
Jamp, psr.Uinds)
else:
d = np.dot(psr.Te.T, model_res/( new_err**2.0 ))
N = 1./( new_err**2.0 )
right = (N*psr.Te.T).T
TtNT = np.dot(psr.Te.T, right)
logdet_N = np.sum(np.log( new_err**2.0 ))
# triple product in likelihood function
dtNdt = np.sum(model_res**2.0/( new_err**2.0 ))
else:
d = np.dot(psr.Te.T, model_res/( new_err**2.0 ))
N = 1./( new_err**2.0 )
right = (N*psr.Te.T).T
TtNT = np.dot(psr.Te.T, right)
logdet_N = np.sum(np.log( new_err**2.0 ))
# triple product in likelihood function
dtNdt = np.sum(model_res**2.0/( new_err**2.0 ))
loglike1 += -0.5 * (logdet_N + dtNdt)
####################################
####################################
# parameterize intrinsic red noise as power law
Tspan = (1/fqs[0])*86400.0
f1yr = 1/3.16e7
# parameterize intrinsic red-noise and DM-variations as power law
if args.incDM:
kappa = np.log10( np.append( Ared**2/12/np.pi**2 * \
f1yr**(gam_red-3) * \
(fqs/86400.0)**(-gam_red)/Tspan,
Adm**2/12/np.pi**2 * \
f1yr**(gam_dm-3) * \
(fqs/86400.0)**(-gam_dm)/Tspan ) )
else:
kappa = np.log10( Ared**2/12/np.pi**2 * \
f1yr**(gam_red-3) * \
(fqs/86400.0)**(-gam_red)/Tspan )
# construct elements of sigma array
if args.incDM:
mode_count = 4*nmode
else:
mode_count = 2*nmode
diagonal = np.zeros(mode_count)
diagonal[0::2] = 10**kappa
diagonal[1::2] = 10**kappa
# compute Phi inverse
red_phi = np.diag(1./diagonal)
logdet_Phi = np.sum(np.log( diagonal ))
# now fill in real covariance matrix
Phi = np.zeros( TtNT.shape )
for kk in range(0,mode_count):
Phi[kk+psr.Gc.shape[1],kk+psr.Gc.shape[1]] = red_phi[kk,kk]
# symmeterize Phi
Phi = Phi + Phi.T - np.diag(np.diag(Phi))
# compute sigma
Sigma = TtNT + Phi
# cholesky decomp for second term in exponential
try:
cf = sl.cho_factor(Sigma)
expval2 = sl.cho_solve(cf, d)
logdet_Sigma = np.sum(2*np.log(np.diag(cf[0])))
except np.linalg.LinAlgError:
#print 'Cholesky Decomposition Failed second time!! Using SVD instead'
#u,s,v = sl.svd(Sigma)
#expval2 = np.dot(v.T, 1/s*np.dot(u.T, d))
#logdet_Sigma = np.sum(np.log(s))
print 'Cholesky Decomposition Failed second time!! Getting outta here...'
return -np.inf
logLike = -0.5 * (logdet_Phi + logdet_Sigma) + \
0.5 * (np.dot(d, expval2)) + loglike1
prior_fac = 0.0
if args.redPrior == 'uniform':
prior_fac += np.log(Ared * np.log(10.0))
if args.incDM and (args.dmPrior == 'uniform'):
prior_fac += np.log(Adm * np.log(10.0))
return logLike + prior_fac
#########################
#########################
parameters = ["log(A_red)","gam_red"]
if args.incDM:
parameters.append("log(A_dm)")
parameters.append("gam_dm")
for ii in range(len(systems)):
parameters.append('EFAC_'+systems.keys()[ii])
if args.fullN:
for ii in range(len(systems)):
parameters.append('EQUAD_'+systems.keys()[ii])
if 'pta' in t2psr.flags():
if 'NANOGrav' in list(set(t2psr.flagvals('pta'))):
if len(psr.sysflagdict['nano-f'].keys())>0:
if rank == 0:
print "\n You have some NANOGrav ECORR parameters..."
for ii,nano_sysname in enumerate(psr.sysflagdict['nano-f'].keys()):
parameters.append('ECORR_'+nano_sysname)
if args.incGlitch:
parameters += ["glitch_epoch","glitch_lamp"]
n_params = len(parameters)
if rank == 0:
print "\n You are searching for the following single-pulsar parameters: {0}\n".format(parameters)
print "\n The total number of parameters is {0}\n".format(n_params)
# Define a unique file tag
file_tag = 'pta_'+psr.name
file_tag += '_red{0}'.format(args.redPrior)
if args.incDM:
file_tag += '_dm{0}'.format(args.dmPrior)
if args.incGlitch:
file_tag += '_glitch'
file_tag += '_nmodes{0}'.format(nmode)
#####################
# Now, we sample....
#####################
if rank == 0:
print "\n Now, we sample... \n"
print """\
_______ .__ __. _______ ___ _______ _______ __
| ____|| \ | | / _____| / \ / _____|| ____|| |
| |__ | \| | | | __ / ^ \ | | __ | |__ | |
| __| | . ` | | | |_ | / /_\ \ | | |_ | | __| | |
| |____ | |\ | | |__| | / _____ \ | |__| | | |____ |__|
|_______||__| \__| \______| /__/ \__\ \______| |_______|(__)
"""
###########################
# Define function wrappers
###########################
if args.sampler == 'mnest':
#dir_name = './chains_nanoAnalysis/nano_singlePsr/'+file_tag+'_mnest'
#dir_name = './chn_eptapsr/'+file_tag+'_mnest'
dir_name = args.dirExt+file_tag+'_mnest'
if rank == 0:
if not os.path.exists(dir_name):
os.makedirs(dir_name)
if rank == 0:
# Printing out the list of searched parameters
fil = open(dir_name+'/parameter_list.txt','w')
for ii,parm in enumerate(parameters):
print >>fil, ii, parm
fil.close()
# Saving command-line arguments to file
with open(dir_name+'/run_args.json', 'w') as fp:
json.dump(vars(args), fp)
def prior_func(xx,ndim,nparams):
for ii in range(nparams):
xx[ii] = pmin[ii] + xx[ii]*(pmax[ii]-pmin[ii])
def like_func(xx,ndim,nparams):
xx = np.array([xx[ii] for ii in range(nparams)])
return ln_prob(xx)
pymultinest.run(like_func, prior_func, n_params,
importance_nested_sampling = args.ins,
resume = args.resume, verbose = True,
n_live_points=args.nlive,
outputfiles_basename=u'{0}/mnest_'.format(dir_name),
sampling_efficiency=args.sampleEff,
const_efficiency_mode=args.constEff)
if args.sampler == 'ptmcmc':
x0 = np.array([-15.0,2.0])
cov_diag = np.array([0.5,0.5])
if args.incDM:
x0 = np.append(x0,np.array([-15.0,2.0]))
cov_diag = np.append(cov_diag,np.array([0.5,0.5]))
x0 = np.append(x0,np.random.uniform(0.75,1.25,len(systems)))
cov_diag = np.append(cov_diag,0.5*np.ones(len(systems)))
if args.fullN:
x0 = np.append(x0,np.random.uniform(-10.0,-5.0,len(systems)))
cov_diag = np.append(cov_diag,0.5*np.ones(len(systems)))
if 'pta' in t2psr.flags():
if 'NANOGrav' in list(set(t2psr.flagvals('pta'))):
if len(psr.sysflagdict['nano-f'].keys())>0:
x0 = np.append(x0, np.random.uniform(-8.5,-5.0,len(psr.sysflagdict['nano-f'].keys())))
cov_diag = np.append(cov_diag,0.5*np.ones(len(psr.sysflagdict['nano-f'].keys())))
if rank == 0:
print "\n Your initial parameters are {0}\n".format(x0)
print "\n Running a quick profile on the likelihood to estimate evaluation speed...\n"
cProfile.run('ln_prob(x0)')
########################################
# Creating parameter sampling groupings
ind = []
param_ct = 0
##### red noise #####
ids = [[0,1]]
[ind.append(id) for id in ids]
param_ct += 2
##### DM noise #####
if args.incDM:
ids = [[2,3]]
[ind.append(id) for id in ids]
param_ct += 2
##### White noise #####
if args.fullN:
efacs = [param_ct+ii for ii in range(len(systems))]
ids = [efacs]
[ind.append(id) for id in ids if len(id) > 0]
param_ct += len(systems)
##
equads = [param_ct+ii for ii in range(len(systems))]
ids = [equads]
[ind.append(id) for id in ids if len(id) > 0]
param_ct += len(systems)
##
if 'pta' in t2psr.flags():
if 'NANOGrav' in list(set(t2psr.flagvals('pta'))):
ecorrs = [param_ct+ii for ii
in range(len(psr.sysflagdict['nano-f'].keys()))]
ids = [ecorrs]
[ind.append(id) for id in ids if len(id) > 0]
param_ct += len(psr.sysflagdict['nano-f'].keys())
##### all parameters #####
all_inds = range(len(x0))
ind.insert(0, all_inds)
if rank == 0:
print "Your parameter index groupings for sampling are {0}".format(ind)
########
dir_name = args.dirExt+file_tag+'_ptmcmc'
if rank == 0:
if not os.path.exists(dir_name):
os.makedirs(dir_name)
if rank == 0:
# Printing out the list of searched parameters
fil = open(dir_name+'/parameter_list.txt','w')
for ii,parm in enumerate(parameters):
print >>fil, ii, parm
fil.close()
# Saving command-line arguments to file
with open(dir_name+'/run_args.json', 'w') as fp:
json.dump(vars(args), fp)
sampler = ptmcmc.PTSampler(ndim = n_params, logl = ln_prob,
logp = my_prior, cov = np.diag(cov_diag),
outDir='./{0}'.format(dir_name),
resume = args.resume, groups = ind)
def drawFromRedNoisePrior(parameters, iter, beta):
# post-jump parameters
q = parameters.copy()
# transition probability
qxy = 0
# log prior
if args.redPrior == 'loguniform':
q[0] = np.random.uniform(pmin[0], pmax[0])
qxy += 0
elif args.redPrior == 'uniform':
q[0] = np.random.uniform(pmin[0], pmax[0])
qxy += 0
q[1] = np.random.uniform(pmin[1], pmax[1])
qxy += 0
return q, qxy
def drawFromDMNoisePrior(parameters, iter, beta):
# post-jump parameters
q = parameters.copy()
# transition probability
qxy = 0
# log prior
if args.dmPrior == 'loguniform':
q[2] = np.random.uniform(pmin[2], pmax[2])
qxy += 0
elif args.dmPrior == 'uniform':
q[2] = np.random.uniform(pmin[2], pmax[2])
qxy += 0
q[3] = np.random.uniform(pmin[3], pmax[3])
qxy += 0
return q, qxy
def drawFromEfacPrior(parameters, iter, beta):
# post-jump parameters
q = parameters.copy()
# transition probability
qxy = 0
if args.incDM:
ind = np.unique(np.random.randint(4, 4+len(systems), 1))
else:
ind = np.unique(np.random.randint(2, 2+len(systems), 1))
for ii in ind:
q[ii] = np.random.uniform(pmin[ii], pmax[ii])
qxy += 0
return q, qxy
def drawFromEquadPrior(parameters, iter, beta):
# post-jump parameters
q = parameters.copy()
# transition probability
qxy = 0
if args.incDM:
ind = np.unique(np.random.randint(4+len(systems), 4+2*len(systems), 1))
else:
ind = np.unique(np.random.randint(2+len(systems), 2+2*len(systems), 1))
for ii in ind:
q[ii] = np.random.uniform(pmin[ii], pmax[ii])
qxy += 0
return q, qxy
def drawFromEcorrPrior(parameters, iter, beta):
# post-jump parameters
q = parameters.copy()
# transition probability
qxy = 0
if args.incDM:
ind = np.unique(np.random.randint(4+2*len(systems), 4+2*len(systems)+len(psr.sysflagdict['nano-f'].keys()), 1))
else:
ind = np.unique(np.random.randint(2+2*len(systems), 2+2*len(systems)+len(psr.sysflagdict['nano-f'].keys()), 1))
for ii in ind:
q[ii] = np.random.uniform(pmin[ii], pmax[ii])
qxy += 0
return q, qxy
# add jump proposals
sampler.addProposalToCycle(drawFromRedNoisePrior, 10)
if args.incDM:
sampler.addProposalToCycle(drawFromDMNoisePrior, 10)
if args.fullN:
sampler.addProposalToCycle(drawFromEfacPrior, 10)
sampler.addProposalToCycle(drawFromEquadPrior, 10)
if 'pta' in t2psr.flags():
if 'NANOGrav' in list(set(t2psr.flagvals('pta'))):
if len(psr.sysflagdict['nano-f'].keys())>0:
sampler.addProposalToCycle(drawFromEcorrPrior, 10)
sampler.sample(p0=x0, Niter=int(5e6), thin=10,
covUpdate=1000, AMweight=20,
SCAMweight=30, DEweight=50,
writeHotChains=args.writeHotChains,
hotChain=args.hotChain)