-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdrift_analysis.py
More file actions
2643 lines (2117 loc) · 109 KB
/
drift_analysis.py
File metadata and controls
2643 lines (2117 loc) · 109 KB
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
__version__ = "0.9.10"
import sys
import copy
import numpy as np
from numpy.polynomial.polynomial import polyfit, polyval
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoLocator
from matplotlib.pyplot import cm
from scipy.interpolate import interp1d
from scipy.ndimage import gaussian_filter1d
from scipy.optimize import curve_fit
import tkinter
import tkinter.filedialog
import tkinter.simpledialog
import json
import bisect
import pulsestack
class Subpulses:
def __init__(self):
self.data = None
self.with_driftbands_plt = None
self.no_driftbands_plt = None
def plot_subpulses(self, ax, pulse_range=None, **kwargs):
if self.get_nsubpulses() == 0:
return
# Get array masks for those subpulses with and without valid driftbands
with_driftbands_subset = self.in_pulse_range(pulse_range, with_valid_driftband=True)
no_driftbands_subset = np.logical_not(with_driftbands_subset)
# WITH DRIFTBANDS
if np.any(with_driftbands_subset): # If there ARE any with driftbands
# If not yet plotted, plot them anew (in blue)
ph = self.get_phases(subset=with_driftbands_subset)
p = self.get_pulses(subset=with_driftbands_subset)
if self.with_driftbands_plt is None:
self.with_driftbands_plt, = ax.plot(ph, p, 'bx', **kwargs)
else:
self.with_driftbands_plt.set_data(ph, p)
else:
# If there are none to plot, clear any pre-existing ones
self.clear_plots(with_driftbands=True, no_driftbands=False)
# NO ASSIGNED DRIFTBANDS
if np.any(no_driftbands_subset): # If there ARE any without driftbands
# If not yet plotted, plot them anew (in green)
ph = self.get_phases(subset=no_driftbands_subset)
p = self.get_pulses(subset=no_driftbands_subset)
if self.no_driftbands_plt is None:
self.no_driftbands_plt, = ax.plot(ph, p, 'gx', **kwargs)
else:
self.no_driftbands_plt.set_data(ph, p)
else:
# If there are none to plot, clear any pre-existing ones
self.clear_plots(with_driftbands=False, no_driftbands=True)
def clear_plots(self, with_driftbands=True, no_driftbands=True):
if with_driftbands:
if self.with_driftbands_plt is not None:
self.with_driftbands_plt.set_data([], [])
self.with_driftbands_plt = None
if no_driftbands:
if self.no_driftbands_plt is not None:
self.no_driftbands_plt.set_data([], [])
self.no_driftbands_plt = None
def serialize(self):
serialized = {}
if self.data is not None:
serialized["pulses"] = list(self.get_pulses().astype(float))
serialized["phases"] = list(self.get_phases().astype(float))
serialized["widths"] = list(self.get_widths().astype(float))
serialized["driftbands"] = list(self.get_driftbands().astype(float))
return serialized
def unserialize(self, serialized):
if len(serialized) > 0:
pulses = serialized["pulses"]
phases = serialized["phases"]
widths = serialized["widths"]
driftbands = serialized["driftbands"]
self.add_subpulses(phases, pulses, widths=widths, driftbands=driftbands)
else:
self.data = None
def add_subpulses(self, phases, pulses, widths=None, driftbands=None):
if len(phases) != len(pulses):
print("Lengths of phases and pulses don't match. No subpulses added.")
return
nnewsubpulses = len(phases)
if widths is None:
widths = np.full((nnewsubpulses), np.nan)
elif np.isscalar(widths):
widths = np.full((nnewsubpulses), widths)
elif len(widths) != nnewsubpulses:
print("Length of widths doesn't match phases and pulses. No subpulses added.")
return
if driftbands is None:
driftbands = np.full((nnewsubpulses), np.nan)
elif np.isscalar(driftbands):
driftbands = np.full((nnewsubpulses), driftbands)
elif len(driftbands) != nnewsubpulses:
print("Length of driftbands doesn't match phases and pulses. No subpulses added.")
return
newsubpulses = np.transpose([phases, pulses, widths, driftbands])
if self.data is None:
self.data = newsubpulses
else:
self.data = np.vstack((self.data, newsubpulses))
def delete_subpulses(self, delete_idxs):
self.data = np.delete(self.data, delete_idxs, axis=0)
def delete_all_subpulses(self):
self.data = None
def get_nsubpulses(self):
if self.data is None:
return 0
else:
return self.data.shape[0]
def get_phases(self, subset=None):
if subset is None:
return self.data[:,0]
else:
return self.data[subset, 0]
def get_pulses(self, subset=None):
if subset is None:
return self.data[:,1]
else:
return self.data[subset, 1]
def count_unique_pulse_numbers(self, subset=None):
return len(set(self.get_pulses(subset)))
def get_widths(self, subset=None):
if subset is None:
return self.data[:,2]
else:
return self.data[subset, 2]
def get_driftbands(self, subset=None):
if subset is None:
return self.data[:,3]
else:
return self.data[subset, 3]
def get_positions(self):
'''
Returns an Nx2 numpy array of subpulse positions (phase, pulse)
'''
return self.data[:,:2]
def set_phases(self, phases, subset=None):
if subset is None:
self.data[:,0] = phases
else:
self.data[subset,0] = phases
def set_pulses(self, pulses, subset=None):
if subset is None:
self.data[:,1] = pulses
else:
self.data[subset,1] = pulses
def set_widths(self, widths, subset=None):
if subset is None:
self.data[:,2] = widths
else:
self.data[subset,2] = widths
def set_driftbands(self, driftbands, subset=None):
if subset is None:
self.data[:,3] = driftbands
else:
self.data[subset,3] = driftbands
def shift_all_subpulses(self, dphase=None, dpulse=None):
if dphase is not None:
self.data[:,0] += dphase
if dpulse is not None:
self.data[:,1] += dpulse
def calc_drift(self, subpulse_idxs):
'''
Fits a line to the given set of subpulses
Returns the driftrate and y-intercept of the line at the fiducial point
'''
if len(subpulse_idxs) < 2:
print("Not enough subpulses selected. No drift line fitted")
return
phases = self.get_phases()
pulses = self.get_pulses()
linear_fit = polyfit(phases, pulses, 1)
driftrate = 1/linear_fit[1]
yintercept = linear_fit[0]
return driftrate, yintercept
def in_pulse_range(self, pulse_range=None, with_valid_driftband=False):
'''
Returns a logical mask for those subpulses within the specified range
'''
p = self.get_pulses()
if pulse_range is not None:
p_lo, p_hi = pulse_range
is_in_range = np.logical_and(p >= p_lo, p <= p_hi)
else:
is_in_range = np.ones(p.shape).astype(bool) # Should be an array of all True
if with_valid_driftband:
d = self.get_driftbands()
is_valid_driftband = np.logical_not(np.isnan(d))
return np.logical_and(is_in_range, is_valid_driftband)
else:
return is_in_range
def in_phase_range(self, phase_range=None, with_valid_driftband=False):
'''
Returns a logical mask for those subpulses within the specified range
'''
ph = self.get_phases()
if phase_range is not None:
ph_lo, ph_hi = phase_range
is_in_range = np.logical_and(ph >= ph_lo, ph <= ph_hi)
else:
is_in_range = np.ones(ph.shape).astype(bool) # Should be an array of all True
if with_valid_driftband:
d = self.get_driftbands()
is_valid_driftband = np.logical_not(np.isnan(d))
return np.logical_and(is_in_range, is_valid_driftband)
else:
return is_in_range
def assign_driftbands_to_subpulses(self, model_fit):
'''
model_fit - an object of ModelFit
This will classify each subpulse in the appropriate pulse range
into a driftband according to the given model.
'''
# Get only those subpulses within the valid range of the quadratic fit
pulse_range = np.array(model_fit.get_pulse_bounds())
subset = self.in_pulse_range(pulse_range)
ph = self.get_phases(subset=subset)
p = self.get_pulses(subset=subset)
d = model_fit.get_nearest_driftband(p, ph)
self.set_driftbands(d, subset=subset)
# For good measure, return the subset of affected subpulse
return subset
class DriftSequences:
def __init__(self):
self.boundaries = []
self.modes = [""]
def serialize(self):
serialized = {}
serialized["boundaries"] = list(self.boundaries)
serialized["modes"] = list(self.modes)
return serialized
def unserialize(self, serialized):
if "boundaries" in serialized.keys():
self.boundaries = serialized["boundaries"]
else:
self.boundaries = []
if "modes" in serialized.keys():
self.modes = serialized["modes"]
else:
self.modes = ["" for i in range(len(self.boundaries) + 1)]
def number_of_sequences(self):
return len(self.boundaries) + 1
def has_boundary(self, pulse_idx):
if pulse_idx in self.boundaries:
return True
else:
return False
def add_boundary(self, pulse_idx, pulsestack):
if not self.has_boundary(pulse_idx):
# Work out where to put the new boundary
sequence_idx = self.get_sequence_number(pulse_idx, pulsestack)
# Get the mode of the current mode
mode = self.modes[sequence_idx]
self.modes.insert(sequence_idx, mode)
# Insert the pulse idx as a new boundary
self.boundaries.insert(sequence_idx, pulse_idx)
def delete_boundaries(self, boundary_idxs):
self.boundaries = [int(v) for i, v in enumerate(self.boundaries) if i not in boundary_idxs]
self.modes = [v for i, v in enumerate(self.modes) if i not in boundary_idxs]
def add_offset_to_boundaries(self, offset):
self.boundaries = [b + offset for b in self.boundaries]
def get_bounding_pulse_idxs(self, sequence_idx, pulsestack):
'''
Returns the first and last pulses indexes in this sequence
'''
p0 = pulsestack.get_pulse_from_bin(0)
pf = pulsestack.get_pulse_from_bin(pulsestack.npulses - 1)
if len(self.boundaries) == 0:
return p0, pf
if sequence_idx < 0:
sequence_idx = len(self.boundaries) + 1 + sequence_idx
if sequence_idx == 0:
first_idx = p0
else:
first_idx = self.boundaries[sequence_idx - 1] + 1
if sequence_idx == len(self.boundaries):
last_idx = pf
else:
last_idx = self.boundaries[sequence_idx]
return [first_idx, last_idx]
def get_all_first_pulses(self):
return [0] + [i+1 for i in self.boundaries]
def get_all_last_pulses(self, pulsestack):
pf = pulsestack.get_pulse_from_bin(pulsestack.npulses - 1)
return self.boundaries + [pf]
def is_pulse_in_sequence(self, sequence_idx, pulse_idx, pulsestack):
first_idx, last_idx = self.get_bounding_pulse_idxs(sequence_idx, pulsestack)
if pulse_idx >= first_idx and pulse_idx <= last_idx:
return True
else:
return False
def get_pulse_mid_idxs(self, boundary_idxs=None):
if boundary_idxs is None:
return np.array(self.boundaries) + 0.5
else:
return np.array(self.boundaries)[boundary_idxs] + 0.5
def get_sequence_number(self, pulse_idx, pulsestack):
# There are lots of corner cases!
# Remember, the first boundary sits between sequences 0 and 1,
# and the last sits between sequences n and n+1, where
# n = len(self.boundaries) - 1
# All the "0.5"s around the place is to make this function give sensible
# results when pulse_idx is a fractional value
_, _, plo, phi = pulsestack.calc_image_extent()
if pulse_idx < plo or pulse_idx >= phi:
sequence_number = None
elif self.number_of_sequences() == 1:
sequence_number = 0
elif pulse_idx <= self.boundaries[0] + 0.5:
sequence_number = 0
elif len(self.boundaries) == 0:
sequence_number = 0
elif pulse_idx > self.boundaries[-1] + 0.5:
sequence_number = len(self.boundaries)
else:
is_no_more_than = pulse_idx <= np.array(self.boundaries) + 0.5
sequence_number = np.argwhere(is_no_more_than)[0][0]
return sequence_number
def set_sequence_mode(self, sequence_idx, mode):
self.modes[sequence_idx] = mode
def get_number_of_modes(self):
# Count the number of unique modes
return len(set(self.modes))
def get_mode_colours(self):
# Get the number of unique modes
nmodes = self.get_number_of_modes()
# Make a list of colours accordingly, but make the first color black
if nmodes == 1:
colour_list = np.array([[0, 0, 0, 1]])
else:
colour_list = cm.rainbow(np.linspace(0, 1, nmodes - 1))
colour_list = np.insert(colour_list, 0, [0, 0, 0, 1], axis=0)
# Make a dictionary where keys are modes and values are colours
colour_dict = {list(set(self.modes))[i]: colour_list[i] for i in range(nmodes)}
return colour_dict
class ModelFit(pulsestack.Pulsestack):
def __init__(self):
self.parameters = None
self.pcov = None
self.first_pulse = None
self.last_pulse = None
self.model_name = None
# A dictionary for keeping track of line plot objects
# Dictioney keys are intended to be driftband numbers
self.driftband_plts = {}
def get_nparameters(self):
return len(self.get_parameter_names())
def get_parameter_names(self, display_type=None, with_units=False):
'''
display_type can be 'latex'. None defaults to ascii-type output
'''
if self.model_name == "quadratic":
if display_type == "latex":
return ["a_1", "a_2", "a_3", "a_4"]
else:
return ["a1", "a2", "a3", "a4"]
elif self.model_name == "exponential":
if display_type == "latex":
if with_units:
return ["D_0\\,(^\\circ/P)", "D_f\\,(^\\circ/P)", "k\\,(1/P)", "\\varphi_0\\,(^\\circ)", "P_2\\,(^\\circ)"]
else:
return ["D_0", "D_f", "k", "\\varphi_0", "P_2"]
else:
if with_units:
return ["D0 (deg/P)", "Df (deg/P)", "k (1/P)", "phi0 (deg)", "P2 (deg)"]
else:
return ["D0", "Df", "k", "phi0", "P2"]
else:
self.print_unecognised_model_error()
def get_parameter_by_name(self, parameter_name):
try:
idx = self.get_parameter_names().index(parameter_name)
return self.parameters[idx]
except:
return None
def __str__(self):
if self.model_name == "quadratic":
equation_string = "phi = a1*p^2 + a2*p + a3 + a4*d"
elif self.model_name == "exponential":
equation_string = "phi = (D0/k)*(1 - exp(-k*(p - p0)) + Df*(p - p0) + phi0 + P2*d)"
else:
return "Unrecognised model '{}'".format(self.model)
model_string = "Model: {} ({})\nPulse range: {:.1f} - {:.1f}\n".format(self.model_name, equation_string, self.first_pulse, self.last_pulse)
parameter_names = self.get_parameter_names()
for i in range(len(self.parameters)):
model_string += " {:4} = {}".format(parameter_names[i], self.parameters[i])
if self.pcov is not None:
model_string += " +- {}".format(np.sqrt(self.pcov[i,i]))
model_string += "\n"
return model_string
def print_unrecognised_model_error(self):
print("Unrecognised model '" + self.model_name + "'")
def set_pulse_bounds(self, first_pulse, last_pulse):
self.first_pulse = first_pulse
self.last_pulse = last_pulse
def get_pulse_bounds(self):
return [self.first_pulse, self.last_pulse]
def convert_to_model(self, new_model_name):
'''
This will convert the existing into a (very rough!) approximation of the specified model.
Details of the conversions are given in the comments.
'''
if new_model_name == self.model_name:
return
p0, pf = self.get_pulse_bounds()
if new_model_name == "exponential":
# This conversion keeps the phase and P2 of the driftbands at the beginning of the drift
# sequence the same, and chooses the exponential model which matches the drift rate at
# both the beginning and the end of the sequence. It is NOT guaranteed that the phase
# of the driftbands match at the end of the drift sequence
P2 = self.calc_P2()
phi0 = self.calc_phase(p0, 0)
D0 = self.calc_driftrate(p0)
Dend = self.calc_driftrate(pf) # The drift rate at the end of the sequence
Df = 0 # The drift rate as p -> oo
k = -np.log(Dend/D0) / (pf - p0)
self.parameters = [D0, Df, k, phi0, P2]
self.model_name = new_model_name
if new_model_name == "quadratic":
# This conversion keeps the phase and P2 of the driftbands at the beginning of the drift
# sequence the same, and chooses the quadratic model which matches the drift rate at
# both the beginning and the end of the sequence. It is NOT guaranteed that the phase
# of the driftbands match at the end of the drift sequence
P2 = self.calc_P2()
D0 = self.calc_driftrate(p0)
Dend = self.calc_driftrate(pf) # The drift rate at the end of the sequence
phi0 = self.calc_phase(p0, 0)
a1 = (D0 - Dend)/(2*(p0 - pf))
a2 = (D0*pf - Dend*p0)/(pf - p0)
a3 = phi0 - a1*p0**2 - a2*p0
a4 = P2
self.parameters = [a1, a2, a3, a4]
self.model_name = new_model_name
def optimise_fit_to_subpulses(self, phases, pulses, driftbands):
# A valid model must be specified in self.model_name
if self.model_name is None:
print("Unspecified model. Cannot optimise model fit. Aborting")
return
print("Fitting points to mode \"" + self.model_name + "\"")
# phases, pulses, and driftbands must be vectors with the same length
npoints = len(phases)
if len(pulses) != npoints or len(driftbands)!= npoints:
print("phases, pulses, driftbands have lengths {}, {}, and {}, but they must be the same".format(len(phases), len(pulses), len(driftbands)))
return
# Form the matrices for least squares fitting
ph = np.array(phases)
p = np.array(pulses)
d = np.array(driftbands)
# Get things in a form that curve_fit needs
xdata = np.array([p, d])
ydata = np.array(ph)
# Use the existing model as the initial guess
p0 = self.parameters
if p0 is None:
print("No initial guess supplied. Results may vary")
if self.model_name == "quadratic":
p0 = np.ones((4,))
elif self.model_name == "exponential":
p0 = np.ones((5,))
# Call curve_fit
popt, pcov = curve_fit(self.calc_phase_for_curvefit, xdata, ydata, p0=p0)
# TO DO: Include Jacobian in the above call to curve_fit
# Set these parameters!
self.parameters = popt
self.pcov = pcov
print(self.parameters)
def serialize(self):
serialized = {}
if self.model_name is not None:
serialized["model_name"] = self.model_name
if self.parameters is not None:
serialized["parameters"] = list(self.parameters)
if self.first_pulse is not None and self.last_pulse is not None:
serialized["pulse_range"] = [int(self.first_pulse), int(self.last_pulse)]
if self.pcov is not None:
serialized["pcov"] = list(self.pcov.flatten())
return serialized
def unserialize(self, data):
if "model_name" in data.keys():
self.model_name = data["model_name"]
else:
self.model_name = None
if "parameters" in data.keys():
self.parameters = data["parameters"]
nparameters = len(self.parameters)
# Only attempt to make sense of the pcov if there are already parameters
# Also, the number of elements in pcov MUST be the square of the number of parameters
if "pcov" in data.keys():
if len(data["pcov"]) == nparameters**2:
self.pcov = np.reshape(data["pcov"], (nparameters, nparameters))
else:
self.pcov = None
else:
self.pcov = None
else:
self.parameters = None
if "pulse_range" in data.keys():
self.first_pulse, self.last_pulse = data["pulse_range"]
else:
self.first_pulse = None
self.last_pulse = None
def calc_jacobian(self, pulse, driftband):
p = pulse
d = driftband
p0 = self.first_pulse
if self.model_name == "quadratic":
# See McSweeney et al. (2017)
a1, a2, a3, a4 = self.parameters
dph_da1 = p**2
dph_da2 = p
dph_da3 = 1
dph_da4 = d
J = np.array([dph_da1, dph_da2, dph_da3, dph_da4])
return J
elif self.model_name == "exponential":
D0, Df, k, phi0, P2 = self.parameters
E = 1 - np.exp(-k*(p - p0))
dph_dD0 = E/k
dph_dDf = p - p0
dph_dk = -D0*E/k**2 + D0*(1 - E)*(p - p0)/k
dph_dphi0 = 1
dph_dP2 = d
J = np.array([dph_dD0, dph_dDf, dph_dk, dph_dphi0, dph_dP2])
return J
else:
self.print_unrecognised_model_error()
return
def calc_phase_err(self, pulse, driftband):
p = pulse
d = driftband
J = self.calc_jacobian(p, d)
ph_err = np.sqrt(J @ self.pcov @ J.T)
return ph_err
def calc_phase(self, pulse, driftband):
p = pulse
d = driftband
p0 = self.first_pulse
if self.model_name == "quadratic":
# See McSweeney et al. (2017)
a1, a2, a3, a4 = self.parameters
ph = a1*p**2 + a2*p + a3 + a4*d
return ph
elif self.model_name == "exponential":
D0, Df, k, phi0, P2 = self.parameters
ph = (D0/k)*(1 - np.exp(-k*(p - p0))) + Df*(p - p0) + phi0 + P2*d
return ph
else:
self.print_unrecognised_model_error()
return
def calc_phase_for_curvefit(self, xdata, *params):
'''
A wrapper for calc_phase(), so that it can be used with scipy's curvefit
'''
p = xdata[0,:]
d = xdata[1,:]
model = copy.copy(self)
model.parameters = np.array([*params])
return model.calc_phase(p, d)
def calc_driftrate(self, pulse):
p = pulse
p0 = self.first_pulse
if self.model_name == "quadratic":
a1, a2, _, _ = self.parameters
D = 2*a1*p + a2
return D
elif self.model_name == "exponential":
D0, Df, k, _, _ = self.parameters
D = D0*np.exp(-k*(p - p0)) + Df
return D
else:
self.print_unrecognised_model_error()
return
def calc_driftrate_err(self, pulse):
'''
Returns the fully covariant error on the driftrate at the specified pulse number
'''
# If pulse is a single number, force it to be an array
pulse = np.squeeze([pulse])
# Calculate the Jacobian
if self.model_name == "quadratic":
J = np.array([[2*p, 1, 0, 0] for p in pulse]) # Make it an explicit 2D array for easier matrix multiplcation later
elif self.model_name == "exponential":
D0, Df, k, _, _ = self.parameters
p0 = self.first_pulse
J = np.array([[np.exp(-k*(p - p0)), 1, -(p - p0)*D0*np.exp(-k*(p - p0)), 0, 0] for p in pulse])
else:
self.print_unrecognised_model_error()
return
Derr = np.array([J[i] @ self.pcov @ J[i].T for i in range(len(pulse))])
if len(Derr) == 1:
Derr = Derr[0]
return Derr
def calc_driftrate_derivative(self, pulse):
'''
Returns the driftrate derivative w.r.t. pulse
'''
p = pulse
p0 = self.first_pulse
if self.model_name == "quadratic":
a1, _, _, _ = self.parameters
return 2*a1
elif self.model_name == "exponential":
D0, _, k, _, _ = self.parameters
return -k*D0*np.exp(-k*(p - p0)) # also could write -k*self.calc_driftrate(p)
else:
self.print_unrecognised_model_error()
return
def calc_driftrate_decay_rate(self, pulse):
return -self.calc_driftrate_derivative(pulse)/self.calc_driftrate(pulse)
def calc_residual(self, pulse, phase, driftband):
'''
Calculates subpulse phase minus model phase
'''
model_phase = self.calc_phase(pulse, driftband)
residual = phase - model_phase
return residual
def shift_phase(self, phase_shift):
'''
Recalculate the model parameters to shift the model in phase.
This calculation is model-dependent, so in principle has to be done for each
model separately (even though they may turn out to look the same in some cases)
'''
if self.model_name == "quadratic":
self.parameters[2] += phase_shift
elif self.model_name == "exponential":
self.parameters[3] += phase_shift
else:
self.print_unrecognised_model_error()
return
def get_nearest_driftband(self, pulse, phase):
p = pulse
ph = phase
if self.model_name == "quadratic":
a1, a2, a3, a4 = self.parameters
return np.round((ph - a1*p**2 - a2*p - a3)/a4)
elif self.model_name == "exponential":
D0, Df, k, phi0, P2 = self.parameters
p0 = self.first_pulse
return np.round((ph - (D0/k)*(1 - np.exp(-k*(p - p0))) - Df*(p - p0) - phi0)/P2)
else:
self.print_unrecognised_model_error()
return
def calc_P2(self):
if self.model_name == "quadratic":
_, _, _, a4 = self.parameters
return a4
elif self.model_name == "exponential":
_, _, _, _, P2 = self.parameters
return P2
else:
self.print_unrecognised_model_error()
return
def calc_P3(self, pulse):
return self.calc_P2()/self.calc_driftrate(pulse)
def get_driftband_range(self, phlim):
# Figure out if drift rate is positive or negative (at the first pulse)
p0 = self.first_pulse
pf = self.last_pulse
if self.calc_driftrate(p0) < 0:
ph0 = phlim[0]
else:
ph0 = phlim[1]
if self.calc_driftrate(pf) < 0:
phf = phlim[1]
else:
phf = phlim[0]
if self.model_name == "quadratic":
a1, a2, a3, a4 = self.parameters
d0 = np.ceil((ph0 - a1*p0**2 - a2*p0 - a3)/a4)
df = np.floor((phf - a1*pf**2 - a2*pf - a3)/a4)
elif self.model_name == "exponential":
D0, Df, k, phi0, P2 = self.parameters
d0 = np.ceil((ph0 - phi0)/P2)
df = np.floor((phf - (D0/k)*(1 - np.exp(-k*(pf - p0))) - Df*(pf - p0) - phi0)/P2)
else:
self.print_unrecognised_model_error()
return
return [int(d0), int(df)]
def plot_driftband(self, ax, driftband, phlim=None, pstep=1, **kwargs):
'''
driftband: driftband number to plot
phlim: phase limits between which to draw the driftband
'''
d = driftband
p = np.arange(self.first_pulse, self.last_pulse + pstep, pstep)
ph = self.calc_phase(p, d)
if phlim is not None:
in_phase_range = np.logical_and(ph >= phlim[0], ph <= phlim[1])
p = p[in_phase_range]
ph = ph[in_phase_range]
# If there's no part of this driftband that falls inside the phase range
# (and pulse range), then do nothing
if len(p) == 0:
if d in self.driftband_plts.keys():
self.driftband_plts.pop(d)
return
if d in self.driftband_plts.keys():
self.driftband_plts[d][0].set_data(ph, p)
else:
self.driftband_plts[d] = ax.plot(ph, p, **kwargs)
def plot_all_driftbands(self, ax, phlim, pstep=1, **kwargs):
first_d, last_d = self.get_driftband_range(phlim)
for d in range(first_d, last_d+1):
self.plot_driftband(ax, d, phlim=phlim, pstep=pstep, **kwargs)
def clear_all_plots(self):
for d in self.driftband_plts:
self.driftband_plts[d][0].set_data([], [])
self.driftband_plts = {}
class DriftAnalysis(pulsestack.Pulsestack):
def __init__(self):
super().__init__()
self.fig = None
self.ax = None
self.subpulses = Subpulses()
self.maxima_plt = None
self.maxima_threshold = 0.0
self.drift_sequences = DriftSequences()
self.dm_boundary_plt = None
self.jsonfile = None
self.candidate_quadratic_model = ModelFit()
self.candidate_quadratic_model.model_name = "quadratic"
self.onpulse = None
self.model_fits = {} # Keys = drift sequence numbers
self.quadratic_visible = True
self.clim = [None, None]
def get_local_maxima(self, maxima_threshold=None):
if maxima_threshold is None:
maxima_threshold = self.maxima_threshold
else:
self.maxima_threshold = maxima_threshold
if self.onpulse is None:
leading_bin = 1
trailing_bin = self.nbins - 1
else:
leading_bin = int(np.ceil(self.get_phase_bin(self.onpulse[0])))
trailing_bin = int(np.floor(self.get_phase_bin(self.onpulse[1])))
is_bigger_than_left = self.values[:,leading_bin+1:trailing_bin] >= self.values[:,leading_bin:trailing_bin-1]
is_bigger_than_right = self.values[:,leading_bin+1:trailing_bin] >= self.values[:,leading_bin+2:trailing_bin+1]
is_local_max = np.logical_and(is_bigger_than_left, is_bigger_than_right)
if maxima_threshold is not None:
is_local_max = np.logical_and(is_local_max, self.values[:,leading_bin+1:trailing_bin] > maxima_threshold)
self.max_locations = np.array(np.where(is_local_max)).astype(float)
# Add leading bin to phase (bin) locations because of previous splicing
self.max_locations[1,:] += leading_bin + 1
# Convert locations to data coordinates (pulse and phase)
self.max_locations[0,:] = self.max_locations[0,:]*self.dpulse + self.first_pulse
self.max_locations[1,:] = self.max_locations[1,:]*self.dphase_deg + self.first_phase
def save_json(self, jsonfile=None):
if jsonfile is None:
jsonfile = self.jsonfile
# If jsonfile is STILL unspecified, open file dialog box
if jsonfile is None:
root = tkinter.Tk()
root.withdraw()
jsonfile = tkinter.filedialog.asksaveasfilename(filetypes=(("All files", "*.*"),))
# And if THAT still didn't produce a filename, cancel
if not jsonfile:
return
drift_dict = {
"version": __version__,
"pulsestack": self.serialize(),
"subpulses": self.subpulses.serialize(),
"model_fits": [[int(i), self.model_fits[i].serialize()] for i in self.model_fits],
"maxima_threshold": self.maxima_threshold,
"drift_mode_boundaries": self.drift_sequences.serialize()
}
try:
with open(jsonfile, "w") as f:
json.dump(drift_dict, f)
self.jsonfile = jsonfile
except TypeError as err:
print("Could not save out json file:", err)
def load_json(self, jsonfile=None):
if jsonfile is None:
jsonfile = self.jsonfile
with open(jsonfile, "r") as f:
drift_dict = json.load(f)
if drift_dict["version"] != __version__:
print("Warning: version mismatch, File = {}, Software = {}".format(drift_dict["version"], __version__))
# Load the pulsestack data
self.unserialize(drift_dict["pulsestack"])
self.subpulses.unserialize(drift_dict["subpulses"])
for item in drift_dict["model_fits"]:
self.model_fits[item[0]] = ModelFit()
self.model_fits[item[0]].unserialize(item[1])
self.maxima_threshold = drift_dict["maxima_threshold"]
self.drift_sequences.unserialize(drift_dict["drift_mode_boundaries"])
self.jsonfile = jsonfile
def plot_drift_mode_boundaries(self):
xlo = self.first_phase
xhi = self.first_phase + self.nbins*self.dphase_deg