forked from milegroup/ghrv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gHRV.py
executable file
·1658 lines (1268 loc) · 67.6 KB
/
gHRV.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/python
# -*- coding:utf-8 -*-
# ----------------------------------------------------------------------
# gHRV: a graphical application for Heart Rate Variability analysis
# Copyright (C) 2016 Milegroup - Dpt. Informatics
# University of Vigo - Spain
# www.milegroup.net
#
# 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/>.
# ----------------------------------------------------------------------
# TODO:
# - report con un fichero grande es muy lento
# - colores/monocromo
# - Yo veo muy interesante el poder especificar una fecha base para el registro, y visualizar sobre el eje horizontal fechas absolutas y no sólo el tiempo en segundos. Esto es muy importante para añadir episodios manualmente
# - Extra column for the frame based results export which shows give the episode (if any) for that frame.
# - To have separate main reports (and comparison reports like the poincare plots) for different episodes.
# - Seria util si junto con SD1 y SD2 fuera posibil saber el valor del centroid, el punto de encuentro entre los dos SD
# - Report: bpm en vez de bps
# - Poincaré: SD1 and SD2 in float point format
# - Time-domain TINN differs from Kubios
# - Report before Poincaré throws an error
# - In Linux Mint it depends on python-tk package
# - In MAC problems with foreign characters in paths
# - In certain linux systems these lines must be included:
# import wxversion
# wxversion.select("2.8")
# - URGENT: press "skip" does funny things with version in ghrv.cfg
# - Terminal mode in linux needs full paths of files to find them
import wx
import matplotlib
# matplotlib.use('WXAgg')
# from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
import matplotlib.pyplot
import os
import numpy as np
from sys import platform
from DataModel import DM
from configvalues import *
from AboutDlg import AboutDlg
from FrameBased import *
from EditEpisodes import EditEpisodesWindow
from EditNIHR import EditNIHRWindow
from PoincarePlot import PoincarePlotWindow
from ReportWindow import *
import Utils
# os.chdir("/usr/share/ghrv") # Uncomment when building a .deb package
dm=DM(Verbose)
# For debugging errors
# import sys
# sys.stdout = open('~/program.out', 'w')
# sys.stderr = open('~/program.err', 'w')
class MainWindow(wx.Frame):
""" Main window application"""
configDir = os.path.expanduser('~')+os.sep+'.ghrv'
configFile = configDir+os.sep+"ghrv.cfg"
sbDefaultText=" gHRV %s - http://ghrv.milegroup.net" % Version
def __init__(self, parent, id, title):
self.ConfigInit()
wx.Frame.__init__(self, parent, id, title)
if platform != "darwin":
icon = wx.Icon("LogoIcon.ico", wx.BITMAP_TYPE_ICO)
self.SetIcon(icon)
self.Bind(wx.EVT_CLOSE,self.OnExit)
self.MainPanel=wx.Panel(self)
self.fbWindowPresent=False
self.configWindowPresent=False
self.updateWindowPresent=False
self.editNIHRWindowPresent=False
self.editEpisodesWindowPresent=False
self.aboutWindowPresent=False
self.reportWindowPresent=False
self.signifWindowPresent=False
self.poincareWindowPresent=False
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
vboxLeftLeft = wx.BoxSizer(wx.VERTICAL)
panel11 = wx.Panel(self.MainPanel, 1, size=(30, 80))
panel11.SetBackgroundColour(LogoVertColor)
vboxLeftLeft.Add(panel11, proportion=1, flag=wx.GROW)
LogoBitmap=wx.Bitmap('LogoVert.png')
Logo = wx.StaticBitmap(self.MainPanel, bitmap=LogoBitmap )
vboxLeftLeft.Add(Logo, flag=wx.ALIGN_BOTTOM)
self.sizer.Add(vboxLeftLeft,flag=wx.EXPAND|wx.ALL, border=0)
vboxLeft = wx.BoxSizer(wx.VERTICAL)
# ----------------------------------
# Begin of sizer for project buttons
sbProjectButtons = wx.StaticBox(self.MainPanel, label="Projects")
sbProjectButtonsSizer = wx.StaticBoxSizer(sbProjectButtons, wx.VERTICAL)
sbProjectButtonsSizerRow1=wx.BoxSizer(wx.HORIZONTAL)
self.buttonLoadProject = wx.Button(self.MainPanel, -1, label="Load...")
sbProjectButtonsSizerRow1.Add(self.buttonLoadProject, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnProjectLoad, id=self.buttonLoadProject.GetId())
self.buttonLoadProject.SetToolTip(wx.ToolTip("Click to load gHRV project"))
sbProjectButtonsSizerRow1.AddStretchSpacer(1)
self.buttonSaveProject = wx.Button(self.MainPanel, -1, label="Save...")
sbProjectButtonsSizerRow1.Add(self.buttonSaveProject, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnProjectSave, id=self.buttonSaveProject.GetId())
self.buttonSaveProject.SetToolTip(wx.ToolTip("Click to save gHRV project"))
self.buttonSaveProject.Disable()
self.buttonClearProject = wx.Button(self.MainPanel, -1, label="Clear")
sbProjectButtonsSizerRow1.Add(self.buttonClearProject, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnProjectClear, id=self.buttonClearProject.GetId())
self.buttonClearProject.SetToolTip(wx.ToolTip("Click to clear all data"))
self.buttonClearProject.Disable()
sbProjectButtonsSizerRow2=wx.BoxSizer(wx.HORIZONTAL)
#sbProjectButtonsSizerRow2.AddStretchSpacer(1)
self.buttonOptionsProject = wx.Button(self.MainPanel, -1, label="Settings")
sbProjectButtonsSizerRow2.Add(self.buttonOptionsProject, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnProjectOptions, id=self.buttonOptionsProject.GetId())
self.buttonOptionsProject.SetToolTip(wx.ToolTip("Click to set project options"))
self.buttonOptionsProject.Disable()
sbProjectButtonsSizer.Add(sbProjectButtonsSizerRow1,flag=wx.EXPAND)
sbProjectButtonsSizer.Add(sbProjectButtonsSizerRow2,flag=wx.EXPAND)
vboxLeft.Add(sbProjectButtonsSizer, flag=wx.EXPAND | wx.TOP, border=borderVeryBig)
# End of sizer for project buttons
# --------------------------------
# --------------------------------
# Begin of sizer for beats buttons
sbBeatsButtons = wx.StaticBox(self.MainPanel, label="Heart rate data")
sbBeatsButtonsSizer = wx.StaticBoxSizer(sbBeatsButtons, wx.VERTICAL)
sbBeatsButtonsSizerRow1=wx.BoxSizer(wx.HORIZONTAL)
self.buttonLoadBeats = wx.Button(self.MainPanel, -1, label="Load...")
sbBeatsButtonsSizerRow1.Add(self.buttonLoadBeats, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnLoadBeat, id=self.buttonLoadBeats.GetId())
self.buttonLoadBeats.SetToolTip(wx.ToolTip("Click to load file"))
self.buttonFilterHR = wx.Button(self.MainPanel, -1, label="Filter")
sbBeatsButtonsSizerRow1.Add(self.buttonFilterHR, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnFilterNIHR, id=self.buttonFilterHR.GetId())
self.buttonFilterHR.SetToolTip(wx.ToolTip("Automatic removal of outliers"))
self.buttonFilterHR.Disable()
self.buttonEditHR = wx.Button(self.MainPanel, -1, label="Edit...")
sbBeatsButtonsSizerRow1.Add(self.buttonEditHR, flag=wx.ALL, border=borderSmall)
self.MainPanel.Bind(wx.EVT_BUTTON, self.OnNIHREdit, id=self.buttonEditHR.GetId())
self.buttonEditHR.SetToolTip(wx.ToolTip("Interactive removal of outliers"))
if platform != 'darwin' and ColoredButtons:
self.buttonEditHR.SetBackgroundColour(EditBGColor)
self.buttonEditHR.Disable()
sbBeatsButtonsSizerRow2=wx.BoxSizer(wx.HORIZONTAL)
self.buttonExportHR = wx.Button(self.MainPanel, -1, label="Export...")
sbBeatsButtonsSizerRow2.Add(self.buttonExportHR, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnExportHR, id=self.buttonExportHR.GetId())
self.buttonExportHR.SetToolTip(wx.ToolTip("Export beats/HR/RR"))
self.buttonExportHR.Disable()
sbBeatsButtonsSizer.Add(sbBeatsButtonsSizerRow1, flag=wx.EXPAND)
sbBeatsButtonsSizer.Add(sbBeatsButtonsSizerRow2, flag=wx.EXPAND)
vboxLeft.Add(sbBeatsButtonsSizer, flag=wx.EXPAND | wx.TOP, border=borderVeryBig)
# End of sizer for beats buttons
# --------------------------------
# ---------------------------------
# Begin of sizer for episodes buttons
sbEpisodesButtons = wx.StaticBox(self.MainPanel, label="Episodes")
sbEpisodesButtonsSizer = wx.StaticBoxSizer(sbEpisodesButtons, wx.VERTICAL)
sbEpisodesButtonsSizerRow1=wx.BoxSizer(wx.HORIZONTAL)
self.buttonLoadEpisodes = wx.Button(self.MainPanel, -1, label="Load...")
sbEpisodesButtonsSizerRow1.Add(self.buttonLoadEpisodes, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnLoadEpisodes, id=self.buttonLoadEpisodes.GetId())
self.buttonLoadEpisodes.SetToolTip(wx.ToolTip("Click to load ascii episodes file"))
self.buttonLoadEpisodes.Disable()
self.buttonClearEpisodes = wx.Button(self.MainPanel, -1, label="Clear")
sbEpisodesButtonsSizerRow1.Add(self.buttonClearEpisodes, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnEpisodesClear, id=self.buttonClearEpisodes.GetId())
self.buttonClearEpisodes.SetToolTip(wx.ToolTip("Click to clear episodes information"))
self.buttonClearEpisodes.Disable()
self.buttonEditEpisodes = wx.Button(self.MainPanel, -1, label="Edit...")
sbEpisodesButtonsSizerRow1.Add(self.buttonEditEpisodes, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnEpisodesEdit, id=self.buttonEditEpisodes.GetId())
self.buttonEditEpisodes.SetToolTip(wx.ToolTip("Click to open episodes editor"))
self.buttonEditEpisodes.Disable()
if platform != 'darwin' and ColoredButtons:
self.buttonEditEpisodes.SetBackgroundColour(EpisodesEditionBGColor)
sbEpisodesButtonsSizer.Add(sbEpisodesButtonsSizerRow1, flag=wx.EXPAND)
vboxLeft.Add(sbEpisodesButtonsSizer,flag=wx.EXPAND | wx.TOP, border=borderVeryBig)
# End of sizer for episodes buttons
# ---------------------------------
# --------------------------------
# Begin of sizer for tools buttons
sbToolsButtons = wx.StaticBox(self.MainPanel, label="Tools")
sbToolsButtonsSizer = wx.StaticBoxSizer(sbToolsButtons, wx.VERTICAL)
self.buttonAnalyze = wx.Button(self.MainPanel, -1, label="Interpolate")
sbToolsButtonsSizer.Add(self.buttonAnalyze, flag=wx.ALL | wx.EXPAND , border=borderSmall)
self.MainPanel.Bind(wx.EVT_BUTTON, self.OnInterpolateNIHR, id=self.buttonAnalyze.GetId())
self.buttonAnalyze.SetToolTip(wx.ToolTip("Interpolate heart rate signal"))
self.buttonAnalyze.Disable()
self.buttonTemporal = wx.Button(self.MainPanel, -1, label="Frame-based evolution")
sbToolsButtonsSizer.Add(self.buttonTemporal, flag=wx.ALL | wx.EXPAND, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnFrameBased, id=self.buttonTemporal.GetId())
self.buttonTemporal.SetToolTip(wx.ToolTip("Temporal evolution of parameters"))
if platform != 'darwin' and ColoredButtons:
self.buttonTemporal.SetBackgroundColour(TemporalBGColor)
self.buttonTemporal.Disable()
self.buttonReport = wx.Button(self.MainPanel, -1, label="Report")
sbToolsButtonsSizer.Add(self.buttonReport, flag=wx.ALL | wx.EXPAND, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnReport, id=self.buttonReport.GetId())
self.buttonReport.SetToolTip(wx.ToolTip("Create report"))
if platform != 'darwin' and ColoredButtons:
self.buttonReport.SetBackgroundColour(ReportBGColor)
self.buttonReport.Disable()
self.buttonPoincare = wx.Button(self.MainPanel, -1, label="Poincare plot")
sbToolsButtonsSizer.Add(self.buttonPoincare, flag=wx.ALL | wx.EXPAND, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnPoincare, id=self.buttonPoincare.GetId())
self.buttonPoincare.SetToolTip(wx.ToolTip("Poincare plot tool"))
if platform != 'darwin' and ColoredButtons:
self.buttonPoincare.SetBackgroundColour(PoincareBGColor)
self.buttonPoincare.Disable()
vboxLeft.Add(sbToolsButtonsSizer,flag=wx.TOP | wx.EXPAND, border=borderVeryBig)
# End of sizer for tools buttons
# ------------------------------
vboxLeft.AddStretchSpacer(1)
# ----------------------------------
# Begin of sizer for control buttons
sbControlButtons = wx.StaticBox(self.MainPanel, label="gHRV")
sbControlButtonsSizer = wx.StaticBoxSizer(sbControlButtons, wx.VERTICAL)
sbControlButtonsSizerRow1=wx.BoxSizer(wx.HORIZONTAL)
buttonQuit = wx.Button(self.MainPanel, -1, label="Quit")
sbControlButtonsSizerRow1.Add(buttonQuit, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnExit, id=buttonQuit.GetId())
buttonQuit.SetToolTip(wx.ToolTip("Click to quit using gHRV"))
self.buttonAbout = wx.Button(self.MainPanel, -1, label="About")
sbControlButtonsSizerRow1.Add(self.buttonAbout,flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnAbout, id=self.buttonAbout.GetId())
self.buttonAbout.SetToolTip(wx.ToolTip("Click to see information about gHRV"))
self.buttonConfig = wx.Button(self.MainPanel, -1, label="Config")
sbControlButtonsSizerRow1.Add(self.buttonConfig, flag=wx.ALL, border=borderSmall)
self.Bind(wx.EVT_BUTTON, self.OnConfig, id=self.buttonConfig.GetId())
self.buttonConfig.SetToolTip(wx.ToolTip("Click to open configuration window"))
sbControlButtonsSizer.Add(sbControlButtonsSizerRow1, flag=wx.EXPAND)
vboxLeft.Add(sbControlButtonsSizer,flag=wx.EXPAND|wx.TOP, border=borderVeryBig)
# End of sizer for control buttons
# --------------------------------
self.sizer.Add(vboxLeft,flag=wx.ALL|wx.EXPAND, border=borderBig)
# ------------------
# Begin of plot area
if ColoredBGPlots:
self.fig = matplotlib.figure.Figure((4,5),facecolor=HRBGColor)
else:
self.fig = matplotlib.figure.Figure((4,5))
#self.fig.set_figwidth(5)
#self.fig.set_figheight(5)
self.canvas = FigureCanvas(self.MainPanel, -1, self.fig)
#self.axes = self.fig.add_axes([0,0,1,1])
#self.axes.imshow(self.data, interpolation="quadric")
self.sizer.Add(self.canvas,1, wx.ALL | wx.GROW, border=borderSmall)
# End of plot area
# ----------------
self.sb = self.CreateStatusBar()
self.sb.SetStatusText(self.sbDefaultText)
defSize,minSize=Utils.RecalculateWindowSizes(mainWindowSize,mainWindowMinSize)
self.SetSize(defSize)
self.SetMinSize(minSize)
self.SetTitle('gHRV')
self.Centre()
self.MainPanel.SetSizer(self.sizer)
self.MainPanel.Layout()
import sys
HelpString = (
" -help: shows this information\n"
" -loadBeatTXT beatfile: loads beats file (TXT format)\n"
" -loadEpTXT episodesfile: loads episodes (TXT format)\n"
" -filter: filters the HR sequence\n"
" -interp: interpolates the HR sequence\n"
)
if (len(sys.argv) != 1 and sys.platform=='linux2'):
arguments = sys.argv[1:]
# arguments = [sys.argv[x].lower() for x in range(1,len(sys.argv))]
# print arguments
possibleArguments = ['-help','-loadBeatTXT','-loadEpTXT',
'-filter','-interp']
for argument in arguments:
if argument[0] == '-':
if argument not in possibleArguments:
print "\n** ERROR: command '"+argument+"' not recognized **\n"
print "** gHRV terminal mode commands:"
print HelpString
sys.exit(0)
if "-help" in arguments:
print ("\n** gHRV: terminal mode **\n")
print HelpString
sys.exit(0)
else:
print ("\n** gHRV: terminal mode **\n")
dm.SetVerbose(True)
BeatTXTFilePresent = False
EpisodesAsciiFilePresent = False
InterpolationFlagPresent = False
FilterFlagPresent = False
if "-loadBeatTXT" in arguments:
BeatTXTFile = arguments[arguments.index("-loadBeatTXT")+1]
BeatTXTFilePresent = True
if "-loadEpTXT" in arguments:
EpisodesAsciiFile = arguments[arguments.index("-loadEpTXT")+1]
EpisodesAsciiFilePresent = True
if "-interpolate" in arguments:
InterpolationFlagPresent = True
if "-filter" in arguments:
FilterFlagPresent = True
if (EpisodesAsciiFilePresent and not BeatTXTFilePresent):
print "** ERROR: trying to load episodes without beats! **\n"
sys.exit()
if (FilterFlagPresent and not BeatTXTFilePresent):
print "** ERROR: trying to filter without beats! **\n"
sys.exit()
if (InterpolationFlagPresent and not BeatTXTFilePresent):
print "** ERROR: trying to interpolate without beats! **\n"
sys.exit()
try:
dm.LoadFileAscii(BeatTXTFile, self.settings)
except:
print "** ERROR: the file does not seem to be a valid beats file **"
sys.exit(1)
if FilterFlagPresent:
dm.FilterNIHR()
if InterpolationFlagPresent:
dm.InterpolateNIHR()
if EpisodesAsciiFilePresent:
try:
dm.LoadEpisodesAscii(EpisodesAsciiFile)
except:
print "** ERROR: the file does not seem to be a valid episodes file **"
sys.exit(1)
EpisodesTags=dm.GetEpisodesTags()
for Tag in EpisodesTags:
dm.AssignEpisodeColor(Tag)
self.RefreshMainWindow()
self.RefreshMainWindowButtons()
# sys.exit(1)
# if DebugMode:
# dm.LoadFileAscii("../data/beat_ascii.txt", self.settings)
# dm.FilterNIHR()
# dm.LoadEpisodesAscii("../data/apnea_ascii.txt")
# EpisodesTags=dm.GetEpisodesTags()
# for Tag in EpisodesTags:
# dm.AssignEpisodeColor(Tag)
# dm.InterpolateNIHR()
# self.RefreshMainWindow()
# PoincarePlotWindow(self,-1,'Poincaré plot',dm)
# self.poincareWindowPresent=True
# self.RefreshMainWindowButtons()
# if dm.HasFrameBasedParams()==False:
# dm.CalculateFrameBasedParams(showProgress=True)
# self.fbWindow = FrameBasedEvolutionWindow(self,-1,"Temporal evolution of parameters",dm)
# self.fbWindowPresent=True
# self.RefreshMainWindowButtons()
# EditEpisodesWindow(self,-1,'Episodes Edition',dm)
# self.editEpisodesWindowPresent=True
# import tempfile
# reportName="report.html"
# reportDir=tempfile.mkdtemp(prefix="gHRV_Report_")
# dm.CreateReport(reportDir,reportName,'report_files')
# ReportWindow(self,-1,'Report: '+dm.GetName(),reportDir+os.sep+reportName, dm)
# self.reportWindowPresent=True
# self.RefreshMainWindowButtons()
self.canvas.SetFocus()
self.CheckVersion()
def ConfigInit(self):
"""If config dir and file does not exist, it is created
If config file exists, it is loaded"""
from ConfigParser import SafeConfigParser
# print "Intializing configuration"
if not os.path.exists(self.configDir):
# print "Directory does not exists ... creating"
os.makedirs(self.configDir)
if os.path.exists(self.configFile):
self.ConfigLoad()
else:
self.settings=factorySettings
self.ConfigSave()
def ConfigLoad(self):
""" Loads configuration file"""
from ConfigParser import SafeConfigParser
self.settings={}
options=SafeConfigParser()
options.read(self.configFile)
for section in options.sections():
for param,value in options.items(section):
self.settings[param]=value
#print self.settings
def ConfigSave(self):
""" Saves configuration file"""
from ConfigParser import SafeConfigParser
options = SafeConfigParser()
options.add_section('ghrv')
for param in self.settings.keys():
options.set('ghrv',param,self.settings[param])
tempF = open(self.configFile,'w')
options.write(tempF)
tempF.close()
if platform=="win32":
import win32api,win32con
win32api.SetFileAttributes(self.configDir,win32con.FILE_ATTRIBUTE_HIDDEN)
#print self.settings
def CheckVersion(self):
from ConfigParser import SafeConfigParser
from sys import argv
import urllib2
if "lastcheckedversion" not in self.settings.keys(): # First run of the program
self.settings["lastcheckedversion"]=Version
self.ConfigSave()
if Version > self.settings["lastcheckedversion"]: # gHRV was just updated
self.settings["lastcheckedversion"]=Version
self.ConfigSave()
remoteVersion = ""
remoteVersionFile = ""
string =""
platformString=""
if argv[0].endswith("gHRV.py"):
string = string + "Running gHRV from source. Version: " + Version + "\n"
platformString = "src"
remoteVersionFile = "https://raw.github.com/milegroup/ghrv/master/ProgramVersions/src.txt"
if platform=="linux2" and argv[0]=="/usr/share/ghrv/gHRV.py":
string = string + "Running gHRV deb package. Version: " + Version + "\n"
platformString = "deb"
remoteVersionFile = "https://raw.github.com/milegroup/ghrv/master/ProgramVersions/deb.txt"
if platform=="darwin" and "gHRV.app" in argv[0]:
string = string + "Running gHRV mac package. Version: " + Version + "\n"
platformString = "mac"
remoteVersionFile = "https://raw.github.com/milegroup/ghrv/master/ProgramVersions/mac.txt"
if platform=="win32" and "gHRV.exe" in argv[0]:
string = string + "Running gHRV win package. Version: " + Version + "\n"
platformString = "win"
remoteVersionFile = "https://raw.github.com/milegroup/ghrv/master/ProgramVersions/win.txt"
try:
remoteFile = urllib2.urlopen(remoteVersionFile)
remoteVersion=remoteFile.readline().strip()
remoteFile.close()
string = string + "Version avalaible in gHRV web page: " + remoteVersion + "\n"
except urllib2.URLError:
string = string + "I couldn't check for updates\n"
string = string + "Last checked version "+self.settings["lastcheckedversion"]+"\n"
if remoteVersion:
if remoteVersion > self.settings["lastcheckedversion"]:
string = string + "Now I ask if the user wants to update!!!\n"
self.UpdateWindowOpen(remoteVersion,platformString)
if argv[0]=="gHRV.py":
print string
if ReportVersion:
dial = wx.MessageDialog(self, caption="Version info", message=string, style=wx.OK)
result = dial.ShowModal()
dial.Destroy()
def UpdateWindowOpen(self,remoteVersion,platformString):
self.updateWindowPresent=True
self.RefreshMainWindowButtons()
#print 'Before configuration: ',self.settings
UpdateSoftwareWindow(self,-1,remoteVersion,platformString)
def UpdateWindowClose(self):
self.updateWindowPresent=False
self.RefreshMainWindowButtons()
#print 'After configuration: ',self.settings
self.canvas.SetFocus()
def DisableAllButtons(self):
self.buttonLoadProject.Disable()
self.buttonSaveProject.Disable()
self.buttonClearProject.Disable()
self.buttonOptionsProject.Disable()
self.buttonLoadBeats.Disable()
self.buttonFilterHR.Disable()
self.buttonEditHR.Disable()
self.buttonExportHR.Disable()
self.buttonAnalyze.Disable()
self.buttonLoadEpisodes.Disable()
self.buttonEditEpisodes.Disable()
self.buttonClearEpisodes.Disable()
self.buttonTemporal.Disable()
self.buttonPoincare.Disable()
self.buttonConfig.Disable()
self.buttonAbout.Disable()
self.buttonReport.Disable()
def RefreshMainWindowButtons(self):
"""Redraws main window buttons"""
self.DisableAllButtons() # by default all disabled
if self.configWindowPresent or self.updateWindowPresent or self.aboutWindowPresent or self.editNIHRWindowPresent or self.editEpisodesWindowPresent or self.reportWindowPresent or self.signifWindowPresent or self.poincareWindowPresent:
return
self.buttonAbout.Enable()
self.buttonConfig.Enable()
if dm.HasHR():
self.buttonSaveProject.Enable()
if not self.fbWindowPresent:
self.buttonClearProject.Enable()
self.buttonOptionsProject.Enable()
self.buttonEditEpisodes.Enable()
self.buttonPoincare.Enable()
self.buttonExportHR.Enable()
if not self.reportWindowPresent:
self.buttonReport.Enable()
else:
self.buttonLoadBeats.Enable()
self.buttonLoadProject.Enable()
if dm.HasHR() and not dm.HasEpisodes():
self.buttonLoadEpisodes.Enable()
if dm.HasHR() and dm.HasEpisodes():
self.buttonClearEpisodes.Enable()
if dm.HasHR() and not dm.HasInterpolatedHR():
self.buttonEditHR.Enable()
self.buttonFilterHR.Enable()
self.buttonAnalyze.Enable()
if dm.HasInterpolatedHR() and not self.fbWindowPresent:
self.buttonTemporal.Enable()
def RefreshMainWindow(self):
"""Redraws main window"""
self.RefreshMainWindowButtons()
self.RefreshMainWindowPlot()
self.canvas.SetFocus()
def RefreshMainWindowPlot(self):
"""Redraws the plot of the main window"""
self.fig.clear()
dm.CreatePlotHREmbedded(self.fig)
self.canvas.draw()
self.canvas.SetFocus()
def WarningWindow(self,messageStr,captionStr="WARNING"):
"""Generic warning window"""
dial = wx.MessageDialog(self, caption=captionStr, message=messageStr, style=wx.OK | wx.ICON_WARNING)
result = dial.ShowModal()
dial.Destroy()
self.canvas.SetFocus()
def OnLoadBeat(self, event):
filetypes = "Supported files (*.txt;*.hrm;*sdf;*.hea)|*.txt;*.TXT;*.hrm;*.HRM;*.sdf;*.SDF;*.hea;*.HEA|TXT ascii files (*.txt)|*.txt;*.TXT|Polar files (*.hrm)|*.hrm;*.HRM|Suunto files (*.sdf)|*.sdf;*.SDF|WFDB header files (*.hea)|*.hea;*.HEA|All files (*.*)|*.*"
fileName=""
dial = wx.FileDialog(self, message="Load file", wildcard=filetypes, style=wx.FD_OPEN)
result = dial.ShowModal()
if result == wx.ID_OK:
fileName=dial.GetPath()
# ext=fileName[-3:].lower()
ext = os.path.splitext(fileName)[1][1:].strip()
dial.Destroy()
if ext=="txt":
try:
dm.LoadFileAscii(str(unicode(fileName)),self.settings)
except UnicodeEncodeError:
Utils.ErrorWindow(messageStr="Ilegal characters in filename: "+fileName,
captionStr="Error loading ascii file")
except:
Utils.ErrorWindow(messageStr=fileName+" does not seem to be a valid ascii file",
captionStr="Error loading ascii file")
else:
self.RefreshMainWindow()
elif ext=="hrm":
try:
dm.LoadFilePolar(str(unicode(fileName)),self.settings)
except UnicodeEncodeError:
Utils.ErrorWindow(messageStr="Ilegal characters in filename: "+fileName,
captionStr="Error loading polar file")
except:
Utils.ErrorWindow(messageStr=fileName+" does not seem to be a valid polar file",
captionStr="Error loading polar file")
else:
self.RefreshMainWindow()
elif ext=="sdf":
try:
dm.LoadFileSuunto(str(unicode(fileName)),self.settings)
except UnicodeEncodeError:
Utils.ErrorWindow(messageStr="Ilegal characters in filename: "+fileName,
captionStr="Error loading suunto file")
except:
Utils.ErrorWindow(messageStr=fileName+" does not seem to be a valid suunto file",
captionStr="Error loading suunto file")
else:
self.RefreshMainWindow()
elif ext=="hea":
# dial = wx.MessageDialog(self, "Not yet implemented", "Soon...", wx.OK)
# result = dial.ShowModal()
# dial.Destroy()
try:
dm.LoadBeatWFDB(str(unicode(fileName)),self.settings)
except UnicodeEncodeError:
Utils.ErrorWindow(messageStr="Ilegal characters in filename:\n"+fileName,
captionStr="Error loading WFDB file")
except:
Utils.ErrorWindow(messageStr="Problem loading WFDB file:\n"+fileName,
captionStr="Error loading WFDB file")
else:
if dm.HasHR():
self.RefreshMainWindow()
else:
try:
dm.LoadFileAscii(str(unicode(fileName)),self.settings)
except UnicodeEncodeError:
Utils.ErrorWindow(messageStr="Ilegal characters in filename: "+fileName,
captionStr="Error loading ascii file")
except:
Utils.ErrorWindow(messageStr=fileName+" does not seem to be a valid ascii file",
captionStr="Error loading ascii file")
else:
self.RefreshMainWindow()
self.canvas.SetFocus()
def OnLoadEpisodes(self,event):
fileName=""
filetypes = "Supported episodes files (*.txt;*.hea)|*.txt;*.TXT;*.hea;*.HEA|TXT ascii files (*.txt)|*.txt;*.TXT|WFDB header files (*.hea)|*.hea;*.HEA|All files (*.*)|*.*"
dial = wx.FileDialog(self, message="Load episodes file", wildcard=filetypes, style=wx.FD_OPEN)
result = dial.ShowModal()
if result == wx.ID_OK:
fileName=dial.GetPath()
ext = os.path.splitext(fileName)[1][1:].strip()
dial.Destroy()
if ext=="txt":
try:
dm.LoadEpisodesAscii(str(unicode(fileName)))
except UnicodeEncodeError:
Utils.ErrorWindow(messageStr="Ilegal characters in filename: "+fileName,
captionStr="Error loading episodes file")
return
except:
Utils.ErrorWindow(messageStr=fileName+" does not seem to be a valid episodes file",captionStr="Error loading episodes file")
return
elif ext=="hea":
try:
dm.LoadEpisodesWFDB(str(unicode(fileName)))
except UnicodeEncodeError:
Utils.ErrorWindow(messageStr="Ilegal characters in filename: "+fileName,
captionStr="Error loading episodes file")
return
except:
Utils.ErrorWindow(messageStr=fileName+" does not seem to be a valid episodes file",captionStr="Error loading episodes file")
return
EpisodesTags=dm.GetEpisodesTags() # New episodes were added
if len(EpisodesTags)!=0:
for Tag in EpisodesTags:
dm.AssignEpisodeColor(Tag)
self.RefreshMainWindow()
if self.fbWindowPresent:
self.fbWindow.Refresh()
EpInit = dm.GetEpisodes()[1]
EpDur = dm.GetEpisodes()[2]
EpFin = [float(EpInit[x])+float(EpDur[x]) for x in range(len(EpInit))]
EpFinMax = max(EpFin)
if EpFinMax > dm.GetHRDataPlot()[0][-1]:
self.WarningWindow(messageStr="WARNING: one or more episodes are outside of time axis",captionStr="Episodes warning")
self.canvas.SetFocus()
def OnProjectLoad(self,event):
filetypes = "gHRV project files (*.ghrv)|*.ghrv|" "All files (*.*)|*.*"
fileName=""
dial = wx.FileDialog(self, message="Load ghrv project", wildcard=filetypes, style=wx.FD_OPEN)
result = dial.ShowModal()
if result == wx.ID_OK:
fileName=dial.GetPath()
dial.Destroy()
try:
dm.LoadProject(str(unicode(fileName)))
except UnicodeEncodeError:
Utils.ErrorWindow(messageStr="Ilegal characters in filename: "+fileName,
captionStr="Error loading project file")
except:
import sys
print sys.exc_info()
Utils.ErrorWindow(messageStr=fileName+" does not seem to be a valid project file",captionStr="Error loading project file")
else:
self.RefreshMainWindow()
def OnProjectSave(self,event):
fileName=""
dial = wx.FileDialog(self, message="Save project as...", defaultFile=dm.GetName()+".ghrv", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
result = dial.ShowModal()
if result == wx.ID_OK:
fileName=dial.GetPath()
try:
dm.SaveProject(str(unicode(fileName)))
Utils.InformCorrectFile(fileName)
except UnicodeEncodeError:
Utils.ErrorWindow(messageStr="Ilegal characters in filename: "+fileName,
captionStr="Error saving project file")
except:
Utils.ErrorWindow(messageStr="Error saving project to file: "+fileName,captionStr="Error saving project file")
dial.Destroy()
def OnProjectClear(self,event):
dial = wx.MessageDialog(self, "Deletting data\nAre you sure?", "Confirm clear", wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
result = dial.ShowModal()
dial.Destroy()
if result == wx.ID_YES:
dm.ClearAll()
self.RefreshMainWindowButtons()
self.fig.clear()
self.canvas.draw()
def OnEpisodesEdit(self,event):
EditEpisodesWindow(self,-1,'Episodes Edition',dm)
self.editEpisodesWindowPresent=True
self.RefreshMainWindowButtons()
def OnEpisodesEditEnded(self):
self.editEpisodesWindowPresent=False
self.RefreshMainWindow()
if self.fbWindowPresent:
self.fbWindow.Refresh()
def OnPoincare(self,event):
dm.ClearPP()
PoincarePlotWindow(self,-1,'Poincare plot',dm)
self.poincareWindowPresent=True
self.RefreshMainWindowButtons()
def OnPoincareEnded(self):
self.poincareWindowPresent=False
self.RefreshMainWindowButtons()
def OnEpisodesClear(self,event):
dm.ClearEpisodes()
dm.ClearColors()
self.RefreshMainWindow()
if self.fbWindowPresent:
self.fbWindow.Refresh()
def OnFilterNIHR(self,event):
dm.FilterNIHR()
self.RefreshMainWindow()
def OnNIHREdit(self,event):
EditNIHRWindow(self,-1,'Non interpolated HR Edition',dm)
self.editNIHRWindowPresent=True
self.RefreshMainWindowButtons()
def OnNIHREditEnded(self):
self.editNIHRWindowPresent=False
self.RefreshMainWindow()
def OnExportHR(self,event):
self.buttonExportHR.Disable()
exportSettingsWindow=HRExportSettings(self,-1,"Export options", dm)
def OnExportHREnded(self):
self.buttonExportHR.Enable()
def OnInterpolateNIHR(self,event):
dm.InterpolateNIHR()
self.RefreshMainWindow()
def OnReport(self,event):
import tempfile
reportName="report.html"
reportDir=tempfile.mkdtemp(prefix="gHRV_Report_")
dm.CreateReport(reportDir,reportName,'report_files')
ReportWindow(self,-1,'Report: '+dm.GetName(),reportDir+os.sep+reportName, dm)
self.reportWindowPresent=True
self.RefreshMainWindowButtons()
def OnReportEnded(self):
self.reportWindowPresent=False
self.RefreshMainWindow()
self.canvas.SetFocus()
def OnFrameBased(self,event):
if dm.HasFrameBasedParams()==False:
try:
dm.CalculateFrameBasedParams(showProgress=True)
except Utils.FewFramesException as e:
Utils.ErrorWindow(messageStr="Too few data for analysis: "+str(max(0,e.NumOfFrames))+" frames\nMinimum number of frames is "+str(minNumFrames),
captionStr="Error calculating frame-based parameters")
if dm.HasFrameBasedParams():
self.fbWindow = FrameBasedEvolutionWindow(self,-1,"Temporal evolution of parameters",dm)
self.fbWindowPresent=True
self.RefreshMainWindowButtons()
def OnFrameBasedEnded(self):
self.fbWindowPresent=False
self.RefreshMainWindowButtons()
self.canvas.SetFocus()
def OnExit(self, event):
dial = wx.MessageDialog(self, "Quitting gHRV\nAre you sure?", "Confirm exit", wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
result = dial.ShowModal()
dial.Destroy()
if result == wx.ID_YES:
self.Destroy()
def Abort(self):
self.Destroy()
def OnAbout(self, event):
self.aboutWindowPresent=True
self.RefreshMainWindowButtons()
AboutDlg(self,-1)
def OnAboutEnded(self):
self.aboutWindowPresent=False
self.RefreshMainWindowButtons()
self.canvas.SetFocus()
def OnConfig(self,event):
self.configWindowPresent=True
self.RefreshMainWindowButtons()
#print 'Before configuration: ',self.settings
ConfigurationWindow(self,-1,self.settings,conftype="general")
def OnConfigEnded(self):