-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrespmech.py
1663 lines (1341 loc) · 72.2 KB
/
respmech.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 27 14:11:39 2019
@author: Emil S. Walsted
------------------------------------------------------------------------
Respiratory mechanics and work of breathing calculation
------------------------------------------------------------------------
(c) Copyright 2019 Emil Schwarz Walsted <emilwalsted@gmail.com>
This is a rewrite of my MATLAB code from 2016, with some changes/additions.
The latest version of this code is available at GitHub:
https://github.com/emilwalsted/respmech
This code calculates respiratory mechanics and/or in- and expiratory work of
breathing and/or diaphragm EMG entropy from a time series of
pressure/flow/volume recordings obtained e.g. from LabChart.
Currently, supported input formats are: MATLAB, Excel and CSV. You can extend
this yourself by modifying the 'load()' function.
For usage, please see the example file 'example.py'.
*** Note to respiratory scientists: ***
I created this code for the purpose of my own
work and shared it hoping that someone else might find it useful. If you have
any suggestions that will make the code more useful to you or generally, please
email me to discuss.
*** Note to software engineers/computer scientists: ***
I realise that this code is not as concise or computationally efficient as it
could be. I have focused on readability in an attempt to enable respiratory
scientists with basic programming skills to understand, debug and modify/extend
the code themselves.
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/>
"""
VERSION = "1.0.0"
CREATED = "Created with RespMech.py version " + VERSION + " (www.github.com/emilwalsted/respmech)"
import sys
import os
import glob
import ntpath
import math
import datetime
from os.path import join as pjoin
import numpy as np
from pandas.core.construction import array
import scipy as sp
import scipy.io as sio
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
from matplotlib.patches import Polygon, Rectangle
import json
from types import SimpleNamespace
from collections import namedtuple
import seaborn as sns; sns.set()
plt.style.use('seaborn-v0_8-white')
def import_file(full_name, path):
from importlib import util
spec = util.spec_from_file_location(full_name, path)
mod = util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def checknotset(setting, text):
if setting is None or len(str(setting)) == 0: raise ValueError(text)
def checkoptions(setting, settingname, options):
if not setting in options: raise ValueError(settingname + " can be one of the following values: " + ' '.join(options))
def validatesettings(s):
checknotset(s.input.inputfolder, text="Input folder not specified in settings")
if not os.path.isdir(s.input.inputfolder): raise ValueError("Input folder not found: " + s.input.inputfolder)
checknotset(s.input.files, "Input file(s) not specified in settings")
checknotset(s.input.format.samplingfrequency, "Sampling frequency not specified in settings")
if not isinstance(s.input.format.samplingfrequency, int): raise ValueError("Sampling frequency must be an integer")
if ".mat" in str.lower(s.input.files):
checknotset(s.input.format.matlabfileformat, "MatLab file format not specified in settings")
checknotset(s.input.data.column_flow, "Flow data column not specified in settings")
checknotset(s.input.data.column_poes, "Oesophageal pressure data column not specified in settings")
checknotset(s.input.data.column_pgas, "Gastric pressure data column not specified in settings")
checknotset(s.input.data.column_pdi, "PDI data column not specified in settings")
if not s.processing.mechanics.integratevolumefromflow:
checknotset(s.input.data.column_volume, "Volume data column not specified in settings – please set 'integratevolumefromflow' to True to allow for automated volume integration.")
checknotset(s.processing.mechanics.breathseparationbuffer, "Breath separation buffer not specified in settings")
if not isinstance(s.processing.mechanics.breathseparationbuffer, int): raise ValueError("Breath separation buffer must be an integer")
checkoptions(s.processing.mechanics.volumetrendadjustmethod, "Volume trend adjust method", ['linear', 'nearest', 'nearest-up', 'zero', 'slinear', 'quadratic', 'cubic', 'previous', 'next'])
checkoptions(s.processing.wob.calcwobfrom, "WOB calculation method (calcwobfrom setting)", ['average', 'individual'])
if s.processing.wob.calcwobfrom == 'average':
if not isinstance(s.processing.wob.avgresamplingobs, int): raise ValueError("Average resampling observations must be an integer")
checknotset(s.output.outputfolder, text="Output folder not specified in settings")
if not os.path.isdir(s.output.outputfolder): raise ValueError("Output folder not found: " + s.output.outputfolder)
def checkcolumn(text, data):
if np.isnan(data).any(): raise ValueError(text + " contains NaN values.")
if any(isinstance(d, str) for d in data): raise ValueError(text + " contains text values – all values must be numeric.")
from itertools import groupby
def alleq(iterable):
g = groupby(iterable)
return next(g, True) and not next(g, False)
def validatedata(flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns, settings):
checkcolumn("Flow column", flow)
checkcolumn("Volume column", volume)
checkcolumn("Oesophageal pressure column", poes)
checkcolumn("Gastric pressure column", pgas)
checkcolumn("Trans-diaphragmatic pressure column", pdi)
collens = [len(flow), len(volume), len(poes), len(pgas), len(pdi)]
coltitles = ["Flow", "Volume", "Poes", "Pgas", "Pdi"]
n=0
if len(entropycolumns)>0:
for i in range(0, len(entropycolumns[0, :])):
c=entropycolumns[:,i]
n += 1
coltitles += ["Entropy column #" + str(n) + " (data column #" + str(settings.input.data.columns_entropy[n-1]) + ")"]
checkcolumn("Entropy column #" + str(n) + " (#" + str(settings.input.data.columns_entropy[n-1]) + " in input data)" , c)
collens += [len(c)]
n=0
if len(emgcolumns)>0:
for i in range(0, len(emgcolumns[0, :])):
c=emgcolumns[:,i]
n += 1
coltitles += ["EMG column #" + str(n) + " (#" + str(settings.input.data.columns_emg[n-1]) + " in input data)"]
checkcolumn("EMG column #" + str(n) + " (column #" + str(settings.input.data.columns_emg[n-1]) + " in input data)" , c)
collens += [len(c)]
if not alleq(collens):
cols = "Column lengths:\n"
for s in range(0, len(collens)):
cols += coltitles[s] + ": " + str(collens[s]) + " observations.\n"
raise ValueError("Data column lengths differ. All columns must have the same number of observations.\n" + cols)
def load(filepath, settings):
_, fext = os.path.splitext(filepath)
def loadmat(path):
try:
if settings.input.format.matlabfileformat == 2:
flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns = loadmatmac(filepath)
else:
flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns = loadmatwin(filepath)
except:
raise ImportError("Cannot load MATLab file – please verify your MATLab file format settings. RespMech only supports some MATLab versions / simple format. Alternatively, you can export your MATLab data as a CSV file.")
return flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns
def loadmatmac(filename):
rawdata = sio.loadmat(filename)
data = OrderedDict(rawdata)
cols = list(data.items())
flow = cols[settings.input.data.column_flow-1][1]
if np.isnan(settings.input.data.column_volume):
volume = []
else:
volume = cols[settings.input.data.column_volume-1][1]
poes = cols[settings.input.data.column_poes-1][1]
pgas = cols[settings.input.data.column_pgas-1][1]
pdi = cols[settings.input.data.column_pdi-1][1]
if len(settings.input.data.columns_entropy)==0:
entropycolumns = []
else:
entropycolumns = np.empty([len(cols[settings.input.data.columns_entropy[0]][1]), len(settings.input.data.columns_entropy)])
for i in range(0, len(settings.input.data.columns_entropy)):
entropycolumns[:,i] = cols[settings.input.data.columns_entropy[i]-1][1].squeeze()
if len(settings.input.data.columns_emg)==0:
emgcolumns = []
else:
emgcolumns = np.empty([len(cols[settings.input.data.columns_emg[0]][1]), len(settings.input.data.columns_emg)])
for i in range(0, len(settings.input.data.columns_emg)):
emgcolumns[:,i] = cols[settings.input.data.columns_emg[i]-1][1].squeeze()
return flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns
def loadmatwin(filename):
rawdata = sio.loadmat(filename)
data = OrderedDict(rawdata)
cols = list(data["data_block1"])
flow = cols[settings.input.data.column_flow-1]
if np.isnan(settings.input.data.column_volume):
volume = []
else:
volume = cols[settings.input.data.column_volume-1]
poes = cols[settings.input.data.column_poes-1]
pgas = cols[settings.input.data.column_pgas-1]
pdi = cols[settings.input.data.column_pdi-1]
if len(settings.input.data.columns_entropy)==0:
entropycolumns = []
else:
entropycolumns = np.empty([len(cols[settings.input.data.columns_entropy[0]]), len(settings.input.data.columns_entropy)])
for i in range(0, len(settings.input.data.columns_entropy)):
entropycolumns[:,i] = cols[settings.input.data.columns_entropy[i]-1]
if len(settings.input.data.columns_emg)==0:
emgcolumns = []
else:
emgcolumns = np.empty([len(cols[settings.input.data.columns_entcolumns_emgropy[0]]), len(settings.input.data.columns_emg)])
for i in range(0, len(settings.input.data.columns_emg)):
emgcolumns[:,i] = cols[settings.input.data.columns_emg[i]-1]
return flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns
def loadxls(filename):
data = pd.read_excel(filename)
flow = data.iloc[:,settings.input.data.column_flow-1].to_numpy()
if np.isnan(settings.input.data.column_volume):
volume = []
else:
volume = data.iloc[:,settings.input.data.column_volume-1].to_numpy()
poes = data.iloc[:,settings.input.data.column_poes-1].to_numpy()
pgas = data.iloc[:,settings.input.data.column_pgas-1].to_numpy()
pdi = data.iloc[:,settings.input.data.column_pdi-1].to_numpy()
if len(settings.input.data.columns_entropy)==0:
entropycolumns = []
else:
entropycolumns = data.iloc[:,np.array(settings.input.data.columns_entropy)-1].to_numpy()
if len(settings.input.data.columns_emg)==0:
emgcolumns = []
else:
emgcolumns = data.iloc[:,np.array(settings.input.data.columns_emg)-1].to_numpy()
return flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns
def loadcsv(filename):
data = pd.read_csv(filename)
flow = data.iloc[:,settings.input.data.column_flow-1].to_numpy()
if np.isnan(settings.input.data.column_volume):
volume = []
else:
volume = data.iloc[:,settings.input.data.column_volume-1].to_numpy()
poes = data.iloc[:,settings.input.data.column_poes-1].to_numpy()
pgas = data.iloc[:,settings.input.data.column_pgas-1].to_numpy()
pdi = data.iloc[:,settings.input.data.column_pdi-1].to_numpy()
if len(settings.input.data.columns_entropy)==0:
entropycolumns = []
else:
entropycolumns = data.iloc[:,np.array(settings.input.data.columns_entropy)-1].to_numpy().squeeze()
if len(settings.input.data.columns_emg)==0:
emgcolumns = []
else:
emgcolumns = data.iloc[:,np.array(settings.input.data.columns_emg)-1].to_numpy().squeeze()
return flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns
def loadtxt(filename):
data = pd.read_csv(filename, sep='\t', decimal=settings.input.format.decimalcharacter)
flow = data.iloc[:,settings.input.data.column_flow-1].to_numpy()
if np.isnan(settings.input.data.column_volume):
volume = []
else:
volume = data.iloc[:,settings.input.data.column_volume-1].to_numpy()
poes = data.iloc[:,settings.input.data.column_poes-1].to_numpy()
pgas = data.iloc[:,settings.input.data.column_pgas-1].to_numpy()
pdi = data.iloc[:,settings.input.data.column_pdi-1].to_numpy()
if len(settings.input.data.columns_entropy)==0:
entropycolumns = []
else:
entropycolumns = data.iloc[:,np.array(settings.input.data.columns_entropy)-1].to_numpy().squeeze()
if len(settings.input.data.columns_emg)==0:
emgcolumns = []
else:
emgcolumns = data.iloc[:,np.array(settings.input.data.columns_emg)-1].to_numpy().squeeze()
return flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns
def loadfext(x):
return {
#Add new file extensions and a handler function here.
'.xls': loadxls,
'.xlsx': loadxls,
'.csv': loadcsv,
'.mat': loadmat,
'.txt': loadtxt
}.get(x) #, default)
flow = []
volume = []
poes = []
pgas = []
pdi = []
loadfunc = loadfext(fext)
flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns = loadfunc(filepath)
flow = flow.squeeze()
if len(volume)>0:
volume = volume.squeeze()
poes = poes.squeeze()
pgas = pgas.squeeze()
pdi = pdi.squeeze()
if settings.processing.mechanics.inverseflow:
flow = -flow
if settings.processing.mechanics.integratevolumefromflow:
xval = np.linspace(0, len(flow)/settings.input.format.samplingfrequency, len(flow))
volume = np.concatenate([-sp.integrate.cumtrapz(flow, xval), [0.0000001]])
if settings.processing.mechanics.inversevolume:
volume = -volume
validatedata(flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns, settings)
return flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns
def zero(indata):
return indata-(indata[0])
def correctdrift(volume, settings):
xno = len(volume)-1
a = ((volume[xno])-volume[0])/xno
val = a
corvol=np.zeros(len(volume))
for i in range(0, xno):
corvol[i] = volume[i] + val
val = val - a
return corvol
def correcttrend(title, volume, settings):
from scipy import signal
vol = volume.squeeze()
peaks = signal.find_peaks((vol*-1)+max(vol), height=settings.processing.mechanics.volumetrendpeakminheight, distance=settings.processing.mechanics.volumetrendpeakmindistance * settings.input.format.samplingfrequency)[0]
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(21,29.7))
title = title + " - Volume trend adjustment (" + settings.processing.mechanics.volumetrendadjustmethod + ")"
plt.suptitle(title, fontsize=48)
f = sp.interpolate.interp1d(peaks, vol[peaks], settings.processing.mechanics.volumetrendadjustmethod, fill_value="extrapolate")
peaksresampled = f(np.linspace(0, vol.size-1, vol.size))
axes[0].plot(volume)
axes[0].plot(peaks, vol[peaks], "x", markersize=20)
axes[1].plot(volume, linewidth=1.5)
axes[1].plot(peaksresampled, linewidth=1.5)
corvol = volume - peaksresampled
axes[2].plot(corvol)
axes[2].plot(np.zeros(corvol.size), '--', linewidth=1.5)
savefile = pjoin(settings.output.outputfolder, "plots", title + ".pdf")
plt.figtext(0.99, 0.01, CREATED + " on " + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), horizontalalignment='right')
fig.savefig(savefile)
return corvol
def trim(timecol, flow, volume, poes, pgas, pdi, emgcolumns, settings):
startix = np.argmax(flow <= 0)
posflow = np.argwhere(flow >= 0)
endix = posflow[:,0][len(posflow[:,0])-1]
return timecol[startix:endix], flow[startix:endix], volume[startix:endix], poes[startix:endix], pgas[startix:endix], pdi[startix:endix], emgcolumns[startix:endix], startix, endix
def ignorebreaths(curfile, settings):
allignore = settings.processing.mechanics.excludebreaths
d = dict(allignore)
if curfile in d:
return d[curfile]
else:
return []
def separateintobreathsbyflow(filename, timecol, flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns, settings):
breaths = OrderedDict()
j = len(flow)
bufferwidth = settings.processing.mechanics.breathseparationbuffer
ib = ignorebreaths(filename, settings)
i = 0
breathno = 0
breathcnt = 0
while i<j:
breathcnt += 1
instart = i
while (i<j and ((flow[i]<0) or (np.mean(flow[i:min(j,i+bufferwidth)])<0))):
i += 1
inend = i-1
exstart = i
while (i<j and ((flow[i]>0) or (np.mean(flow[i:min(j,i+bufferwidth)])>0))):
i += 1
exend = i-1
exend = min(exend, j)
exp = {'time':timecol[exstart:exend].squeeze(), 'flow':flow[exstart:exend].squeeze(), 'poes':poes[exstart:exend].squeeze(),
'pgas': pgas[exstart:exend].squeeze(), 'pdi':pdi[exstart:exend].squeeze(), 'volume':volume[exstart:exend].squeeze()
}
insp = {'time':timecol[instart:inend].squeeze(), 'flow':flow[instart:inend].squeeze(), 'poes':poes[instart:inend].squeeze(),
'pgas':pgas[instart:inend].squeeze(), 'pdi':pdi[instart:inend].squeeze(), 'volume':volume[instart:inend].squeeze()}
if len(entropycolumns)>0:
exp = {**exp, **{'entcols': entropycolumns[exstart:exend, :].squeeze()}}
insp = {**insp, **{'entcols': entropycolumns[instart:inend, :].squeeze()}}
if len(emgcolumns)>0:
exp = {**exp, **{'emgcols': emgcolumns[exstart:exend, :].squeeze()}}
insp = {**insp , **{'emgcols': emgcolumns[instart:inend, :].squeeze()}}
if breathcnt in ib:
ignored = True
else:
breathno += 1
ignored = False
entlen = exend-instart
if len(entropycolumns) > 0:
entcols = np.zeros([entlen, entropycolumns.shape[1]])
for ix in range(0, entropycolumns.shape[1]):
entcols[:,ix] = entropycolumns[instart:exend,ix]
else:
entcols = []
if len(emgcolumns) > 0:
emgcols = np.zeros([entlen, emgcolumns.shape[1]])
for ix in range(0, emgcolumns.shape[1]):
emgcols[:,ix] = emgcolumns[instart:exend,ix]
else:
emgcols = []
breath = OrderedDict([('number', breathcnt),
('name','Breath #' + str(breathcnt)),
('expiration', exp),
('inspiration', insp),
('time', np.concatenate((insp["time"], exp["time"])).squeeze()),
('flow', np.concatenate((insp["flow"], exp["flow"])).squeeze()),
('volume', np.concatenate((insp["volume"], exp["volume"])).squeeze()),
('poes', np.concatenate((insp["poes"], exp["poes"])).squeeze()),
('pgas', np.concatenate((insp["pgas"], exp["pgas"])).squeeze()),
('pdi', np.concatenate((insp["pdi"], exp["pdi"])).squeeze()),
('breathcnt', breathcnt),
('ignored', ignored),
('entcols', entcols),
('emgcols', emgcols),
('filename', filename)])
breaths[breathcnt] = breath
return breaths
def separateintobreathsbyvolume(filename, timecol, flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns, settings):
from scipy import signal
breaths = OrderedDict()
ib = ignorebreaths(filename, settings)
breathno = 0
breathcnt = 0
invol = volume
exvol = -1 * volume
exvol = exvol + min(exvol)*-1
samplingfrequency = settings.input.format.samplingfrequency
peakheight = settings.processing.mechanics.peakheight
peakdistance = settings.processing.mechanics.peakdistance
peakwidth = settings.processing.mechanics.peakwidth
inpeaks, _ = signal.find_peaks(invol, height=peakheight, distance=peakdistance*samplingfrequency, width=peakwidth*samplingfrequency)
expeaks, _ = signal.find_peaks(exvol, height=peakheight, distance=peakdistance*samplingfrequency, width=peakwidth*samplingfrequency)
for inpeak in inpeaks:
breathcnt += 1
if breathcnt == 1:
instart = 0
inend = inpeak - 1
else:
instart = expeaks[breathcnt-2]
inend = inpeak - 1
exstart = inend + 1
if breathcnt < len(inpeaks):
expeak = expeaks[breathcnt-1]
exend = expeak - 1
else:
exend = len(invol)-1
exp = {'time':timecol[exstart:exend].squeeze(), 'flow':flow[exstart:exend].squeeze(), 'poes':poes[exstart:exend].squeeze(),
'pgas': pgas[exstart:exend].squeeze(), 'pdi':pdi[exstart:exend].squeeze(), 'volume':volume[exstart:exend].squeeze()}
insp = {'time':timecol[instart:inend].squeeze(), 'flow':flow[instart:inend].squeeze(), 'poes':poes[instart:inend].squeeze(),
'pgas':pgas[instart:inend].squeeze(), 'pdi':pdi[instart:inend].squeeze(), 'volume':volume[instart:inend].squeeze()}
if len(entropycolumns)>0:
exp = {**exp, **{'entcols': entropycolumns[exstart:exend, :].squeeze()}}
insp = {**insp, **{'entcols': entropycolumns[instart:inend, :].squeeze()}}
if len(emgcolumns)>0:
exp = {**exp, **{'emgcols': emgcolumns[exstart:exend, :].squeeze()}}
insp = {**insp , **{'emgcols': emgcolumns[instart:inend, :].squeeze()}}
if breathcnt in ib:
ignored = True
else:
breathno += 1
ignored = False
entlen = exend-instart
if len(entropycolumns) > 0:
entcols = np.zeros([entlen, entropycolumns.shape[1]])
for ix in range(0, entropycolumns.shape[1]):
entcols[:,ix] = entropycolumns[instart:exend,ix]
else:
entcols = []
if len(emgcolumns) > 0:
emgcols = np.zeros([entlen, emgcolumns.shape[1]])
for ix in range(0, emgcolumns.shape[1]):
emgcols[:,ix] = emgcolumns[instart:exend,ix]
else:
emgcols = []
# print("instart:" + str(instart) + " inend:" + str(inend) + " exstart:" + str(exstart) + " exend:" + str(exend))
breath = OrderedDict([('number', breathcnt),
('name','Breath #' + str(breathcnt)),
('expiration', exp),
('inspiration', insp),
('time', np.concatenate((insp["time"], exp["time"])).squeeze()),
('flow', np.concatenate((insp["flow"], exp["flow"])).squeeze()),
('volume', np.concatenate((insp["volume"], exp["volume"])).squeeze()),
('poes', np.concatenate((insp["poes"], exp["poes"])).squeeze()),
('pgas', np.concatenate((insp["pgas"], exp["pgas"])).squeeze()),
('pdi', np.concatenate((insp["pdi"], exp["pdi"])).squeeze()),
('breathcnt', breathcnt),
('ignored', ignored),
('entcols', entcols),
('emgcols', emgcols),
('filename', filename)])
breaths[breathcnt] = breath
return breaths
def separateintobreaths(method, filename, timecol, flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns, settings):
if str(str.lower(method)) == "volume":
return separateintobreathsbyvolume(filename, timecol, flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns, settings)
else:
return separateintobreathsbyflow(filename, timecol, flow, volume, poes, pgas, pdi, entropycolumns, emgcolumns, settings)
def calculatemechanics(breath, bcnt, vefactor, avgvolumein, avgvolumeex, avgpoesin, avgpoesex, settings):
retbreath = breath
print(' Mechanics', end="")
retbreath["inspiration"]["volumeavg"] = avgvolumein
retbreath["expiration"]["volumeavg"] = avgvolumeex
retbreath["volumeavg"] = np.concatenate([avgvolumein, avgvolumeex])
retbreath["inspiration"]["poesavg"] = avgpoesin
retbreath["expiration"]["poesavg"] = avgpoesex
retbreath["poesavg"] = np.concatenate([avgpoesin, avgpoesex])
retbreath["eilv"] = [retbreath["inspiration"]["volume"][len(retbreath["inspiration"]["volume"])-1], retbreath["inspiration"]["poes"][len(retbreath["inspiration"]["poes"])-1]]
retbreath["eelv"] = [retbreath["expiration"]["volume"][len(retbreath["expiration"]["volume"])-1], retbreath["expiration"]["poes"][len(retbreath["expiration"]["poes"])-1]]
retbreath["eilvavg"] = [retbreath["inspiration"]["volumeavg"][len(retbreath["inspiration"]["volumeavg"])-1], retbreath["inspiration"]["poesavg"][len(retbreath["inspiration"]["poesavg"])-1]]
retbreath["eelvavg"] = [retbreath["expiration"]["volumeavg"][len(retbreath["expiration"]["volumeavg"])-1], retbreath["expiration"]["poesavg"][len(retbreath["expiration"]["poesavg"])-1]]
exp = retbreath["expiration"]
poes_maxexp = max(exp["poes"])
poes_endexp = exp["poes"][len(exp["poes"])-1]
pdi_minexp = min(exp["pdi"])
pdi_endexp = exp["pdi"][len(exp["pdi"])-1]
pgas_endexp = exp["pgas"][len(exp["pgas"])-1]
pgas_maxexp = max(exp["pgas"])
pgas_minexp = min(exp["pgas"])
midvolexp = min(exp["volume"]) + ((max(exp["volume"])-min(exp["volume"]))/2)
midvolexpix = np.where(exp["volume"] <= midvolexp)[0][0]
poes_midvolexp = exp["poes"][midvolexpix]
flow_midvolexp = -exp["flow"][midvolexpix]
insp = retbreath["inspiration"]
poes_mininsp = min(insp["poes"])
poes_endinsp = insp["poes"][len(insp["poes"])-1]
pdi_maxinsp = max(insp["pdi"])
pdi_endinsp = insp["pdi"][len(insp["pdi"])-1]
pgas_endinsp = insp["pgas"][len(insp["pgas"])-1]
poes_tidal_swing = abs(max(retbreath["poes"]) - min(retbreath["poes"]))
pgas_tidal_swing = abs(max(retbreath["pgas"]) - min(retbreath["pgas"]))
pdi_tidal_swing = abs(max(retbreath["pdi"]) - min(retbreath["pdi"]))
midvolinsp = min(insp["volume"]) + ((max(insp["volume"])-min(insp["volume"]))/2)
midvolinspix = np.where(insp["volume"] >= midvolinsp)[0][0]
poes_midvolinsp = insp["poes"][midvolinspix]
flow_midvolinsp = -insp["flow"][midvolinspix]
vol_endinsp = insp["volume"][len(insp["volume"])-1]
vol_endexp = exp["volume"][len(exp["volume"])-1]
ti = len(insp["flow"])/settings.input.format.samplingfrequency
te = len(exp["flow"])/settings.input.format.samplingfrequency
ttot = len(retbreath["flow"])/settings.input.format.samplingfrequency
ti_ttot = ti/ttot
vt = max(retbreath["volume"])-min(retbreath["volume"])
ve = vt * bcnt * vefactor
vmrnumerator = (pgas_endinsp-pgas_endexp)
vmrdenominator = (poes_endinsp-poes_endexp)
vmr = np.divide(vmrnumerator, vmrdenominator, out=np.zeros_like(vmrnumerator), where=vmrdenominator!=0)
tlr_insp = abs((poes_midvolexp-poes_midvolinsp)/(flow_midvolexp-flow_midvolinsp))
insp_pdi_rise = pdi_maxinsp - min(insp["pdi"])
exp_pgas_rise = pgas_maxexp - min(exp["pgas"])
poesinsp = adjustforintegration(-insp["poes"])
ptp_oesinsp, int_oesinsp = calcptp(poesinsp, bcnt, vefactor, settings.input.format.samplingfrequency)
pdiinsp = insp["pdi"]-min(insp["pdi"])
ptp_pdiinsp, int_pdiinsp = calcptp(pdiinsp, bcnt, vefactor, settings.input.format.samplingfrequency)
pgasexp = exp["pgas"]-min(exp["pgas"]) #adjustforintegration(exp["pgas"])
ptp_pgasexp, int_pgasexp = calcptp(pgasexp, bcnt, vefactor, settings.input.format.samplingfrequency)
max_in_flow = min(insp["flow"]) * -1
max_ex_flow = max(exp["flow"])
inflowmidvol = insp["flow"][midvolinspix] * -1
exflowmidvol = exp["flow"][midvolexpix]
print(', WOB', end="")
wob = calculatewob(breath, bcnt, vefactor, avgvolumein, avgvolumeex, avgpoesin, avgpoesex, settings)
retbreath["wob"] = wob
if len(breath["emgcols"]) > 0:
print(', EMG RMS', end="")
rmdir = os.path.dirname(os.path.realpath(__file__))
try:
emglib = import_file("emglib", os.path.join(rmdir, "emg.py"))
except:
raise FileNotFoundError("emg.py not found at expected location: " + rmdir)
retbreath["rms"], retbreath["intemg"] = emglib.calculate_rms(breath["emgcols"], settings.processing.emg.rms_s, settings.input.format.samplingfrequency)
retbreath["rms_insp"], retbreath["intemg_insp"] = emglib.calculate_rms(breath["inspiration"]["emgcols"], settings.processing.emg.rms_s, settings.input.format.samplingfrequency)
retbreath["rms_exp"], retbreath["intemg_exp"] = emglib.calculate_rms(breath["expiration"]["emgcols"], settings.processing.emg.rms_s, settings.input.format.samplingfrequency)
if len(settings.input.data.columns_entropy) > 0:
print(', Entropy', end="")
entropy = calculateentropy(breath, settings)
entropy_insp = calculateentropy(breath, settings, "inspiration")
entropy_exp = calculateentropy(breath, settings, "expiration")
retbreath["entropy"] = np.append(entropy.T, [max(entropy.T), min(entropy.T), np.mean(entropy.T)])
retbreath["entropy_insp"] = np.append(entropy_insp.T, [max(entropy_insp.T), min(entropy_insp.T), np.mean(entropy_insp.T)])
retbreath["entropy_exp"] = np.append(entropy_exp.T, [max(entropy_exp.T), min(entropy_exp.T), np.mean(entropy_exp.T)])
else:
retbreath["entropy"] = []
mechs = OrderedDict([ ('poes_maxexp', poes_maxexp),
('poes_mininsp', poes_mininsp),
('poes_endinsp', poes_endinsp),
('poes_endexp',poes_endexp),
('poes_midvolexp',poes_midvolexp),
('poes_midvolinsp',poes_midvolinsp),
('int_oesinsp',int_oesinsp),
('ptp_oesinsp',ptp_oesinsp),
('poes_tidal_swing',poes_tidal_swing),
('pgas_endinsp',pgas_endinsp),
('pgas_endexp',pgas_endexp),
('pgas_maxexp',pgas_maxexp),
('pgas_minexp',pgas_minexp),
('exp_pgas_rise',exp_pgas_rise),
('int_pgasexp',int_pgasexp),
('ptp_pgasexp',ptp_pgasexp),
('pgas_tidal_swing',pgas_tidal_swing),
('int_pdiinsp',int_pdiinsp),
('ptp_pdiinsp',ptp_pdiinsp),
('pdi_minexp',pdi_minexp),
('pdi_maxinsp',pdi_maxinsp),
('pdi_endinsp',pdi_endinsp),
('pdi_endexp',pdi_endexp),
('insp_pdi_rise',insp_pdi_rise),
('pdi_tidal_swing',pdi_tidal_swing),
('flow_midvolexp',flow_midvolexp),
('flow_midvolinsp',flow_midvolinsp),
('vol_endinsp',vol_endinsp),
('vol_endexp',vol_endexp),
('max_in_flow',max_in_flow),
('max_ex_flow',max_ex_flow),
('in_flow_midvol',inflowmidvol),
('ex_flow_midvol',exflowmidvol),
('ti',ti),
('te',te),
('ttot',ttot),
('ti_ttot',ti_ttot),
('vt',vt),
('bf',bcnt * vefactor),
('ve',ve),
('vmr',vmr),
('tlr_insp',tlr_insp)
])
retbreath["mechanics"] = mechs
return retbreath
def adjustforintegration(data):
mind = min(min(data),0)
maxd = max(data)
adjustment = mind
if (maxd<0):
adjustment = maxd
return data - adjustment
def calcptp(pressure, bcnt, vefactor, samplingfreq):
pressure = pressure.squeeze() - pressure[0]
xval = np.linspace(0, len(pressure)/samplingfreq, len(pressure))
integral = sp.integrate.simps(pressure, xval)
ptp = integral * bcnt * vefactor
return ptp, integral
def calculatewob(breath, bcnt, vefactor, avgvolumein, avgvolumeex, avgpoesin, avgpoesex, settings):
WOBUNITCHANGEFACTOR = 98.0638/1000 #Multiplication factor to change cmH2O to Joule; Pa = J / m3.
if settings.processing.wob.calcwobfrom == "average":
volin = breath["inspiration"]["volumeavg"]
volex = breath["expiration"]["volumeavg"]
poesin = breath["inspiration"]["poesavg"]
poesex = breath["expiration"]["poesavg"]
else:
volin = breath["inspiration"]["volume"]
volex = breath["expiration"]["volume"]
poesin = breath["inspiration"]["poes"]
poesex = breath["expiration"]["poes"]
eilv = [volin[len(poesin)-1], poesin[len(poesin)-1]]
eelv = [volex[len(volex)-1], poesex[len(volex)-1]]
#Inspiratory elastic WOB:
tbase = abs(eilv[0]-eelv[0])
theight = abs(eilv[1]-eelv[1])
wobinela = tbase * theight / 2 * WOBUNITCHANGEFACTOR
#Inspiratory resistive WOB:
slope = (poesin[len(poesin)-1]-poesin[0]) / (volin[len(volin)-1]-volin[0])
flyin = volin * slope + poesin[0]
levelpoesin = (poesin*-1) - (flyin*-1)
levelpoesin[np.where(levelpoesin<0)]=0
wobinres = max(abs(sp.integrate.simps(levelpoesin, volin)),0) * WOBUNITCHANGEFACTOR
#Expiratory WOB:
levelpoesex = poesex - poesex[len(poesex)-1]
levelpoesex[np.where(levelpoesex<0)]=0
wobex = max(abs(sp.integrate.simps(levelpoesex, volex)),0) * WOBUNITCHANGEFACTOR
#Totals
wobin = wobinela + wobinres
wobtotal = wobin + wobex
wob = OrderedDict([
('wobtotal', wobtotal * bcnt * vefactor),
('wob_in_total', wobin * bcnt * vefactor),
('wob_ex_total', wobex * bcnt * vefactor),
('wob_in_ela', wobinela * bcnt * vefactor),
('wob_in_res', wobinres * bcnt * vefactor)
])
return wob
def calculatebreathmechsandwob(breaths, bcnt, vefactor, avgvolumein, avgvolumeex, avgpoesin, avgpoesex, settings):
retbreaths = OrderedDict()
for breathno in breaths:
print('\n\t\t... breath #' + str(breathno) + ":", end="")
breath = breaths[breathno]
if breath["ignored"]:
print(' (ignored)', end="")
retbreaths[breathno] = breath
else:
breathmechswob = calculatemechanics(breath, bcnt, vefactor, avgvolumein, avgvolumeex, avgpoesin, avgpoesex, settings)
retbreaths[breathno] = breathmechswob
print("")
return retbreaths
def resample(x, settings, kind='linear'):
x = x.squeeze()
n = settings.processing.wob.avgresamplingobs
f = sp.interpolate.interp1d(np.linspace(0, 1, x.size), x, kind)
return f(np.linspace(0, 1, n))
def calculateaveragebreaths(breaths, settings):
resamplingobs = settings.processing.wob.avgresamplingobs
nobreaths = 0
for breathno in breaths:
if not breaths[breathno]["ignored"]:
nobreaths += 1
volumein = np.empty([resamplingobs, nobreaths])
volumeex = np.empty([resamplingobs, nobreaths])
poesin = np.empty([resamplingobs, nobreaths])
poesex = np.empty([resamplingobs, nobreaths])
for breathno in breaths:
breath = breaths[breathno]
if not breath["ignored"]:
nobreaths -= 1
try:
volumein[:,nobreaths] = resample(breath["inspiration"]["volume"], settings)
volumeex[:,nobreaths] = resample(breath["expiration"]["volume"], settings)
poesin[:,nobreaths] = resample(breath["inspiration"]["poes"], settings)
poesex[:,nobreaths] = resample(breath["expiration"]["poes"], settings)
except:
raise ValueError("Could not resample breath #" + str(breath["number"]) + ". Please inspect your 'avgresamplingobs' setting (if separating by flow) or peak settings (if separating by volume) and breath separation settings (examine diagnostic output plots)")
avgvolumein = np.mean(volumein, axis=1)
avgvolumeex = np.mean(volumeex, axis=1)
avgpoesin = np.mean(poesin, axis=1)
avgpoesex = np.mean(poesex, axis=1)
return avgvolumein, avgvolumeex, avgpoesin, avgpoesex
def calculateentropy(breath, settings, phase = None):
rmdir = os.path.dirname(os.path.realpath(__file__))
try:
ent = import_file("ent", os.path.join(rmdir, "entropy.py"))
except:
raise FileNotFoundError("entropy.py not found at expected location: " + rmdir)
if phase is None:
columns = breath["entcols"]
else:
columns = breath[phase]["entcols"]
#If EMG columns contained in entropy columns, use the processed data (not the original input)
if len(settings.input.data.columns_emg)>0:
emgcolnos = settings.input.data.columns_emg
for entcolno in range(0, len(settings.input.data.columns_entropy)):
entc = settings.input.data.columns_entropy[entcolno]
if entc in emgcolnos:
if phase is None:
columns[:,entcolno] = breath["emgcols"][:,emgcolnos.index(entc)]
else:
columns[:,entcolno] = breath[phase]["emgcols"][:,emgcolnos.index(entc)]
epoch = settings.processing.entropy.entropy_epochs
tolerancesd = settings.processing.entropy.entropy_tolerance
sampen = np.zeros(len(columns[1,:]))
for i in range(0,columns.shape[1]):
std_ds = np.std(columns[:,i])
sample_entropy = ent.sample_entropy(columns[:,i], epoch, tolerancesd * std_ds)
sampen[i] = sample_entropy[len(sample_entropy)-1]
return sampen
def savepvbreaths(file, breaths, flow, volume, poes, pgas, pdi, settings, averages=False):
try:
os.makedirs(pjoin(settings.output.outputfolder, "plots"))
except FileExistsError:
pass
nobreaths = len(breaths)
maxnocols = settings.output.diagnostics.pvcolumns
maxnorows = settings.output.diagnostics.pvrows
plotsperpage = maxnocols * maxnorows
nopages = -(-nobreaths // plotsperpage)
nocols = maxnocols #math.floor(math.sqrt(nobreaths))
norows = maxnorows #math.ceil(nobreaths/nocols)
maxx = -np.inf
minx = np.inf
maxy = -np.inf
miny = np.inf
no=0
for breathno in breaths:
no += 1
breath = breaths[breathno]
if averages:
calcvol = "volumeavg"
calcpoes = "poesavg"
else:
calcvol = "volume"
calcpoes = "poes"
if not breath["ignored"]:
maxnewx = max(breath[calcvol])
maxnewy = max(breath[calcpoes])
minnewx = min(breath[calcvol])
minnewy = min(breath[calcpoes])
maxx = max(maxx, maxnewx, 0)
maxy = max(maxy, maxnewy, 0)
minx = min(minx, minnewx, 0)
miny = min(miny, minnewy, 0)
maxx = maxx*1.1
maxy = maxy*1.1
minx = minx*1.1
miny = miny*1.1
if averages:
savefile = pjoin(settings.output.outputfolder, "plots", "All files – average Campbell.pdf")
else:
savefile = pjoin(settings.output.outputfolder, "plots", file + " - Campbell.pdf")
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages(savefile) as pdf:
no=0
tno=0
pno = 1
for breathno in breaths: #for no in range(1, nobreaths+1):
no += 1
tno += 1
if (no == 1):
fig, _ = plt.subplots(nrows=norows, ncols=nocols, figsize=(21,29.7))
if averages:
plt.suptitle("Averages - Campbell diagrams (page " + str(pno) + " of " + str(nopages) + ")", fontsize=48)
else:
plt.suptitle(file + " - Campbell diagrams (page " + str(pno) + " of " + str(nopages) + ")", fontsize=48)
breath = breaths[breathno]
if breath["ignored"]:
aline = 0.2
afill = 0.2
else:
aline = 1
afill = 0.5
ax = plt.subplot(norows, nocols, no)
ax.set_xlim([minx, maxx])
ax.set_ylim([miny, maxy])
ax.invert_xaxis()
if averages:
ax.set_title(breath["filename"],fontweight="bold", size=20)
else:
ax.set_title("Breath #" + str(breathno),fontweight="bold", size=20)
ax.set_xlabel('Inspired volume (L)', size=16)
ax.set_ylabel(r'Oesophageal pressure (cm ' + r'$H_2O$' + ')', size=16)
ax.grid(True)
ax.plot(breath[calcvol], breath[calcpoes], '-k', linewidth=2, alpha=aline)
if breath["ignored"]:
ax.plot([minx, maxx], [miny, maxy], '-r', linewidth=1)
ax.plot([minx, maxx], [maxy, miny], '-r', linewidth=1)