-
Notifications
You must be signed in to change notification settings - Fork 1
/
frbgui.py
1560 lines (1370 loc) · 63.8 KB
/
frbgui.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
import dearpygui.demo as demo
import dearpygui.dearpygui as dpg
from dearpygui_ext import logger, themes
import driftrate, driftlaw
import os, glob, itertools, io
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pandas as pd
from datetime import datetime
import warnings
from your.utils.rfi import sk_sg_filter
import time
warnings.filterwarnings("ignore")
defaultmpl_backend = matplotlib.get_backend()
twidth_default = 150
logwin = None
# flag for switching the main thread from DPG to Matplotlib. Matplotlib is not threadsafe
exportPDF = False
# GUI data is stored in this object. Defaults initialized here and at the bottom
gdata = {
'globfilter' : '*.npz',
'masks' : {}, # will store masks, either lists of channels or ranges
'datadir' : '',
'multiburst' : { # store all multiburst metadata
'numregions': 1,
'enabled' : False,
'regions' : {}
},
'resultsdf' : None,
'p0' : None, # currently displayed initial fit guess
'displayedBurst' : '', # name of displayed burst
}
def getscale(m, M=-1): # used for dynamically rounding numbers for display
if M == -1: M = m
ret = 1
c = abs((m+M)/2)
while c < 1:
c *= 10; ret += 1
return ret
def compressArr(arr):
# adapted from https://www.geeksforgeeks.org/compress-the-array-into-ranges/
i, j, n = 0, 0, len(arr)
arr.sort()
while i < n:
j = i
while (j + 1 < n) and (arr[j + 1] == arr[j] + 1):
j += 1
if i == j:
print(arr[i], end=" ")
i += 1
else:
print(arr[i], "-", arr[j], end=" ")
i = j + 1
def applyMasks(wfall):
for mask in gdata['masks'][gdata['currfile']]['chans']:
if mask < len(wfall):
wfall[mask] = 0
for rangeid, maskrange in gdata['masks'][gdata['currfile']]['ranges'].items():
masks = np.arange(maskrange[0], maskrange[1]+1)
for mask in masks:
if mask < len(wfall):
wfall[mask] = 0
if 'sksgmask' in gdata and dpg.get_value('EnableSKSGMaskBox'):
wfall[gdata['sksgmask'], :] = 0
return wfall
def makeburstname(filename):
return filename.split(os.sep)[-1].split('.')[0]
def log_cb(sender, data):
print(f"{sender}, {data}")
logwin.log_debug(f"{sender}, {data}")
def error_log_cb(sender, data):
print(f"{sender}, {data}")
logwin.log_error(f"{sender}, {data}")
def updatedata_cb(sender, data, udata):
if not data: data = {}
if not udata: udata = {}
wfall = None
if 'filename' in udata.keys(): # load burst from disk
filename = udata['filename']
gdata['currfile'] = filename
if gdata['currfile'] not in gdata['masks'].keys():
gdata['masks'][gdata['currfile']] = {'chans':[], 'ranges':{}}
burstname = makeburstname(filename)
dpg.set_value('burstname', burstname)
loaded = np.load(filename)
if type(loaded) == np.ndarray:
wfall = loaded.astype(np.float64)
wfall = np.nan_to_num(wfall) # automatically convert nan mask to 0s
elif type(loaded) == np.lib.npyio.NpzFile:
wfall = loaded['wfall'].astype(np.float64)
storedshape = wfall.shape
gdata['burstmeta'] = {}
for key in loaded.files:
if key != 'wfall':
gdata['burstmeta'][key] = loaded[key]
if key == 'dfs':
# dfs = loaded[key]
gdata['burstmeta']['bandwidth'] = abs(loaded['bandwidth'])
df = gdata['burstmeta']['bandwidth'] / wfall.shape[0]
# print(df, loaded['bandwidth'], storedshape[1]*1000)
gdata['burstmeta']['fres_original'] = df
gdata['burstmeta']['fres'] = df
dpg.set_value('df', df)
dpg.configure_item('df', format='%.{}f'.format(getscale(df)+1))
elif key == 'duration' or key == 'dt':
dt = loaded['duration'] / storedshape[1]*1000
# print(dt, loaded['duration'], storedshape[1]*1000)
gdata['burstmeta']['duration'] = loaded['duration']
gdata['burstmeta']['tres_original'] = dt
gdata['burstmeta']['tres'] = dt
dpg.set_value('dt', dt)
dpg.set_value('duration', loaded['duration'])
dpg.configure_item(key, format='%.{}f'.format(getscale(dt)+3))
else:
if dpg.does_alias_exist(key):
dpg.set_value(key, loaded[key]) # this line sets all the burst fields
# post loading tweaks
if key == 'time_unit':
dpg.configure_item('duration', label=f"Data Duration ({loaded[key]})")
# initialize DM range elements
gdata['displayedDM'] = loaded['DM']
gdata['burstDM'] = loaded['DM']
dpg.set_value('dmdisplayed', str(gdata['displayedDM']))
dpg.set_value('burstdisplayed', burstname)
if dpg.get_value('dmrange')[0] == 0:
dmrange = [gdata['burstDM']*0.99, gdata['burstDM']*1.01]
dpg.set_value('dmrange', dmrange)
dpg.configure_item('dmrange', speed=0.1)
dmrange_cb(sender, None)
gdata['wfall'] = wfall # wfall at burstdm
gdata['wfall_original'] = np.copy(wfall) # wfall at burstdm without additional subsampling
# update subsample controls
dpg.set_value('Wfallshapelbl', 'Original Size: {}'.format(np.shape(wfall)))
dpg.set_value('Subfallshapelbl', 'Current Size: {}'.format(np.shape(wfall)))
dpg.configure_item('numfreqinput', enabled=True, min_value=0, max_value=wfall.shape[0])
dpg.configure_item('numtimeinput', enabled=True, min_value=0, max_value=wfall.shape[1])
dpg.configure_item('ResetSamplingBtn', enabled=True)
dpg.set_value('numfreqinput', wfall.shape[0])
dpg.set_value('numtimeinput', wfall.shape[1])
# update meta controls
dpg.set_value('twidth', twidth_default)
dpg.configure_item('twidth', max_value=round(wfall.shape[1]/2))
dpg.configure_item('SaveDMButton', enabled=False)
# update mask range controls
gdata['maskrangeid'] = 0
dpg.delete_item("MaskRangeGroup", children_only=True)
if gdata['masks'][gdata['currfile']]['ranges']:
rangeids = []
for rangeid, maskrange in gdata['masks'][gdata['currfile']]['ranges'].items():
rangeids.append(rangeid)
addMaskRange_cb(sender, rangeid)
dpg.set_value(f'rangeslider##{rangeid}', maskrange)
gdata['maskrangeid'] = max(rangeids) # guarantee no collisions
# update result controls and reproduce measurement state
if gdata['resultsdf'] is not None:
hasResults = burstname in gdata['resultsdf'].index.unique()
dpg.configure_item('PrevDM', enabled=hasResults)
dpg.configure_item('NextDM', enabled=hasResults)
dpg.configure_item('ExportCSVBtn', enabled=hasResults)
dpg.configure_item('ExportPDFBtn', enabled=hasResults)
dpg.configure_item('DeleteBurstBtn', enabled=False) # unimplemented
dpg.configure_item('DeleteAllBtn', enabled=False) # unimplemented
dpg.configure_item('EnableP0Box', enabled=hasResults)
if hasResults:
gdata['burstdf'] = gdata['resultsdf'][gdata['resultsdf'].index.str.startswith(burstname)]
# reload waterfall cleanup
cols = ['tsamp_width', 'subbg_start (ms)', 'subbg_end (ms)', 'sksigma', 'skwindow']
twidth, subbgstart, subbgend, sksigma, skwindow = gdata['burstdf'][cols].iloc[0]
if sender == 'burstselect':
dpg.set_value('twidth', int(twidth))
if not pd.isnull(subbgstart):
dpg.set_value('EnableSubBGBox', True)
toggle_config('EnableSubBGBox', {'kwargs': ['enabled'], 'items': ['SubtractBGRegion']})
dpg.set_value('SubtractBGRegion', [subbgstart, subbgend])
else:
dpg.set_value('EnableSubBGBox', False)
toggle_config('EnableSubBGBox', {'kwargs': ['enabled'], 'items': ['SubtractBGRegion']})
skitems = ['SKSGSigmaInput','SKSGWindowInput']
if not pd.isnull(sksigma):
dpg.set_value("EnableSKSGMaskBox", True)
dpg.set_value('SKSGSigmaInput', int(sksigma))
dpg.set_value('SKSGWindowInput', int(skwindow))
toggle_config('EnableSKSGMaskBox', {'kwargs': ['enabled'], 'items': skitems})
else:
dpg.set_value('EnableSKSGMaskBox', False)
toggle_config('EnableSKSGMaskBox', {'kwargs': ['enabled'], 'items': skitems})
# check if subsampling is needed (for eg. if results have been loaded)
dmframe = gdata['burstdf'].set_index('DM')
downf, downt = map(int, dmframe.loc[np.isclose(dmframe.index, gdata['displayedDM'])].iloc[0][['downf', 'downt']])
dpg.set_value('numfreqinput', int(wfall.shape[0]/downf))
dpg.set_value('numtimeinput', int(wfall.shape[1]/downt))
if downf != 1 or downt != 1:
wfall = subsample_cb('loadresults_cb', None) # this updates gdata['burstmeta']
dpg.set_value('twidth', int(twidth)) # force twidth to match results row after subsampling
updateResultTable(gdata['burstdf'])
initializeP0Group()
else:
updateResultTable(pd.DataFrame())
gdata['burstdf'] = pd.DataFrame()
gdata['p0'] = None
dpg.set_value('EnableP0Box', False)
items = ['P0AllDMsBox','AmplitudeDrag','AngleDrag','x0y0Drag','SigmaXYDrag', 'RedoBtn']
toggle_config('EnableP0Box', {'kwargs': ['enabled'], 'items': items})
dpg.set_value('NumMeasurementsText', "# of Measurements for this burst: {}".format(len(gdata['burstdf'])))
dpg.set_value('TotalNumMeasurementsText', "Total # of Measurements: {}".format(len(gdata['resultsdf'])))
# setup burst splitting
for regid in range(1, gdata['multiburst']['numregions']):
if dpg.does_item_exist('RegionSelector{}'.format(regid)):
maxval = driftrate.cropwfall(wfall, twidth=dpg.get_value('twidth')).shape[1]*gdata['burstmeta']['tres']
dpg.configure_item('Region{}'.format(regid), max_value=maxval, speed=maxval*0.005)
if burstname in gdata['multiburst']['regions']:
if not gdata['multiburst']['enabled']:
dpg.set_value('MultiBurstBox', True)
enablesplitting_cb('MultiBurstBox', {'kwargs': ['enabled']})
regions = gdata['multiburst']['regions'][burstname]
numregions = len(regions.keys())
while numregions > gdata['multiburst']['numregions']-1:
addregion_cb(sender, None)
while numregions < gdata['multiburst']['numregions']-1:
removeregion_cb([gdata['multiburst']['numregions']-1], None)
# set the elements based on gdata['regions']
for regid, name in enumerate(regions):
regid += 1 # off by one
regiontype = "Background" if 'background' in name else "Burst" # matches UI elements
dpg.set_value(f'Region{regid}', regions[name])
dpg.set_value(f'RegionType{regid}', regiontype)
drawregion_cb([regid], None)
elif sender == 'subsample_cb' and udata['subsample']: # ie. sender == 'subsample_cb' dpg.get_value('DM')
wfall = gdata['wfall']
disp_bandwidth = gdata['extents'][3] - gdata['extents'][2] # == gdata['burstmeta']['bandwidth']
disp_duration = gdata['extents'][1] - gdata['extents'][0]
twidth = disp_duration/gdata['burstmeta']['tres_original']/2
dpg.set_value('twidth', round(twidth * (wfall.shape[1]/gdata['wfall_original'].shape[1])))
dpg.configure_item('twidth', max_value=round(wfall.shape[1]/2))
# wfall_cr = driftrate.cropwfall(wfall, twidth=dpg.get_value('twidth'))
gdata['burstmeta']['fres'] = gdata['burstmeta']['bandwidth'] / wfall.shape[0]
gdata['burstmeta']['tres'] = gdata['burstmeta']['duration']*1000 / wfall.shape[1]
dpg.set_value('Subfallshapelbl', 'Current Size: {}'.format(np.shape(wfall)))
else:
wfall = gdata['wfall']
if wfall.shape == gdata['wfall_original'].shape:
wfall = applyMasks(np.copy(gdata['wfall_original']))
if dpg.get_value('EnableSubBGBox'):
tleft, tright, _, _ = dpg.get_value('SubtractBGRegion')
timerange = [gdata['extents'][0], gdata['extents'][1]]
tleft = round(np.interp(tleft, timerange, [0, wfall.shape[1]]))
tright = round(np.interp(tright, timerange, [0, wfall.shape[1]]))
wfall = driftrate.subtractbg(wfall, tleft, tright)
else:
subsample_cb(sender, 'stop') # updates gdata['wfall']
wfall = gdata['wfall']
gdata['wfall'] = wfall
# gdata['ts'] = np.nanmean(wfall, axis=0) # time series at burstDM
# gdata['pkidx'] = np.nanargmax(gdata['ts']) # pkidx at burstDM, for displaying across DMs
plotdata_cb(sender, data, udata)
# plt.figure will fail unless it is on the main thread, and DPG runs callbacks on a seperate thread
matplotlib.use('agg') # this is a workaround to the thread issue
def getcorr2dtexture(corr, popt=None, p0=None, extents=None, slope=None, clim=None):
plt.figure(figsize=(5, 5))
plt.imshow(corr, origin='lower', interpolation='none', aspect='auto', cmap='gray',
extent=extents)
plt.clim(0, np.max(corr))
if clim and clim > 0:
plt.clim(0, clim)
if popt is not None and popt[0] > 0:
fitmap = driftrate.makeDataFitmap(popt, corr, extents)
if 1 not in fitmap.shape: # subsample ui can result in fitmaps unsuitable for countour plotting
plt.contour(fitmap, [popt[0]/4, popt[0]*0.9], colors='b', alpha=0.75, extent=extents)
if slope is not None:
print(f"{slope = } {list(popt) = }")
xo = popt[1]
x = np.array([extents[2] / slope + xo, extents[3] / slope + xo])
plt.plot(x, slope*(x-xo), 'g--')
if p0 is not None and p0[0] > 0:
fitmap = driftrate.makeDataFitmap(p0, corr, extents)
plt.contour(fitmap, [p0[0]/4, p0[0]*0.9], colors='g', alpha=0.75, origin='lower',
extent=extents)
plt.xlim(extents[:2])
plt.ylim(extents[2:])
# remove axes, whitespace
plt.gca().set_axis_off()
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
plt.margins(0,0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
fig = plt.gcf()
fig.canvas.draw()
texture = np.frombuffer(fig.canvas.tostring_argb(), dtype='uint8')
w, h = fig.get_size_inches()*fig.dpi
texture = texture.reshape(int(w*h), 4)[:, [1, 2, 3, 0]].flatten()/255 # reshape to rgba, and normalize
plt.close('all')
return texture, int(w), int(h)
def plotdata_cb(sender, data, userdata):
if not data: data = {}
if not userdata: userdata = {}
df, dt = gdata['burstmeta']['fres'], gdata['burstmeta']['tres']
lowest_freq = min(gdata['burstmeta']['dfs']) # mhz
ddm = gdata['displayedDM'] - gdata['burstDM']
burstname = dpg.get_value('burstname').replace(',', '')
popt, slope = None, None
poptcols = ['amplitude', 'xo', 'yo', 'sigmax', 'sigmay', 'angle']
if gdata['resultsdf'] is not None:
subburstdf = gdata['resultsdf'][gdata['resultsdf'].index.str.startswith(burstname)]
if not subburstdf.empty:
dmframe = subburstdf.loc[burstname].set_index('DM')
popt = dmframe.loc[np.isclose(dmframe.index, gdata['displayedDM'])].iloc[0][poptcols]
slope = dmframe.loc[np.isclose(dmframe.index, gdata['displayedDM'])]['slope (mhz/ms)'].iloc[0]
subname = None if 'resultidx' not in userdata else subburstdf.index[userdata['resultidx']]
if ('resultidx' not in userdata) or (subname == burstname):
gdata['displayedBurst'] = burstname
wfall = gdata['wfall'].copy()
wfall_cr = driftrate.cropwfall(wfall, twidth=dpg.get_value('twidth'))
wfall_dd_cr = driftrate.dedisperse(wfall_cr, ddm, lowest_freq, df, dt)
elif ('resultidx' in userdata) and (subname != burstname):
gdata['displayedBurst'] = subname
subbursts = getSubbursts()
subburst = subbursts[subname]
wfall_cr = subburst
wfall_dd_cr = driftrate.dedisperse(wfall_cr, ddm, lowest_freq, df, dt)
dmframe = subburstdf.loc[subname].set_index('DM')
popt = dmframe.loc[np.isclose(dmframe.index, gdata['displayedDM'])].iloc[0][poptcols]
slope = dmframe.loc[np.isclose(dmframe.index, gdata['displayedDM'])]['slope (mhz/ms)'].iloc[0]
tseries = np.nanmean(wfall_dd_cr, axis=0)
extents, correxts = driftrate.getExtents(wfall_dd_cr, df=df, dt=dt, lowest_freq=lowest_freq)
gdata['extents'], gdata['correxts'] = extents, correxts
dpg.set_value('twidth_ms', wfall_dd_cr.shape[1]*dt)
dpg.set_value('pkidx', int(np.nanargmax(np.nanmean(wfall_dd_cr, axis=0))))
corr = driftrate.autocorr2d(wfall_dd_cr)
## enable scale sliders
mostmin, mostmax = np.min(wfall_dd_cr), np.max(wfall_dd_cr)
mmincorr, mmaxcorr = np.min(corr), np.max(corr)
if sender not in ['wfallscale', 'corrscale']:
dpg.configure_item('wfallscale', enabled=True, min_value=mostmin, max_value=mostmax,
format='%.{}f'.format(getscale(mostmin, mostmax)+1))
dpg.configure_item('corrscale', enabled=True, min_value=mmincorr, max_value=mmaxcorr,
format='%.{}f'.format(getscale(mmincorr, mmaxcorr)+1))
smin, smax = mostmin, mostmax
scmin, scmax = mmincorr, mmaxcorr
if sender == 'wfallscale':
smin, smax = dpg.get_value('wfallscale')[:2]
if sender == 'corrscale':
scmin, scmax = dpg.get_value('corrscale')[:2]
dpg.set_value('wfallscale', [smin, smax])
dpg.set_value('corrscale', [scmin, scmax])
flatwfall = list(np.flipud(wfall_dd_cr).flatten())
if dpg.does_item_exist("Waterfall"):
dpg.delete_item('Waterfall')
before = "Region1Series" if dpg.does_item_exist("Region1Series") else 0
dpg.add_heat_series(flatwfall,
wfall_dd_cr.shape[0], wfall_dd_cr.shape[1],
tag="Waterfall", parent="freq_axis", before=before, scale_min=smin, scale_max=smax,
bounds_min=(extents[0],extents[2]), bounds_max=(extents[1], extents[3]), format='')
for axis in ['time_axis', 'freq_axis']: dpg.fit_axis_data(axis)
p0 = gdata['p0'] if dpg.get_value('EnableP0Box') else None
corr2dtexture, txwidth, txheight = getcorr2dtexture(corr, popt, p0, correxts, slope, clim=scmax)
if dpg.does_alias_exist('corr2dtexture'):
dpg.delete_item('Corr2d') # texture won't delete unless items using it are deleted too
time.sleep(2*0.017) # hack for strange race bug when deleting textures. wait two frames
dpg.delete_item('corr2dtexture')
dpg.add_static_texture(txwidth, txheight, corr2dtexture, tag='corr2dtexture', parent="TextureRegistry")
dpg.add_image_series("corr2dtexture", parent="freq_lag_axis",
bounds_min=[correxts[0],correxts[2]], bounds_max=[correxts[1], correxts[3]],
tag='Corr2d')
for axis in ['time_lag_axis', 'freq_lag_axis']: dpg.fit_axis_data(axis)
tx = np.linspace(extents[0], extents[1], num=len(tseries))
if dpg.does_alias_exist('TimeSeries'): dpg.delete_item('TimeSeries')
with dpg.theme() as theme:
with dpg.theme_component(dpg.mvLineSeries):
dpg.add_theme_color(dpg.mvPlotCol_Line, (60+19, 103+10, 164+10, 255), category=dpg.mvThemeCat_Plots)
dpg.add_line_series(tx, tseries, tag="TimeSeries", parent="tseries_int_axis")
dpg.bind_item_theme('TimeSeries', theme)
for axis in ['tseries_t_axis', 'tseries_int_axis']: dpg.fit_axis_data(axis)
def twidth_cb(_, data):
twidth = data
wfall_cr = getCurrentBurst()[4]
if round(wfall_cr.shape[1]/2) != twidth:
print(f"twidth_cb: {wfall_cr.shape = } {twidth = }")
for regid in range(1, gdata['multiburst']['numregions']):
if dpg.does_item_exist('RegionSelector{}'.format(regid)):
maxval = wfall_cr.shape[1]*gdata['burstmeta']['tres']
dpg.configure_item('Region{}'.format(regid), max_value=maxval, speed=maxval*0.005)
plotdata_cb(_, None, None)
def pkidx_cb(_, data):
enabled = dpg.get_value('pkidxbool')
if dpg.get_value('pkidxbool'):
pkidx = dpg.get_value('pkidx')
print(pkidx)
twidth_cb(_, data)
def subsample_cb(sender, data):
if sender == 'ResetSamplingBtn':
dpg.set_value('numfreqinput', gdata['wfall_original'].shape[0])
dpg.set_value('numtimeinput', gdata['wfall_original'].shape[1])
numf, numt = dpg.get_value("numfreqinput"), dpg.get_value("numtimeinput")
try:
# Make a copy of the original fall, apply the masks, then downsample
wfall = applyMasks(np.copy(gdata['wfall_original']))
if dpg.get_value('EnableSubBGBox'):
tleft, tright, _, _ = dpg.get_value('SubtractBGRegion')
timerange = [gdata['extents'][0], gdata['extents'][1]]
tleft = round(np.interp(tleft, timerange, [0, wfall.shape[1]]))
tright = round(np.interp(tright, timerange, [0, wfall.shape[1]]))
wfall = driftrate.subtractbg(wfall, tleft, tright)
subfall = driftrate.subsample(wfall, numf, numt)
except (ValueError, ZeroDivisionError) as e:
error_log_cb('subsample_cb', (numf, numt, e))
else:
gdata['wfall'] = subfall
log_cb('subsample_cb', (numf, numt))
if data != 'stop':
updatedata_cb('subsample_cb', data, {'subsample': True})
return subfall
def directory_cb(sender, data):
path = data['file_path_name']
dpg.set_value('Dirtext', 'Selected: {}'.format(path))
dpg.configure_item('Filter', enabled=True)
dpg.configure_item('clearfilter', enabled=True)
files = sorted(glob.glob(path+'/{}'.format(gdata['globfilter'])))
dpg.configure_item('burstselect', items=[os.path.basename(x) for x in files])
gdata['datadir'] = path
gdata['files'] = files
log_cb(sender, path)
def filter_cb(sender, data):
globfilter = dpg.get_value('Filter')
if globfilter == '':
globfilter = '*'
gdata['globfilter'] = globfilter
directory_cb(sender, [gdata['datadir']])
def clearfilter_cb(s, d):
dpg.set_value('Filter', '')
filter_cb(s, d)
def burstselect_cb(sender, data):
filename = dpg.get_value('burstselect')
filename = gdata['files'][[os.path.basename(f) for f in gdata['files']].index(filename)]
updatedata_cb(sender, data, {'filename': filename})
log_cb(sender, f'Opening file {filename}')
def exportmask_cb(sender, data):
datestr = datetime.now().strftime('%b%d')
filename = f'masks_{datestr}.npy'
np.save(filename, [gdata['masks']])
dpg.set_value('maskstatus', f'saved: {filename}')
print(f'Saved {filename}')
def importmask_cb(sender, data):
if data is None:
return
if type(data) == str:
filename = data
filename = data['file_path_name']
log_cb(sender, 'mask selected: {}'.format(data))
if filename.split('.')[-1] == 'npy':
masks = np.load(filename, allow_pickle=True)[0]
if type(masks) == dict:
gdata['masks'].update(masks)
updatedata_cb(sender, {'filename': gdata['currfile']}, None)
masktable_cb(sender, None)
else:
error_log_cb(sender, 'invalid mask dictionary selected.')
else:
error_log_cb(sender, 'invalid mask file selected.')
def removemask_cb(sender, data, userdata):
mask = userdata
if mask in gdata['masks'][gdata['currfile']]['chans']:
gdata['masks'][gdata['currfile']]['chans'].remove(mask)
logwin.log_debug('removing {} from {} mask'.format(mask, gdata['currfile']))
updatedata_cb(sender, {'keepview': True}, None)
masktable_cb(sender, None)
def masktable_cb(sender, data):
dpg.delete_item('Masktable')
tableheight = 125
with dpg.table(tag='Masktable', header_row=True, height=tableheight,
borders_innerV=True, borders_outerH=True, borders_outerV=True,
policy=dpg.mvTable_SizingFixedFit,
scrollX=True, parent='Masking', before='MaskRangeGroup'):
shortnames = [s.split('.')[0][-8:] for s in gdata['masks'].keys()]
numcols = 0
for key, masks in gdata['masks'].items():
numcols = max(numcols, len(masks['chans']))
for col in range(0, 1+numcols): # enough cols for the burst name and masks
if col == 0: dpg.add_table_column(label="Burst")
if col == 1: dpg.add_table_column(label="chan#:")
if col > 1: dpg.add_table_column()
for (key, masks), name in zip(gdata['masks'].items(), shortnames):
with dpg.table_row():
dpg.add_text(name)
for chanmask in masks['chans']:
dpg.add_selectable(label=chanmask, callback=removemask_cb, user_data=chanmask)
def sksgmask_cb(sender, data):
items = ['SKSGSigmaInput','SKSGWindowInput']
if sender == 'EnableSKSGMaskBox':
toggle_config(sender, {'kwargs': ['enabled'], 'items': items})
sigma, window = dpg.get_value('SKSGSigmaInput'), dpg.get_value('SKSGWindowInput')
df, dt = gdata['burstmeta']['fres'], gdata['burstmeta']['tres']
sksgmask = sk_sg_filter(
data=gdata['wfall_original'].copy().T,
foff=df,
tsamp=dt/1000,
spectral_kurtosis_sigma=sigma,
savgol_frequency_window=window,
savgol_sigma=sigma,
)
gdata['sksgmask'] = sksgmask
updatedata_cb(sender, {'keepview': True}, None)
def resulttable_cb(sender, data, userdata):
displayresult_cb('User', data, {
'burstname': userdata[0],
'trialDM': userdata[1]
})
def updateResultTable(resultsdf):
if 'slope (mhz/ms)' in resultsdf.columns:
resultsdf = driftlaw.computeModelDetails(resultsdf)
dpg.delete_item('Resulttable')
# subset of driftrate.columns:
columns = ['name', 'DM', 'amplitude', 'slope (mhz/ms)', 'tau_w_ms', 'angle', 'center_f']
# columns = ['name', 'DM', 'amplitude', 'tsamp_width','subbg_start (ms)', 'subbg_end (ms)']
with dpg.table(tag='Resulttable', header_row=True, height=225, parent='ResultsGroup',
borders_innerV=True, borders_outerH=True, borders_outerV=True,
scrollY=True,
resizable=True,
policy=dpg.mvTable_SizingStretchSame,
row_background=True,
reorderable=True):
for col in columns:
dpg.add_table_column(label=col)
# [burstname, trialDM, center_f, slope, slope_err, theta, red_chisq], popt, perr, [fres_MHz, tres_ms/1000]
for burstname, rowdata in resultsdf.iterrows():
trialDM = rowdata['DM']
with dpg.table_row():
# adding a component automatically moves to the next cell
dpg.add_selectable(label=burstname, height=20, span_columns=True,
callback=resulttable_cb, user_data=(burstname, trialDM))
for col in columns[1:]:
dpg.add_text(f"{rowdata[col]}")
def mousemask_cb(sender, data):
isOnWaterfall = dpg.is_item_hovered('WaterfallPlot')
if isOnWaterfall:
tchan, fchan = dpg.get_plot_mouse_pos()
rawmask = round(fchan)
# map frequency (rawmask) to channel number
spectralrange = [gdata['extents'][2], gdata['extents'][3]]
mask = np.interp(rawmask, spectralrange, [0, gdata['wfall_original'].shape[0]])
mask = int(mask)
if mask not in gdata['masks'][gdata['currfile']]['chans']:
gdata['masks'][gdata['currfile']]['chans'].append(mask)
updatedata_cb(sender, {'keepview': True}, None)
masktable_cb(sender, None)
log_cb('mousemask_cb ', [[tchan, fchan], isOnWaterfall])
else:
return
def dmrange_cb(sender, data):
dmrange = dpg.get_value('dmrange')
dmrange = np.round(dmrange, 4) # dpg.get_value introduces rounding errors
numtrials = dpg.get_value('numtrials')
dmstep = round(dpg.get_value('dmstep'), 3)
burstDM = gdata['burstDM']
if dmrange[1] < dmrange[0]:
dmrange.sort()
dpg.set_value('dmrange', dmrange)
if not (dmrange[0] < burstDM < dmrange[1]):
dpg.configure_item('DMWarning', show=True)
else:
dpg.configure_item('DMWarning', show=False)
if sender == 'dmstep' or sender == 'user':
numtrials = round((dmrange[1] - dmrange[0])/dmstep)+1
dpg.set_value('numtrials', numtrials)
elif sender == 'numtrials':
dmstep = round((dmrange[1] - dmrange[0])/numtrials, 3)
dpg.set_value('dmstep', dmstep)
gdata['trialDMs'] = np.arange(dmrange[0], dmrange[1]+dmstep, step=dmstep)
def getCurrentBurst():
# Return the currently loaded waterfall at its burst DM
burstname = dpg.get_value('burstname').replace(',', '')
df, dt = gdata['burstmeta']['fres'], gdata['burstmeta']['tres']
lowest_freq = min(gdata['burstmeta']['dfs']) # mhz
wfall = gdata['wfall'].copy()
# pkidx = dpg.get_value('pkidx') if dpg.get_value('pkidxbool') else None
wfall_cr = driftrate.cropwfall(wfall, twidth=dpg.get_value('twidth'), pkidx=None)
burstDM = gdata['burstDM']
return burstname, df, dt, lowest_freq, wfall_cr, burstDM
def getMeasurementInfo(wfall_cr):
tsamp_width = dpg.get_value('twidth')
downf = gdata['wfall_original'].shape[0] / gdata['wfall'].shape[0]
downt = gdata['wfall_original'].shape[1] / gdata['wfall'].shape[1]
fchans, tchans = wfall_cr.shape
subbgstart, subbgend, sksigma, skwindow = None, None, None, None
if dpg.get_value('EnableSubBGBox'):
subbgstart, subbgend, _, _= dpg.get_value('SubtractBGRegion')
if dpg.get_value('EnableSKSGMaskBox'):
sksigma, skwindow = dpg.get_value('SKSGSigmaInput'), dpg.get_value('SKSGWindowInput')
cols = ['downf', 'downt', 'fchans', 'tchans', 'tsamp_width','subbg_start (ms)', 'subbg_end (ms)','sksigma','skwindow']
row = [downf, downt, fchans, tchans, tsamp_width, subbgstart, subbgend, sksigma, skwindow]
# TODO: raw shape, mask info
regions = getAllRegions() # is empty when regions is disabled
for regname, region in regions.items():
if regname == 'background':
cols.append('background')
row.append(region[1])
else:
cols.append(f'regstart_{regname}')
row.append(region[0])
cols.append(f'regend_{regname}')
row.append(region[1])
return cols, row
def progress_cb(val, data):
dpg.set_value('SlopeStatus', val)
overlay = dpg.get_item_configuration("SlopeStatus")['overlay'].split(' (')[0]
dpg.configure_item('SlopeStatus', overlay=f"{overlay} ({data})")
def slope_cb(sender, data, userdata):
burstname, df, dt, lowest_freq, wfall_cr, burstDM = getCurrentBurst()
if userdata is not None:
dpg.configure_item('SlopeStatus', overlay='Status: Doing second pass...')
p0 = userdata['p0']
trialDMs = userdata['badfitDMs']
else:
dpg.configure_item('SlopeStatus', overlay='Status: Calculating...')
p0 = [] if not gdata['p0'] else gdata['p0']
trialDMs = np.unique(np.round(np.append(gdata['trialDMs'], burstDM), decimals=5))
if not dpg.get_value('RepeatBox') and gdata['resultsdf'] is not None:
trialDMs = list(set(gdata['resultsdf'].loc[burstname]['DM']) ^ set(trialDMs))
# remove DMs that are in gdata['resultsdf'] from trialDMs
progress = io.StringIO()
results, burstdf = driftrate.processDMRange(burstname, wfall_cr, burstDM, trialDMs, df, dt,
lowest_freq, p0,
tqdmout=None, progress_cb=progress_cb)
if gdata['multiburst']['enabled']:
subbursts, corrsigma, wfallsigma = getSubbursts(getsigmas=True)
subresults, subdf = [], pd.DataFrame()
for subname, subburst in subbursts.items():
print('processing {}'.format(subname))
ret, retdf = driftrate.processDMRange(subname, subburst, burstDM, trialDMs, df, dt,
lowest_freq, corrsigma=corrsigma, wfallsigma=wfallsigma)
subresults.append(ret)
subdf = pd.concat([subdf, retdf])
burstdf = pd.concat([burstdf, subdf])
# Do a second pass using the best p0 just found
p0 = getOptimalFit(burstdf)
if userdata is None:
return slope_cb(sender, data, {'p0' : p0, 'badfitDMs': trialDMs})
# Add measurement info to row (things needed to reproduce/reload the measurement)
cols, row = getMeasurementInfo(wfall_cr)
print('measurement info >>', cols, row)
burstdf[cols] = row
# Save results
if gdata['resultsdf'] is None:
gdata['resultsdf'] = burstdf
else:
# overwrite if there are already results while adding new results
gdata['resultsdf'] = (pd.concat([burstdf, gdata['resultsdf']]) # add new and updated measurements
.reset_index().drop_duplicates(['name', 'DM']) # drop old measurements
.set_index('name').sort_values(['name', 'DM'])) # sort table
backupresults()
print(gdata['resultsdf'])
burstdf = gdata['resultsdf'][gdata['resultsdf'].index.str.startswith(burstname)]
gdata['burstdf'] = burstdf
dpg.configure_item('SlopeStatus', overlay='Status: Done.')
dpg.set_value('NumMeasurementsText', "# of Measurements for this burst: {}".format(len(burstdf)))
dpg.set_value('TotalNumMeasurementsText', "Total # of Measurements: {}".format(len(gdata['resultsdf'])))
dpg.configure_item('PrevDM', enabled=True)
dpg.configure_item('NextDM', enabled=True)
dpg.configure_item('ExportCSVBtn', enabled=True)
dpg.configure_item('ExportPDFBtn', enabled=True)
dpg.configure_item('EnableP0Box', enabled=True)
initializeP0Group()
updateResultTable(burstdf)
plotdata_cb(sender, data, userdata)
def redodm_cb(sender, data, userdata):
p0 = gdata['p0']
useForAll = dpg.get_value('P0AllDMsBox')
burstname, df, dt, lowest_freq, wfall_cr, burstDM = getCurrentBurst()
displayedname = gdata['displayedBurst']
corrsigma, wfallsigma = None, None
if gdata['multiburst']['enabled'] and displayedname != burstname:
subbursts, corrsigma, wfallsigma = getSubbursts(getsigmas=True)
wfall_cr = subbursts[displayedname]
print('redoing ', displayedname, gdata['displayedDM'], f'with {df = } {dt =} {lowest_freq = }')
result, burstdf = driftrate.processDMRange(
displayedname, wfall_cr, burstDM, [float(gdata['displayedDM'])],
df, dt, lowest_freq, p0=p0, corrsigma=corrsigma, wfallsigma=wfallsigma
)
print(f'{result = }')
cols, row = getMeasurementInfo(wfall_cr)
burstdf[cols] = row
df = gdata['resultsdf']
df[(df.index == displayedname) & (np.isclose(df['DM'], gdata['displayedDM']))] = burstdf
gdata['resultsdf'] = df
gdata['burstdf'] = gdata['resultsdf'].loc[burstname]
dispdm = gdata['displayedDM']
if gdata['multiburst']['enabled']:
subburstdf = gdata['resultsdf'][gdata['resultsdf'].index.str.startswith(burstname)]
updateResultTable(subburstdf)
subburstdf = subburstdf.reset_index()
resultidx = subburstdf[(subburstdf.name == displayedname) & (np.isclose(subburstdf.DM, dispdm))].index[0]
if userdata is None:
userdata = {}
userdata['resultidx'] = resultidx
else:
updateResultTable(gdata['burstdf'])
backupresults()
plotdata_cb(sender, data, userdata)
# if useForAll programatically click "next DM" then repeat this block
# that will preserve the behaviour where regions only need to be read at the start
if useForAll:
tabledf = gdata['resultsdf'][gdata['resultsdf'].index.str.startswith(burstname)].reset_index()
redoidx = tabledf[(tabledf.name == gdata['displayedBurst']) & (np.isclose(tabledf.DM, dispdm))].index[0]
maxidx = len(tabledf)
if redoidx+1 < maxidx:
displayresult_cb('NextDM', None, None)
redodm_cb(sender, None, None)
def getAllRegions():
ret = {}
suffixes = itertools.cycle(subburst_suffixes)
if gdata['multiburst']['enabled']:
for regid in range(1, gdata['multiburst']['numregions']):
region = dpg.get_value('Region{}'.format(regid))[:2]
regiontype = dpg.get_value('RegionType{}'.format(regid))
if regiontype == "Burst":
suffix = next(suffixes)
ret[suffix] = region
else:
ret['background'] = region
return ret
def loadresults_cb(sender, data):
if data is None:
return
if type(data) == str:
resultfile = data
resultsfile = data['file_path_name']
resultsdf = pd.read_csv(resultsfile).set_index('name')
gdata['resultsdf'] = resultsdf
regionsobj = driftrate.readRegions(resultsdf)
gdata['multiburst']['regions'] = regionsobj
s = data['file_path_name'] # extract prefix from loaded file
dpg.set_value('ExportPrefix', s[:s.index(s.split('_')[-2])-1].split('/')[-1])
burstselect_cb(sender, data)
def exportresults_cb(sender, data):
global exportPDF
resultsdf = gdata['resultsdf']
df = driftlaw.computeModelDetails(resultsdf)
datestr = datetime.now().strftime('%b%d')
prefix = dpg.get_value('ExportPrefix')
filename = f'{prefix}_{len(df.index)}rows_{datestr}.csv'
if sender == 'ExportCSVBtn' or sender == 'ExportPDFBtn':
dpg.configure_item('ExportCSVText', show=True)
try:
df.to_csv(filename)
dpg.set_value('ExportCSVText', 'Saved to {}'.format(filename))
except PermissionError as e:
dpg.set_value('ExportCSVText', 'Permission Denied')
if sender == "ExportPDFBtn":
exportPDF = True # callback thread lets main thread know to run matplotlib on next frame
elif sender == 'MainThread':
success = driftrate.plotResults(filename, datafiles=gdata['files'], masks=gdata['masks'])
if success:
dpg.set_value('ExportPDFText', f'Saved to {filename.split(".")[0]+".pdf"}')
else:
dpg.set_value('ExportPDFText', f'Permission Denied')
def backupresults():
resultsdf = gdata['resultsdf']
df = driftlaw.computeModelDetails(resultsdf)
datestr = datetime.now().strftime('%b%d')
prefix = 'backup'
if not os.path.isdir('backups'):
os.makedirs('backups', exist_ok=True)
filename = 'backups/{}_results_{}.csv'.format(prefix, datestr)
df.to_csv(filename)
def displayresult_cb(sender, data, userdata):
burstDM = gdata['burstDM']
dmlist = list(gdata['burstdf'].loc[gdata['burstdf'].index[0]]['DM'])
if userdata is None:
userdata = {}
subname, dispdm = gdata['displayedBurst'], gdata['displayedDM']
else:
subname, dispdm = userdata['burstname'], userdata['trialDM']
burstname = dpg.get_value('burstname').replace(',', '')
subburstdf = gdata['resultsdf'][gdata['resultsdf'].index.str.startswith(burstname)].reset_index()
resultidx = subburstdf[(subburstdf.name == subname) & (np.isclose(subburstdf.DM, dispdm))].index[0]
subburstdf = subburstdf.set_index('name')
if sender == 'NextDM':
resultidx = resultidx + 1
if not (resultidx < len(subburstdf)):
resultidx = 0
elif sender == 'PrevDM':
resultidx = resultidx - 1
userdata['resultidx'] = resultidx
subname = subburstdf.index[resultidx]
gdata['displayedDM'] = dmlist[resultidx % len(dmlist)]
dpg.set_value('dmdisplayed', str(round(gdata['displayedDM'], getscale(gdata['displayedDM']))))
dpg.set_value('burstdisplayed', subname)
plotdata_cb(sender, data, userdata)
def confirmpopup(data, cb):
with popup("main", "ConfirmDelete", modal=True):
add_text("All those beautiful results will be deleted.\nThis operation cannot be undone!")
add_button("OK", width=75,
callback=lambda s, d: cb('ConfirmDelete', data)
)
add_same_line()
add_button("Cancel", width=75,
callback=lambda s, d: cb("ConfirmDelete", data)
)
def deleteresults_cb(sender, data):
# TODO: implement
burstname = dpg.get_value('burstname').replace(',', '')
if sender == 'ConfirmDelete':
if data == 'burst':
df = gdata['resultsdf'].loc[~burstname] # use df.drop see slope_cb
elif data == 'all':
gdata['resultsdf'] = None
else:
confirmpopup(data, deleteresults_cb)
print(sender, data)
def getOptimalFit(df):
params = ['amplitude', 'xo', 'yo', 'sigmax', 'sigmay', 'angle']
bestrow = df[df.red_chisq == df.red_chisq.min()]
if len(bestrow) > 1:
bestrow = bestrow.head(1)
p0 = [float(bestrow[param]) for param in params]
return p0
def initializeP0Group():
p0 = []
burstname = dpg.get_value('burstname').replace(',', '')
subburstdf = gdata['resultsdf'][gdata['resultsdf'].index.str.startswith(burstname)]
wfall_cr = getCurrentBurst()[-2]
p0 = getOptimalFit(subburstdf)
p0f = [p0i for p0i in p0] # why?
if p0f[0] < 0:
p0f = [-p0fi if p0fi < 0 else p0fi for p0fi in p0f]
gdata['p0'] = p0
dpg.set_value("AmplitudeDrag", p0f[0])
dpg.set_value("AngleDrag", p0f[5])
# solution will always be near the center
dpg.set_value("x0y0Drag", [0.01, 0.01]) # dpg glitches if you use 0,0
dpg.set_value("SigmaXYDrag", [p0f[3], p0f[4]])
for item in ['AmplitudeDrag', 'AngleDrag', 'x0y0Drag', 'SigmaXYDrag']:
val = dpg.get_value(item)
if type(val) == list:
val = val[0]
dpg.configure_item(item, speed=1/10**getscale(val), format='%.{}f'.format(getscale(val)+1))
dpg.configure_item('AngleDrag', speed=0.01, format='%.8f')
return p0
def enablep0_cb(sender, data, userdata):
toggle_config(sender, userdata)
updatep0_cb(sender, data, userdata)
def updatep0_cb(sender, data, userdata):
if not userdata: userdata = {}
p0 = []
# get resultidx
subname, dispdm = gdata['displayedBurst'], gdata['displayedDM']
burstname = dpg.get_value('burstname').replace(',', '')
subburstdf = gdata['resultsdf'][gdata['resultsdf'].index.str.startswith(burstname)].reset_index()
resultidx = subburstdf[(subburstdf.name == subname) & (np.isclose(subburstdf.DM, dispdm))].index[0]
if gdata['multiburst']['enabled']:
userdata['resultidx'] = resultidx
for item in ['AmplitudeDrag', 'x0y0Drag', 'SigmaXYDrag', 'AngleDrag']:
val = dpg.get_value(item)
if type(val) == list: # x0y0Drag or SigmaXYDrag
p0 = p0 + val[:2]
else:
p0.append(val)
gdata['p0'] = p0
print(f"{sender = }, {data = }, {userdata = }")
plotdata_cb(sender, data, userdata)
def enablesplitting_cb(sender, data):
items = ['Region', 'RegionType', 'RemoveRegionBtn', 'AddRegionBtn']
gdata['multiburst']['enabled'] = dpg.get_value(sender)
items = items.copy()
items.remove('AddRegionBtn')
toggle_config(sender, {'kwargs': ['enabled'], 'items': ['AddRegionBtn']})
for regid in range(1, gdata['multiburst']['numregions']):
if dpg.does_item_exist('RegionSelector{}'.format(regid)):
itemsid = list(map(lambda item: item+'{}'.format(regid), items))
toggle_config(sender, {'kwargs': ['enabled'], 'items': itemsid})
if gdata['multiburst']['enabled']:
drawregion_cb([regid], None)
else:
seriesnames = [f'Region{regid}Series', f'Region{regid}TSeries']
for axis, seriesname in zip(['freq_axis', 'tseries_int_axis'], seriesnames):
dpg.delete_item(seriesname)