-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathDataModel.py
2650 lines (2062 loc) · 109 KB
/
DataModel.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
# ----------------------------------------------------------------------
# gHRV: a graphical application for Heart Rate Variability analysis
# Copyright (C) 2020 LIA2 Research Group - Dpt. Informatics
# University of Vigo - Spain
#
# Authors:
# - Leandro Rodríguez-Liñares
# - Arturo Méndez
# - María José Lado
# - Xosé Antón Vila
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------
import os, random
import numpy as np
from sys import platform
from configvalues import *
import matplotlib
import Utils
from matplotlib.widgets import Button
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
listofsettings=['interpfreq','windowsize','windowshift','ulfmin','ulfmax','vlfmin','vlfmax','lfmin','lfmax','hfmin','hfmax','name']
class DM:
data={}
labelColors=['Orange','cyan','red','blue','green','yellow','grey','pink','purple','maroon','lightgreen']
def __init__(self,Verbose):
"""Initialization of the data model"""
self.ClearAll()
self.data["Verbose"]=Verbose
if (self.data["Verbose"]==True):
print("** Creating data model")
def SetVerbose(self,verboseValue):
self.data["Verbose"] = verboseValue
def ClearAll(self):
self.data={}
self.data["Verbose"]=Verbose
self.data["name"]=""
#self.data["version"]=Version
self.ClearColors()
self.ClearBands()
self.ClearPP()
if (self.data["Verbose"]==True):
print("** Clearing all data")
def ClearColors(self):
"""Resets colors for episodes"""
self.data["ColorIndex"]=0
self.data["DictColors"]={}
def ClearBands(self):
self.data["Bands"]=["LF/HF","ULF","VLF","LF","HF","Power","Mean HR","HR STD","pNN50","rMSSD","ApEn","FracDim","Heart rate"]
self.data["VisibleBands"]=["LF/HF","ULF","VLF","LF","HF","Heart rate"]
self.data["FixedBands"]=["Heart rate"]
def ClearPP(self):
self.data["PPActiveTagLeft"]="Global"
self.data["PPActiveTagRight"]="None"
def AssignEpisodeColor(self,Tag):
"""Assigns color to episodes tags"""
if self.data["ColorIndex"] == len(self.labelColors)-1:
self.data["DictColors"][Tag]=(random.random(),random.random(),random.random())
else:
self.data["DictColors"][Tag]=self.labelColors[self.data["ColorIndex"]]
self.data["ColorIndex"] += 1
def GetEpisodeColor(self,Tag):
"""Returns color assigned to an episode Tag"""
return self.data["DictColors"][Tag]
def LoadFileAscii(self,asciiFile,settings):
"""Loads from ascii file
One data (beats instants in seconds, rr in msec. or rr in sec.) per line"""
if (self.data["Verbose"]==True):
print(("** Loading ascii file "+asciiFile))
asciiData = np.loadtxt(asciiFile)
asciiDataDiffs=np.diff(asciiData)
asciiDataNeg = [ x for x in asciiDataDiffs if x<0]
if len(asciiDataNeg)>0: # The file contains an RR series
asciiDataBig = [x for x in asciiData if x>100]
if len(asciiDataBig)>0:
if (self.data["Verbose"]==True):
print(" File contains RR data in milliseconds")
self.LoadRRMillisec(asciiData,settings)
else:
if (self.data["Verbose"]==True):
print(" File contains RR data in seconds")
self.LoadRRMillisec(asciiData*1000.0,settings)
else:
if (self.data["Verbose"]==True):
print(" File contains beats instants in seconds")
self.LoadBeatSec(asciiData,settings)
self.data["name"]=os.path.splitext(os.path.basename(asciiFile))[0]
if (self.data["Verbose"]):
print((" Project created: "+self.data["name"]))
self.data["version"]=Version
def LoadBeatSec(self,dataSec,settings):
"""Loads a vector containing beats positions in seconds"""
self.data["BeatTime"]=dataSec
self.data["niHR"] = 60.0/(self.data["BeatTime"][1:]-self.data["BeatTime"][0:-1])
self.data["niHR"] = np.insert(self.data["niHR"],[0],self.data["niHR"][0])
self.data["RR"] = 1000.0*(self.data["BeatTime"][1:]-self.data["BeatTime"][0:-1])
self.data["RR"] = np.insert(self.data["RR"],[0],self.data["RR"][0])
if (self.data["Verbose"]):
print((" BeatTime: "+str(len(self.data["BeatTime"]))+" points (max: "+str(self.data["BeatTime"][-1])+")"))
print((" niHR: "+str(len(self.data["niHR"]))+" points"))
print((" RR: "+str(len(self.data["RR"]))+" points"))
for k in list(settings.keys()):
self.data[k]=float(settings[k])
if (self.data["Verbose"]):
print(" Parameters set to default values")
def LoadRRMillisec(self,dataMSec,settings):
"""Loads a vector containing milliseconds"""
self.data["RR"]=np.array(dataMSec)
self.data["BeatTime"]=np.cumsum(self.data["RR"])/1000.0
self.data["niHR"]=60.0/(self.data["RR"]/1000.0)
if (self.data["Verbose"]==True):
print((" BeatTime: "+str(len(self.data["BeatTime"]))+" points (max: "+str(self.data["BeatTime"][-1])+")"))
print((" RR: "+str(len(self.data["RR"]))+" points"))
print((" niHR: "+str(len(self.data["niHR"]))+" points"))
for k in list(settings.keys()):
self.data[k]=float(settings[k])
if (self.data["Verbose"]):
print(" Parameters set to default values")
def LoadFilePolar(self,polarFile,settings):
"""Loads polar file
Polar files contain rr series, expresed in milliseconds"""
if (self.data["Verbose"]==True):
print(("** Loading polar file "+polarFile))
dataMillisec=[]
dataFound=False
File = open(polarFile,'r')
for line in File:
if dataFound:
data=line.strip()
if data:
dataMillisec.append(float(data))
if line.strip() == "[HRData]":
dataFound=True
File.close()
self.LoadRRMillisec(dataMillisec,settings)
self.data["name"]=os.path.splitext(os.path.basename(polarFile))[0]
if (self.data["Verbose"]):
print((" Project created: "+self.data["name"]))
self.data["version"]=Version
def LoadFileSuunto(self,suuntoFile,settings):
"""Loads suunto file
suunto files contain rr series, expresed in milliseconds"""
if (self.data["Verbose"]==True):
print(("** Loading suunto file "+suuntoFile))
dataMillisec=[]
dataFound=False
File = open(suuntoFile,'r')
for line in File:
if dataFound:
data=line.strip()
if data:
dataMillisec.append(float(data))
if line.strip() == "[CUSTOM1]":
dataFound=True
File.close()
self.LoadRRMillisec(dataMillisec,settings)
self.data["name"]=os.path.splitext(os.path.basename(suuntoFile))[0]
if (self.data["Verbose"]):
print((" Project created: "+self.data["name"]))
self.data["version"]=Version
def LoadBeatWFDB(self,wfdbheaderfile,settings):
"""Loads wfdb file"""
import glob
if (self.data["Verbose"]==True):
print(("** Loading WFDB file "+wfdbheaderfile))
heaFile = open(wfdbheaderfile,'r')
line=heaFile.readline()
heaFile.close()
lineFields = line.split(" ")
if len(lineFields)>2:
try:
samplingFrequency = float(lineFields[2])
except:
samplingFrequency = 250.0
else:
samplingFrequency = 250.0
if (self.data["Verbose"]==True):
print((" Sampling frequency: "+str(samplingFrequency)))
filesfound = glob.glob(wfdbheaderfile[:-4]+".*")
extensionsfound=[]
for filefound in filesfound:
extension = os.path.splitext(filefound)[1][1:]
extensionsfound.append(extension)
extensionsfound.remove('hea')
if len(extensionsfound)==0:
Utils.ErrorWindow(messageStr="No data file found with: "+wfdbheaderfile,captionStr="Error loading beats ")
return
if 'dat' in extensionsfound:
extensionsfound.remove('dat')
if 'atr' in extensionsfound:
extensionsfound.remove('atr')
extensionsfound.insert(0,'atr')
if 'qrs' in extensionsfound:
extensionsfound.remove('qrs')
extensionsfound.insert(0,'qrs')
if len(extensionsfound)>1:
AnnotatorSelection=Utils.SelectAnnotator(extensionsfound)
extensionSelected = AnnotatorSelection.GetValue()
if extensionSelected == '':
return
else:
extensionSelected=extensionsfound[0]
# 'qrs' in first place, then 'atr'
wfdbdatafile=wfdbheaderfile[:-4]+"."+extensionSelected
if (self.data["Verbose"]==True):
print((" Trying data file: "+wfdbdatafile))
try:
datafile = open(wfdbdatafile,'rb')
accumulator=0.0
beats=[]
while True:
value = ord(datafile.read(1))+ord(datafile.read(1))*256
code = value >> 10
time = value % 1024
# print ("Value: "+str(int(value)))
# print ("Code: "+str(code))
# print ("Time: "+str(time))
if code==0 and time==0:
break
# Original code:
# if code==1: # Only normal beats
# Modified code:
if code<50:
accumulator = accumulator+time
# print "Sec: ",accumulator/samplingFrequency
beats.append(accumulator/samplingFrequency)
else:
if code==63:
# Modified code:
jump = int(time) + int(time)%2
x = datafile.read(jump)
value = ord(datafile.read(1))+ord(datafile.read(1))*256
# Original code:
# jump = int(time)/2 + int(time)%2
# for i in range(jump):
# value = ord(datafile.read(1))+ord(datafile.read(1))*256
else:
if code==59 and time==0:
for i in range(2):
value = ord(datafile.read(1))+ord(datafile.read(1))*256
else:
if code!=60 and code!=61 and code!=62 and code!=22 and code!=0:
accumulator = accumulator+time
except:
if (self.data["Verbose"]==True):
print((" File "+wfdbdatafile+" didn't work"))
Utils.ErrorWindow(messageStr="Error loading file: "+wfdbdatafile,captionStr="Error loading beats ")
return
else:
if (self.data["Verbose"]==True):
print((" File "+wfdbdatafile+" has been loaded"))
self.LoadBeatSec(np.array(beats),settings)
self.data["name"]=os.path.splitext(os.path.basename(wfdbheaderfile))[0]
if (self.data["Verbose"]):
print((" Project created: "+self.data["name"]))
self.data["version"]=Version
def LoadEpisodesAscii(self,episodesFile):
"""Reads espisodes from ascii file
episodesFile -> file containing episodes. Must be in the following format:
Init_Time Resp_Events Durat SaO2
00:33:00 GEN_HYPO 120.0 82.9
01:30:00 OBS_APNEA 60.0 81.0
...
First line of file is discarded
Duration in seconds"""
if (self.data["Verbose"]):
print(("** Opening episodes file: "+episodesFile))
epFile = open(episodesFile,'r')
index=0
for line in epFile:
if index!=0:
linedata=line.strip().split()
if "EpisodesType" not in self.data:
self.__CreatesEpisodesInfo()
self.data["EpisodesType"].append(linedata[1])
self.data["EpisodesDuration"].append(float(linedata[2]))
HMS=linedata[0].split(":")
self.data["EpisodesInitTime"].append(float(HMS[0])*3600.0+float(HMS[1])*60.0+float(HMS[2]))
index += 1
epFile.close()
self.data["EpisodesVisible"]=list(set(self.data["EpisodesType"]))
if (self.data["Verbose"]):
print((" Read "+str(len(self.data["EpisodesType"]))+" episodes from file"))
print((" Read "+str(len(self.data["EpisodesVisible"]))+" types of episodes"))
def LoadEpisodesWFDB(self,wfdbheaderfile):
"""Loads episodes from physionet files"""
import glob
if (self.data["Verbose"]==True):
print(("** Loading episodes from WFDB file "+wfdbheaderfile))
heaFile = open(wfdbheaderfile,'r')
line=heaFile.readline()
heaFile.close()
lineFields = line.split(" ")
if len(lineFields)>2:
try:
samplingFrequency = float(lineFields[2])
except:
samplingFrequency = 250.0
else:
samplingFrequency = 250.0
if (self.data["Verbose"]==True):
print((" Sampling frequency: "+str(samplingFrequency)))
filesfound = glob.glob(wfdbheaderfile[:-4]+".*")
extensionsfound=[]
for filefound in filesfound:
extension = os.path.splitext(filefound)[1][1:]
extensionsfound.append(extension)
extensionsfound.remove('hea')
if len(extensionsfound)==0:
Utils.ErrorWindow(messageStr="No data file found with: "+wfdbheaderfile,captionStr="Error loading episodes ")
return
if 'dat' in extensionsfound:
extensionsfound.remove('dat')
if 'atr' in extensionsfound:
extensionsfound.remove('atr')
extensionsfound.append('atr')
if 'qrs' in extensionsfound:
extensionsfound.remove('qrs')
extensionsfound.append('qrs')
if len(extensionsfound)>1:
AnnotatorSelection=Utils.SelectAnnotator(extensionsfound)
extensionSelected = AnnotatorSelection.GetValue()
if extensionSelected == '':
return
else:
extensionSelected=extensionsfound[0]
wfdbdatafile=wfdbheaderfile[:-4]+"."+extensionSelected
if (self.data["Verbose"]==True):
print((" Trying data file: "+wfdbdatafile))
try:
ApneaTag="Apnea"
datafile = open(wfdbdatafile,'rb')
accumulator=0.0
ActiveTags=[]
ActiveTagsOnsets=[]
EpisodesTypes=[]
EpisodesInits=[]
EpisodesEnds=[]
if extensionSelected=="apn":
while True:
value = ord(datafile.read(1))+ord(datafile.read(1))*256
code = value >> 10
time = value % 1024
if code==0 and time==0:
break
if code==8 and ApneaTag not in ActiveTags:
ActiveTags.append(ApneaTag)
ActiveTagsOnsets.append(accumulator)
if code==1 and ApneaTag in ActiveTags:
EpisodesTypes.append(ApneaTag)
EpisodesInits.append(ActiveTagsOnsets[0])
EpisodesEnds.append(accumulator)
del ActiveTags[0]
del ActiveTagsOnsets[0]
if code == 59:
interval = (ord(datafile.read(1))+ord(datafile.read(1))*256)*65536+(ord(datafile.read(1))+ord(datafile.read(1))*256)
accumulator=accumulator+interval/samplingFrequency
next
else:
while True:
value = ord(datafile.read(1))+ord(datafile.read(1))*256
code = value >> 10
time = value % 1024
if code==0 and time==0:
break
if code <= 49:
next
if code == 59:
interval = (ord(datafile.read(1))+ord(datafile.read(1))*256)*65536+(ord(datafile.read(1))+ord(datafile.read(1))*256)
accumulator=accumulator+interval/samplingFrequency
next
if code==22:
ll = ord(datafile.read(1))
datafile.read(1) # value 252
comment = datafile.read(ll)
# print " String: ",comment
Tags=comment.split()
if (ll%2):
datafile.read(1)
for ActiveTag in ActiveTags:
if ActiveTag not in Tags:
ii=ActiveTags.index(ActiveTag)
EpisodesTypes.append(ActiveTag)
EpisodesInits.append(ActiveTagsOnsets[ii])
EpisodesEnds.append(accumulator)
del ActiveTags[ii]
del ActiveTagsOnsets[ii]
for Tag in Tags:
if Tag not in ActiveTags:
ActiveTags.append(Tag)
ActiveTagsOnsets.append(accumulator)
for ActiveTag in ActiveTags:
ii=ActiveTags.index(ActiveTag)
EpisodesTypes.append(ActiveTag)
EpisodesInits.append(ActiveTagsOnsets[ii])
EpisodesEnds.append(self.GetHRDataPlot()[0][-1]) # Last beat
except:
if (self.data["Verbose"]==True):
print((" File "+wfdbdatafile+" didn't work"))
Utils.ErrorWindow(messageStr="Error loading file: "+wfdbdatafile,captionStr="Error loading episodes ")
return
else:
if (self.data["Verbose"]==True):
print((" File "+wfdbdatafile+" has been loaded"))
# print EpisodesTypes
# print EpisodesInits
# print EpisodesEnds
if len(EpisodesTypes)==0:
Utils.ErrorWindow(messageStr="No valid episodes found in: "+wfdbdatafile,captionStr="Error loading episodes ")
return
if extensionSelected=="apn":
TagsSelected=[ApneaTag]
else:
TagsDetected=sorted(list(set(EpisodesTypes)))
TagsSelection=Utils.SelectEpisodesTags(TagsDetected)
IndexTagsSelected = TagsSelection.GetValues()
if len(IndexTagsSelected) == 0:
return
TagsSelected=[]
for indexTag in IndexTagsSelected:
TagsSelected.append(TagsDetected[indexTag])
numAddedEpisodes=0
for indexEpisode in range(len(EpisodesTypes)):
if EpisodesTypes[indexEpisode] in TagsSelected:
self.AddEpisode(EpisodesInits[indexEpisode],EpisodesEnds[indexEpisode],EpisodesTypes[indexEpisode])
numAddedEpisodes += 1
Utils.InformEpisodesFile(wfdbdatafile,numAddedEpisodes)
def LoadProject(self,datamodelFile):
"""Loads the data model from a zip file"""
import zipfile, tempfile, shutil
tempDir = tempfile.mkdtemp(prefix="gHRV")
if self.data["Verbose"]:
print(("** Loading project: "+datamodelFile))
print((" Temporal directory: "+tempDir))
zf = zipfile.ZipFile(datamodelFile, mode='r')
for zfitem in zf.namelist():
zf.extract(zfitem,tempDir)
fileName=tempDir+os.sep+zfitem
dataName=zfitem[1:]
# print("--- Reading file: "+fileName)
if zfitem[0]=="#":
self.data[dataName]=np.loadtxt(fileName)
# print(" Length: "+str(len(self.data[dataName])))
else:
tempF = open(fileName,'r')
if dataName=="name" or dataName=='PPActiveTagLeft' or dataName=='PPActiveTagRight':
self.data[dataName]=tempF.read()
else:
self.data[dataName]=eval(tempF.read())
tempF.close()
# print(" Data: "+str(self.data[dataName]))
zf.close()
if "version" in list(self.data.keys()):
self.data["version"] = str(self.data["version"])
# version needs to be a string for comparison purposes
# print ("Keys: "+str(self.data.keys()))
#print self.data["name"]
if "interpfreq" not in list(self.data.keys()): # Project generated with gHRV 0.17
if self.data['Verbose']:
print(" Importing project from gHRV 0.17")
if 'FreqHR' in list(self.data.keys()):
del self.data['FreqHR']
for k in list(factorySettings.keys()):
self.data[k]=float(factorySettings[k])
self.data['name']='mygHRVproject'
if "version" not in list(self.data.keys()): # Project generated with gHRV 0.18 or older
if self.data['Verbose']:
print(" Importing project from gHRV 0.18 or older")
self.ClearBands()
if self.HasFrameBasedParams():
self.ClearFrameBasedParams()
self.CalculateFrameBasedParams(showProgress=True)
self.data["version"]=Version
if self.data["version"]<Version:
if self.data['Verbose']:
print((" gHRV version: *"+Version+"*"))
print((" Project build with gHRV version: *"+self.data["version"]+"*"))
print(" Importing project from an old version of gHRV")
self.ClearBands()
if self.HasFrameBasedParams():
self.ClearFrameBasedParams()
self.CalculateFrameBasedParams(showProgress=True)
self.data["version"]=Version
shutil.rmtree(tempDir)
def GetSettings(self):
"""Returns parameters of the project"""
settings={}
for k in listofsettings:
settings[k]=str(self.data[k])
return settings
def SetSettings(self,settings):
"""Sets parameters of the project"""
for k in listofsettings:
if k != 'name':
self.data[k]=float(settings[k])
else:
self.data[k]=settings[k]
def SaveProject(self,datamodelFile):
"""Saves the data model into a zip file"""
import zipfile,shutil,tempfile
tempDir = tempfile.mkdtemp(prefix="gHRV")
if self.data["Verbose"]:
print(("** Saving project: "+datamodelFile))
#print(" Temporal directory: "+tempDir)
for kData in list(self.data.keys()):
if type(self.data[kData])==np.ndarray:
tempFName=tempDir+os.sep+"#"+str(kData)
np.savetxt(tempFName,self.data[kData])
else:
# print kData, ": ", type(self.data[kData])
tempFName=tempDir+os.sep+"%"+str(kData)
tempF = open(tempFName,'w')
tempF.write(str(self.data[kData]))
tempF.close()
zf = zipfile.ZipFile(datamodelFile, mode='w',compression=zipfile.ZIP_DEFLATED)
list = os.listdir(tempDir)
for file in list:
#print("File: "+str(file))
zf.write(tempDir+os.sep+file,str(file))
zf.close()
shutil.rmtree(tempDir)
def SaveFrameBasedData(self,dataFile,listOfBands,SepChar,RHeader,CHeader):
if self.data["Verbose"]:
print(("** Saving frame-based data: "+dataFile))
print((" List of bands: "+str(listOfBands)))
print((" Separator: '"+SepChar+"'"))
print((" Row header: "+str(RHeader)))
print((" Column header: "+str(CHeader)))
NumFrames=len(self.data["ULF"])
File = open(dataFile,'w')
if RHeader:
FirstColumn = True
if CHeader:
File.write("Frame")
FirstColumn=False
for Band in listOfBands:
if FirstColumn:
FirstColumn=False
else:
File.write(SepChar)
File.write(Band.replace(" ","_"))
File.write("\n")
for x in range(NumFrames):
FirstColumn = True
if CHeader:
File.write(str(x))
FirstColumn=False
for Band in listOfBands:
if FirstColumn:
FirstColumn = False
else:
File.write(SepChar)
if Band == "LF/HF":
File.write(str(self.data["LFHF"][x]))
else:
File.write(str(self.data[Band][x]))
File.write("\n")
File.close()
if self.data["Verbose"]:
print((" No. of lines: "+str(NumFrames)))
def ClearEpisodes(self):
"""Purges episodes from data model"""
del self.data["EpisodesType"]
del self.data["EpisodesInitTime"]
del self.data["EpisodesDuration"]
del self.data["EpisodesVisible"]
if (self.data["Verbose"]):
print("** Episodes removed from data model")
def ClearHR(self):
"""Purges interpolated HR from data model"""
del self.data["HR"]
del self.data["PlotHRXMin"]
del self.data["PlotHRXMax"]
if (self.data["Verbose"]):
print("** Interpolated HR removed from data model")
def ClearFrameBasedParams(self):
"""Purges power bands information from data model"""
del self.data["ULF"]
del self.data["VLF"]
del self.data["LF"]
del self.data["HF"]
del self.data["LFHF"]
if (self.data["Verbose"]):
print("** Power bands removed from data model")
def __CreatesEpisodesInfo(self):
"""Creates blank episodes structure"""
self.data["EpisodesType"]=[]
self.data["EpisodesInitTime"]=[]
self.data["EpisodesDuration"]=[]
self.data["EpisodesVisible"]=[]
def AddEpisode(self,init,end,tag):
"""Adds information of one episode"""
if (self.data["Verbose"]):
print(("** Adding an episode ({0:.2f},{1:.2f}) with label {2:s}".format(init,end,tag)))
if "EpisodesType" not in self.data:
self.__CreatesEpisodesInfo()
self.data["EpisodesType"].append(tag)
self.data["EpisodesInitTime"].append(init)
self.data["EpisodesDuration"].append(float(end)-float(init))
if tag not in self.data["EpisodesVisible"]:
self.data["EpisodesVisible"].append(tag)
def SetEpisodes(self,Episodes):
if (self.data["Verbose"]):
print ("** Changing episodes from manual edition")
if len(Episodes)==0:
self.ClearEpisodes()
self.ClearColors()
if (self.data["Verbose"]):
print (" Episodes information removed")
return
EpVis = list(self.data["EpisodesVisible"])
self.__CreatesEpisodesInfo()
for Ep in Episodes:
self.data["EpisodesType"].append(Ep[0])
self.data["EpisodesInitTime"].append(Ep[1])
self.data["EpisodesDuration"].append(Ep[3])
# Removes tags label if all episodes of this label were removed
self.data["EpisodesVisible"]=[Tag for Tag in EpVis if Tag in self.data["EpisodesType"]]
if (self.data["Verbose"]):
print((" Number of episodes: "+str(len(Episodes))))
def ReplaceHRVectors(self,xvector,yvector,rrvector):
"""After EditNIHR the beats (Time, niHR and RR) are replaced"""
self.data["BeatTime"]=xvector
self.data["niHR"]=yvector
self.data["RR"]=rrvector
if (self.data["Verbose"]):
print("** HR vectors replaced")
print((" BeatTime: "+str(len(self.data["BeatTime"]))+" points (max: "+str(self.data["BeatTime"][-1])+")"))
print((" niHR: "+str(len(self.data["niHR"]))+" points"))
print((" RR: "+str(len(self.data["RR"]))+" points"))
def FilterNIHR(self,winlength=50,last=13,minbpm=24,maxbpm=198):
"""Removes outliers from non interpolated heart rate"""
if (self.data["Verbose"]):
print ("** Filtering non-interpolated heart rate")
print((" Number of original beats: "+str(len(self.data["niHR"]))))
# threshold initialization
ulast=last
umean=1.5*ulast
index=1
while index<len(self.data["niHR"])-1:
v=self.data["niHR"][max(index-winlength,0):index]
M=np.mean(v)
if ( ( (100*abs((self.data["niHR"][index]-self.data["niHR"][index-1])/self.data["niHR"][index-1]) < ulast) |
(100*abs((self.data["niHR"][index]-self.data["niHR"][index+1])/self.data["niHR"][index+1]) < ulast) |
(100*abs((self.data["niHR"][index]-M)/M) < umean) )
& (self.data["niHR"][index] > minbpm) & (self.data["niHR"][index] < maxbpm)):
index += 1
else:
self.data["BeatTime"]=np.delete(self.data["BeatTime"],index)
self.data["niHR"]=np.delete(self.data["niHR"],index)
self.data["RR"]=np.delete(self.data["RR"],index)
if (self.data["Verbose"]):
print((" Number of filtered beats: "+str(len(self.data["BeatTime"]))))
def InterpolateNIHR(self):
"Interpolates instantaneous heart rate (linear method)"
from scipy import interpolate
if self.data["Verbose"]:
print ("** Interpolating instantaneous heart rate (method: linear interpolation)")
print((" Frequency: "+str(self.data["interpfreq"])+" Hz"))
xmin=self.data["BeatTime"][0]
xmax=self.data["BeatTime"][-1]
step=1.0/self.data["interpfreq"]
tck = interpolate.interp1d(self.data["BeatTime"],self.data["niHR"])
xnew = np.arange(xmin,xmax,step)
if self.data["Verbose"]:
print((" Original signal from: "+str(self.data["BeatTime"][0])+" to "+str(self.data["BeatTime"][-1])))
print((" Interpolating from "+str(xmin)+" to "+str(xmax)+" seconds"))
self.data["HR"] = tck(xnew)
if self.data["Verbose"]:
print((" Obtained "+str(len(self.data["HR"]))+" points"))
def GetNumFrames(self,interfreq,windowsize,windowshift):
shiftsamp=windowshift*interfreq
sizesamp=windowsize*interfreq
numframes=int(((len(self.data["HR"])-sizesamp)/shiftsamp)+1.0)
return numframes
def CalculateFrameBasedParams(self, showProgress=False):
"""Calculates power per band
size -> size of window (seconds)
shift -> displacement of window (seconds)"""
hammingfactor=1.586
def power(spec,freq,fmin,fmax):
band = [spec[i] for i in range(len(spec)) if freq[i] >= fmin and freq[i]<fmax]
powerinband = hammingfactor*np.sum(band)/(2*len(spec)**2)
return powerinband
if self.data["Verbose"]:
print("** Calculating power per band")
signal=1000/(self.data["HR"]/60.0) # msec.
shiftsamp=self.data['windowshift']*self.data["interpfreq"]
sizesamp=self.data['windowsize']*self.data["interpfreq"]
numframes=int(((len(signal)-sizesamp)/shiftsamp)+1.0)
lenZeroPadding=2**int(np.ceil(np.log2(sizesamp)))-int(sizesamp)
if (numframes < minNumFrames):
raise Utils.FewFramesException(numframes)
sizesamp2=sizesamp
if (sizesamp2%2 != 0):
sizesamp2=sizesamp2+1
hw=np.hamming(sizesamp2)
if numframes<=10:
showProgress = False
if showProgress:
import wx
dlg = wx.ProgressDialog("Calculating parameters","Preparing data...",maximum = (numframes-1)//10,
style=wx.PD_CAN_ABORT | wx.PD_AUTO_HIDE | wx.PD_REMAINING_TIME | wx.PD_ESTIMATED_TIME)
if self.data["Verbose"]:
print((" Signal length: "+str(len(signal))+" samples"))
print((" Frame length: "+str(sizesamp)+" samples"))
print((" Frame shift: "+str(shiftsamp)+" samples"))
print((" Number of frames: "+str(numframes)))
self.data["ULF"]=[]
self.data["VLF"]=[]
self.data["LF"]=[]
self.data["HF"]=[]
self.data["LFHF"]=[]
self.data["Power"]=[]
self.data["Mean HR"]=[]
self.data["HR STD"]=[]
self.data["pNN50"]=[]
self.data["rMSSD"]=[]
self.data["ApEn"]=[]
self.data["FracDim"]=[]
KeepGoing = True
indexframe = 0
while indexframe<numframes and KeepGoing:
if showProgress:
if indexframe%10 == 0:
KeepGoing = dlg.Update(indexframe//10, "Frame number: %s/%s" % (indexframe,numframes))[0]
# print "Keep: "+str(KeepGoing)
begframe=int(indexframe*shiftsamp)
endframe=int(begframe+sizesamp) # samples
frame=signal[begframe:endframe]
if (len(frame)%2 != 0):
frame=np.append(frame,[0])
begtime=indexframe*self.data['windowshift']
endtime=begtime+self.data['windowsize'] # seconds
frame=frame-np.mean(frame)
frame=frame*hw
frame = np.append(frame,np.zeros(lenZeroPadding))
# print("-----------------------")
# print("Frame "+str(indexframe))
# print("Frame power (time): "+str(hammingfactor*np.mean(frame*frame))+" ms^2")
spec_tmp=np.absolute(np.fft.fft(frame))**2
spec=spec_tmp[0:(len(spec_tmp)//2)] # Only positive half of spectrum
freqs = np.linspace(start=0,stop=self.data["interpfreq"]/2,num=len(spec),endpoint=True)
# print("Frame power (frequency): "+str(power(spec,freqs,0,self.data["interpfreq"]/2)))
ulfpower=power(spec,freqs,self.data["ulfmin"],self.data["ulfmax"])
self.data["ULF"].append(ulfpower)
#print("ULF power: "+str(ulfpower))
vlfpower=power(spec,freqs,self.data["vlfmin"],self.data["vlfmax"])
self.data["VLF"].append(vlfpower)
#print("VLF power: "+str(vlfpower))
lfpower=power(spec,freqs,self.data["lfmin"],self.data["lfmax"])
self.data["LF"].append(lfpower)
#print("LF power: "+str(lfpower))
hfpower=power(spec,freqs,self.data["hfmin"],self.data["hfmax"])
self.data["HF"].append(hfpower)
#print("HF: "+str(hfpower))
totalpower=power(spec,freqs,0,self.data["interpfreq"]/2.0)
self.data["Power"].append(totalpower)
#print("ULF+VLF+LF+HF power: "+str(ulfpower+vlfpower+lfpower+hfpower))
self.data["LFHF"].append(lfpower/hfpower)