-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtempo.py
2718 lines (2583 loc) · 114 KB
/
tempo.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
'''A module that handles TOA files.
'''
#import numpy, os
#from numpy import mean, std, var, array, double, angle
from math import *
from numpy.core.records import fromfile
#from numpy import fromfile
#from fileio import *
#from SaveLoadable import MetaSaveLoader
#from decimal import *
#from numpy import float64 as __Decimal
def initmatplotlib(cols = 2):
import matplotlib as mpl
inches_per_pt = 1.0/72.27 # Convert pt to inches
#golden_mean = (sqrt(5)-1.0)/2.0 # Aesthetic ratio
if cols == 2:
fig_width_pt = 513.17 # Get this from LaTeX using \showthe\columnwidth
fig_width = fig_width_pt*inches_per_pt # width in inches
golden_mean = (sqrt(5)-1.0)/2.0 # Aesthetic ratio
fig_height =fig_width*golden_mean # height in inches
fig_size = [fig_width,fig_height]
elif cols == 1:
#print 'use cols', cols
fig_width_pt = 246.5 # Get this from LaTeX using \showthe\columnwidth
fig_width = fig_width_pt*inches_per_pt # width in inches
golden_mean = 0.7
fig_height =fig_width*golden_mean # height in inches
fig_size = [fig_width,fig_height]
else:
fig_width_pt = 246.5 # Get this from LaTeX using \showthe\columnwidth
fig_width = fig_width_pt*inches_per_pt # width in inches
fig_height =fig_width #square fig
fig_size = [fig_width,fig_height]
#print fig_size
#fig_size = [fig_width,fig_width]
params = {#'backend': 'pdf',
'axes.labelsize': 10,
'lines.markersize': 4,
'font.size': 10,
'xtick.major.size':6,
'xtick.minor.size':3,
'ytick.major.size':6,
'ytick.minor.size':3,
'xtick.major.width':1,
'ytick.major.width':1,
'xtick.minor.width':1,
'ytick.minor.width':1,
'lines.markeredgewidth':1,
'axes.linewidth':1,
'legend.fontsize': 7,
'xtick.labelsize': 10,
'ytick.labelsize': 10,
#'text.usetex': True,
'savefig.dpi':300,
'path.simplify':True,
'font.family':'serif',
#'axes.color_cycle': ['b', 'lime', 'r', 'purple', 'g', 'c', 'm', 'orange', 'darkblue', \
#'darkcyan', 'y','orangered','chartreuse','brown','deeppink','lightgreen', 'k'],
'axes.color_cycle': ['b', 'lime', 'r', 'purple', 'g', 'c', 'm', 'orange', 'darkblue', \
'darkcyan', 'y','orangered','chartreuse','deeppink','lightgreen', 'k'],
#'axes.formatter.useOffset':False,
#'font.serif':cm,
'figure.figsize': fig_size,
'figure.subplot.left':0.15,
'figure.subplot.bottom':0.20,
'figure.subplot.right':0.95,
'figure.subplot.top':0.95}
if not cols == 2:
params['axes.labelsize'] = 10
params['xtick.labelsize'] = 7
params['ytick.labelsize'] = 7
params['font.size'] = 10
mpl.rcParams.update(params)
#from matplotlib import pyplot
#pyplot.locator_params(nbins=6)
return mpl
mpl = initmatplotlib()
from decimal import Decimal as __Decimal
from decimal import getcontext
getcontext().prec = 25
secperday = 86400
def Decimal(value):
"""Convert string segment from TOA line to a float number.
return 0 when the input is an empty string.
"""
if isinstance(value, (int,float)):
return __Decimal(repr(value))
elif isinstance(value, (basestring)):
if value.strip() == '':
return __Decimal('0')
else:
return __Decimal(value)
else:
return __Decimal(value)
from scipy.special import fdtr
def Ftest(chi2_1, dof_1, chi2_2, dof_2):
"""
Ftest(chi2_1, dof_1, chi2_2, dof_2):
Compute an F-test to see if a model with extra parameters is
significant compared to a simpler model. The input values are the
(non-reduced) chi^2 values and the numbers of DOF for '1' the
original model and '2' for the new model (with more fit params).
The probability is computed exactly like Sherpa's F-test routine
(in Ciao) and is also described in the Wikipedia article on the
F-test: http://en.wikipedia.org/wiki/F-test
The returned value is the probability that the improvement in
chi2 is due to chance (i.e. a low probability means that the
new fit is quantitatively better, while a value near 1 means
that the new model should likely be rejected).
"""
delta_chi2 = chi2_1 - chi2_2
delta_dof = dof_1 - dof_2
new_redchi2 = chi2_2 / dof_2
F = (delta_chi2 / delta_dof) / new_redchi2
return 1.0 - fdtr(delta_dof, dof_2, F)
Observatory_list = {
'@': 'Bary Center',
'1': 'GBT',
'2': 'QUABBIN',
'3': 'ARECIBO',
'4': 'Hobart, Tasm',
'5': 'PRINCETON',
'6': 'VLA',
'7': 'PARKES',
'8': 'JODRELL BANK',
'9': 'GB 300FT',
'A': 'GB 140FT',
'B': 'GB 85-3',
'C': 'VLA SITE',
'D': 'NORTHERN CRO',
'E': 'MOST',
'F': 'Nancay',
'G': 'Effelsberg',
'H': 'JODRELL BANK',
'I': 'JODRELL BANK',
'J': 'mkiii',
'K': 'tabley',
'L': 'darnhall',
'M': 'knockin',
'N': 'defford',
'P': 'JODRELL BANK',
'Q': 'JODRELL BANK',
'R': 'GMRT',
'S': 'WSRT',
'T': 'VLT',
'U': 'VLT',
'k': 'FAST',
'fast':'FAST'
}
class TOA(object):
"""A class for reading/formating a single TOA line """
#__metaclass__ = MetaSaveLoader
#reserved_words = ['MODE', 'JUMP']
def __init__(self, line, file=None, **flags): #this way the keys in flags are passed as immutable values (parameters) to TOA, no need to do the copy/deepcopy.
self.flags = flags
if file:
self.file = file
else:
self.file = ''
if len(line) < 25:
raise "Line too short."
elif line[0] == 'C':
raise "Commentted line."
if line[0] == ' ':
self.format = 'Parkes'
self.info = []
self.line = line.ljust(80, ' ')
self._Observatory = self.line[79].strip()[0]
self.Observatory = Observatory_list[str(self._Observatory).upper()]
self.info.append(self.line[1:25].strip())
self.frequency = Decimal(self.line[25:34])
self.TOA = Decimal(self.line[34:55])
self.DMcorr = Decimal(self.line[55:63])
self.TOAsigma = Decimal(self.line[63:71])
self.info.append(self.line[71:80].strip())
elif line[1] == ' ' and not line[0] == ' ':
self.format = 'Princeton'
self.info = []
self.line = line.ljust(78, ' ')
self._Observatory = self.line[0].strip()[0]
self.Observatory = Observatory_list[str(self._Observatory).upper()]
self.info.append(self.line[2:15].strip())
self.frequency = Decimal(self.line[15:24])
try:
self.TOA = Decimal(self.line[24:44])
self.TOAsigma = Decimal(self.line[44:53])
except:
self.TOA = Decimal('4'+self.line[25:47])
self.TOAsigma = Decimal(self.line[49:53])
self.info.append(self.line[53:68].strip())
self.DMcorr = Decimal(self.line[68:77])
elif not line[0] ==' ' and not line[1] == ' ' and line[14] == '.' and len(line.rstrip(' ')) <= 60:
self.format = 'ITOA'
self.info = []
self.line = line.ljust(59, ' ')
self._Observatory = self.line[57:59].strip()[0]
self.Observatory = Observatory_list[str(self._Observatory).upper()]
self.info.append(self.line[:9].strip())
self.TOA = Decimal(self.line[9:28])
self.TOAsigma = Decimal(self.line[28:34])
self.frequency = Decimal(self.line[34:45])
self.DMcorr = Decimal(self.line[45:55])
self.info.append(self.line[55:57].strip())
else:
self.format = 'Tempo2'
self.info = []
self.line = line
line = self.line.split()
self.info.append(line[0])
self.frequency = Decimal(line[1])
self.TOA = Decimal(line[2])
self.TOAsigma = Decimal(line[3])
self._Observatory = line[4].strip()
if self._Observatory == 'ao':
self._Observatory = '3'
elif self._Observatory == 'gbt':
self._Observatory = '1'
if str(self._Observatory).upper() in Observatory_list:
self.Observatory = Observatory_list[str(self._Observatory).upper()]
else:
self.Observatory = str(self._Observatory)
#self.info.extend(line[5:])
tags = ' '.join(line[5:])
#self.flags = {'i':flags['i']}
import re
p = re.compile('-(?P<par>\w+)\s+(?P<value>\S+)', re.VERBOSE)
for m in p.finditer(tags):
par = str(m.group('par'))
try:
value = int(m.group('value'))
except:
value = str(m.group('value'))
if par in self.flags:
if par == 'to':
self.flags['to'] = str(float(self.flags['to']) + float(value))
elif par == 'f':
pass
else:
if self.flags[par] == value:
pass
else:
print 'duplicated flags in command line (%s %s) and in toa line (%s %s)' % (par, self.flags[par], par, value)
raise Error
else:
self.flags[par] = value
self.info.append(tags)
self.DMcorr = Decimal(0)
if self.TOA < 30000:
self.TOA += 39126
#if self.flags.has_key('EQUAD'):
#self.TOAsigma = sqrt(self.TOAsigma**2 + self.flags['EQUAD']**2)
def __repr__(self):
return '%s format TOA %s(%s us) at %s MHZ' % (self.format, self.TOA, self.TOAsigma, self.frequency)
def __str__(self):
TOAsigma = Decimal(self.TOAsigma)
if self.flags.has_key('EMAX'):
if float(TOAsigma) > float(self.flags['EMAX']):
return ''
if self.flags.has_key('EMIN'):
if TOAsigma < Decimal(self.flags['EMIN']):
TOAsigma = Decimal(self.flags['EMIN'])
if self.flags.has_key('EQUAD'):
TOAsigma = sqrt(TOAsigma**2 + self.flags['EQUAD']**2)
if self.flags.has_key('EFAC'):
TOAsigma = Decimal(TOAsigma) * self.flags['EFAC']
#if self.flags.has_key('to'):
#ActualTOA = self.TOA + Decimal(self.flags['to'])/secperday
else:
ActualTOA = self.TOA
if self.format == 'Princeton':
#return '%s %s%8.2f %s%9.3f%s%9.5f' % (self._Observatory, self.info[0][:13].ljust(13, ' '), self.frequency, (str(ActualTOA).ljust(20, ' '))[:20], TOAsigma, self.info[1][:15].rjust(15,' '), self.DMcorr)
return '%s %s%8.2f %s%9.3f%s%9.5f' % (self._Observatory, self.info[0][:13].ljust(13, ' '), self.frequency, str(ActualTOA.quantize(Decimal(0.00000000000001))).rjust(20, ' '), TOAsigma, self.info[1][:15].rjust(15,' '), self.DMcorr)
if self.format == 'Parkes':
return ' %s%8.2f %s%8.5f%8.3f%s%s' % (self.info[0].ljust(24, ' '), self.frequency,str(ActualTOA .quantize(Decimal(0.00000000000001))).rjust(21, ' '), self.DMcorr, TOAsigma, self.info[1][:8].rjust(8, ' '), self._Observatory)
if self.format == 'ITOA':
try:
info = ' '.join(self.info).strip().ljust(9, ' ')
except TypeError:
info = ' '.join(self.info).strip()[:9]
if info[0] == ' ' or info[1] == ' ': info = 'IT'+info[2:]
return '%s%s%6.3f%11.3f%10.5f %s' % (info,str(ActualTOA .quantize(Decimal(0.0000000000001))).rjust(19, ' '), TOAsigma,self.frequency, self.DMcorr, self._Observatory)
if self.format == 'Tempo2':
kwpars = ''
for key in [k for k in sorted(self.flags.keys(), reverse=True) if not k == 'EQUAD' and not k == 'JUMPflag' and not k =='EMAX' and not k =='EFAC' and not k =='EMIN']:
kwpars += ' -%s %s ' % (key, self.flags[key])
return '%s %s %s %s %s %s' % (self.info[0], self.frequency, str(ActualTOA .quantize(Decimal(0.00000000000001))).rjust(20, ' '), str(TOAsigma.quantize(Decimal(0.001))), self._Observatory, kwpars)
def tempo2fmt(self):
TOAsigma = Decimal(self.TOAsigma)
if self.flags.has_key('EMAX'):
if float(TOAsigma) > float(self.flags['EMAX']):
return ''
if self.flags.has_key('EMIN'):
if self.TOAsigma < Decimal(self.flags['EMIN']):
TOAsigma = Decimal(self.flags['EMIN'])
if self.flags.has_key('EQUAD'):
TOAsigma = sqrt(TOAsigma**2 + self.flags['EQUAD']**2)
if self.flags.has_key('EFAC'):
TOAsigma = Decimal(TOAsigma) * self.flags['EFAC']
#if self.flags.has_key('to'):
#timeoffset = Decimal(('%.11f' % float(self.flags['to'])))/secperday
#ActualTOA = self.TOA + timeoffset
#else:
#ActualTOA = self.TOA
ActualTOA = self.TOA
if self._Observatory == '1':
self._Observatory = 'gbt'
elif self._Observatory == '3':
self._Observatory = 'ao'
file = self.file.split('/')[-1].replace(' ','_').replace('-', '_')
file = file.ljust(10)[-15:]
#print ActualTOA
#fmtstr = '%s %s %s %s %s' % (file, self.frequency, str(ActualTOA.quantize(Decimal(0.00000000000001))).ljust(21, ' '), TOAsigma, self._Observatory)
fmtstr = '%s %s %s %s %s' % (file, self.frequency, str(ActualTOA).ljust(21, ' ')[:21], TOAsigma, self._Observatory)
kwpars = ''
#for key in [k for k in sorted(self.flags.keys(), reverse=True) if not k == 'EQUAD' and not k == 'JUMPflag' and not k =='EMAX' and not k == 'EFAC' and not k == 'EMIN' and not k == 'to']:
for key in [k for k in sorted(self.flags.keys(), reverse=True) if not k == 'EQUAD' and not k == 'JUMPflag' and not k =='EMAX' and not k == 'EFAC' and not k == 'EMIN']:
kwpars += ' -%s %s ' % (key, self.flags[key])
result = fmtstr+kwpars
if result[14] == '.':
result = result[:14] + '_' + result[15:]
return result
class TOAcommand(object):
def __init__(self, cmd, *args):
self.cmd = cmd
self.args = args
def __str__(self):
return '%s %s' % (self.cmd, ' '.join(self.args))
def __repr__(self):
return '%s %s' % (self.cmd, ' '.join(self.args))
class TOAfile(object):
"""A class for read/operate TOA files. """
def __init__(self, file, kws='', F0=None, infotag=None):
if kws == '':
kws = {'JUMPflag':False} #use to be in __init()__; but I forgto why I did that.
self.toafile = file
self.list = []
self.cmdlist = []
self.PHASEJUMPS = {}
self.TIMEOFFSETS = {}
self.EQUADvalues = {}
self.start = Decimal('1000000')
self.end = Decimal('0')
self.F0 = F0
self.infotags = ['f', 'i']
if not infotag==None:
self.infotags.append(infotag)
with open(file,'rt') as f:
text = f.read()
lines = text.split('\n')
toagroup = []
SKIPflag = False
PHASEJUMPFlag = False
TIMEOFFSETflag = False
for line in lines:
l = line.strip()
l = l.strip(' ')
s =l.strip().find('INCLUDE')
if l.strip().startswith('NOSKIP'):
SKIPflag = False
continue
elif l.strip().startswith('SKIP'):
SKIPflag = True
if not SKIPflag:
if len(l) == 0:pass
elif l[0] == 'C' or l[0] == '#':
pass #commented
elif not s == -1:
fn = l[s+7:].strip()
if not fn.find(' ') == -1:raise 'file name %s contains space?' % fn
tf = TOAfile(fn, kws=kws, F0=self.F0)
if tf.start < self.start: self.start = tf.start
if tf.end > self.end: self.end = tf.end
self.list.extend(tf.list)
self.cmdlist.extend(tf.cmdlist)
elif len(l) < 25:
if len(toagroup) > 0:self.list.append(toagroup)
command = TOAcommand(*l.split())
self.cmdlist.append(command)
toagroup = []
if command.cmd == 'INFO':
INFO = command.args[0]
kws.update({'i': INFO})
if PHASEJUMPFlag:
self.PHASEJUMPS[INFO] = PHASE
if TIMEOFFSETflag:
self.TIMEOFFSETS[INFO] = OFFSET
self.list.append(command)#ignore
elif command.cmd == 'JUMP':
kws['JUMPflag'] = not kws['JUMPflag']
if kws['JUMPflag']:
if kws.has_key('jump'):
kws['jump'] += 1
else:
kws['jump'] = 1
#self.list.append(command)#ignore
elif command.cmd == 'PHASE':
PHASE = float(command.args[0])
if kws.has_key('padd'):
NewPhase = kws['padd'] + PHASE
if NewPhase == 0.:
del kws['padd']
PHASEJUMPFlag = False
else:
kws['padd'] = NewPhase
if 'INFO' in locals():
self.PHASEJUMPS[INFO] = NewPhase
else:
kws['padd'] = PHASE
PHASEJUMPFlag = True
if 'INFO' in locals():
self.PHASEJUMPS[INFO] = NewPhase
elif command.cmd == 'TIME':
OFFSET = float(command.args[0])
if kws.has_key('to'):
NewOffset = kws['to'] + OFFSET
if NewOffset == 0.:
del kws['to']
TIMEOFFSETflag = False
else:
kws['to'] = NewOffset
if 'INFO' in locals():
self.TIMEOFFSETS[INFO] = NewOffset
else:
kws['to'] = OFFSET
TIMEOFFSETflag = True
if 'INFO' in locals():
self.TIMEOFFSETS[INFO] = OFFSET
elif command.cmd == 'EQUAD':
EQUAD = Decimal(command.args[0])
kws.update({'EQUAD':EQUAD})
if not kws.has_key('f'):
key = 1
self.EQUADvalues[str(key)]=EQUAD
else:
key = int(kws['f']) + 1
self.EQUADvalues[str(key)]=EQUAD
kws.update({'f':str(key)})
elif command.cmd == 'EMAX':
self.EMAX = Decimal(command.args[0])
kws['EMAX'] = self.EMAX
self.list.append(command)#ignore
elif command.cmd == 'EMIN':
self.EMIN = Decimal(command.args[0])
kws['EMIN'] = self.EMIN
self.list.append(command)#ignore
elif command.cmd == 'EFAC':
self.EFAC = Decimal(command.args[0])
self.list.append(command)#ignore
kws['EFAC'] = self.EFAC
elif command.cmd == 'FMIN':
self.FMIN = Decimal(command.args[0])
self.list.append(command)#ignore
kws['FMIN'] = self.FMIN
elif command.cmd == 'FMAX':
self.FMAX = Decimal(command.args[0])
self.list.append(command)#ignore
kws['FMAX'] = self.FMAX
else:
self.list.append(command)#ignore
else:
if len(self.cmdlist) == 0 or not self.cmdlist[-1] == 'TOAlist':
self.cmdlist.append('TOAlist')
if not SKIPflag:
if not file.find(' ') == -1:
file = ''
try:
t= TOA(line, file = file, **kws)
except TypeError:
print 'Probamatic line: ', l
print 'from file %s' % file
if t.flags.has_key('EMAX'):
if float(t.TOAsigma) > float(t.flags['EMAX']):
continue
#if t.flags.has_key('EFAC') and t.flags.has_key('EMAX'):
#if t.TOAsigma * t.flags['EFAC'] > t.flags['EMAX']:
#continue
KICKOUT = False
if t.flags.has_key('FMAX'):
if t.frequency > t.flags['FMAX']:
KICKOUT = True
if t.flags.has_key('FMIN'):
if t.frequency < t.flags['FMIN']:
KICKOUT = True
if KICKOUT == False:
toagroup.append(t)
if t.TOA < self.start:self.start = t.TOA
if t.TOA > self.end: self.end = t.TOA
KICKOUT = False
else:
pass # skipped
if len(toagroup) > 0:self.list.append(toagroup)
toalist = []
for toa in self.list:
if not type(toa) == TOAcommand:
toalist.extend(toa)
self.toalist = toalist
self.issubgroup = False
self.inspect()
def inspect(self):
commandgrps = {}
subcmdgrp = []
info = 'Untaged'
for c in self.cmdlist:
if type(c) == TOAcommand:
if not c.cmd.find('SKIP') == -1:continue
if c.cmd in ['EQUAD', 'EMAX', 'EFAC', 'EMIN']:
#if c.cmd in ['EQUAD', 'EMAX']:
#subcmdgrp.append(c)
pass
if c.cmd == 'INFO':info = c.args[0]
if c.cmd == 'MODE':self.MODE = c.args[0]
else:
#if not len(subcmdgrp) == 0:
if not commandgrps.has_key(info):
commandgrps[info] = subcmdgrp
else:
commandgrps[info].extend(subcmdgrp)
subcmdgrp = []
self.commandgrps = commandgrps
toagrp = {}
jumpgrp = {}
phasegroups = {}
othergroups = {}
toalist = self.toalist
for i in range(len(toalist)):
toa = toalist[i]
#if not toa.flags.has_key('i'):
#info = 'Untaged'
#else:
#info = toa.flags['i']
#if not toa.flags.has_key('jump'):
#jump = 0
#else:
#jump = toa.flags['jump']
info = 'Untaged'
jump = 0
for tag in self.infotags:
if tag in toa.flags:
info = toa.flags[tag]
#if 'i' in toa.flags:
#info = toa.flags['i']
#elif 'f' in toa.flags:
#info = toa.flags['f']
if toa.flags.has_key('padd'):
phase = float(toa.flags['padd'])
if phasegroups.has_key(info):
if not phasegroups[info] == phase:
print info, phasegroups[info], 'differs:', '-padd', toa.flags['padd']
#print "different phase jump for the same info group %s" % info;
#print toa.flags
#raise Error
else:
phasegroups[info] = phase
for key in toa.flags:
#if key == 'i':
#pass
if key == 'jump':
jump = toa.flags['jump']
elif key == 'padd':
#phase = float(toa.flags['padd'])
pass
else:
keyword = '-'+key+' '+str(toa.flags[key])
if othergroups.has_key(keyword):
othergroups[keyword].append(i)
else:
othergroups[keyword] = [i]
if not toagrp.has_key(info):
toagrp[info] = [i]
else:
toagrp[info].append(i)
if not jumpgrp.has_key(jump):
jumpgrp[jump] = [i]
else:
jumpgrp[jump].append(i)
self.groups = toagrp
self.jumpgroups = jumpgrp
self.phasegroups = phasegroups
self.othergroups = othergroups
#print jumpgrp
self.matchdict = {}
self.matchnotag = {}
self.firstgrp = None
self.grouporder = []
for grp in self.groups.keys():#now go through all groups and see if they contain the jump gropups
self.matchdict[grp] = []
if self.jumpgroups.has_key(0):
if set(self.jumpgroups[0]) <= set(self.groups[grp]):
self.matchdict[grp].append(0)
self.firstgrp = grp
self.grouporder.append(grp)
if self.firstgrp == None:
self.matchdict['notag'] = [0]
self.firstgrp = 'notag'
self.grouporder.append('notag')
for jpgrp in [k for k in self.jumpgroups.keys() if not k == 0]:
tagged = False
for grp in self.groups.keys():
if set(self.jumpgroups[jpgrp]) <= set(self.groups[grp]) and tagged == False:
self.matchdict[grp].append(jpgrp)
tagged = True
if not self.grouporder[-1] == grp and not grp in self.grouporder:
self.grouporder.append(grp)
if tagged == False:
if not self.matchdict.has_key('notag'):
self.matchdict['notag'] = [jpgrp]
else:
self.matchdict['notag'].append(jpgrp)
if not self.grouporder[-1] == 'notag' and not 'notag' in self.grouporder:
self.grouporder.append('notag')
if self.matchdict.has_key('notag') and any([len(self.matchdict[k])==0 for k in self.matchdict.keys()]):
self.matchnotag = {} #See if jump group contains multiple info tags
for jpgrp in self.matchdict['notag']:
for grp in [k for k in self.matchdict.keys() if len(self.matchdict[k]) == 0 ]:
#print grp, self.matchdict[grp],len(self.matchdict[grp])
if self.jumpgroups.has_key(0) and set(self.groups[grp]) < set(self.jumpgroups[jpgrp]):
if not self.matchnotag.has_key(jpgrp):
self.matchnotag[jpgrp] = [grp]
else:
self.matchnotag[jpgrp].append(grp)
alluntagged =set()
#print self.toafile
#print self.matchnotag
#print self.matchdict
#print self.jumpgroups.keys()
for jpgrp in self.matchdict['notag']:
#print jpgrp, self.matchnotag[jpgrp]
for s in [set(self.groups[grp]) for grp in self.matchnotag[jpgrp]]:
alluntagged |= s
alluntaggedjp =set()
for s in [set(self.jumpgroups[jpgrp]) for jpgrp in self.matchdict['notag']]:
alluntaggedjp |= s
if not alluntagged == alluntaggedjp:
print 'self.matchnotag: ', self.matchnotag
print 'self.matchdic: ', self.matchdict
#print [grp for grp in self.matchnotag[jpgrp] for jpgrp in [0,1]]
#print [grp for grp in self.matchnotag[jpgrp] for jpgrp in self.matchdict['notag']]
#print alluntagged #, alluntaggedjp
#print alluntaggedjp
print 'Warning: some toas does not belong to a jump group:' ,
self.groups['UntagedJump'] = list(alluntaggedjp - alluntagged)
print self.groups['UntagedJump']
self.jumpdict = self.matchdict.copy()
for jumpgrp in self.matchnotag.keys():
for grp in self.matchnotag[jumpgrp]:
self.jumpdict[grp] = [jumpgrp]
self.jumpdict.pop('notag')
if not self.toalist[0].format == 'Tempo2':
self.format = 'Tempo1'
else:
self.format = 'Tempo2'
def subgroup(self, groups=None):
from copy import deepcopy
new = deepcopy(self)
if groups == None:
return new
elif not type(groups) == list:
raise "Expecting groups to be list by get %s" % type(groups)
new.start = Decimal('1000000')
new.end = Decimal('0')
new.list = []
nextjump = 0
newjumpgrp = {}
subcmdgrp = []
subtoalist = []
EQUADgroups = []
for c in self.list:
if type(c) == TOAcommand:
if not c.cmd.find('SKIP') == -1:continue
if c.cmd in ['EQUAD', 'EMAX', 'EFAC', 'EMIN']:
subcmdgrp.append(c)
if c.cmd == 'INFO':
info = c.args[0]
subcmdgrp.append(c)
if not len(subtoalist) == 0:
new.list.append(subtoalist)
subtoalist = []
else:
if not len(subcmdgrp) == 0:
if info in groups:
new.list.extend(subcmdgrp)
subcmdgrp = []
for t in c:
if t.flags.has_key('i') and t.flags['i'] in groups:
if t.flags.has_key('jump'):
i = int(t.flags['jump'])
else:
i = 0
if newjumpgrp.has_key(i):
if newjumpgrp[i] == 0:
try:
t.flags.pop('jump')
except:pass
else:
t.flags['jump'] = newjumpgrp[i]
else:
newjumpgrp[i] = nextjump
nextjump += 1
t.flags['jump'] = newjumpgrp[i]
subtoalist.append(t)
if t.TOA < new.start:new.start = t.TOA
if t.TOA > new.end: new.end = t.TOA
if t.flags.has_key('f') and not t.flags['f'] in EQUADgroups:
EQUADgroups.append(t.flags['f'])
else:
#print t.flags
pass
if not len(subtoalist) == 0:
new.list.append(subtoalist)
subtoalist = []
toalist = []
for toa in new.list:
if not type(toa) == TOAcommand:
toalist.extend(toa)
new.toalist = toalist
for key in new.EQUADvalues.keys():
if not key in EQUADgroups:
new.EQUADvalues.pop(key)
new.inspect()
new.newjumpgrp = newjumpgrp
new.newjumpgroup = {}
for key in newjumpgrp:
new.newjumpgroup[newjumpgrp[key]] = key
if new.toalist[0].__dict__.has_key('npulse'):
new.npulse = []
for i in range(len(new.toalist)):
t = new.toalist[i]
new.npulse.append(t.npulse)
new.issubgroup = True
return new
def __str__(self):
#text = ''
#for x in self.list:
#if type(x) == TOAcommand:
#text += str(x)+'\n'
#else:
#for t in x:
#text += str(t)+'\n'
#return text
return '\n'.join([str(x) for x in self.list])
def tempo1fmt(self, format = 'Princeton'):
"""convert TOA file to tempo1 format, use the format keyword to define which version (Princeton, Parkes or ITOA) """
for toa in self.toalist:
toa.format = format
text = ''
if self.__dict__.has_key('MODE'):
text += 'MODE %s\n' % self.MODE
phaseoffset = 0.
for grp in self.grouporder:
if not grp == 'notag':
if grp in self.phasegroups.keys():
if not phaseoffset == self.phasegroups[grp]:
text += 'PHASE %s\n' % (self.phasegroups[grp] - phaseoffset)
phaseoffset = self.phasegroups[grp]
else:
if not phaseoffset == 0.:
text += 'PHASE %s\n' % (0. - phaseoffset)
phaseoffset = 0.
text += 'INFO %s\n' % (grp)
for cmd in self.commandgrps[grp]:
text += '%s\n' % cmd
for jpgrp in self.matchdict[grp]:
if not jpgrp == 0:
text += 'JUMP\n'
for i in self.jumpgroups[jpgrp]:
toa = self.toalist[i]
oldfmt = toa.format
toa.format = format
text += '%s\n' % str(toa)
toa.format = oldfmt
if not jpgrp == 0:
text += 'JUMP\n'
else:
for jpgrp in self.matchdict['notag']:
if not jpgrp == 0:
text += 'JUMP\n'
for grp in self.matchnotag[jpgrp]:
if grp in self.phasegroups.keys():
if not phaseoffset == self.phasegroups[grp]:
text += 'PHASE %s\n' % (self.phasegroups[grp] - phaseoffset)
phaseoffset = self.phasegroups[grp]
else:
if not phaseoffset == 0.:
text += 'PHASE %s\n' % (0. - phaseoffset)
phaseoffset = 0.
text += 'INFO %s\n' % (grp)
for cmd in self.commandgrps[grp]:
text += '%s\n' % cmd
for i in self.groups[grp]:
toa = self.toalist[i]
oldfmt = toa.format
toa.format = format
text += '%s\n' % str(toa)
toa.format = oldfmt
if not jpgrp == 0:
text += 'JUMP\n'
return text
def tempo2fmt(self, tempo1use=False, applycut=False):
"""convert TOA file to tempo2 format"""
fmtstr = """
"""
fmtstr += '\n'
hasphasejump = False
currentphasejump = 0
accumulatephasejump = 0
jumpnumber = 0
hasjump = False
'''*** try to temporarily put PHASE/jumps in tempo2 format for tempo1 use'''
for toas in self.list:
if isinstance(toas, (list,tuple)):
if tempo1use:
#if 'padd' in toas[0].flags and not hasphasejump:
#currentphasejump = toas[0].flags['padd']
#accumulatephasejump += toas[0].flags['padd']
#fmtstr += 'PHASE %s\n' % (currentphasejump)
#hasphasejump = True
#elif 'padd' in toas[0].flags and hasphasejump:
#currentphasejump = toas[0].flags['padd'] - accumulatephasejump
#if not currentphasejump == 0.:
#fmtstr += 'PHASE %s\n' % (currentphasejump)
#elif not 'padd' in toas[0].flags and hasphasejump:
#currentphasejump = 0 - accumulatephasejump
#fmtstr += 'PHASE %s\n' % (currentphasejump)
#hasphasejump = False
#accumulatephasejump = 0
if 'jump' in toas[0].flags and jumpnumber == 0:
jumpnumber = toas[0].flags['jump']
fmtstr += 'JUMP\n'
elif 'jump' in toas[0].flags and not toas[0].flags['jump'] == jumpnumber:
jumpnumber = toas[0].flags['jump']
fmtstr += 'JUMP\n'
fmtstr += 'JUMP\n'
'''*** try to temporarily put PHASE/jumps in tempo2 format for tempo1 use'''
if not applycut:
fmtstr += '\n'.join([t.tempo2fmt() for t in toas])
else:
fmtstr += '\n'.join([t.tempo2fmt() for t in toas if ((t.TOA > self.start) and (t.TOA < self.end))])
fmtstr += '\n'
elif isinstance(toas, TOAcommand) and not toas.cmd in ['EMAX', 'EFAC', 'EQUAD', 'MODE', 'EMIN']:
fmtstr += '%s\n' % (toas)
Extrastr = 'FORMAT 1\nMODE 1\n'
#for key in self.EQUADvalues.keys():
#Extrastr += 'T2EQUAD -f %s %s\n' % (key, self.EQUADvalues[key])
return Extrastr + fmtstr
#from datatools.timing import ephemeris
def residual(file = 'resid2.tmp'):
data = fromfile(file='resid2.tmp', dtype=[
('N', 'i4'),
('toa', 'f8'),
('res_phase', 'f8'),
('res_sec', 'f8'),
('ophase', 'f8'),
('rf_bary', 'f8'),
('weight', 'f8'),
('err_us', 'f8'),
('prefit_sec', 'f8'),
('ddm', 'f8'),
('M', 'i4'),
])
return data
# read jump offsets
def jumps(file = 'tempo.lis'):
import re
with open(file, 'r') as f: # open the file
text = f.read()
lines = text.split('\n')
N = len(lines)
p = re.compile('Iteration\s+(?P<interation>\d+)\s+of\s+(?P<total>\d+).*', re.VERBOSE)
e = re.compile('.*Weighted\s+RMS\s+residual.*', re.VERBOSE)
# find out the useful part (the last interation)
itr = 0
istart = 0
iend = N
foundstart = False
for i in range(N):
l = lines[i]
m = p.match(l)
if not m == None:
nitr = m.group('interation')
#if nitr > itr:
#itr = nitr
istart = i
foundstart = True
if foundstart:
if not e.match(l) == None:
iend = i
p = re.compile('PSR\s+\d{4}[-\+]\d{2,4}\s+Ephem.*', re.VERBOSE) #find the parameter section
foundstart = False
for i in range(istart, iend):
l = lines[i]
if not p.match(l) == None:
istart = i
foundstart = True
#write down the DMX parameters
#DMX = {}
#DMXmjdrange = {}
#p = re.compile('(\s+(?P<par>(DM\s(Dot|Off))(\s*(?P<idx>\d+)))\s*)+', re.VERBOSE) # look for the DM parameter definition line. The values are 6 lines below the parameters.
#e = re.compile('(?P<par>(DM\s(Dot|Off))(\s*(?P<idx>\d+)))', re.VERBOSE)
#for i in range(istart, iend):
#l = lines[i]
#if l.find('=') == -1 and l.find(':') == -1:
#if not p.match(l) == None:
#j = i
#parlist = []
#matchs = e.finditer(l)
#for m in matchs:
#parlist.append(m.group('idx'))#, m.group('idx')
#valuelist = lines[j+6].split()
#rangelist = lines[j+2].split(' ')[1:]
#for k in range(len(parlist)):
#DMX.update({parlist[k]:float(valuelist[k])})
#mjds, mjde = [float(x) for x in rangelist[k].split('-')]
#DMXmjdrange.update({parlist[k]: (mjds,mjde)})
#maxidx = max([int(k) for k in DMX.keys()])
#DMXarray = []
#DMXrange = []
#for i in range(maxidx):
#DMXarray.append(DMX[str(i+1)]) # make sure no DMX parameter is missed
#DMXrange.append(DMXmjdrange[str(i+1)])
#search for and write down the offset parameters
offset = {}
mjdrange = {}
p = re.compile('(\s+(?P<par>(Offset)(\s*(?P<idx>\d+)))\s*)+', re.VERBOSE)
e = re.compile('(?P<par>(Offset)(\s*(?P<idx>\d+)))', re.VERBOSE)
#idx = []
for i in range(istart, iend):
l = lines[i]
if l.find('=') == -1 and l.find(':') == -1:
if not p.match(l) == None:
j = i
parlist = []
matchs = e.finditer(l)
for m in matchs:
parlist.append(m.group('idx'))#, m.group('idx')
valuelist = lines[j+6].split()
rangelist = lines[j+2].split(' ')[1:]
for k in range(len(parlist)):
offset.update({parlist[k]:float(valuelist[k])})
mjds,mjde = [float(x) for x in rangelist[k].split('-')]
mjdrange.update({parlist[k]: (mjds,mjde)})
maxidx = max([int(k) for k in offset.keys()])
offsetarray = []
offsetrange = []
for i in range(maxidx):
offsetarray.append(offset[str(i+1)]) # make sure no offset parameter is missed
offsetrange.append(mjdrange[str(i+1)])
#inspect results
from numpy import array