forked from zhuww/ubc_AI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpfdviewer.py
executable file
·3149 lines (2816 loc) · 125 KB
/
pfdviewer.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
"""
Aaron Berndsen: A GUI to view and rank PRESTO candidates.
Requires a GUI input file with (at least) one column of the
candidate filename/location (can be .pfd, .ps, or .png).
Subsequent columns are the AI and user votes.
pfd: use of these files requires PRESTO's show_pfd command
We search for it, but you may hard-code the location below
Allows for AI_view, which downsamples and pca's the data
to the same form that typical AI algorithms use.
ps: requires either PythonMagick, or system calls to ImageMagick
png: quick to display
"""
import atexit
import cPickle
import datetime
import fractions
import glob
import numpy as np
import os, pwd
import shutil
import subprocess
import sys
import tempfile
import ubc_AI
from os.path import abspath, basename, dirname, exists
from optparse import OptionParser
from gi.repository import Gtk, Gdk
import pylab as plt
#next taken from ubc_AI.training and ubc_AI.samples
from ubc_AI.training import pfddata
from ubc_AI.data import pfdreader
from sklearn.decomposition import RandomizedPCA as PCA
import ubc_AI.known_pulsars as known_pulsars
#check for ps --> png conversion utilities
try:
from PythonMagick import Image
pyimage = True
except ImportError:
pyimage = False
if not pyimage:
conv = subprocess.call(['which','convert'], stdout=open('/dev/null','w'))
if conv == 1:
print "pfdviewer requires imagemagik's convert utility"
print "or, PythonMagick. Exiting..."
sys.exit()
#PRESTO's show_pfd command:
show_pfd = False
for p in os.environ.get('PATH').split(':'):
cmd = '%s/show_pfd' % p
if exists(cmd):
show_pfd = cmd
break
pdmp = False
for p in os.environ.get('PATH').split(':'):
cmd = '%s/pdmp' % p
if exists(cmd):
pdmp = cmd
break
if not show_pfd:
print "\tCouldn't find PRESTO's show_pfd executable"
print "\t This will limit functionality"
try:
from ubc_AI.prepfold import pfd as PFD
except(ImportError):
print "please add PRESTO's modules to your python path for more functionality"
PFD = None
#do not allow active voter = sort column. warn once
have_warned = False
#iter on each "n". auto-save after every 10
cand_vote = 0
#store AI_view png's in a temporary dir
tempdir = tempfile.mkdtemp(prefix='AIview_')
atexit.register(lambda: shutil.rmtree(tempdir, ignore_errors=True))
bdir = '/'.join(__file__.split('/')[:-1])
AI_path = AI_PATH = '/'.join(ubc_AI.__file__.split('/')[:-1])
class MainFrameGTK(Gtk.Window):
"""This is the Main Frame for the GTK application"""
def __init__(self, data=None, tmpAI=None, spplot=False):
Gtk.Window.__init__(self, title='pfd viewer')
if AI_path:
self.gladefile = "%s/pfdviewer.glade" % AI_path
else:
self.gladefile = "pfdviewer.glade"
self.builder = Gtk.Builder()
self.builder.add_from_file(self.gladefile)
## glade-related objects
self.voterbox = self.builder.get_object("voterbox")
self.pfdwin = self.builder.get_object("pfdwin")
self.builder.connect_signals(self)
self.pfdwin.show_all()
self.listwin = self.builder.get_object('listwin')
self.listwin.show_all()
self.statusbar = self.builder.get_object('statusbar')
self.pfdtree = self.builder.get_object('pfdtree')
self.pfdstore = self.builder.get_object('pfdstore')
self.image = self.builder.get_object('image')
self.image_disp = self.builder.get_object('image_disp')
self.autosave = self.builder.get_object('autosave')
self.pfdtree.connect("cursor-changed",self.on_pfdtree_select_row)
#info window stuff
self.info_win = self.builder.get_object('info_win')
self.info_win.set_deletable(False)
self.info_win.connect('delete-event', lambda w, e: w.hide() or True)
self.tmpAI_exp = self.builder.get_object('tmpAI_expander')
self.AIview_exp = self.builder.get_object('AIview_expander')
#palfa query window
self.palfaqry_tog = self.builder.get_object('PALFAqry')
self.palfaqry_win = self.builder.get_object('PALFAqry_win')
self.palfaqry_win.set_deletable(False)
self.palfaqry_win.connect('delete-event', lambda w, e: w.hide() or True)
self.palfaqrybuf = self.builder.get_object('qry_view').get_buffer()
self.palfaqry_subfile = self.builder.get_object('qry_subfile')
self.palfa_qu = self.builder.get_object('qry_uname')
self.palfa_qp = self.builder.get_object('qry_pwd')
self.palfa_sampleqry = self.builder.get_object('sample_qry')
self.palfa_sampleqry.set_active(0)
self.qry_dwnld = self.builder.get_object('qry_dwnld')
#use this to keep track of Query candidates
self.qry_results = {}
self.qry_saveloc = './'
self.qry_savefil = '%s-qry.npy' % datetime.datetime.now().strftime('%Y_%m_%d')
self.data_fromQry = False
#keep query in separate location, moving to self.qry_saveloc on save
self.qrybasedir = '/dev/shm/pfdvwr.%s' % pwd.getpwuid(os.getuid())[0]
#os.getlogin()
#aiview window
self.aiview_tog = self.builder.get_object('aiview')
self.pmatchwin_tog = self.builder.get_object('pmatchwin_tog')
self.col_options = []
self.col1 = self.builder.get_object('col1')
self.col2 = self.builder.get_object('col2')
self.active_col1 = None
self.active_col2 = None
self.view_limit = self.builder.get_object('view_limit')
self.limit_toggle = self.builder.get_object('limit_toggle')
self.verbose_match = self.builder.get_object('verbose_match')
self.matchsep = self.builder.get_object('matchsep')
#advance to next non-voted candidate, or next in list.
self.advance_next = self.builder.get_object('advance_next')
self.advance_col = self.builder.get_object('advance_col')
self.DM_limit_toggle = self.builder.get_object('DM_limit_toggle')
self.DM_limit = self.builder.get_object('DM_limit_val')
#feature-labelling stuff
self.builder.get_object('FL_grid').hide()
self.fl_voting_tog = self.builder.get_object('FL_voting_tog')
self.FL_text = self.builder.get_object('FL_label')
#when feature-labeling, do 5 votes.
self.fl_nvote = 0
#tmpAI window
self.tmpAI_win = self.builder.get_object('tmpAI_votemat')
self.tmpAI_overall = self.builder.get_object('overall_vote')
self.tmpAI_phasebins = self.builder.get_object('phasebins_vote')
self.tmpAI_intervals = self.builder.get_object('intervals_vote')
self.tmpAI_subbands = self.builder.get_object('subbands_vote')
self.tmpAI_DMbins = self.builder.get_object('DMbins_vote')
self.tmpAI_tog = self.builder.get_object('tmpAI_tog')
self.tmpAI_lab = self.builder.get_object('tmpAI_lab')
if tmpAI is not None:
self.tmpAI = cPickle.load(open(tmpAI,'r'))
self.tmpAI_tog.set_active(1)
self.info_win.show_all()
self.tmpAI_exp.set_expanded(1)
#hack to get the checkmark "on", and preserve the tmpAI
self.tmpAI = cPickle.load(open(tmpAI,'r'))
# self.info_win.resize()
else:
self.tmpAI = None
self.tmpAI_tog.set_active(0)
if not self.aiview_tog.get_active():
#then both 'info' views are off, so hide window
self.info_win.hide()
#keep track of seen/voted pfd's so things are quicker
self.tmpAI_avgs= {}
#pulsar-matching stuff
self.pmatch_win = self.builder.get_object('pmatch_win')
self.pmatch_tree = self.builder.get_object('pmatch_tree')
self.pmatch_store = self.builder.get_object('pmatch_store')
self.pmatch_lab = self.builder.get_object('pmatch_lab')
self.pmatch_tree.connect("cursor-changed", self.on_pmatch_select_row)
self.pmatch_tree.connect("row-activated", self.on_pmatch_row_activated)
self.pmatch_tree.hide()
self.pmatch_lab.hide()
#allow Ctrl+s like key-functions
self.modifier = None
#where are pfd/png/ps files stored
self.basedir = '.'
#define the list columns
for vi, v in enumerate(['n','fname','col1_prob', 'col2_prob']):
#only show two columns at a time
cell = Gtk.CellRendererText()
col = Gtk.TreeViewColumn(v, cell, text=vi)
col.set_property("alignment", 0.5)
col.set_sort_indicator(True)
col.set_sort_column_id(vi)
if v == 'fname':
expcol = col
col.set_expand(True)
col.set_max_width(180)
elif v == 'n':
col.set_expand(False)
col.set_max_width(42)
col.set_sort_indicator(False)
else:
col.set_expand(False)
col.set_max_width(80)
self.pfdtree.append_column(col)
self.pfdtree.set_expander_column(expcol)
#default sort on fname, later changed if number of voters > 1
self.pfdstore.set_sort_column_id(1,1)#arg1=fname, arg2=sort/revsort
# set up the matching-pulsar tree
self.pmatch_tree_init()
## data-analysis related objects
self.voters = []
self.savefile = None
self.loadfile = None
self.knownpulsars = {}
#ATNF, PALFA and GBNCC list of known pulsars
if exists('%s/known_pulsars.pkl' % AI_path):
self.knownpulsars = cPickle.load(open('%s/known_pulsars.pkl' % AI_path))
elif exists('known_pulsars.pkl'):
self.knownpulsars = cPickle.load(open('known_pulsars.pkl'))
else:
self.knownpulsars = known_pulsars.get_allpulsars()
#if we were passed a data file, read it in
if data != None:
self.on_open(event='load', fin=data)
else:
self.data = None
# start with default and '<new>' voters
if self.data != None:
self.voters = [name for name in self.data.dtype.names[1:] \
if not name.endswith('_FL')]
if len(self.voters) > 1:
self.pfdstore.set_sort_column_id(2,1)#arg1=fname, arg2=sort/revsort
# self.voters = list(self.data.dtype.names[1:]) #strip off 'fname'
for v in self.voters:
if v not in self.col_options:
self.col_options.append(v)
self.col1.append_text(v)
self.col2.append_text(v)
#<new> is a special case used to add new voters
if '<new>' not in self.voters:
self.voters.insert(0,'<new>')
#display first voter column from input data, making it "active"
self.active_col1 = self.col_options.index(self.voters[1])
self.col1.set_active(self.active_col1)
#make active voter the first non-"AI" and non-"_FL" column
names = [name for name in self.data.dtype.names[1:] \
if not name.endswith('_FL')]
av = np.where( np.array(names != 'AI'))[0]
# av = np.where(np.array(self.data.dtype.names[1:] != 'AI'))[0]
if len(av) == 0:
self.active_voter = 1
self.statusbar.push(0, 'Warning, voting overwrites AI votes')
else:
name = names[av[0]]
idx = self.voters.index(name)
if 'AI' in self.voters:
idx += 1
self.active_voter = idx
self.voterbox.set_active(idx)
#set up the second column if there are multiple "voters"
if len(self.voters) > 2:
# self.active_voter = 1
# self.voterbox.set_active(self.active_voter)
if 'AI' in self.voters:
self.active_col2 = self.col_options.index(self.voters[self.active_voter])
self.col2.set_active(self.active_col2)
else:
self.active_col2 = self.col_options.index(self.voters[self.active_voter+1])
self.col2.set_active(self.active_col2)
self.dataload_update()
#put cursor on first col. if there is data
self.pfdtree.set_cursor(0)
else:
self.statusbar.push(0,'Please load a data file')
self.voters = []
self.active_voter = None
#keep track of the AI view files created (so we don't need to generate them)
self.AIviewfiles = {}
############################
## data-manipulation actions
def on_sep_change(self, widget):
"""
respond to changes in the pulsar matching separation
"""
self.find_matches()
def on_viewlimit_toggled(self, widget):
self.on_view_limit_changed( widget)
def on_DM_limit_toggled(self, widget):
self.on_DM_limit_val_changed( widget)
def on_verbose_match(self, widget):
self.find_matches()
def on_view_limit_changed(self, widget):
"""
change what is displayed when the view limit is changed
"""
col1 = self.col1.get_active_text()
col2 = self.col2.get_active_text()
idx1 = self.col_options.index(col1)
if col2 == None:
col2 = col1
self.col2.set_active(idx1)
idx2 = self.col_options.index(col2)
limtog = self.limit_toggle.get_active()
lim = self.view_limit.get_value()
#turn off the model first for speed-up
self.pfdtree.set_model(None)
self.pfdstore.clear()
if idx1 != idx2:
data = self.data[['fname',col1,col2]]
if data.ndim == 0:
dtyp = [(name, self.data.dtype[name].str) \
for name in ['fname', col1, col2]]
data = np.array([data], dtype=dtyp)
data.sort(order=[col1,'fname'])
limidx = data[col1] >= lim - 1e-5
if limidx.size > 1 and np.any(limidx) and limtog:
data = data[limidx]
self.statusbar.push(0,'Showing %s/%s candidates above %s' %
(limidx.sum(),len(limidx),lim))
else:
self.statusbar.push(0,'No %s candidates > %s. Showing all' % (col1, lim))
for vi, v in enumerate(data[::-1]):
d = (vi,) + v.tolist()
self.pfdstore.append(d)
else:
data = self.data[['fname',col1]]
if data.ndim == 0:
dtyp = [(name, self.data.dtype[name].str) \
for name in ['fname', col1]]
data = np.array([data], dtype=dtyp)
data.sort(order=[col1,'fname'])
limidx = data[col1] >= lim - 1e-5
if limidx.size > 1 and np.any(limidx) and limtog:
data = data[limidx]
self.statusbar.push(0,'Showing %s/%s candidates above %s' %
(limidx.sum(),len(limidx),lim))
else:
self.statusbar.push(0,'No %s candidates > %s. Showing all' % (col1, lim))
for vi, v in enumerate(data[::-1]):
v0, v1 = v
self.pfdstore.append((vi,v0,float(v1),float(v1)))
self.pfdtree.set_model(self.pfdstore)
self.find_matches()
def on_DM_limit_val_changed(self, widget):
"""
set limit on the DM of candidadtes to display
"""
limtog = self.DM_limit_toggle.get_active()
try:
lim = float(self.DM_limit.get_text())
except:
return
if not limtog:
self.on_view_limit_changed(widget)
return
col1 = self.col1.get_active_text()
col2 = self.col2.get_active_text()
idx1 = self.col_options.index(col1)
if col2 == None:
col2 = col1
self.col2.set_active(idx1)
idx2 = self.col_options.index(col2)
if len(self.pfdstore) == 0:return None #do nothing
#if idx1 != idx2:
#dtyp = [('n', '<i8')] + [(name, self.data.dtype[name].str) for name in ['fname', col1, col2]]
#else:
#dtyp = [('n', '<i8')] + [(name, self.data.dtype[name].str) for name in ['fname', col1]]
removecount = 0
for i, one in enumerate(self.pfdstore):
onesdm = pfddata(one[1]).bestdm
if not onesdm > lim:
self.pfdstore.remove(one.iter)
removecount += 1
print "removed %s candidates with DM < %s" % (removecount, lim)
self.statusbar.push(0,'removed %s candidates with DM < %s.' % (removecount, lim))
return
#turn off the model first for speed-up
"""
#if idx1 != idx2:
#data = self.data[['fname',col1,col2]]
#if data.ndim == 0:
#dtyp = [(name, self.data.dtype[name].str) \
#for name in ['fname', col1, col2]]
#data = np.array([data], dtype=dtyp)
#data.sort(order=[col1,'fname'])
#limidx = data[col1] >= lim - 1e-5
#if limidx.size > 1 and np.any(limidx) and limtog:
#data = data[limidx]
#self.statusbar.push(0,'Showing %s/%s candidates above %s in DM' %
#(limidx.sum(),len(limidx),lim))
#else:
#self.statusbar.push(0,'No %s candidates > %s in DM. Showing all' % (col1, lim))
#for vi, v in enumerate(data[::-1]):
#d = (vi,) + v.tolist()
#self.pfdstore.append(d)
#else:
#data = self.data[['fname',col1]]
#if data.ndim == 0:
#dtyp = [(name, self.data.dtype[name].str) \
#for name in ['fname', col1]]
#data = np.array([data], dtype=dtyp)
data.sort(order=[col1,'fname'])
limidx = data[col1] >= lim - 1e-5
if limidx.size > 1 and np.any(limidx) and limtog:
data = data[limidx]
self.statusbar.push(0,'Showing %s/%s candidates above %s in DM' %
(limidx.sum(),len(limidx),lim))
else:
self.statusbar.push(0,'No %s candidates > %s in DM. Showing all' % (col1, lim))
for vi, v in enumerate(data[::-1]):
v0, v1 = v
self.pfdstore.append((vi,v0,float(v1),float(v1)))
self.pfdtree.set_model(self.pfdstore)
self.find_matches()
"""
def on_pfdwin_key_press_event(self, widget, event):
"""
controls keypresses on over-all window
#recently added "feature-label" voting, where
#we cycle through the subplots before advancing
"""
global cand_vote, have_warned
#are we doing feature-label voting?
FL = False
if self.fl_voting_tog.get_active():
FL = True
#key codes which change the voting data
votes = {'1':1., 'p':1., #pulsar
'r': np.nan, #reset to np.nan
'5':.5, 'm':.5, #50/50 pulsar/rfi
'k':2., #known pulsar
'h':3., #harmonic of known
'0':0. #rfi (not a pulsar)
}
#checkboxes for FL voting (vote: glade checkbox)
FL_votes = {0: 'FL_overall',
1: 'FL_profile',
2: 'FL_intervals',
3: 'FL_subbands',
4: 'FL_DMcurve'
}
key = Gdk.keyval_name(event.keyval)
ctrl = event.state &\
Gdk.ModifierType.CONTROL_MASK
if self.active_voter:
act_name = self.voters[self.active_voter]
if self.fl_voting_tog.get_active():
act_name += '_FL'
else:
act_name = 'AI'
#don't allow voting/actions if sort_column = active voter
col1 = self.col1.get_active_text()
col2 = self.col2.get_active_text()
sort_id = self.pfdstore.get_sort_column_id()[0]
#0=number, 1=fname, 2=col1, 3=col2
if (sort_id == 2) and (act_name == col1) and key in votes:
note = "Note. Voting disabled when active voter = sort column. \n"
note += "Try sorting by filename"
if not have_warned:
dlg = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK, note)
response = dlg.run()
dlg.destroy()
have_warned = True
self.statusbar.push(0, 'Vote not recorded. voter = sort column')
else:
self.statusbar.push(0, note)
return
elif (sort_id == 3) and (act_name == col2) and key in votes:
note = "Note. Voting disabled when active voter = sort column"
if not have_warned:
dlg = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK,note)
response = dlg.run()
dlg.destroy()
have_warned = True
self.statusbar.push(0, 'Vote not recorded. voter = sort column')
else:
self.statusbar.push(0, note)
return
elif act_name == 'AI' and key in votes:
note = 'Note: AI voter is not editable. Change active voter'
print note
self.statusbar.push(0, note)
return
#if we've made it this far than we can record the vote...
(model, pathlist) = self.pfdtree.get_selection().get_selected_rows()
#only use first selected object
if len(pathlist) == 0:
#nothing selected, so go back to first
path = None
this_iter = None
next_path = None
else:
path = pathlist[0]
this_iter = model.get_iter(path)
next_iter = model.iter_next(this_iter)
#look for next non-ranked candidates
advance = self.advance_next.get_active()
adv_col = int(self.advance_col.get_value()) + 1 #plus 'number' and 'fname'
if advance:
data = self.pfdstore[next_iter]
while not np.isnan(data[adv_col]):
next_iter = model.iter_next(next_iter)
if next_iter == None:
self.statusbar.push(0,'No unranked candidates in voter col %i. You are Done!' % adv_col)
break
else:
data = self.pfdstore[next_iter]
#keep modifier keys until they are released
if key in ['Control_L','Control_R','Alt_L','Alt_R']:
self.modifier = key
if key == 'q' and self.modifier in\
['Control', 'Control_L', 'Control_R', 'Primary']:
self.on_menubar_delete_event(widget, event)
elif key == 's' and self.modifier in ['Control_L', 'Control_R', 'Primary']:
self.on_save(widget)
elif key == 'l' and self.modifier in ['Control_L', 'Control_R', 'Primary']:
self.on_open()
elif key == 'n':
self.pfdtree_next(model, next_iter, FL=FL)
elif key == 'b':
self.pfdtree_prev(FL=FL)
elif key == 'a':
#toggle aiview
d = self.aiview_tog.get_active()
self.aiview_tog.set_active(not(d))
elif key == 'd':
#download the candidate if we are in QRY mode
if self.data_fromQry:
#get the filename
fname = self.pfdstore[this_iter][1]
if not os.path.exists(os.path.join(self.qrybasedir,fname)):
self.PALFA_download_qry(fname)
elif key == 'Delete':
# remove this file from the list of tracked files
if this_iter is not None:
fname = self.pfdstore[this_iter][1]
next_path = model.get_path(next_iter)
self.remove_fname(fname)
self.pfdtree.set_cursor(next_path)
elif key in ['Left', 'Right']:
# FL and 'left' goes back a FL
if key == 'Left':
self.fl_nvote = max(0, self.fl_nvote - 1)
elif key == 'Right':
self.fl_nvote = min(4, self.fl_nvote + 1)
self.FL_color()
a = FL_votes[self.fl_nvote].strip('FL_')
self.FL_text.set_text('FL vote:\n (%s)' % a)
#data-related (needs to be loaded)
if self.data != None:
if key in votes:
cand_vote += 1
#download the candidate if we are in QRY mode
if self.data_fromQry:
#get the filename
fname = self.pfdstore[this_iter][1]
if not os.path.exists(os.path.join(self.qrybasedir,fname)):
self.PALFA_download_qry(fname)
value = votes[key]
#FL only votes 0/1
if FL:
value = int(value)
if value in [0,1]:
#set the checkbox
o = self.builder.get_object(FL_votes[self.fl_nvote])
o.set_active(value)
fname = self.pfdstore_set_value(value, this_iter=this_iter, \
return_fname=True, FL=FL)
else:
fname = self.pfdstore_set_value(value, this_iter=this_iter, \
return_fname=True)
if key in ['1', 'p', 'm', '5', 'h', 'k']:
if FL and self.fl_nvote == 0:
self.add_candidate_to_knownpulsars(fname)
elif not(FL):
self.add_candidate_to_knownpulsars(fname)
if FL and value in [0,1]:
self.fl_nvote = (self.fl_nvote + 1) % 5
self.FL_color()
a = FL_votes[self.fl_nvote].strip('FL_')
self.FL_text.set_text('FL vote:\n (%s)' % a)
#advance to the next candidate?
if next_iter is not None:
if FL and value in [0, 1]:
if (self.fl_nvote % 5 == 0):
#then we've done all the FL voting
self.pfdtree_next(model, next_iter, FL=FL)
elif (not FL):
self.pfdtree_next(model, next_iter, FL=FL)
elif key == 'c':
# cycle between ranked candidates
self.pmatchtree_next()
if cand_vote//10 == 1:
if self.autosave.get_active():
self.on_save()
else:
self.statusbar.push(0,'Remember to save your output')
awards = [30, 75, 150, 250, 400, 600, 1000]
if 0 and (cand_vote in awards) | ( (cand_vote > max(awards)) & (cand_vote%500 == 0) ):
try:
idx = awards.index(cand_vote)
level = idx + 1
except(ValueError):
level = cand_vote//500 + len(awards) - max(awards)//500
note = 'Congratulations %s. You are a level %s classifier!\n' % (act_name, level)
if level < len(awards):
nl = awards[level] - awards[idx]
else:
nl = 500
note += 'Only %s votes to the next level, and possibly a free coffee from Aaron and Weiwei.\n' % nl
note += 'Save a screenshot of this window for proof.'
dlg = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK, note)
response = dlg.run()
dlg.destroy()
def add_candidate_to_knownpulsars(self, fname):
"""
as a user ranks candidates, add the pulsar candidates to the list
of known pulsars
input:
filename of the pfd file
"""
if exists(fname) and fname.endswith('.pfd'):
pfd = pfddata(fname)
pfd.dedisperse()
dm = pfd.bestdm
ra = pfd.rastr
dec = pfd.decstr
p0 = pfd.bary_p1
name = basename(fname)
if float(pfd.decstr.split(':')[0]) > 0:
sgn = '+'
else:
sgn = ''
name = 'J%s%s%s' % (''.join(pfd.rastr.split(':')[:2]), sgn,\
''.join(pfd.decstr.split(':')[:2]))
# this_pulsar = known_pulsars.pulsar(fname, name, ra, dec, p0*1e-3, dm)
this_pulsar = known_pulsars.pulsar(fname, name, ra, dec, p0, dm, catalog='local')
self.knownpulsars[fname] = this_pulsar
def dataload_update(self):
"""
update the pfdstore whenever we load in a new data file
set columns to "fname, AI, [1st non-AI voter... if exists]"
"""
if self.active_voter:
act_name = self.voters[self.active_voter]
#update the Treeview...
if self.data is not None:
col1 = self.col1.get_active_text()
col2 = self.col2.get_active_text()
idx1 = self.col_options.index(col1)
if col2 == None:
col2 = col1
self.col2.set_active(idx1)
idx2 = self.col_options.index(col2)
limtog = self.limit_toggle.get_active()
lim = self.view_limit.get_value()
#turn off the model first for speed-up
self.pfdtree.set_model(None)
self.pfdstore.clear()
self.active_col1 = idx1
self.active_col2 = idx2
if idx1 != idx2:
data = self.data[['fname',col1,col2]]
if data.ndim == 0:
dtyp = [(name, self.data.dtype[name].str) \
for name in ['fname', col1, col2]]
data = np.array([data], dtype=dtyp)
data.sort(order=[col1,'fname'])
limidx = data[col1] >= lim - 1e-5
if limidx.size > 1 and np.any(limidx) and limtog:
data = data[limidx]
self.statusbar.push(0,'Showing %s/%s candidates above %s' %
(limidx.sum(),len(limidx),lim))
else:
self.statusbar.push(0,'No %s candidates > %s. Showing All.' % (col1, lim))
for vi, v in enumerate(data[::-1]):
d = (vi,) + v.tolist()
self.pfdstore.append(d)
else:
data = self.data[['fname',col1]]
if data.ndim == 0:
dtyp = [(name, self.data.dtype[name].str) \
for name in ['fname', col1]]
data = np.array([data], dtype=dtyp)
data.sort(order=[col1,'fname'])
limidx = data[col1] >= lim - 1e-5
if limidx.size > 1 and np.any(limidx) and limtog:
data = data[limidx]
self.statusbar.push(0,'Showing %s/%s candidates above %s' %
(limidx.sum(),len(limidx),lim))
else:
self.statusbar.push(0,'No %s candidates > %s. Showing all.' % (col1, lim))
for vi, v in enumerate(data[::-1]):
v0, v1 = v
self.pfdstore.append((vi,v0,float(v1),float(v1)))
self.pfdtree.set_model(self.pfdstore)
self.find_matches()
def on_col_changed(self, widget):
"""
change the pfdstore whenever we change the column box
"""
if self.data != None and self.active_col1 != None and self.active_col2 != None:
col1 = self.col1.get_active_text()
col2 = self.col2.get_active_text()
idx1 = self.col_options.index(col1)
if col2 == None:
col2 = col1
self.col2.set_active(idx1)
idx2 = self.col_options.index(col2)
if (self.active_col1 != idx1) or (self.active_col2 != idx2):
self.pfdtree.set_model(None)
self.pfdstore.clear()
self.active_col1 = idx1
self.active_col2 = idx2
limtog = self.limit_toggle.get_active()
lim = self.view_limit.get_value()
if idx1 != idx2:
data = self.data[['fname',col1,col2]]
if data.ndim == 0:
dtyp = [(name, self.data.dtype[name].str) \
for name in ['fname', col1, col2]]
data = np.array([data], dtype=dtyp)
data.sort(order=[col1,'fname'])
limidx = data[col1] >= lim - 1e-5
if limidx.size > 1 and np.any(limidx) and limtog:
data = data[limidx]
self.statusbar.push(0,'Showing %s/%s candidates above %s' %
(limidx.sum(),len(limidx),lim))
else:
self.statusbar.push(0,'No %s candidates > %s' % (col1, lim))
for vi, v in enumerate(data[::-1]):
d = (vi,) + v.tolist()
self.pfdstore.append(d)
else:
data = self.data[['fname',col1]]
if data.ndim == 0:
dtyp = [(name, self.data.dtype[name].str) \
for name in ['fname', col1]]
data = np.array([data],dtype=dtyp)
data.sort(order=[col1,'fname'])
limidx = data[col1] >= lim - 1e-5
if limidx.size > 1 and np.any(limidx) and limtog:
data = data[limidx]
self.statusbar.push(0,'Showing %s/%s candidates above %s' %
(limidx.sum(),len(limidx),lim))
else:
self.statusbar.push(0,'No %s candidates > %s' % (col1, lim))
for vi, v in enumerate(data[::-1]):
v0, v1 = v
self.pfdstore.append((vi, v0, v1, v1))
self.pfdtree.set_model(self.pfdstore)
self.find_matches()
def on_pfdtree_select_row(self, widget, event=None):#, data=None):
"""
responds to keypresses/cursor-changes in the pfdtree view,
placing the appropriate candidate plot in the pfdwin.
We also look for the .pfd or .ps files and convert them
to png if necessary... though we make system calls for this
if ai_view is active, we make a plot of data downsamples
to the AI and show that. If any of the AIview params are illegal
we take (nbins, n_pca_comp) = (32, 0)... no pca
if feature-label voting, load up the votes
"""
gsel = self.pfdtree.get_selection()
if gsel:
tmpstore, tmpiter = gsel.get_selected()
else:
tmpiter = None
FL = False
if self.fl_voting_tog.get_active():
FL = True
ncol = self.pfdstore.get_n_columns()
if tmpiter != None:
name = tmpstore.get_value(tmpiter,1)
if self.data_fromQry:
idx = np.where(self.qry_results['filename'] == basename(name))[0]
if len(idx) == 1 and self.qry_results['keep'][idx]:
basedir = self.qry_saveloc
else:
basedir = self.qrybasedir
else:
basedir = self.basedir
fname = os.path.join(basedir, name)
#are we displaying the prediction from a tmpAI?
if exists(fname) and fname.endswith('.pfd') \
and (self.tmpAI != None) and self.tmpAI_tog.get_active():
if fname not in self.tmpAI_avgs:
pfd = pfdreader(fname)
#pfd = pfddata(fname)
#pfd.dedisperse()
avgs = feature_predict(self.tmpAI, pfd)
self.tmpAI_avgs[fname] = avgs
else:
avgs = self.tmpAI_avgs[fname]
self.update_tmpAI_votemat(avgs)
disp_apnd = '(tmpAI: %0.3f)' % (avgs['overall'])
elif (self.tmpAI != None) and self.tmpAI_tog.get_active():
avgs = {'phasebins':np.nan,'subbands':np.nan,'intervals':np.nan,\
'DMbins':np.nan,'overall':np.nan}
self.update_tmpAI_votemat(avgs)
disp_apnd = '(pfd not found)'
else:
disp_apnd = ''
# find/create png file from input file
#try:
fpng = self.create_png(fname)
#except:
#print 'failed to create png file for %' % (fname)
#update the basedir if necessary
if not exists(fpng):
fname = self.find_file(fname)
fpng = self.create_png(fname)
#we are not doing "AI view" of data
if not self.aiview_tog.get_active():
if fpng and exists(fpng):
self.image.set_from_file(fpng)
self.image_disp.set_text('displaying : %s %s' %
(basename(fname), disp_apnd))
else:
note = "Failed to generate png file %s" % fname
print note
self.statusbar.push(0,note)
self.image.set_from_file('')
else:
#we are doing the AI view of the data
fpng= ''
if exists(fname) and fname.endswith('.pfd'):
self.statusbar.push(0,'Generating AIview...')
#have we generated this AIview before?
fpng = self.check_AIviewfile_match(fname)
if not fpng:
fpng = self.generate_AIviewfile(fname)
if fpng and exists(fpng):
self.image.set_from_file(fpng)
self.image_disp.set_text('displaying : %s %s' % (fname, disp_apnd))
else:
note = "Failed to generate png file %s" % fname
print note
self.statusbar.push(0,note)
self.image.set_from_file('')
self.image_disp.set_text('displaying : %s %s' % (fname, disp_apnd))
elif fname.endswith('.png'):
note = "Can't generate AIview from png files"
self.statusbar.push(0, note)
fpng = fname
self.image.set_from_file(fpng)
self.image_disp.set_text('displaying: %s %s' % (fpng, disp_apnd))
#load up the feature-label votes
if FL:
self.fl_nvote = 0
idx = np.where(self.data['fname'] == name)
act_name = self.voters[self.active_voter] + '_FL'
kv = self.data[act_name][idx][0]
for i, v in enumerate(['FL_overall', 'FL_profile', 'FL_intervals',\
'FL_subbands','FL_DMcurve']):
o = self.builder.get_object(v)
o.set_active(kv[i])
self.FL_color()
self.find_matches()
def create_png(self, fname):
"""
given some pfd or ps file, create the png file
for i, t in enumerate(self.pfdstore):
print i, list(t)
if it doesn't already exist
"""
if fname.endswith('.ps'):
fpng = fname.replace('.ps', '.png')
if not exists(fpng):
#convert ps file to png
if exists(fname):
fpng = convert(fname)
#convert using the pfd file
else:
pfdfile = os.path.splitext(fname)[0]
if exists(pfdfile):
fname = pfdfile
fpng = convert(fname)
elif fname.endswith('.pfd'):
fpng = '%s.png' % fname
if not exists(fpng):
fpng = convert(fname)
elif fname.endswith('.ar2') or fname.endswith('.ar'):