-
Notifications
You must be signed in to change notification settings - Fork 0
/
plotdemon.py
executable file
·2454 lines (1854 loc) · 98.3 KB
/
plotdemon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
# |----------------------------------------------------------------------|
# |------------------------------PLOT DEMON------------------------------|
# |----------------------------------------------------------------------|
# Call as ./plotdemon.py FILE1 [FILE2] [FILE3] BINNING
# Takes 1-3 .plotd files and plots relevant astrometric plots
#
# Arguments:
#
# FILE1
# The absolute path to the first file to be used (generally the lowest energy band)
#
# [FILE2]
# The absolute path to the second file to be used
#
# [FILE3]
# The absolute path to the third file to be used (generally the highest energy band)
#
# [BINNING]
# Optional: the size, in seconds, of bins into which data will be sorted.
#
#
#-----User-set Parameters----------------------------------------------------------------------------------------------
minbin=0.0078125 # The minimum bin size the code is allowed to attempt to use. This can prevent long hang-ups
version=4.3 # The version of PlotDemon
cbin=32.0 # The number of bins to use when calculating inhomonogeneity in circfold
#-----Welcoming Header-------------------------------------------------------------------------------------------------
print ''
print '-------Running Plot Demon: J.M.Court, 2014------'
print ''
#-----Importing Modules------------------------------------------------------------------------------------------------
try:
import sys,os,imp
import pylab as pl
import pan_lib as pan
import numpy as np
import scipy.signal as sig
import scipy.optimize as optm
from math import pi
except ImportError:
print 'Modules missing! Aborting!'
print ''
print '------------------------------------------------'
print ''
exit()
try:
imp.find_module('PyAstronomy') # Check if PyAstronomy exists
module_pyastro=True
except ImportError:
module_pyastro=False
#-----Opening Files----------------------------------------------------------------------------------------------------
args=sys.argv # Fetching arguments; softest energy band first please
pan.argcheck(args,1)
try:
float(args[-1]) # If the final argument can be converted to integer, assume user intends it as a binning
isbininp=True # "IS BINsize given as an INPut?"
except:
isbininp=False
nfiles=max(len(args)-isbininp-1,1) # Fetch number of infiles (total args minus one or two iff binsize given)
if nfiles>3: nfiles=3
if len(args)<2:
file1=raw_input('Filename: ')
else:
file1=args[1]
isplotd1=pan.filenamecheck(file1,'plotd',continu=True) # Work out whether input file is a plotdemon file or a csv
ch={} # Save channel info in a library
bg1=0
bg2=0
bg3=0
print 'Opening',file1 # Opening file 1
x1r,y1r,ye1r,tst1,bsz1,gti,pcus1,bg1,bsub1,bdata1,flv1,ch[1],mis1,obsd1,v1=pan.pdload(file1,isplotd1)
y1r=y1r/float(pcus1) # Normalising flux by dividing by the number of active PCUs and the binsize
ye1r=ye1r/float(pcus1)
flavour=flv1
if flavour=='':
qflav=''
else:
qflav=' "'+flavour+'"'
if nfiles>1:
file2=args[2]
isplotd2=pan.filenamecheck(file2,'plotd',continu=True)
print 'Opening',file2 # Opening file 2
x2r,y2r,ye2r,tst2,bsz2,gti2,pcus2,bg2,bsub2,bdata2,flv2,ch[2],mis2,obsd2,v2=pan.pdload(file2,isplotd2)
y2r=y2r/float(pcus2) # Normalising flux by dividing by the number of active PCUs and the binsize
ye2r=ye2r/float(pcus2)
else: x2r=y2r=ye2r=tst2=bsz2=None
if nfiles>2:
file3=args[3]
isplotd3=pan.filenamecheck(file3,'plotd',continu=True)
print 'Opening',file3 # Opening file 3
x3r,y3r,ye3r,tst3,bsz3,gti3,pcus3,bg3,bsub3,bdata3,flv3,ch[3],mis3,obsd3,v3=pan.pdload(file3,isplotd3)
y3r=y3r/float(pcus3) # Normalising flux by dividing by the number of active PCUs and the binsize
ye3r=ye3r/float(pcus3)
else: x3r=y3r=ye3r=tst3=bsz3=None
bg=(bg1+bg2+bg3)/float(pcus1)
xit1=x1r[-1]
if nfiles>1:
xit2=x2r[-1]
else:
xit2=None
if nfiles==3:
xit3=x3r[-1]
else:
xit3=None
oet=max(xit1,xit2,xit3) # Fetch the observation end time
mint=0 # Save original start and endpoints for use in clipping
maxt=oet
if nfiles>1: # Checking that start-times of files 1 & 2 match
if tst1!=tst2:
if tst1>tst2:
while x1r[0]+tst1>x2r[0]+tst2: # Hack data off of the start of file 2 until its startpoint matches file 1
if len(x2r)==0:
print 'Times domains for files 1 & 2 do not overlap! Aborting!'
pan.signoff()
exit()
x2r=np.delete(x2r,0)
y2r=np.delete(y2r,0)
ye2r=np.delete(ye2r,0)
if tst1+x1r[0]!=tst2+x2r[0]:
print 'Starting times for files 1 & 2 do not match! Aborting!'# If this butchering overshoots, give up
pan.signoff()
exit()
else:
tst2+=x2r[0] # Amend new start time
x2r=x2r-x2r[0]
else:
while x2r[0]+tst2>x1r[0]+tst1: # Or Hack data off of the start of file 1 until its startpoint matches file 2
if len(x1r)==0:
print 'Times domains for files 1 & 2 do not overlap! Aborting!'
pan.signoff()
exit()
x1r=np.delete(x1r,0)
y1r=np.delete(y1r,0)
ye1r=np.delete(ye1r,0)
if tst1+x1r[0]!=tst2+x2r[0]:
print 'Starting times for files 1 & 2 do not match! Aborting!'
pan.signoff()
exit()
else:
tst1+=x1r[0]
x1r=x1r-x1r[0]
if nfiles>2: # Checking that start-times of files 1 & 3 match (and thus 2 & 3 also match)
if tst1!=tst3:
if tst1>tst3:
while x1r[0]+tst1>x3r[0]+tst3: # Hack data off of the start of file 3 until its startpoint matches file 1
if len(x3r)==0:
print 'Times domains for files 1 & 3 do not overlap! Aborting!'
pan.signoff()
exit()
x3r=np.delete(x3r,0)
y3r=np.delete(y3r,0)
ye3r=np.delete(ye3r,0)
if tst1+x1r[0]!=tst3+x3r[0]:
print 'Starting times for files 1 & 3 do not match! Aborting!'# If this butchering overshoots, give up
pan.signoff()
exit()
else:
tst3+=x3r[0] # Amend new start time
x3r=x3r-x3r[0]
else:
while x3r[0]+tst3>x1r[0]+tst1: # Or Hack data off of the start of files 1 & 2 until their startpointa matches file 3
if len(x1r)==0:
print 'Times domains for files 1 & 3 do not overlap! Aborting!'
pan.signoff()
exit()
x1r=np.delete(x1r,0)
y1r=np.delete(y1r,0)
ye1r=np.delete(ye1r,0)
x2r=np.delete(x2r,0)
y2r=np.delete(y2r,0)
ye2r=np.delete(ye2r,0)
if tst1+x1r[0]!=tst3+x3r[0]:
print 'Starting times for files 1 & 3 do not match! Aborting!'
pan.signoff()
exit()
else:
tst1+=x1r[0]
x1r=x1r-x1r[0]
#-----Binning----------------------------------------------------------------------------------------------------------
if isbininp:
binning=float(args[-1]) # Collect binsize input if given
else:
while True: # Keep asking until a good response is given
try:
binning=float(raw_input("Enter bin size (s): ")) # Ask for binsize in dialogue box
break
except:
print 'Invalid bin size input!'
if minbin>max(binning,bsz1,bsz2,bsz3):
print 'Warning! User-entered bin is smaller than the minimum!'
print 'Minimum can be changed in the user-input section of this code'
binning=max(binning,bsz1,bsz2,bsz3,minbin) # Prevent overbinning by setting minimum binning to the maximum of the binnings of the files
print ''
print 'Bin size='+str(binning)+'s'
print 'Binning File 1...'
x1,y1,ye1=pan.binify(x1r,y1r,ye1r,binning) # Bin File 1 using 'binify' in pan_lib
if nfiles>1:
print 'Binning File 2...'
x2,y2,ye2=pan.binify(x2r,y2r,ye2r,binning) # Bin File 2 using 'binify' in pan_lib
if nfiles>2:
print 'Binning File 3...'
x3,y3,ye3=pan.binify(x3r,y3r,ye3r,binning) # Bin File 3 using 'binify' in pan_lib
print 'Binning complete!'
print ''
wrongsize=False
x3l=len(x1) # Sloppy fix to make this work for 2 or 3 mismatched files
#-----Force file lengths to match--------------------------------------------------------------------------------------
if nfiles>1: # Checking file lengths match
if len(x1)!=len(x2):
print 'Warning! Files 1&2 of different lengths!'
wrongsize=True
if nfiles==3:
if len(x1)!=len(x3):
print 'Warning! Files 1&3 of different lengths!'
wrongsize=True
x3l=len(x3)
if wrongsize: # Forcing file lengths to match if possible
print 'Attempting to crop files...'
mindex=min(len(x1),len(x2),x3l)-1
if x1[mindex]!=x2[mindex]:
print 'Cannot crop, aborting!'
pan.signoff()
exit()
if nfiles==3:
if x1[mindex]!=x3[mindex]:
print 'Cannot crop, aborting!'
pan.signoff()
exit()
mindex+=1
x1=x1[:mindex]
y1=y1[:mindex]
ye1=ye1[:mindex]
x2=x2[:mindex]
y2=y2[:mindex]
ye2=ye2[:mindex]
if nfiles==3:
x3=x3[:mindex]
y3=y3[:mindex]
ye3=ye3[:mindex]
print 'Cropped succesfully!'
print ''
#-----Fetch GTI Mask---------------------------------------------------------------------------------------------------
print 'Fetching GTI mask...'
def getmask(xarr,gtis):
if gtis is None:
return np.array([True]*len(xarr)) # Assume all is in gtis if loaded from csv
else:
return pan.gtimask(xarr,gtis)
gmask=getmask(x1,gti) # A mask to blank values that fall outside of the GTIs
if nfiles>1:
gmask2=getmask(x2,gti2) # 'And' masks for different files
gmask=gmask&gmask2
if nfiles>2:
gmask3=getmask(x3,gti3)
gmask=gmask&gmask3
print str(int(100*sum(gmask)/len(gmask)))+'% of data within GTI!'
print ''
#-----Fetch Colours----------------------------------------------------------------------------------------------------
def colorget(verbose=True): # Define colorget to easily re-obtain colours if base data is modified
if verbose:
print 'Analysing Data...'
times=x1[gmask]
timese=np.zeros(len(times))
ys={}
yes={}
col={}
cole={}
if nfiles==1: # If only one file given, flux and flux_error are just the flux and error of this one file
flux=y1[gmask] # Use gmask to clip out the areas outside of GTI
fluxe=ye1[gmask]
elif nfiles==2:
flux,fluxe,ys,yes,col,cole=pan.pdcolex2(y1,y2,ye1,ye2,gmask) # Get 2/1 and 1/2 colour information using PDColEx in pan_lib
elif nfiles==3:
flux,fluxe,ys,yes,col,cole=pan.pdcolex3(y1,y2,y3,ye1,ye2,ye3,gmask) # Get ALL colour values with 3D PDColEx
else:
print 'Error! Too much data somehow.' # This warning should never come up...
pan.signoff()
exit()
return times,timese,flux,fluxe,ys,yes,col,cole
times,timese,flux,fluxe,ys,yes,col,cole=colorget() # Use colorget
print 'Done!'
print ''
#-----Setting up plot environment--------------------------------------------------------------------------------------
show_block=False # Do not force plots to stay open by default
plotopt=''
es=True # Options to keep track of what form the data is in. 'es': with error bars.
cs=False # 'cs' with colour key
ls=False # 'ls' with delineation
folded=False # 'folded' has been folded over some period
saveplots=False
def doplot(x,xe,y,ye,ovr=False,ft='-k',per2=False): # Defining short function to determine whether errorbars are needed on the fly
# 'ovr' allows to override colour and line options, so lightcurves can be made differently
if ovr: formst=ft # If override given, accept input format; if none given, just plot lines
elif ls: formst='-ok' # If deLineate mode on, connect points with lines and mark points
else: formst='ok' # If neither deLineate nor override on, just plot points. No lines here, buddy
if ls and not ovr:
plotx=np.append(x,x[0])
ploty=np.append(y,y[0])
plotxe=np.append(xe,xe[0])
plotye=np.append(ye,ye[0])
elif per2 and ovr:
plotx=np.append(x,x+1.0)
ploty=np.append(y,y)
plotxe=np.append(xe,xe)
plotye=np.append(ye,ye)
pl.axvline(1,color='0.7',linestyle=':')
else:
plotx=x
ploty=y
plotxe=xe
plotye=ye
if cs and not ovr: # If coloured mode on, colour first 5 data points unless override given
if len(x)<5: # Abort if less than 5 data points present
print 'Not enough data to colour!'
else:
pl.plot(x[0],y[0],'or',zorder=1) # Plot a round marker over each of the first five points with colour ascending red->blue
pl.plot(x[1],y[1],'oy',zorder=2)
pl.plot(x[2],y[2],'og',zorder=3)
pl.plot(x[3],y[3],'oc',zorder=4)
pl.plot(x[4],y[4],'ob',zorder=5)
if es:
pl.errorbar(plotx,ploty,xerr=plotxe,yerr=plotye,fmt=formst,zorder=0)# Plot errorbar plot if errors turned on
else:
pl.plot(plotx,ploty,formst,zorder=0) # Else plot regular graph
def plot_save(saveplots,show_block): # Add a function to redirect all show calls to savefigs if toggled
if saveplots:
pl.savefig(raw_input('Save plot as: '))
print 'Plot saved!'
else:
pl.show(block=show_block)
def burstplot(key,text,units):
if bursts is None:
print 'No burst data to plot! Run "burst get" first!'
return
print 'Plotting Histogram of Burst '+text+'...'
pl.figure()
pl.hist(bursts[key],bins=np.arange(min(bursts[key]),max(bursts[key]),(max(bursts[key])-min(bursts[key]))/21.0))
pl.xlabel(text,'('+units+')')
pl.ylabel('Frequency')
pl.title('Histogram of Burst '+text)
plot_save(saveplots,show_block)
fldtxt=''
bursts=None
burst_alg='cubic spline'
flux_axis=r'Flux (cts s$^{-1}$ PCU$^{-1}$)'
time_n=0 # Normalise dump time
#-----User Menu--------------------------------------------------------------------------------------------------------
def give_inst(): # Define printing this list of instructions as a function
print 'COMMANDS: Enter a command to manipulate data.'
print ''
print 'DATA:'
print '* "rebin" to reset the data and load it with a different binning.'
print '* "clip" to clip the data.'
print '* "norm time" to renormalise the times by the start time of the data'
print '* "mask" to remove a range of data.'
print '* "rms" to return the fractional rms of the data.'
print '* "fold" to fold data over a period of your choosing'+(' (requires PyAstronomy module!)' if not module_pyastro else '')+'.'
print '* "autofold" to automatically seek a period over which to fold data'+(' (requires PyAstronomy module!)' if not module_pyastro else '')+'.'
print '* "varifold" to fold over a non-constant period using an algorithm optimised for high-amplitude quasi-periodic flares.'
print '* "plot bursts" to plot the results of the peak-finding algorithm used in varifold.'
print ''
print '1+ DATASET PLOTS:'
print '* "lc" to plot a simple graph of flux over time.'
print '* "bg" to plot background over time, if background has been estimated for these files.'
print '* "animate" to create an animation of the lightcurve as the binning is increased.'
print '* "circanim" to create an animation of the lightcurve circularly folded as the period is increased.'
print '* "lombscargle" to create a Lomb-Scargle periodogram of the lightcurve.'
print '* "autocor" to plot the auto-correlation function.'
print '* "rmsflux" to plot the rms-flux relationship of the data.'
if nfiles>1: # Only display 2-data-set instructions if 2+ datasets given
print ''
print '2+ DATASET PLOTS:'
print '* "hardness21" to plot a hardness/time diagram of file2/file1 colour over time.'
print '* "hardness12" to plot a hardness/time diagram of file1/file2 colour over time.'
print '* "hid21" to plot a hardness-intensity diagram of file2/file1 colour against total flux.'
print '* "hid12" to plot a hardness-intensity diagram of file1/file2 colour against total flux.'
print '* "calcloop21" to return the probability of a null hysteresis in the 12 HID.'
print '* "col21" to plot file2/file1 colour against time.'
print '* "col12" to plot file1/file2 colour against time.'
print '* "band" to plot the lightcurve of a single energy band.'
print '* "bands" to plot lightcurves of all bands on adjacent axes.'
print '* "xbands" to plot lightcurves of all bands on the same axes.'
print '* "compbands21" to plot lightcurves of bands 2 and 1 against each other.'
print '* "crosscor21" to plot the cross-correlation function of band 1 with band 2.'
print '* "timeres crosscor21" to plot the time-resolved cross-correlation function of band 1 with band 2'
print '* "all" to plot all available data products.'
if nfiles==3: # Only display 3-data-set instructions if 3 datasets given
print ''
print '3 DATASET PLOTS:'
print '* "hardness32" to plot a hardness/time diagram of file3/file2 colour over time.'
print '* "hardness23" to plot a hardness/time diagram of file2/file3 colour over time.'
print '* "hardness31" to plot a hardness/time diagram of file3/file1 colour over time.'
print '* "hardness13" to plot a hardness/time diagram of file1/file3 colour over time.'
print '* "hid32" to plot a hardness-intensity diagram of file3/file2 colour against total flux.'
print '* "hid23" to plot a hardness-intensity diagram of file2/file3 colour against total flux.'
print '* "calcloop32" to return the probability of a null hysteresis in the 32 HID.'
print '* "hid31" to plot a hardness-intensity diagram of file3/file1 colour against total flux.'
print '* "hid13" to plot a hardness-intensity diagram of file1/file3 colour against total flux.'
print '* "calcloop31" to return the probability of a null hysteresis in the 31 HID.'
print '* "col32" to plot file3/file2 colour against time.'
print '* "col23" to plot file2/file3 colour against time.'
print '* "col31" to plot file3/file1 colour against time.'
print '* "col13" to plot file1/file3 colour against time.'
print '* "compbands31" to plot lightcurves of bands 3 and 1 against each other.'
print '* "compbands32" to plot lightcurves of bands 3 and 2 against each other.'
print '* "ccd" to plot a colour-colour diagram (3/1 colour against 2/1 colour).'
print '* "timeres crosscor31" to plot the time-resolved cross-correlation function of band 3 with band 1'
print '* "timeres crosscor32" to plot the time-resolved cross-correlation function of band 3 with band 2'
print '* "crosscor31" to plot the cross-correlation function of band 3 with band 1.'
print '* "crosscor32" to plot the cross-correlation function of band 3 with band 2.'
print ''
print 'BURST ANALYSIS:'
print '* "burst get" to interactively extract burst data for analysis.'
print '* "burst peaks" for a histogram of peak heights of extracted bursts.'
print '* "burst risetimes" for a histogram of rise times of extracted bursts.'
print '* "burst falltimes" for a histogram of fall times of extracted bursts.'
print '* "burst lengths" for a histogram of durations of extracted bursts.'
print '* "burst help" for further information on burst analysis.'
print ''
print 'SAVING DATA TO ASCII:'
print '* "export" to dump the lightcurve and colour data into an ASCII file.'
print '* "bgdump" to export background lightcurve to an ASCII file.'
print '* "timenorm" to toggle absolute or relative time values on x-axis.'
print ''
print 'TOGGLE OPTIONS:'
print '* "errors" to toggle whether to display errors in plots.'
print '* "lines" to toggle lines joining points in graphs.'
print '* "ckey" to toggle colour key (red-blue) for the first five points in all plots.'
print '* "save" to save to disk any plots which would otherwise be shown.'
print ''
print 'ADVANCED OPTIONS:'
print '* "burstalg" to select algorithm for finding pulse peaks in lightcurve.'
print ''
print 'OTHER COMMANDS:'
print '* "info" to display a list of facts and figures about the current PlotDemon session.'
print '* "reflav" to rewrite the flavour text used for graph titles.'
print '* "help" or "?" to display this list of instructions again.'
print '* "quit" to quit.'
#give_inst() # Print the list of instructions
print ''
print ' --------------------'
#-----Entering Interactive Mode----------------------------------------------------------------------------------------
while plotopt not in ['quit','exit']: # If the previous command given was not quit, continue
print ''
plotopt=raw_input('Give command [? for help]: ').lower() # Fetch command from user
print ''
#-----Aliasing options----------------------------------------------------------------------------------------------
if plotopt=='shid': # Let 'shid' refer to the soft 2/1 HID
plotopt='hid21'
elif plotopt=='hhid': # Let 'hhid' refer to the hard 3/1 HID
plotopt='hid31'
elif plotopt=='hid' and nfiles==2:
plotopt='hid21' # Let 'hid' refer to the 2/1 HID if that is the only HID available
#-----Hidden 'stick' option-----------------------------------------------------------------------------------------
if plotopt=='stick': # For use when scripting with Plotdemon. If turned on, this causes
# all plots to block when shown.
show_block=not show_block
if show_block:
print 'Sticky Plots on!'
else:
print 'Sticky Plots off!'
#-----'save' option-------------------------------------------------------------------------------------------------
elif plotopt=='save': # Causes a plot to be saved when it would otherwise have been shown
saveplots=not saveplots
if saveplots:
print 'Plot saving on!'
else:
print 'Plot saving off!'
#-----'rebin' option------------------------------------------------------------------------------------------------
elif plotopt=='rebin': # Rebin data
bursts=None # Remove burst data
fldtxt=''
while True: # Keep asking until a good response is given
try:
binning=float(raw_input("Enter bin size (s): ")) # Ask for binsize in dialogue box
assert binning>=minbin
break
except:
print 'Invalid bin size input!'
print 'Binning File 1...'
x1,y1,ye1=pan.binify(x1r,y1r,ye1r,binning) # Bin File 1 using 'binify' in pan_lib
if nfiles>1:
print 'Binning File 2...'
x2,y2,ye2=pan.binify(x2r,y2r,ye2r,binning) # Bin File 2 using 'binify' in pan_lib
if nfiles>2:
print 'Binning File 3...'
x3,y3,ye3=pan.binify(x3r,y3r,ye3r,binning) # Bin File 3 using 'binify' in pan_lib
if nfiles>1: # Checking file lengths match... need to migrate this to a function one day
if len(x1)!=len(x2):
wrongsize=True
if nfiles==3:
if len(x1)!=len(x3):
wrongsize=True
x3l=len(x3)
if wrongsize: # Forcing file lengths to match if possible
mindex=min(len(x1),len(x2),x3l)-1
if x1[mindex]!=x2[mindex]:
print 'Cannot crop, aborting!'
pan.signoff()
exit()
if nfiles==3:
if x1[mindex]!=x3[mindex]:
print 'Cannot crop, aborting!'
pan.signoff()
exit()
mindex+=1
x1=x1[:mindex]
y1=y1[:mindex]
ye1=ye1[:mindex]
x2=x2[:mindex]
y2=y2[:mindex]
ye2=ye2[:mindex]
if nfiles==3:
x3=x3[:mindex]
y3=y3[:mindex]
ye3=ye3[:mindex]
gmask=getmask(x1,gti) # Re-establish gmask
print 'Binning complete!'
print ''
times,timese,flux,fluxe,ys,yes,col,cole=colorget() # Re-get colours
folded=False # Re-allow clipping
print 'Done!'
print ''
#-----'fold' Option-------------------------------------------------------------------------------------------------
elif plotopt=='fold': # Fold lightcurve
bursts=None # Remove burst data
if folded:
print 'Data already folded! Rebin before re-folding.'
continue
if not module_pyastro: # Only attempt to fold if pyastro is present
print 'PyAstronomy Module not found! Cannot perform fold!' # Warn user they cannot fold as module is missing
continue
while True: # Keep asking user until they give a sensible period
try:
period=float(raw_input('Input period to fold over (s): ')) # Fetch period from user
break
except:
print "Invalid period!" # Keep trying until they give a sensible input
while True: # Keep asking user until they give a sensible phase resolution
try:
phres=float(raw_input('Input phase resolution (0-1): ')) # Fetch phase resolution from user
assert phres<1.0
assert phres>0.0
break
except:
print "Invalid phase resolution!" # Keep trying until they give a sensible input
x1=x1[gmask];y1=y1[gmask];ye1=ye1[gmask] # Zeroing all data points outside of GTI
x1,y1,ye1=pan.foldify(x1,y1,ye1,period,binning,phres=phres,name='ch. '+ch[1]) # Fold using foldify function from pan_lib
fldtxt='Folded '
if nfiles>1:
x2=x2[gmask];y2=y2[gmask];ye2=ye2[gmask] # Zeroing all data points outside of GTI
x2,y2,ye2=pan.foldify(x2,y2,ye2,period,binning,phres=phres,name='ch. '+ch[2]) # Fold data of file 2 if present
if nfiles==3:
x3=x3[gmask];y3=y3[gmask];ye3=ye3[gmask] # Zeroing all data points outside of GTI
x3,y3,ye3=pan.foldify(x3,y3,ye3,period,binning,phres=phres,name='ch. '+ch[3]) # Fold data of file 3 if present
gmask=np.ones(len(x1),dtype=bool) # Re-establish gmask
times,timese,flux,fluxe,ys,yes,col,cole=colorget() # Re-get colours
folded=True
print 'Folding Complete!'
print ''
#-----'norm time' Option------------------------------------------------------------------------------------------------
elif plotopt=='norm time':
if folded:
print 'Cannot renormalise time on folded data!'
continue
times=times-times[0]
print 'Renormalised times!'
#-----'autofold' Option-------------------------------------------------------------------------------------------------
elif plotopt=='autofold': # Autofold data lightcurve
bursts=None # Remove burst data
if folded:
print 'Data already folded! Rebin before re-folding.'
continue
if not module_pyastro: # Only attempt to fold if pyastro is present
print 'PyAstronomy Module not found! Cannot perform fold!' # Warn user they cannot fold as module is missing
continue
ls_st=max(4.0/(times[-1]-times[0]),0.005)
ls_end=0.5/binning
lsx=np.arange(ls_st,ls_end,(ls_end-ls_st)/2500.0) # Perform Lomb-Scargle Analysis on the data to seek best period
lsy=pan.lomb_scargle(times,flux,fluxe,lsx)
period=1.0/(lsx[lsy.tolist().index(max(lsy))])
while True: # Keep asking user until they give a sensible phase resolution
try:
phres=float(raw_input('Input phase resolution (0-1): ')) # Fetch phase resolution from user
assert phres<1.0
assert phres>0.0
break
except:
print "Invalid phase resolution!" # Keep trying until they give a sensible input
print ''
print 'Using period of '+str(period)+'!'
x1=x1[gmask];y1=y1[gmask];ye1=ye1[gmask] # Zeroing all data points outside of GTI
x1,y1,ye1=pan.foldify(x1,y1,ye1,period,binning,phres=phres,name='ch. '+ch[1]) # Fold using foldify function from pan_lib
fldtxt='Folded '
if nfiles>1:
x2=x2[gmask];y2=y2[gmask];ye2=ye2[gmask] # Zeroing all data points outside of GTI
x2,y2,ye2=pan.foldify(x2,y2,ye2,period,binning,phres=phres,name='ch. '+ch[2]) # Fold data of file 2 if present
if nfiles==3:
x3=x3[gmask];y3=y3[gmask];ye3=ye3[gmask] # Zeroing all data points outside of GTI
x3,y3,ye3=pan.foldify(x3,y3,ye3,period,binning,phres=phres,name='ch. '+ch[3]) # Fold data of file 3 if present
gmask=np.ones(len(x1),dtype=bool) # Re-establish gmask
times,timese,flux,fluxe,ys,yes,col,cole=colorget() # Re-get colours
folded=True
print 'Folding Complete!'
print ''
#-----'varifold' Option---------------------------------------------------------------------------------------------
elif plotopt=='varifold':
if folded:
print 'Cannot perform burst analysis on folded data!'
continue
if burst_alg=='cubic spline':
while True:
try:
iq_lo=float(raw_input('Low Threshold: '))
iq_hi=float(raw_input('High Threshold: '))
assert iq_hi>iq_lo
assert iq_hi<=100
assert iq_lo>=0
break
except AssertionError:
print 'Invalid Entry! Valid entry is of the form High>Low.'
else:
iq_lo=0
iq_hi=100
while True:
try:
phase_res=float(raw_input('Input phase resolution (0-1): '))
assert phase_res<1.0
assert phase_res>0.0
break
except AssertionError:
print 'Invalid Phase Resolution!'
phases,numpeaks,flpeaks=pan.fold_bursts(times,flux,iq_hi,iq_lo,do_smooth=False,alg=burst_alg,savgol=5)
peaksep=(times[-1]-times[0])/numpeaks
print numpeaks,'flares identified: average separation of',str(peaksep)+'s'
st_time=flpeaks[0]
endtime=flpeaks[1]
intran=np.array(range(len(times)))
ymask1=intran>=st_time
ymask2=intran<endtime
ymask=ymask1&ymask2
nbins=int(1.0/phase_res)
print len(phases),len(x1),len(times)
print len(gmask)
phases=(nbins*phases[ymask]).astype(int)
x1=x1[gmask][ymask];y1=y1[gmask][ymask];ye1=ye1[gmask][ymask] # Removing all data points outside of GTI
newx1=[]
newy1=[]
newye1=[]
for i in range(nbins):
newx1.append(float(i)/float(nbins))
newy1.append(np.mean(y1[phases==i]))
newye1.append((np.sum(ye1[phases==i]**2))**0.5/len(ye1[phases==i]))
x1=np.array(newx1)
#y1=sig.savgol(np.array(newy1),5,3)
#ye1=sig.savgol(np.array(newye1),5,3)
y1=np.array(newy1)
ye1=np.array(newye1)
if nfiles>1:
x2=x2[gmask][ymask];y2=y2[gmask][ymask];ye2=ye2[gmask][ymask] # Removing all data points outside of GTI
newx2=[]
newy2=[]
newye2=[]
for i in range(nbins):
newx2.append(float(i)/float(nbins))
newy2.append(np.mean(y2[phases==i]))
newye2.append((np.sum(ye2[phases==i]**2))**0.5/len(ye2[phases==i]))
x2=np.array(newx2)
y2=np.array(newy2)
ye2=np.array(newye2)
if nfiles==3:
x3=x3[gmask][ymask];y3=y3[gmask][ymask];ye3=ye3[gmask][ymask] # Removing all data points outside of GTI
newx3=[]
newy3=[]
newye3=[]
for i in range(nbins):
newx3.append(float(i)/float(nbins))
newy3.append(np.mean(y3[phases==i]))
newye3.append((np.sum(ye3[phases==i]**2))**0.5/len(ye3[phases==i]))
x3=np.array(newx3)
y3=np.array(newy3)
ye3=np.array(newye3)
gmask=np.ones(len(x1),dtype=bool) # Re-establish gmask
times,timese,flux,fluxe,ys,yes,col,cole=colorget() # Re-get colours
folded=True
print 'Folding Complete!'
print ''
period='N/A'
#-----Get GTIs------------------------------------------------------------------------------------------------------
elif plotopt=='get gtis':
if folded:
print 'Cannot perform burst analysis on folded data!'
continue
if burst_alg=='cubic spline':
while True:
try:
iq_lo=float(raw_input('Low Threshold: '))
iq_hi=float(raw_input('High Threshold: '))
assert iq_hi>iq_lo
assert iq_hi<=100
assert iq_lo>=0
break
except AssertionError:
print 'Invalid Entry! Valid entry is of the form High>Low.'
else:
iq_lo=0
iq_hi=100
while True:
try:
nphbins=int(raw_input('Number of phase bins: '))
assert nphbins>1
break
except AssertionError:
print 'Invalid Phase Resolution!'
spline=pan.get_phases_intp(flux,windows=1,q_lo=iq_lo,q_hi=iq_hi,peaks=None,givespline=True)
start_valid=times[spline.firstpeak]+tst1
end_valid=times[spline.lastpeak]+tst1
numpeaks=int(spline(spline.lastpeak))
print 'Spline created, extracting phases...'
print ''
flnm_prefix=raw_input('Filename Prefix: ')
gtif={}
for i in range(nphbins):
gtif[i]=open(flnm_prefix+'_'+str(i)+'.csv','w')
guess=spline(0)
prevcut=optm.fsolve(spline,guess)[0]*binning+tst1
for i in range(numpeaks):
for j in range(nphbins):
subval=i+((j+1)/float(nphbins))
def newspline(x):
return spline(x)-subval
newcut=optm.fsolve(newspline,guess)[0]*binning+tst1
if newcut<end_valid and prevcut>start_valid:
gtif[j].write(str(prevcut)+','+str(newcut)+'\n')
prevcut=newcut
for i in range(nphbins):
gtif[i].close()
print ''
print 'GTI files written!'
#-----'Plot Bursts' Option------------------------------------------------------------------------------------------
elif plotopt=='plot bursts':
if folded:
print 'Cannot perform burst analysis on folded data!'
continue
while True:
try:
q_lo=float(raw_input('Low Threshold : '))
assert q_lo<100
assert q_lo>0
break
except:
pass
while True:
try:
q_hi=float(raw_input('High Threshold: '))
assert q_hi<100
assert q_hi>0
assert q_hi>=q_lo
break
except:
pass
peaks=pan.get_bursts_windowed(flux,1,q_lo=q_lo,q_hi=q_hi,smooth=False)
pl.figure()
doplot(times,timese,flux,fluxe,ovr=True,per2=False)
for i in peaks:
pl.plot([times[i]],[flux[i]],'g*',zorder=5)
pl.axhline(np.percentile(flux,q_lo),color='b',zorder=2)
pl.axhline(np.percentile(flux,q_hi),color='r',zorder=2)
plot_save(saveplots,show_block)
#-----'clip' Option-------------------------------------------------------------------------------------------------
elif plotopt=='clip': # Clipping data
bursts=None # Remove burst data
if folded:
print 'Cannot clip folded data!'
else:
print 'Clipping data'
print ''
print 'Time range is '+str(x1[0])+'s - '+str(x1[-1])+'s'
print 'Please choose new range of data:'
mint,maxt,srbool=pan.srinr(x1,binning,'time') # Fetch new time domain endpoints using srinr function from pan_lib
if srbool:
print 'Clipping...'
x1=x1[mint:maxt] # Clip file 1
y1=y1[mint:maxt]
ye1=ye1[mint:maxt]
if nfiles>1: