-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.py
1474 lines (1194 loc) · 48 KB
/
data.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
from __future__ import division
import os, sys, re, glob, urllib, httplib, warnings
from cStringIO import StringIO
try:
set
except:
from sets import Set as set
from matplotlib.cbook import mkdirs, listFiles
from numpy import array, arange, sqrt, sum, zeros
from scipy import fromstring, take, resize,\
transpose
from scipy import median
from utils import all_pairs_ij, all_pairs_eoi
import file_formats
import csv
import gtk
import math
import datetime
import servers
import scipy
import scipy.signal
import pickle
e1020 = set([
'cz', 'c3', 'c4',
't3', 't4', 't5', 't6',
'o1', 'o2',
'pz', 'p3', 'p4',
'fz', 'f3', 'f4', 'f7', 'f8',
'fp1', 'fp2',
'a1', 'a2',
])
class Electrode:
"""
CLASS: Electrode
DESCR:
"""
def __init__(self, name, num, xyz=None):
self.name = name
self.num = num
if xyz is None: self.xyz = array([0.0, 0.0, 0.0])
else: self.xyz = xyz
def set_xyz(self, xyz):
try: xyz.shape
except AttributeError: xyz = array(xyz, 'd')
self.xyz = xyz
def get_xyz(self):
return self.xyz
def get_name(self):
return self.name
def get_num(self):
return self.num
def get_label(self):
return '%s%d' % (self.get_name(), self.get_num())
class Grid(dict):
"""
CLASS: Grid
DESCR:
"""
def __init__(self, name, dim, rgb=None, spacing=1.0):
self.name = name
self.dim = dim # (dim1, dim2) as integers
self.rgb = rgb # (red, green, blue) as floats
self.spacing = spacing # a single float
def set_electrode(self, num, electrode):
self[num] = electrode
def get_electrode(self, num):
return self[num]
def get_electrodes(self):
return self.values()
def has_electrode(self, num):
self.has_key(num)
def get_dimensions(self):
return self.dim
def get_spacing(self):
return self.spacing
def get_rgb(self):
return self.rgb
def get_name(self):
return self.name
def get_number_electrodes(self):
return len(self.keys())
class AssociatedFile:
"""
CLASS: AssociatedFile
DESCR:
"""
def __init__(self, dbaseFields=None, useFile=None):
self.eeg = None
self.filename = None
self.fullpath = None
if dbaseFields is None:
import mx.DateTime
now = mx.DateTime.now()
dbaseFields = {'description': '',
'date': now,
'type': self.filetype,
'filename': 'none.' + self.extension}
self.existsWeb = 0
self.__dict__.update(dbaseFields)
if useFile is not None :
basepath, fname = os.path.split(useFile)
self.filename = fname
self.fullpath = useFile
self.load_data(useFile)
else:
self.__dict__.update(dbaseFields)
self.set_exists_web(pid=dbaseFields['pid'],
filename=dbaseFields['filename'])
self.load_data()
def set_active_eeg(self, eeg) :
self.eeg = eeg
# Set default file name if necessary.
if not self.is_web_file() and self.filename == 'none.' + self.extension :
# Set path to eeg_root.ext.
root, ext = os.path.splitext(eeg.fullpath)
self.fullpath = root + '.' + self.extension
basepath, fname = os.path.split(self.fullpath)
self.filename = fname
def set_exists_web(self, pid, filename):
self.dbaseFilename = filename
self.filename = filename
self.pid = pid
self.existsWeb = 1
#todo: verify existence with sql query?
def is_web_file(self):
return self.existsWeb
def to_conf_file(self):
"Convert self to a config file string"
raise NotImplementedError, 'Derved class must override'
def load_data(self, useFile=None):
if useFile is not None:
try: fh = file(useFile, 'r')
except IOError:
raise ValueError('Failed to open %s for reading' % useFile)
self._load_data(fh)
else:
dm = servers.datamanager
url = dm.get_data_url(self.pid, 'assoc', self.filename)
fh = urllib.urlopen(url)
self._load_data(fh)
def save_data(self, useFile=None, append=False) :
if self.is_web_file() :
# xxx web save
print "web save"
else :
if useFile is None :
useFile = self.fullpath
if useFile is not None :
fh = None
try :
if append :
fh = file(useFile, 'a')
else :
fh = file(useFile, 'w')
except IOError :
raise ValueError('Failed to open %s for writing/appending' % useFile)
self._save_data(fh, append)
def update_web(self, fname=None):
"Update the web version of the file and database"
if not self.is_web_file():
raise RuntimeError, 'Not a web file'
updateName = 0
if fname is None:
fname = self.filename
updateName = 1
fields = {'description': self.description,
'date': self.date,
'pid' : self.pid,
'type:int': self.filetype,
'old_filename' : self.dbaseFilename,
}
fileInfo = {'formvar' : 'filename',
'filename' : fname,
'content' : self.to_conf_file()}
dm = servers.datamanager
auth = dm.get_base64_authorization().replace('\n', '\\n')
headers = {'Authorization' : 'Basic ' + auth}
submit_form(host=dm.host,
path=sm.relpath + '/editedAssocFile',
fields=fields,
headers=headers,
fileInfo=fileInfo )
# if we made it to here, we successfully update the internet
if updateName:
self.dbaseFileName = fname
self.filename = fname
def new_web(self, pid, fname):
"""
Add the file to the web server and database. Raises a NameError if
there is already a file in the assocfile table with primary key
(pid, dname).
"""
if self.is_web_file(): raise RuntimeError, 'This is a web file'
#check for existing file with same name
table = servers.sql.assocfile
result = table.selectone(
where='pid=%s and filename="%s"' % (pid, fname))
if result is not None:
raise NameError, 'assocfile alreay has entry\n%s' % result
fields = {'description': self.description,
'date': self.date,
'pid' : pid,
'type:int': self.filetype,
}
fileInfo = {'formvar' : 'filename',
'filename' : fname,
'content' : self.to_conf_file()}
dm = servers.datamanager
auth = dm.get_base64_authorization().replace('\n', '\\n')
headers = {'Authorization' : 'Basic ' + auth}
submit_form(host=dm.host,
path=dm.relpath+'/addedAssocFile',
fields=fields,
headers=headers,
fileInfo=fileInfo )
# if we made it to here, we successfully update the internet
self.set_exists_web(pid=pid, filename=fname)
def update_map(self, eegFilename):
if not self.is_web_file():
msg = 'EOI must be a web file to map to %s' % eegFilename
raise RuntimeError, msg
# Check to see if the association already exists; if so, just return
cursor = servers.sql.cursor
sql = 'SELECT pid FROM assocmap WHERE ' +\
'filename=%s AND assocfile=%s'
cursor.execute(sql,
(eegFilename, self.filename))
results = cursor.fetchall()
if len(results)>0: return #already mapped
# Do the mapping
sql = 'INSERT INTO assocmap VALUES (%s, %s, %s, %s)'
cursor.execute(sql,
(self.pid, eegFilename, self.filename, 'eeg'))
class Loc3dJr(AssociatedFile):
"""
CLASS: Loc3dJr
DESCR:
"""
extension = 'csv'
filetype = 8
def __init__(self, dbaseFields=None, useFile=None):
AssociatedFile.__init__(self, dbaseFields, useFile)
def _load_data(self, fh):
self.fh = StringIO(fh.read())
class Info(AssociatedFile):
"""
CLASS: Info
DESCR:
"""
extension = 'info'
filetype = 12
def __init__(self, dbaseFields=None, useFile=None):
AssociatedFile.__init__(self, dbaseFields, useFile)
def _load_data(self, fh):
self.fh = StringIO(fh.read())
class EOI(list, AssociatedFile):
"""
CLASS: EOI
DESCR:
"""
extension = 'eoi'
filetype = 5
def __init__(self, dbaseFields=None, useFile=None, electrodes=None):
AssociatedFile.__init__(self, dbaseFields, useFile)
if electrodes is not None:
self.set_electrodes(electrodes)
self._update_seen()
def clear_electrodes(self):
self[:] = []
def set_electrodes(self, trodes):
# The problem is that trodes is self! and we clear it before setting it
if trodes is self: return
self.clear_electrodes()
self.extend(trodes)
def _update_seen(self):
self._seen = {}
for (grdName, grdNum) in self:
self._seen[grdName + str(grdNum)]=1
def contains(self, grdName, grdNum):
return self._seen(grdName + str(grdNum))
def set_description(self, desc):
self.description = desc
def get_description(self):
return self.description
def _load_data(self, fh):
fh.readline() # slurp the header
desc = fh.readline() # slurp the description
while 1:
line = fh.readline().strip()
if len(line)==0: break
desc+=line
trodes = []
for line in fh.readlines():
line = line.strip()
if len(line)==0: continue
vals = line.split()
if len(vals)!=2: break
trodes.append(
(vals[0], int(vals[1])))
self.set_electrodes(trodes)
self.set_description(desc)
def get_data(self, amp, eeg):
"""
Given and Amp instance and an EEG instance, return the data
for this EOI
"""
data = eeg.get_data()
ind = self.to_data_indices(amp)
return take(data, ind, 1)
def to_data_indices(self, amp):
"""
Return value is a list of indicies into the data array for the channels
in the eoi
Raises a KeyError if an eoi channel cannot be found in the amp
struct and returns an error string indicating the problem EOI
"""
d = amp.get_electrode_to_indices_dict()
indices = [d[key] for key in self]
return indices
def to_conf_file(self):
"Convert self to a config file string"
lines = []
lines.append('EOI : Version 1.0')
lines.append(self.get_description())
lines.append('')
for tup in self:
lines.append('%s %d' % tup)
return '\n'.join(lines)
class Amp(list, AssociatedFile):
"""
CLASS: Amp
DESCR:
"""
"""
An amplifier config file. iterable as a list of (ampNum, grdName,
grdNum) tuples
"""
extension = 'amp'
filetype = 3
def __init__(self, dbaseFields=None, useFile=None):
AssociatedFile.__init__(self, dbaseFields, useFile)
self.message = None
def to_eoi(self):
eoi = EOI()
eoi.filename = self.filename + '.' + EOI.extension
electrodes = []
for (cnum, gname, gnum ) in self:
electrodes.append( (gname, gnum) )
eoi.set_electrodes(electrodes)
return eoi
def _load_data(self, fh):
"""
Load the amp data file. Raise a ValueError on illegal file
format
"""
fh.readline() # slurp the header
ampChannels = []
seen = {}
seengrid = {}
count = 0
for line in fh.readlines():
#print "Amp._load_data(): line='%s'" % line
count += 1
vals = line.split()
if len(vals)!=3: break
cnum, gname, gnum = int(vals[0]), vals[1], int(vals[2])
if seen.has_key(cnum):
raise ValueError('Duplicate channel num %d on line %s reading\n\t%s' % (cnum, count, line) )
if seengrid.has_key((gname,gnum)):
raise ValueError('Duplicate grid channel %s %d on line %s reading\n\t%s' % (gname, gnum, count, line))
seen[cnum] = 1
seengrid[(gname, gnum)] = 1
ampChannels.append( (cnum, gname, gnum))
# flush the old list and set the new
self.set_channels(ampChannels)
def clear_channels(self):
self[:] = []
def set_channels(self, channels):
"channels is a list of (channelNum, gridName, gridNum) tuples"
if channels is self: return
self.clear_channels()
self.extend(channels)
def to_conf_file(self):
"Convert self to a config file string"
lines = []
lines.append('AMP : Version 1.0')
for tup in self:
lines.append('%d %s %d' % tup)
return '\n'.join(lines)
def get_channel_num_dict(self):
"return a dict from electrodes to channel num"
return dict([ ( (name,num), ind ) for ind, name, num in self])
def get_electrode_to_indices_dict(self):
"return a dict from electrodes to index into the data array"
return dict([ ( (name,num), ind-1 ) for ind, name, num in self])
def get_dataind_dict(self):
"""
Return a dict mapping data structure index (which is not
necessarily the same as an index into the amp structure)
to gname, gnum tuples
"""
return dict([ ( ind-1, (name,num) ) for ind, name, num in self])
def get_channelnum_dict(self):
"""
Return a dict mapping channel num gname, gnum tuples
mcc XXX: what did I write the below comments for?
amp = eeg.get_amp()
cnumd = amp.get_channelnum_dict()
electrode = cnumd[56]
...in gridmanager....
marker = gridManager.markerd[electrode]
marker.set_center(xyz)
marker.set_color(vtkColor)
....
for e1,e2 in mypairs:
e1, e2 = some_electrodes()
corr = corrdist(e1,e2)
def func(x): return corr
gridManager.connect_markers(e1, e2, scalarfunc=func)
"""
return dict([ ( ind, (name,num) ) for ind, name, num in self])
class Grids(AssociatedFile, dict):
"""
CLASS: Grids
DESCR:
"""
extension = 'grd'
filetype = 4
def __init__(self, dbaseFields=None, useFile=None):
AssociatedFile.__init__(self, dbaseFields, useFile)
def add_grid(self, grid):
self[grid.get_name()] = grid
def get_grid(self, name):
return self[name]
def get_grids(self):
return self.values()
def get_number_electrodes(self):
num = 0
for grid in self.get_grids():
num += g.get_number_electrodes()
return num
def get_number_grids(self):
return len(self.get_grids())
def set_xyz_for_eoi(self, eoi):
for e in eoi:
name, num = g.get_name(), e.get_number()
try:
xyz = self[name][num].get_xyz()
except KeyError, e:
print "unrecognized key", name, num
xyz = array([0.0,0.0,0.0])
e.set_xyz(xyz)
def get_dist_for_eoi(self, eoi):
"""
Creates a dict of each pair with key (e1,e2) and the distance
between them.
"""
eoixyz = {}
xyz = self.get_xyz_for_eoi(eoi)
for e1, e2 in all_pairs_eoi(eoi):
p1 = xyz[e1]
p2 = xyz[e2]
eoixyz[ (e1, e2) ] = sqrt(sum((p1-p2)**2))
return eoixyz
def get_xyz_for_eoi(self, eoi):
"Get the xyz coords for an eoi as a dict from name, num to x,y,z"
XYZ = {}
for name, num in eoi:
try:
xyz = self[name][num].get_xyz()
except KeyError, e:
print "unrecognized key", name, num
xyz = array([0.0,0.0,0.0])
XYZ[ (name, num)] = array(xyz)
return XYZ
def _load_data(self, fh):
fh.readline(), fh.readline() # slurp the header
# clear the current dictionary
self.clear()
numTrodesByDim = 0
while 1:
line = fh.readline()
if len(line)<10: break
vals = line.split()
name=vals[0]
rgb = map(float, vals[1:4])
dim = [int(vals[4]), int(vals[5])]
spacing = float(vals[6])
grid = Grid(name=name, dim=dim, rgb=rgb, spacing=spacing)
self.add_grid(grid)
numTrodesByDim += dim[0]*dim[1]
line = fh.readline()
numTrodesByCount = 0
while 1:
line = fh.readline()
if len(line)<10: break
vals = line.split()
xyz = map(float, vals[2:])
name, num = vals[0], int(vals[1])
electrode = Electrode(name, num, xyz)
grid = self.get_grid(name)
grid.set_electrode(num, electrode)
numTrodesByCount += 1
#todo: check trode by dim vs trode count
def to_conf_file(self):
"Convert self to a config file string"
lines = []
lines.append('GRD : Version 1.0')
lines.append('GrdName R G B dim1 dim2 spacing')
for grid in self.get_grids():
#RF 1.0000 0.0000 1.0000 1 8 1.0000
name = grid.get_name()
r,g,b = grid.get_rgb()
dim1,dim2 = grid.get_dimensions()
spacing = grid.get_spacing()
lines.append('%s %1.4f %1.4f %1.4f %d %d %1.4f' %
(name, r, g, b, dim1, dim2, spacing))
lines.append('')
lines.append('GrdName GrdNum X Y Z')
for grid in self.get_grids():
for e in grid.get_electrodes():
x,y,z = e.get_xyz()
lines.append('%s %d %1.4f %1.4f %1.4f' %
(e.get_name(), e.get_num(), x, y, z))
return '\n'.join(lines)
def to_eoi(self):
"""
Get all the electrodes for every grid in the Grids instance as an
EOI
"""
eoi = EOI()
eoi.set_electrodes([ (e.get_name(), e.get_num())
for aGrid in self.get_grids()
for e in aGrid.get_electrodes()])
return eoi
class Ann(dict, AssociatedFile) :
"""
CLASS: Ann
DESCR:
"""
extension = 'ann.csv'
filetype = 13
currVersion = 1.0
def __init__(self, dbaseFields=None, useFile=None, message=None) :
self.eois = {}
AssociatedFile.__init__(self, dbaseFields, useFile)
self.message = message
# xxx error checking of file format
def _load_data(self, fh) :
reader = csv.reader(fh)
for line in reader :
if not line : continue
version = float(line[0])
if version == 1.0 :
# Get electrodes in eoi
trodes = []
description = line[5]
eoiLine = line[6]
r = re.compile(';\s*')
for trode in r.split(eoiLine) :
grid, num = trode.split('-')
trodes.append((grid, int(num)))
# Check for EOIs with the same name but different electrodes.
# Create a new EOI or use previously created one.
if self.eois.get(description) :
if self.eois[description] <> trodes :
print 'WARNING: EOIs with description, %s, have different electrodes; using first set of electrodes.' % description
eoi = self.eois[description]
else :
eoi = EOI(electrodes=trodes)
eoi.set_description(description)
self.eois[description] = eoi
self['%1.1f' % float(line[1]), '%1.1f' % float(line[2]), line[3]] = {
'version' : float(line[0]),
'startTime' : float(line[1]),
'endTime' : float(line[2]),
'created' : line[3],
'edited' : line[4],
'eoi' : eoi,
'username' : line[7],
'color' : line[8],
'alpha' : float(line[9]),
'code' : line[10],
'state' : line[11],
'visible' : bool(int(line[12])),
'shrink' : bool(int(line[13])),
'annotation' : line[14]}
else :
print "WARNING: Unsupported annotation version: ", line
# XXX what to do - don't lost the entry!
def _save_data(self, fh, append = False) :
writer = csv.writer(fh)
keys = self.keys()
keys.sort()
for key in keys :
eoi = self[key]['eoi']
trodes = ';'.join(['%s-%s' % (grid, num) for grid, num in eoi])
line = [self.currVersion,
self[key]['startTime'],
self[key]['endTime'],
self[key]['created'],
self[key]['edited'],
eoi.description,
trodes,
self[key]['username'],
self[key]['color'],
self[key]['alpha'],
self[key]['code'],
self[key]['state'],
int(self[key]['visible']),
int(self[key]['shrink']),
self[key]['annotation']]
writer.writerow(line)
def assoc_factory_web(entry):
typeMap = { 3 : Amp,
4 : Grids,
5 : EOI,
8 : Loc3dJr,
}
return typeMap[entry.type](entry.get_orig_map())
def assoc_factory_filesystem(filetype, fname):
typeMap = { 3 : Amp,
4 : Grids,
5 : EOI,
8 : Loc3dJr,
12 : Info,
13 : Ann,
}
return typeMap[filetype](useFile=fname)
EDF, BMSI, NSASCII, NSCNT, FLOATARRAY, W18, AXONASCII, NEUROSCANASCII, ALPHAOMEGAASCII = range(9)
EPOCH = 14
class EEGBase:
"""
CLASS: EEGBase
DESCR:
"""
def __init__(self, amp):
#print "EEGBase(amp=", amp, ")"
self.readmap = {BMSI : self._read_nicolet,
W18 : self._read_w18,
EPOCH : self._read_epoch,
AXONASCII: self._read_axonascii,
NEUROSCANASCII: self._read_neuroscanascii,
ALPHAOMEGAASCII: self._read_neuroscanascii
}
self.scale= None
# store the last get_data query so repeated calls will use the
# cached version. lastDataQuery is a
# ( (tmin, tmax), (t, data) ) tuple
self.lastDataQuery = None
self.amp = amp
self.rectifiedChannels = {}
self.hilbertedChannels = {}
for (cnum, cname, gnum) in amp:
self.rectifiedChannels[(cname,gnum)] = False
self.hilbertedChannels[(cname,gnum)] = False
def load_data(self):
raise NotImplementedError('Derived must override')
def get_eois(self):
return self.get_associated_files(5, mapped=1)
def set_rectified(self, rectifiedChannels):
#print "mcc XXX: EEGBase.set_rectified( ", rectifiedChannels, ")"
for i,j in rectifiedChannels.iteritems():
self.rectifiedChannels[i] = j
d = self.amp.get_electrode_to_indices_dict()
print "set_rectified: get_electrode_to_indices_dict is " , d
self.lastDataQuery = None
def set_hilberted(self, hilbertedChannels):
#print "mcc XXX: EEGBase.set_hilberted( ", hilbertedChannels, ")"
for i,j in hilbertedChannels.iteritems():
self.hilbertedChannels[i] = j
d = self.amp.get_electrode_to_indices_dict()
print "set_hilberted: get_electrode_to_indices_dict is " , d
self.lastDataQuery = None
def get_rectified(self):
#print "mcc XXX: EEGBase.get_rectified()"
return self.rectifiedChannels
def get_hilberted(self):
#print "mcc XXX: EEGBase.get_hilberted()"
return self.hilbertedChannels
def get_eoi(self, fname):
eois = self.get_associated_files(5, mapped=0, fname=fname)
if len(eois)==0:
raise ValueError, 'No EOI for patient %d with filename %s' % \
(self.pid, fname)
elif len(eois)>1:
raise ValueError, 'Found multiple EOIS %d with filename %s' % \
(self.pid, fname)
else:
eois[0].set_active_eeg(eeg)
return eois[0]
def get_amp(self, name=None):
if name is not None:
amps = self.get_associated_files(3, mapped=1)
for amp in amps:
if amp.filename == name:
amp.set_active_eeg(self)
self.amp = amp
break
else:
raise ValueError('Could not find amp file with name %s' % name)
try: return self.amp
except AttributeError:
amps = self.get_associated_files(3, mapped=1)
for amp in amps :
amp.set_active_eeg(self)
if len(amps)==1:
amp = amps[0]
elif len(amps)>1:
amp = amps[0]
amp.message = 'Warning: %s has more than one amp file; using %s' %\
(self.filename, amp.filename)
else:
#make a default amp file
amp = Amp()
amp.message = 'No AMP file associated with this EEG; using default'
channels = []
for i in range(self.get_channels()):
channels.append((i+1, 'NA', i+1))
amp.set_channels(channels)
amp.set_active_eeg(self)
self.amp = amp
return amp
def get_grd(self):
try: return self.grd
except AttributeError:
grds = self.get_associated_files(4, mapped=1)
if len(grds)==1:
grd = grds[0]
elif len(grds)>1:
grd = grds[0]
# xxx popup select dialog
print 'Warning: %s has more than one grd file; using %s' %\
(self.filename, grd.filename)
elif len(grds)==0:
return None
grd.set_active_eeg(self)
self.grd = grd
return grd
def get_loc3djr(self):
try: return self.loc3djr
except AttributeError: pass
loc3djrs = self.get_associated_files(8, mapped=0)
if not len(loc3djrs):
return None
self.loc3djr = loc3djrs[0]
self.loc3djr.set_active_eeg(self)
return self.loc3djr
def get_ann(self, name=None) :
if name is not None :
anns = self.get_associated_files(13, mapped=1)
for ann in anns :
if ann.filename == name :
ann.set_active_eeg(self)
self.ann = ann
break
else :
raise ValueError('Could not file annotation file with name %s' % name)
try : return self.ann
except AttributeError :
anns = self.get_associated_files(13, mapped=1)
if len(anns) == 1 :
ann = anns[0]
elif len(anns) > 1 :
ann = anns[0]
ann.message = 'Warning: %s has more than one annotation file; using %s' % \
(self.filename, ann.filename)
else :
ann = Ann(message='No annotation file associated with this EEG; using default')
ann.set_active_eeg(self)
self.ann = ann
return ann
def get_num_samples(self):
print "get_num_samples: self.file_type is ", self.file_type
self.load_data()
if self.file_type==BMSI: # nicolet bmsi
return os.path.getsize(self.fullpath)/(self.channels*2)
elif self.file_type==W18:
return os.path.getsize(self.fullpath)/18432*1000
elif self.file_type==AXONASCII:
raw_data = self.get_raw_data()
print "raw_data.shape is ", raw_data.shape
(rows, cols) = raw_data.shape
num_entries_per_channel = int(rows / self.get_channels())
#print "num_entries_per_channel=", num_entries_per_channel
num_samples = num_entries_per_channel * self.get_freq()
#print "num_samples=", num_samples
return(math.floor(num_samples))
elif self.file_type==NEUROSCANASCII:
raw_data = self.get_raw_data()
#print "raw_data.shape is ", raw_data.shape
(rows, cols) = raw_data.shape
return cols
else: raise ValueError('Can only handle certain file types currently')
def get_tmax(self):
N = self.get_num_samples()
return N/self.freq
def set_baseline(self):
t, data = self.get_data(0, 0.1)
#self.baseline = resize(median(transpose(data)), (1, self.channels))
self.baseline = median(data)
#print self.baseline.shape, data.shape
def get_baseline(self):
try: return self.baseline
except AttributeError:
self.set_baseline()
return self.baseline
def get_data(self, tmin, tmax):
# mcc XXX: removed this (probably speed-improving)
# lastDataQuery optimisation as we may be requerying with new
# prefiltering. maybe bring this back somehow.
# if (self.lastDataQuery is not None and
# self.lastDataQuery[0] == (tmin, tmax) ):
# return self.lastDataQuery[1]
print "EEGBase.get_data(", tmin, tmax,")"
assert(tmax>tmin)
#print 'filetype', type(self.file_type), self.file_type
#print self.file_type, self.readmap[self.file_type]
try: t, data = self.readmap[self.file_type](tmin, tmax)
except KeyError:
raise KeyError('Do not know how to handle file type %s'%self.file_type)