-
Notifications
You must be signed in to change notification settings - Fork 0
/
Standalone_Taufit_simuBF_old.py
executable file
·1251 lines (1126 loc) · 48.2 KB
/
Standalone_Taufit_simuBF_old.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/python
# -*- coding: utf-8 -*-
#Created on Mon Jan 25 13:22:33 2016
#@author: marisa
#Standalone_Taufit_simu.py
import argparse
import os, sys
import pypsr_standalone as psr
import matplotlib.pyplot as plt
from lmfit import Model, conf_interval, printfuncs
from lmfit import minimize, Parameter, Parameters, fit_report
from lmfit.models import LinearModel, PowerLawModel, ExponentialModel, QuadraticModel
import numpy as np
from scipy import special
import DataReadIn as dri
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
#"""Read and print header information"""
"""Define options to the script"""
parser = argparse.ArgumentParser()
parser.add_argument('-f','--filename',
help="Provide the pathway to the data files")
parser.add_argument('-p','--period',type=float,
help="Provide the period of the pulsar in seconds")
parser.add_argument('-c','--counts',type=int,
help="Provide the number of noise realisations (interger)")
parser.add_argument('-s','--simulate',
help="Choosing this option leads to simulated data. For broadening function: choose between 'onedim', 'iso', 'aniso'.")
parser.add_argument('-m','--method',
help="Choosing method to fit data or simulation. Choose between 'onedim', 'iso', 'aniso','postfold', 'isoplusonedim'")
parser.add_argument('-r','--rawfile',
help="filepath to txt file, produced from shifting observing data")
parser.add_argument('-dc','--datacycle',
help="The type of data. Choose from comm., census, cycle5. Only used in creating filenames.")
parser.add_argument('-t','--template',
help="filepath to txt file, containing a high frequency EPN profile. It will use the fixed with of this profile.")
args = parser.parse_args()
"""Allocate variable names to the parsed options"""
filepath = args.filename
pulseperiod = args.period
count = args.counts
simu = args.simulate
meth = args.method
raw = args.rawfile
datac = args.datacycle
temp = args.template
"""Create folder to save to"""
newpath = r'./SummaryPlots_changeSNR'
if not os.path.exists(newpath):
os.makedirs(newpath)
if simu is None:
if raw is None:
print "\n Reading in data \n"
pulsars = []
pulsar, nch, nbins, lm_rms = dri.read_header(filepath)
pulsars = [pulsar for i in range(nch)]
print3 = "RMS: %f" %lm_rms
elif raw.endswith(".ort.prof") == True:
pulsar, nch, nbins, rawdata, freq = dri.read_Krishnak(raw)
pulsars = [pulsar for i in range(nch)]
print3 = ""
elif raw.startswith('1937') == True or raw.startswith('../python-workingdir/Paul') == True:
pulsar, nch, nbins, rawdata, freq = dri.read_Paul(raw)
pulsars = [pulsar for i in range(nch)]
print3 = ""
else:
pulsar, nch, nbins, rawdata, freq = dri.read_raw(raw)
pulsars = [pulsar for i in range(nch)]
print3 = ""
print0 = "Pulsar name: %s" %pulsar
print1 = "Number of channels: %d" %nch
print2 = "Number of bins: %d" %nbins
for k in range(4):
print eval('print{0}'.format(k))
else:
print "\n Simulating data \n"
print(" \n 1. The %s broadening function" %simu)
if simu in ('iso','ISO', 'Iso', 'onedim','1D','Onedim', 'postfold', 'pf', 'Postfold', 'POSTFOLD'):
while True:
try:
taudivP = raw_input("Express max. tau as a fraction of the pulseperiod: ")
taudivP = float(taudivP)
except ValueError:
print("Try again. Enter an int or float.")
continue
else:
break
else:
while True:
try:
taudivP1 = raw_input("Express max. tau1 as a fraction of the pulseperiod: ")
taudivP1 = float(taudivP1)
taudivP2 = raw_input("Express max. tau2 as a fraction of the pulseperiod: ")
taudivP2 = float(taudivP2)
taudivP = np.array([taudivP1, taudivP2])
except ValueError:
print("Try again. Enter an int or float.")
continue
else:
break
print(" \n 2. The simulated pulsar")
if pulseperiod is None:
while True:
try:
pulseperiod = raw_input("Express pulse period in seconds: ")
pulseperiod = float(pulseperiod)
except ValueError:
print("Try again. Enter an int or float.")
continue
else:
break
while True:
try:
dutycycle = raw_input("Express duty cycle as a percentage of pulse period, %s sec: " %pulseperiod)
dutycycle = float(dutycycle)
except ValueError:
print("Try again. Enter an int or float.")
continue
else:
break
print(" \n 3. Data and observing properties")
while True:
try:
freqlow, freqhigh, incr = raw_input("Choose a lowest and highest frequency and increment (MHz), e.g 50 120 5: ").split()
freqlow, freqhigh, incr = float(freqlow), float(freqhigh), float(incr)
except ValueError:
print("Try again. Separate 3 floats with a space.")
continue
else:
break
while True:
try:
# nbins = raw_input("Choose number of bins per pulse period: ")
# nbins = int(nbins)
snr = raw_input("Choose peak SNR: ")
snr = int(snr)
except ValueError:
print("Try again. Enter an int or float.")
continue
else:
break
nbins = 512
freqsimu = np.arange(freqlow,freqhigh+incr,incr)
nch = len(freqsimu)
propconst = taudivP*pulseperiod*(freqlow/1000.)**4
propconst = np.array([propconst])
tausecs = []
for i in range(len(propconst)):
tausec = propconst[i]*(freqsimu/1000.)**(-4)
tausecs.append(tausec)
tausecs = np.array(tausecs).transpose()
pulsars = []
for i in range(nch):
if simu in ('aniso','Aniso','ANISO'):
pulsar = r'Simul.: $\tau_1 = %.2f$, $\tau_2 = %.2f$ ' %(tausecs[i][0],tausecs[i][1])
pulsars.append(pulsar)
else:
pulsar = r'Simul: $\tau_1 = %.2f$' %tausecs[i]
pulsars.append(pulsar)
pulsar = 'Simulated'
print0 = "Pulsar : %s" %pulsar
print1 = "Number of channels: %d" %nch
print2 = "Number of bins: %d" %nbins
print3 = ""
#Find pulseperiod from list if it wasn't parsed
pulsarBnamelist = ['B0037+56','B0114+58','B0540+23','B0611+22','B0740-28','B1848+12','B1907+10','B1911-04','B1915+13','B1920+21','B1933+16','B2255+58','B2303+30']
pulsarnamelist = ['J0040+5716','J0117+5914','J0543+2329','J0614+2229', 'J0742-2822','J1851+1259','J1909+1102','J1913-0440','J1917+1353','J1922+2110','J1935+1616','J2257+5909','J2305+3100']
pulsarperiodlist = [1.118225, 0.101439, 0.245975, 0.33496, 0.166762, 1.205303, 0.283641, 0.825936, 0.194631, 1.077924, 0.358738, 0.368246, 1.575886]
if pulseperiod == None:
if raw is not None and raw.endswith(".ort.prof") == True:
pulsarN = pulsar[0:8]
print pulsarN
pulseind = pulsarBnamelist.index(pulsarN)
pulseperiod = pulsarperiodlist[pulseind]
else:
pulseind = pulsarnamelist.index(pulsar)
pulseperiod = pulsarperiodlist[pulseind]
else:
pulseperiod = pulseperiod
profilexaxis = np.linspace(0,pulseperiod,nbins)
#for i in range(10):
# plt.close()
## Create subplot structure
sp = 12 #number of subplots per figure
#plt.figure(figsize=(16,10))
#Fit profile using tau_fitter
obtainedtaus = []
lmfittausstds = []
obtainedtaus2 = []
lmfittausstds2 = []
bestparamsall = []
bestparams_stdall = []
redchis = []
freqmsMHz =[]
noiselessmodels =[]
comp_rmss = []
comp_fluxes= []
comp_SNRs =[]
datas = []
besttau2 = []
taustd2 = []
#trainlength = 4
halfway = nbins/2.
for i in range(nch):
if simu is None:
if raw is None:
data, freqm = dri.read_data(filepath,i,nbins)
freqmsMHz.append(freqm)
if i == 0:
peakbin = np.argmax(data)
print peakbin
# elif i==1:
# peakbin = np.argmax(data)
# print peakbin
# print "I'm using the second channel to centre the data since the first one is dropped! This is for B1911-04 comm. data"
else:
peakbin = peakbin
print peakbin
shift = int(halfway-int(peakbin))
print shift
data = np.roll(data,int(halfway-int(peakbin)))
print "I'm rolling the data to ensure the lowest freq. peak is in the middle"
elif raw.endswith(".ort.prof") == True:
data = rawdata
freqmsMHz = freq*1000
elif raw.startswith('1937') == True or raw.startswith('../python-workingdir/Paul') == True:
data = rawdata
freqmsMHz = freq*1000
else:
data = rawdata[i]
freqmsMHz = freq*1000
else:
freqmsMHz = freqsimu
freqGHz = freqmsMHz/1000.
data = psr.simulate(pulseperiod,tausecs[i],dutycycle,-1.6,freqGHz[i],freqlow/1000.,nbins,snr,simu)
comp_rms = psr.find_rms(data,nbins)
if temp is None:
if meth is None:
print "No fitting method was chosen. Will default to an isotropic fitting model. \n Use option -m with 'onedim' or 'aniso' to change."
noiselessmodel, besttau, taustd, bestparams, bestparams_std, redchi = psr.tau_fitter(data,nbins)
elif meth in ('iso','Iso','ISO'):
noiselessmodel, besttau, taustd, bestparams, bestparams_std, redchi = psr.tau_fitter(data,nbins)
elif meth in ('onedim','1D','Onedim'):
noiselessmodel, besttau, taustd, bestparams, bestparams_std, redchi = psr.tau_1D_fitter(data,nbins)
elif meth in ('aniso','Aniso','ANISO'):
noiselessmodel, besttau, taustd, besttau2, taustd2, bestparams, bestparams_std, redchi = psr.tau_ani_fitter(data,nbins)
elif meth in ('multi'):
if i == 0:
# bw1 = raw_input("Provide bin-window for 1st the peak (e.g: [20,30]): ")
# bw1 = eval(bw1)
# bw2 = raw_input("Provide bin-window start and end 2nd peak (e.g: [35,45]): ")
# bw2 = eval(bw2)
bw1, bw2 = np.linspace(660,720,2), np.linspace(725,750,2)
peak1 = np.max(data[bw1[0]: bw1[-1]])
peak2 = np.max(data[bw2[0]: bw2[-1]])
maxmean = 2.0*bw2[-1]
else:
bw1,bw2 = bw1,bw2
peak1, peak2, maxmean = peak1, peak2, maxmean
nms, bt, tstd, bp, bpstd, chis = [], [], [], [], [], []
for k in range(0,len(bw1)):
for j in range(0,len(bw2)):
noiselessmodel, besttau, taustd, bestparams, bestparams_std, redchi = psr.tau_fittermulti(data,nbins,bw1[k],bw2[j], peak1, peak2, maxmean)
nms.append(noiselessmodel)
bt.append(besttau)
tstd.append(taustd)
bp.append(bestparams)
bpstd.append(bestparams_std)
chis.append(redchi)
print j*k
tstd = np.array(tstd)
nonz = np.nonzero(tstd)
nonz_min = np.argmin(tstd[np.nonzero(tstd)])
tstd_ind = np.array(nonz).flatten()[nonz_min]
noiselessmodel, besttau, taustd, bestparams, bestparams_std, redchi = nms[tstd_ind], bt[tstd_ind], tstd[tstd_ind], bp[tstd_ind], bpstd[tstd_ind], chis[tstd_ind]
elif meth in ('postfold', 'pf', 'Postfold', 'POSTFOLD'):
trainlength = np.ceil(8*tausecs/pulseperiod)
trainlength = np.array([int(x) for x in trainlength])
print trainlength
noiselessmodel, besttau, taustd = psr.tau_fitter_postfold(data,nbins,trainlength[i])
else:
print "Incorrect fitting method. Choose from iso, onedim, aniso, postfold"
else:
templatefile = np.loadtxt(temp)
if meth is None:
tempdata = templatefile[:,3]
noiselessmodel, besttau, taustd, bestparams, bestparams_std, redchi = psr.tau_tempfitter(data,nbins,tempdata)
elif meth in ('iso','Iso','ISO'):
tempdata = templatefile[:,3]
noiselessmodel, besttau, taustd, bestparams, bestparams_std, redchi = psr.tau_tempfitter(data,nbins,tempdata)
elif meth in ('onedim','1D','Onedim'):
tempdata = templatefile[:,3]
noiselessmodel, besttau, taustd, bestparams, bestparams_std, redchi = psr.tau_1D_tempfitter(data,nbins,tempdata)
else:
print "Incorrect fitting method. Choose from iso or onedim or multi (for analytical double peak)"
""" INPUT SECTION ENDS """
comp_flux = psr.find_modelflux(noiselessmodel,nbins)
comp_SNR_model = psr.find_peaksnr(noiselessmodel,comp_rms)
print 'SNR (from model): %.2f' % comp_SNR_model
comp_SNR = psr.find_peaksnr_smooth(data,comp_rms)
print 'SNR (from data): %.2f' % comp_SNR
# print "The SNR is computed using data only, not model"
# print "The SNR is computed using model"
obtainedtaus.append(besttau)
lmfittausstds.append(taustd)
obtainedtaus2.append(besttau2)
lmfittausstds2.append(taustd2)
bestparamsall.append(bestparams)
bestparams_stdall.append(bestparams_std)
redchis.append(redchi)
noiselessmodels.append(noiselessmodel)
comp_rmss.append(comp_rms)
comp_fluxes.append(comp_flux)
comp_SNRs.append(comp_SNR)
datas.append(data)
"""Considering the generated BW, calculate the monochromatic frequency that should be associated with the tau-fits"""
"""Replace freqmsMHz with this frequency"""
#for now I'm only using an average bandwidth for all observations. Considering changing it from freq to freq.
if nch !=1:
print 'Change observing frequencies + BW to an associated monochromatic frequency'
originalfreq = freqmsMHz
bandwidthMHz = 2*(freqmsMHz[-1]-freqmsMHz[0])/(nch-1)
freqMonoMHzs = []
for i in range(nch):
freqMonoMHz = psr.make_mono(freqmsMHz[i],bandwidthMHz)
freqMonoMHzs.append(freqMonoMHz)
freqmsMHz = freqMonoMHzs
"""Delete profiles with
1. inadequate SNR values,
2. too large tau error values
3. tau error == 0, i.e. not a fit
update other arrays accordingly"""
SNRcutoff = 2.7
tauerrorcutoff = 5.0
print4 = "SNR cutoff: %.2f" % SNRcutoff
print5 = "Tau perc error cutoff: %.2f" % (100*tauerrorcutoff)
for k in range(0,6):
print eval('print{0}'.format(k))
ind_lowSNR = np.where(np.array(comp_SNRs) < SNRcutoff)
ind_tauerr = np.where(np.array(lmfittausstds)/np.array(obtainedtaus) > tauerrorcutoff)
ind_tauerr2 = np.where(np.array(lmfittausstds)==0)
ind_uniq = np.unique(np.hstack((ind_lowSNR,ind_tauerr,ind_tauerr2)))
data_highsnr = np.delete(np.array(datas),ind_uniq,0)
model_highsnr = np.delete(np.array(noiselessmodels),ind_uniq,0)
""""""
taus_highsnr = np.delete(np.array(obtainedtaus),ind_uniq)
lmfitstds_highsnr = np.delete(np.array(lmfittausstds),ind_uniq)
taus2_highsnr = np.delete(np.array(obtainedtaus2),ind_uniq)
lmfitstds2_highsnr = np.delete(np.array(lmfittausstds2),ind_uniq)
freqMHz_highsnr = np.delete(np.array(freqmsMHz),ind_uniq)
freqms_highsnr = np.array(freqMHz_highsnr)/1000.
fluxes_highsnr = np.delete(np.array(comp_fluxes),ind_uniq)
rms_highsnr = np.delete(np.array(comp_rmss),ind_uniq)
number_of_plotted_channels = len(data_highsnr)
npch = number_of_plotted_channels
"""Array with all the other fitting parameters: sigma, A, etc."""
bestpT = np.transpose(bestparamsall)
bestpT_std = np.transpose(bestparams_stdall)
print6 = "Number of plotted channels: %d/%d" %(npch, nch)
print7 = "Number of channels dropped for low SNR: %d" %np.shape(ind_lowSNR)[1]
print8 = "Number of channels dropped for high tau error: %d" %np.shape(ind_tauerr)[1]
for k in range(6,9):
print eval('print{0}'.format(k))
"""Similarly reduce array to only the used data (i.e. lowSNR and hightauerr removed)"""
bestpT_highSNR = np.zeros([len(bestpT),npch])
bestpT_std_highSNR = np.zeros([len(bestpT),npch])
for i in range(len(bestpT)):
bestpT_highSNR[i]= np.delete(bestpT[i],ind_uniq)
bestpT_std_highSNR[i]= np.delete(bestpT_std[i],ind_uniq)
"""Calculate fits for parameters sigma and mu"""
"""Shift data based on mu-trend (DM trend?)"""
pbs = pulseperiod/nbins
"""Fit models to sigma"""
powmod = PowerLawModel()
powpars = powmod.guess(bestpT_highSNR[0], x=freqms_highsnr)
powout = powmod.fit(bestpT_highSNR[0], powpars, x=freqms_highsnr, weights=1/((bestpT_std_highSNR[0])**2))
linmod = LinearModel()
quadmod = QuadraticModel()
quadpars = quadmod.guess(bestpT_highSNR[0], x=freqms_highsnr)
quadout = quadmod.fit(bestpT_highSNR[0], quadpars, x=freqms_highsnr, weights=1/((bestpT_std_highSNR[0])**2))
expmod = ExponentialModel()
exppars = expmod.guess(bestpT_highSNR[0], x=freqms_highsnr)
expout = expmod.fit(bestpT_highSNR[0], exppars, x=freqms_highsnr, weights=1/((bestpT_std_highSNR[0])**2))
"""Fit quadractic/DM model to mu"""
quadpars_mu = quadmod.guess(bestpT_highSNR[1], x=freqms_highsnr)
quadout_mu = quadmod.fit(bestpT_highSNR[1], quadpars_mu, x=freqms_highsnr, weights=1/((bestpT_std_highSNR[1])**2))
"""Fit a DM model to DM"""
delnuarray = [-(1/freqMHz_highsnr[-1]**2-1/freqMHz_highsnr[i]**2) for i in range(npch)] ##in MHz
delmuarray = [(bestpT_highSNR[1][-1] - bestpT_highSNR[1][i])*pbs for i in range(npch)] ##in seconds
delmu_stdarray = [(bestpT_std_highSNR[1][-1] - bestpT_std_highSNR[1][i])*pbs for i in range(npch)]
DM_linpars = linmod.guess(delmuarray, x=delnuarray)
DM_linout = linmod.fit(delmuarray, DM_linpars, x=delnuarray, weights=1/(np.power(delmu_stdarray,2)))
DM_linout = linmod.fit(delmuarray, DM_linpars, x=delnuarray)
DM_CCval = DM_linout.best_values['slope']
DM_CCvalstd = DM_linout.params['slope'].stderr
DMmodelfit = DM_linout.best_fit ##model gives deltime in seconds (used to shift data)
DMconstant = 4148.808
DMval = (DM_CCval/DMconstant)
DMvalstd = (DM_CCvalstd/DMconstant)
DMcheck = psr.DM_checker(freqmsMHz,bestpT_highSNR[1]*pbs)
###Calculate the required shift in bins as an integer
mu_shift_int = np.around(DMmodelfit/pbs).astype(int)
#if raw is None:
# shiftpath = r'./ShiftedTxtfiles'
# if not os.path.exists(shiftpath):
# os.makedirs(shiftpath)
# shiftfile = '%s_rawshiftdata_%s.txt' %(pulsar,meth)
# shiftpathfile = os.path.join(shiftpath,shiftfile)
#
# shifted_data = [np.roll(datas[i],mu_shift_int[i]) for i in range(npch)]
# freqsshape = freqms_highsnr.reshape(npch,1)
# shifted_stackfile = np.hstack((shifted_data,freqsshape))
# np.savetxt(shiftpathfile,shifted_stackfile)
else:
plt.figure(1,figsize=(6,4))
plt.rc('text', usetex = True)
plt.rc('font',family='serif')
plt.plot(data,'m',alpha=0.8, label="data")
plt.plot(noiselessmodel, 'c', alpha=0.7, label="model")
unscat = psr.TwoPeaksModel(np.linspace(1,nbins,nbins), 1024, bp[tstd_ind][4], bp[tstd_ind][5], bp[tstd_ind][2] , bp[tstd_ind][3], bp[tstd_ind][0], bp[tstd_ind][1], bp[tstd_ind][6])
plt.plot(unscat,'g--')
plt.title('%s at %.1f MHz' %(pulsars[0], freqmsMHz))
plt.text(800,0.8,r'$\tau: %.4f \pm %.1e$ms' %(besttau*pulseperiod/(2*nbins)*1000, taustd*pulseperiod/(2*nbins)*1000),fontsize=11)
plt.legend()
plt.xlim(xmin=500,xmax=1024)
# plt.annotate(r'$\tau: %.4f \pm %.4f$ ms' %(besttau*pulseperiod/nbins*1000, taustd*pulseperiod/nbins*1000),xy=(np.max(profilexaxis),np.max(data)),xycoords='data',xytext=(0.8,0.8),textcoords='axes fraction',fontsize=12)
Kplot = '%s_%s.png' % (pulsar,raw[-6:-4])
picpathtau = newpath
fileoutputtau = os.path.join(picpathtau,Kplot)
plt.savefig(fileoutputtau, dpi=150), np.savetxt('%s_%s.txt' % (pulsar,raw[-6:-4]), np.column_stack((bt[tstd_ind], tstd[tstd_ind])).flatten())
plt.savefig(fileoutputtau, dpi=150), np.savetxt('%s_%s_params.txt' % (pulsar,raw[-6:-4]), bp[tstd_ind])
plt.savefig(fileoutputtau, dpi=150), np.savetxt('%s_%s_paramstd.txt' % (pulsar,raw[-6:-4]), bpstd[tstd_ind])
print 'Saved %s in %s' %(Kplot,newpath)
sys.exit()
"""Plotting starts"""
##PLOT PROFILES##
totFig = (npch+5)/sp + 1
#for i in range(totFig):
# plt.figure((totFig-i), figsize=(16,10))
# plt.figure((totFig-i))
profiles = []
#for j in range(npch):
# if j+1 == sp:
# numFig = (j+1)/sp
# subplotcount = sp
# else:
# numFig = (j+1)/sp + 1
# if j+1 < sp:
# subplotcount = j+1
# else:
# subplotcount = j+1 - sp
# bins, profile = psr.makeprofile(nbins = nbins, ncomps = 1, amps = bestpT_highSNR[2][j], means = bestpT_highSNR[1][j], sigmas = bestpT_highSNR[0][j])
# profiles.append(profile)
# smootheddata = psr.smooth(datas[j],int(0.05*nbins))
# plt.figure(numFig,figsize=(16,10))
# plt.subplot(3,4,subplotcount)
# plt.rc('text', usetex=True)
# plt.rc('font', family='serif')
# plt.tight_layout()
## data_highsnr[j] = np.hstack((data_highsnr[j][800:1024],data_highsnr[j][0:800]))
## model_highsnr[j] = np.hstack((model_highsnr[j][800:1024],model_highsnr[j][0:800]))
# plt.plot(profilexaxis,data_highsnr[j],'y',alpha = 0.5)
## plt.plot(profilexaxis,shifted_data[j],'g',alpha = 0.6)
# plt.plot(profilexaxis,model_highsnr[j],'r', alpha = 0.7)
## plt.plot(profilexaxis,smootheddata,'g', alpha = 0.4,lw=2.0)
## plt.plot(profilexaxis,profile,'k', alpha = 0.7)
# plt.title('%s at %.1f MHz' %(pulsars[j], freqMHz_highsnr[j]))
# plt.annotate(r'$\tau: %.4f \pm %.4f$ sec' %(taus_highsnr[j]*pulseperiod/nbins, lmfitstds_highsnr[j]*pulseperiod/nbins),xy=(np.max(profilexaxis),np.max(data_highsnr[j])),xycoords='data',xytext=(0.4,0.8),textcoords='axes fraction',fontsize=12)
# if len(taus2_highsnr) != 0:
# plt.annotate(r'$\tau2: %.5f \pm %.5f$ sec' %(taus2_highsnr[j]*pulseperiod/nbins, lmfitstds2_highsnr[j]*pulseperiod/nbins),xy=(np.max(profilexaxis),np.max(data_highsnr[j])),xycoords='data',xytext=(0.4,0.6),textcoords='axes fraction',fontsize=12)
# plt.ylim(ymax=1.1*np.max(data_highsnr[j]))
## plt.ylim(-200.0,700.0)
# plt.xticks(fontsize=12)
# plt.yticks(fontsize=12)
# plt.xlabel('time (s)')
# plt.ylabel('intensity')
#
if npch >= sp:
subpl_ind = int(npch-sp) +1
else:
subpl_ind = int(npch) + 1
if npch + 1 == sp:
numfig = (npch+1)/sp
else:
numfig = (npch+1)/sp + 1
#
###PLOT FLUX##
#plt.figure(numfig, figsize=(16,10))
#plt.subplot(3,4,subpl_ind)
#plt.rc('text', usetex=True)
#plt.rc('font', family='serif')
#plt.plot(freqMHz_highsnr,fluxes_highsnr,'mo')
#plt.title('%s' %(pulsar))
#plt.xticks(fontsize=12)
#plt.yticks(fontsize=12)
#plt.xlabel(r'$\nu$ (MHz)',fontsize=16)
#plt.ylabel(r'Calibrated flux (mJy)',fontsize=16)
lmfittausstds = np.array(lmfittausstds)
obtainedtaus = np.array(obtainedtaus)
lmfittausstds2 = np.array(lmfittausstds2)
obtainedtaus2 = np.array(obtainedtaus2)
obtainedtausec = obtainedtaus*pulseperiod/nbins
obtainedtausec2 = obtainedtaus2*pulseperiod/nbins
lmfitstdssec_highsnr = lmfitstds_highsnr*pulseperiod/nbins
lmfitstdssec2_highsnr = lmfitstds2_highsnr*pulseperiod/nbins
freqms = np.array(freqmsMHz)/1000. #(Use this one to compare the alpha outcome of all the freq channels with only the high SNR/low tau error ones.)
"""The associated high SNR arrays are"""
taus_highsnr = np.array(taus_highsnr)
taus2_highsnr = np.array(taus2_highsnr)
taussec_highsnr = taus_highsnr*pulseperiod/nbins
taussec2_highsnr = taus2_highsnr*pulseperiod/nbins
"""Order taus in the case of an anisotropic model with 2 taus"""
taus_order, taus2_order = np.zeros(len(taus_highsnr)), np.zeros(len(taus_highsnr))
taus_order_err, taus2_order_err = np.zeros(len(taus_highsnr)), np.zeros(len(taus_highsnr))
if len(taussec2_highsnr) != 0:
for i in range(len(taus_highsnr)):
if taussec_highsnr[i] > taussec2_highsnr[i]:
taus_order[i] = taussec_highsnr[i]
taus2_order[i] = taussec2_highsnr[i]
taus_order_err[i] = lmfitstdssec_highsnr[i]
taus2_order_err[i] = lmfitstdssec2_highsnr[i]
else:
taus_order[i] = taussec2_highsnr[i]
taus2_order[i] = taussec_highsnr[i]
taus_order_err[i] = lmfitstdssec2_highsnr[i]
taus2_order_err[i] = lmfitstdssec_highsnr[i]
else:
taus_order = taussec_highsnr
if len(taussec2_highsnr) != 0:
taussec_highsnr = taus_order
taussec2_highsnr = taus2_order
tausgeo = np.sqrt(taussec_highsnr *taussec2_highsnr)
powmod = PowerLawModel()
#powparstau = powmod.guess(obtainedtausec,x=freqms)
#powouttau = powmod.fit(obtainedtausec,powparstau, x=freqms,weights=1/(lmfittausstds**2))
powparstau_highsnr = powmod.guess(taussec_highsnr,x=freqms_highsnr)
powouttau_highsnr = powmod.fit(taussec_highsnr,powparstau_highsnr, x=freqms_highsnr,weights=1/(lmfitstdssec_highsnr**2))
#specfitdata = -powouttau.best_values['exponent']
specfitdata_highsnr = -powouttau_highsnr.best_values['exponent']
specdata_err_highsnr = powouttau_highsnr.params['exponent'].stderr
spec_amp = powouttau_highsnr.best_values['amplitude']
tau_HBAtop = spec_amp*np.power(freqms_highsnr[-1],-specfitdata_highsnr)
tau_1GHz = psr.tauatfreq(freqms_highsnr[-1],tau_HBAtop,1.0,specfitdata_highsnr)
tau_100MHz = psr.tauatfreq(freqms_highsnr[-1],tau_HBAtop,0.1,specfitdata_highsnr)
#print ""
#print9 = 'alpha (from all data) = %.4f' %specfitdata
print9 =""
print10 = 'alpha (from high SNR, low tau err) = %.4f' %specfitdata_highsnr
print11 = 'pulseperiod = %.6f' %pulseperiod
print originalfreq
print ""
print freqms
print freqmsMHz
print ""
print freqms_highsnr
print freqMHz_highsnr
for k in range(9,12):
print eval('print{0}'.format(k))
print "tau_1GHz = %.8f sec" %tau_1GHz
print "tau_100MHz = %.8f sec" %tau_100MHz
#PLOT TAU##
#if subpl_ind >= sp:
# subpl_ind2 = int(subpl_ind-sp) +1
#else:
# subpl_ind2 = int(subpl_ind) + 1
#
#if npch + 2 == sp:
# numfig2 = (npch+2)/sp
#else:
# numfig2 = (npch+2)/sp + 1
#
#plt.figure(numfig2, figsize=(16,10))
#plt.subplot(3,4,subpl_ind2)
##plt.tight_layout()
#plt.errorbar(1000.*freqms_highsnr,taussec_highsnr,yerr=lmfitstds_highsnr*pulseperiod/nbins,fmt='k*',markersize=9.0,capthick=2,linewidth=1.5)
#plt.plot(1000.*freqms_highsnr, powouttau_highsnr.best_fit, 'k-')
##plt.plot(1000.*freqms_highsnr, powouttau_highsnr1.best_fit, 'k--', label=r'Unweighted: $\alpha = %.2f \pm %.2f$' %(specfitdata_highsnr1,specdata_err_highsnr1))
#plt.title(r'$\alpha = %.2f \pm %.2f$' %(specfitdata_highsnr,specdata_err_highsnr))
##plt.annotate('%s' %pulsar,xy=(np.max(1000*freqms),np.max(obtainedtausec)),xycoords='data',xytext=(0.5,0.7),textcoords='axes fraction',fontsize=14)
#plt.xticks(fontsize=12)
#plt.yticks(fontsize=12)
#plt.xlabel(r'$\nu$ MHz',fontsize=16)
#plt.ylabel(r'$\tau$ (sec)',fontsize=16)
#
#
#
## PLOT TAU LOG ##
#if subpl_ind2 >= sp:
# subpl_ind3 = int(subpl_ind2-sp) +1
#else:
# subpl_ind3 = int(subpl_ind2) + 1
#
#if npch + 3 == sp:
# numfig3 = (npch+3)/sp
#else:
# numfig3 = (npch+3)/sp + 1
#
#
#freqmsMHz = np.array(freqmsMHz)
#ticksMHz = freqmsMHz.astype(np.int)[0:len(freqmsMHz):2]
#
#plt.figure(numfig3,figsize=(16,10))
#plt.subplot(3,4,subpl_ind3)
##plt.figure(NF,figsize=(12,4))
##plt.subplot(1,3,1)
#plt.errorbar(1000.*freqms_highsnr,taussec_highsnr,yerr=lmfitstds_highsnr*pulseperiod/nbins,fmt='k*',markersize=9.0,capthick=2,linewidth=1.5,label=r'$\alpha = %.2f \pm %.2f$' %(specfitdata_highsnr,specdata_err_highsnr))
#plt.plot(1000.*freqms_highsnr, powouttau_highsnr.best_fit, 'k-')
#plt.title('%s' %pulsar)
##plt.annotate('%s' %pulsar,xy=(np.max(1000*freqms),np.max(obtainedtausec)),xycoords='data',xytext=(0.5,0.7),textcoords='axes fraction',fontsize=14)
#plt.yticks(fontsize=12)
#plt.xlabel(r'$\nu$ (MHz)',fontsize=16)
#plt.ylabel(r'$\tau$ (sec)',fontsize=16)
#plt.legend(fontsize=14)
#plt.xscale('log')
#plt.yscale('log')
#plt.xlim(xmin=(freqms[0])*950,xmax=(freqms[-1])*1050)
#plt.xticks(ticksMHz,ticksMHz,fontsize=12)
#plt.tight_layout()
##PLOT CHANGE in ALPHA ##
#if subpl_ind3 >= sp:
# subpl_ind4 = int(subpl_ind3-sp) +1
#else:
# subpl_ind4 = int(subpl_ind3) + 1
#
#if npch + 4 == sp:
# numfig4 = (npch+4)/sp
#else:
# numfig4 = (npch+4)/sp + 1
"""Calculate how the spectral index is changing as more and more low freq. channels are added"""
spec_sec = np.zeros(npch-1)
spec_std_sec = np.zeros(npch-1)
for i in range(npch-1):
bb = npch - (i+2)
ee = npch
# print freqms[bb:ee]
powparstau_sec = powmod.guess(taussec_highsnr[bb:ee],x=freqms_highsnr[bb:ee])
powouttau_sec = powmod.fit(taussec_highsnr[bb:ee],powparstau_sec, x=freqms_highsnr[bb:ee],weights=1/(lmfitstds_highsnr[bb:ee]**2))
spec_sec[i] = -powouttau_sec.best_values['exponent']
spec_std_sec[i] = powouttau_sec.params['exponent'].stderr
freq_incl = 1000*freqms_highsnr[::-1][1:]
#plt.figure(numfig4, figsize=(16,10))
#plt.subplot(3,4,subpl_ind4)
#plt.errorbar(freq_incl,spec_sec,yerr=spec_std_sec,fmt='k*',markersize=5.0,capthick=2,linewidth=0.5)
#plt.title(r'Change in spectral index')
#for x,y in zip(freq_incl[0::2], spec_sec[0::2]):
# plt.annotate('%.2f' %y, xy=(x,1.08*y), xycoords='data',textcoords='data')
#plt.ylim(plt.ylim()[0],1.1*plt.ylim()[1])
#plt.yticks(fontsize=12)
#plt.xticks(fontsize=12)
#plt.xlabel(r'Lowest freq included (MHz)',fontsize=16)
#plt.ylabel(r'$\alpha$',fontsize=16)
#plt.tight_layout()
#
###PLOT CHI ##
#
#if subpl_ind4 >= sp:
# subpl_ind5 = int(subpl_ind4-sp)+1
#else:
# subpl_ind5 = int(subpl_ind4)+1
#
#if npch + 5 == sp:
# numfig5 = (npch+5)/sp
#else:
# numfig5 = (npch+5)/sp + 1
#
#redchis_highsnr = np.delete(np.array(redchis),ind_uniq)
#
#plt.figure(numfig5, figsize=(16,10))
#plt.subplot(3,4,subpl_ind5)
#plt.plot(1000.*freqms_highsnr, redchis_highsnr, 'r*', markersize = 12)
#plt.title(r'Reduced $\chi^2$ values')
#plt.annotate('%s' %pulsar,xy=(np.max(1000*freqms),np.max(obtainedtausec)),xycoords='data',xytext=(0.5,0.7),textcoords='axes fraction',fontsize=14)
#plt.yticks(fontsize=10)
#plt.xticks(fontsize=12)
#plt.xlabel(r'$\nu$ MHz',fontsize=16)
#plt.ylabel(r'$\chi^2$',fontsize=16)
#
#
#### PLOT MU ##
##
##plt.figure(numfig5)
##plt.subplot(3,4,subpl_ind5)
###plt.errorbar(bestpT_highSNR[1]*pbs,freqMHz_highsnr, xerr = bestpT_std_highSNR[1]*pbs, fmt = 'b*',markersize=9.0,capthick=2,linewidth=1.5)
###plt.plot(quadout_mu.best_fit*pbs, freqMHz_highsnr, 'b-', label='a,b = %.2f,%.2f' %(quadout_mu.best_values['a'],quadout_mu.best_values['b']))
##plt.errorbar(np.array(delmuarray),1/freqMHz_highsnr, xerr = delmu_stdarray, fmt = 'b*',markersize=9.0,capthick=2,linewidth=1.5)
###plt.plot(DMbestfit, 1/freqMHz_highsnr, 'b-', label=r'DM = %.4f \pm %.6f' %(DMmyval,DMmyval_std))
###plt.plot(1000.*freqms_highsnr, powout_mu.best_fit*pbs, 'm-', label='pow = %.2f' %powout_mu.best_values['exponent'])
###plt.plot(quadout_mu.best_fit*pbs,1000.*freqms_highsnr, 'b-', label='a,b = %.2f,%.2f' %(quadout_mu.best_values['a'],quadout_mu.best_values['b']))
###plt.plot(bestpT_highSNR[1]*pbs,1000*freqms_highsnr, 'k*-', label=r'DM: %.4f pc.cm^{-3}' %(DMval))
##plt.yticks(fontsize=10)
##plt.xticks(fontsize=7)
##plt.xlabel(r'$\mu (sec)$ MHz',fontsize=16)
##plt.ylabel(r'$\nu$ MHz',fontsize=16)
##plt.legend(fontsize = 9)
#
#powparstau_highsnr = powmod.guess(taussec_highsnr,x=freqms_highsnr)
#powouttau_highsnr = powmod.fit(taussec_highsnr,powparstau_highsnr, x=freqms_highsnr,weights=1/(lmfitstdssec_highsnr**2))
#
#
#
#if len(taussec2_highsnr) != 0:
# resultpow2guess = powmod.guess(taussec2_highsnr,x=freqms_highsnr)
# resultpowdata2_highsnr = powmod.fit(taussec2_highsnr,resultpow2guess, x=freqms_highsnr,weights=1/(lmfitstdssec2_highsnr**2),K=0.001,k=4)
#
# resultpowgeoguess = powmod.guess(tausgeo,x=freqms_highsnr)
# resultpowdatageo_highsnr = powmod.fit(tausgeo,resultpowgeoguess, x=freqms_highsnr,weights=1/(lmfitstdssec2_highsnr**2),K=0.001,k=4)
#
# specfitdata2_highsnr = -resultpowdata2_highsnr.best_values['exponent']
# specdata2_err_highsnr = resultpowdata2_highsnr.params['exponent'].stderr
#
# specfitdatageo_highsnr = -resultpowdatageo_highsnr.best_values['exponent']
# specdatageo_err_highsnr = resultpowdatageo_highsnr.params['exponent'].stderr
#
#
# plt.figure(numfig5)
# plt.subplot(3,4,subpl_ind5)
# plt.plot(1000.*freqms_highsnr,taus2_order,'g*',markersize=9.0,linewidth=1.5,label=r'$\tau2$ from high snr data')
# plt.plot(1000.*freqms_highsnr, resultpowdata2_highsnr.best_fit, 'g-')
# plt.plot(1000.*freqms_highsnr,tausgeo,'r*',markersize=9.0,linewidth=1.5,label=r'$\tau_{geo}$')
# plt.plot(1000.*freqms_highsnr, resultpowdatageo_highsnr.best_fit, 'r-',label=r'$\alpha_{geo} = %.2f \pm %.2f$' %(specfitdatageo_highsnr,specdatageo_err_highsnr))
# plt.title(r'$\alpha = %.2f \pm %.2f$' %(specfitdata2_highsnr,specfitdatageo_highsnr),fontsize=16)
# plt.annotate('%s' %pulsar,xy=(np.max(1000*freqms),np.max(obtainedtausec)),xycoords='data',xytext=(0.5,0.7),textcoords='axes fraction',fontsize=14)
# plt.xticks(fontsize=14)
# plt.yticks(fontsize=14)
# plt.xlabel(r'$\nu$ MHz',fontsize=16)
# plt.ylabel(r'$\tau_2$ (sec)',fontsize=16)
# plt.legend(fontsize = 9)
#
###PLOT SIGMA##
#
#if subpl_ind5 >= sp:
# subpl_ind6 = int(subpl_ind5-sp)+1
#else:
# subpl_ind6 = int(subpl_ind5)+1
#
#if npch + 6 == sp:
# numfig6 = (npch+6)/sp
#else:
# numfig6 = (npch+6)/sp + 1
#
#
#plt.figure(numfig6, figsize=(16,10))
#plt.subplot(3,4,subpl_ind6)
#plt.errorbar(1000.*freqms_highsnr,bestpT_highSNR[0]*pbs,yerr = bestpT_std_highSNR[0]*pbs, fmt = 'm*',markersize=9.0,capthick=2,linewidth=1.5)
##plt.plot(1000.*freqms_highsnr, sigmapow.best_fit, 'm-', label= r'$\beta$ = %.2f' %sigmapow.best_values['k'])
#plt.plot(1000.*freqms_highsnr,powout.best_fit*pbs,'b-', label='pow = %.2f' %powout.best_values['exponent'])
##plt.plot(expout.best_fit*p2bs,1000.*freqms_highsnr, 'g-', label='exp = %.2f' %expout.best_values['decay'])
##plt.plot(1000.*freqms_highsnr, linout.best_fit, 'r-', label='m = %.2f' %linout.best_values['slope'])
#plt.plot(1000.*freqms_highsnr,quadout.best_fit*pbs,'c-', label='a,b = %.2f,%.2f' %(quadout.best_values['a'],quadout.best_values['b']))
#plt.ylabel(r'$\sigma$ (sec)')
##plt.annotate(r'$\beta$ = %.2f' '\n m = %.2f' %(sigmapow.best_values['k'], linout.best_values['slope']),xy=(np.max(1000*freqms),np.max(bestpT[0])),xycoords='data',xytext=(0.5,0.7),textcoords='axes fraction',fontsize=14)
##plt.annotate('%s' %pulsar,xy=(np.max(1000*freqms),np.max(bestpT[0])),xycoords='data',xytext=(0.5,0.7),textcoords='axes fraction',fontsize=14)
#plt.yticks(fontsize=11)
#plt.xticks(fontsize=10)
#plt.xlabel(r'$\nu$ MHz',fontsize=16)
##plt.ylabel(r'$\sigma$',fontsize=16)
#plt.legend(fontsize = 9, loc='best')
#
#
#if subpl_ind6 >= sp:
# subpl_ind7 = int(subpl_ind6-sp)+1
#else:
# subpl_ind7 = int(subpl_ind6)+1
#
#if npch + 7 == sp:
# numfig7 = (npch+7)/sp
#else:
# numfig7 = (npch+7)/sp + 1
#
###PLOT DM##
#
#fig0 = plt.figure(numfig7, figsize=(16,10))
#ax0 = fig0.add_subplot(3,4,subpl_ind7)
#
##fig0 = plt.figure(NF,figsize=(12,4))
##ax0 = plt.subplot(1,3,2)
##plt.errorbar(bestpT_highSNR[1]*pbs,1000.*freqms_highsnr, xerr = bestpT_std_highSNR[1]*pbs, fmt = 'b*',markersize=9.0,capthick=2,linewidth=1.5)
##plt.plot(1000.*freqms_highsnr, quadout_mu.best_fit*p2bs, 'b-', label='a,b = %.2f,%.2f' %(quadout_mu.best_values['a'],quadout_mu.best_values['b']))
##plt.plot(1000.*freqms_highsnr, powout_mu.best_fit*p2bs, 'm-', label='pow = %.2f' %powout_mu.best_values['exponent'])
##plt.plot(quadout_mu.best_fit*pbs,1000.*freqms_highsnr, 'b-', label='a,b = %.2f,%.2f' %(quadout_mu.best_values['a'],quadout_mu.best_values['b']))
##plt.plot(bestpT_highSNR[1]*pbs,1000*freqms_highsnr, 'k*-', label=r'DM: %.4f pc.cm^{-3}' %(DMval))
##plt.errorbar(delmuarray,delnuarray,xerr=delmu_stdarray, fmt='k*', label='DM rough check: %.4f' %DMcheck)
##plt.plot(DMmodelfit,delnuarray, 'm-', label=r'DM: %.4f pc.cm^{-3}' %(DMval))
##plt.errorbar(delmuarray,freqMHz_highsnr, xerr=delmu_stdarray, fmt='k*', label='DM rough check: %.4f' %DMcheck)
#plt.errorbar(delmuarray,freqMHz_highsnr, xerr=delmu_stdarray, fmt='k*')
#plt.plot(DMmodelfit,freqMHz_highsnr, 'm-', label=r'DM: $%.4f \pm %.4f$ $\rm{pc.cm}^{-3}$' %(DMval,DMvalstd))
##plt.plot(powout_mu.best_fit*p2bs,1000.*freqms_highsnr, 'm-', label='pow = %.2f' %powout_mu.best_values['exponent'])
##plt.xlabel(r'$\mu_H - \mu_{ch}$ (sec)', fontsize =18)
#plt.xlabel(r'$\Delta \mu$ (sec)', fontsize =18)
#plt.annotate('%s' %pulsar,xy=(np.max(1000*freqms),np.max(obtainedtausec)),xycoords='data',xytext=(0.5,0.7),textcoords='axes fraction',fontsize=14)
#plt.yticks(fontsize=12)
#plt.xticks(fontsize=12)
#plt.title('%s' %pulsar)
##ax0.xaxis.set_major_formatter(plt.FormatStrFormatter('%.3f'))
##plt.ylabel(r'$1/\nu_{ch}^2 - 1/\nu_H^2 $ MHz',fontsize=16)
#plt.ylabel(r'$\nu$ (MHz)',fontsize=16)
#plt.ticklabel_format(style='sci', axis='x',scilimits=(0,0))
#plt.tight_layout()
#plt.legend(fontsize = 12, loc='best')
#
#
##delnuarray = [-(1/freqmsMHz[-1]**2-1/freqmsMHz[i]**2) for i in range(npch)]
##delmuarray = [(bestpT_highSNR[1][-1] - bestpT_highSNR[1][i])*pbs for i in range(npch)]
#
#
### PLOT A ##
#
#if subpl_ind7 >= sp:
# subpl_ind8 = int(subpl_ind7-sp)+1
#else:
# subpl_ind8 = int(subpl_ind7)+1
#
#if npch + 8 == sp:
# numfig8 = (npch+8)/sp
#elif npch + 8 == 2*sp:
# numfig8 = (npch+8)/sp
#else:
# numfig8 = (npch+8)/sp + 1
#
#
#plt.figure(numfig8,figsize=(16,10))
#plt.subplot(3,4,subpl_ind8)
#plt.errorbar(1000.*freqms_highsnr, bestpT_highSNR[2], yerr = bestpT_std_highSNR[2], fmt = 'g*',markersize=9.0,capthick=2,linewidth=1.5)
#plt.title('Amplitude')
#plt.annotate('%s' %pulsar,xy=(np.max(1000*freqms),np.max(obtainedtausec)),xycoords='data',xytext=(0.5,0.7),textcoords='axes fraction',fontsize=14)
#plt.yticks(fontsize=12)
#plt.xticks(fontsize=12)
#plt.xlabel(r'$\nu$ MHz',fontsize=16)
#plt.tight_layout()
#plt.ylabel(r'$A$',fontsize=16)
#
#
### PLOT DC ##
#
#
#if subpl_ind8 >= sp:
# subpl_ind9 = int(subpl_ind8-sp)+1
#else:
# subpl_ind9 = int(subpl_ind8)+1
#
#if npch + 9 == sp:
# numfig9 = (npch+9)/sp
#elif npch + 9 == 2*sp:
# numfig9 = (npch+9)/sp
#else:
# numfig9 = (npch+9)/sp + 1
#
#
#plt.figure(numfig9, figsize=(16,10))
#plt.subplot(3,4,subpl_ind9)
#plt.errorbar(1000.*freqms_highsnr, bestpT_highSNR[3], yerr = bestpT_std_highSNR[3], fmt = 'k*',markersize=9.0,capthick=2,linewidth=1.5)
#plt.title('DC offset')
#plt.annotate('%s' %pulsar,xy=(np.max(1000*freqms),np.max(bestpT[3])),xycoords='data',xytext=(0.5,0.7),textcoords='axes fraction',fontsize=14)
#plt.yticks(fontsize=12)
#plt.xticks(fontsize=12)
#plt.xlabel(r'$\nu$ MHz',fontsize=16)
#plt.tight_layout()
#plt.ylabel(r'$DC$',fontsize=16)
#
#
### PLOT SNR AND TAU ERROR ###
#
#if subpl_ind9 >= sp:
# subpl_ind10 = int(subpl_ind9-sp)+1
#else:
# subpl_ind10 = int(subpl_ind9)+1
#
#if npch + 10 == sp:
# numfig10 = (npch+10)/sp
#elif npch + 10 == 2*sp:
# numfig10 = (npch+10)/sp
#else: