-
Notifications
You must be signed in to change notification settings - Fork 11
/
NetworkSolutions.py
executable file
·2216 lines (1967 loc) · 96.8 KB
/
NetworkSolutions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
## Program: PyNS
## Module: NetworkSolutions.py
## Language: Python
## Date: $Date: 2012/09/04 10:21:12 $
## Version: $Revision: 0.4.2 $
## Copyright (c) Simone Manini, Luca Antiga. All rights reserved.
## See LICENCE file for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notices for more information.
## Developed with support from the EC FP7/2007-2013: ARCH, Project n. 224390
import csv
from DofMap import DofMap
from InverseWomersley import InverseWomersley
from numpy.core.fromnumeric import mean
from numpy.core.numeric import array, zeros
from math import pi
from numpy.lib.function_base import linspace
from numpy.core.numeric import arange
from numpy.lib.scimath import sqrt
from numpy.ma.core import ceil
from json import dump
from xml.etree import ElementTree as etree
import sys
class NetworkSolutions(object):
'''
NetworkSolutions elaborates results for post processing.
This class provides he following methods:
SetNetworkGraph: a method for setting NetworkGraph input
SetNetworkMesh: a method for setting NetworkMesh input
SetSolutions: a method for setting Solutions input
SetSimulationContext: a method for setting SimulationContext input.
#Json Methods:
WriteJsonInfo: a method for creating the json which includes simulation information (elements and adaptation steps if adaptation is active).
WriteJson: a method for creating a json for a specified mesh which includes all information needed for postprocessing.
WriteJsonAdapt: a method for creating a json for a specified mesh which includes information about vascular adaptation.
#General Methods:
PlotBrachial: a method for plotting Brachial flows, pressure and wss (for each segment) in the same figure. (Requires matplotlib package)
PlotRadial: a method for plotting Radial flows, pressure and wss (for each segment) in the same figure. (Requires matplotlib package)
PlotCephalic: a method for plotting Cephalic flows, pressure and wss (for each segment) in the same figure. (Requires matplotlib package)
WriteToXML: a method for writing solutions in XML Solutions File.
GetSolution: a method for plotting flow, pressure and WSS for specific entity.
#Flow Methods:
GetInflow: a method for plotting input flow function.
PlotFlow: a method for plotting mean flow for a single mesh. (Requires matplotlib package)
PlotFlowComparative: a method for plotting brachial, radial and ulnar mean flow. (Requires matplotlib package)
GetFlowSignal: a method for returning flow signal for specific mesh.
WriteFlowOutput: a method for writing flow output values for a specific mesh in a .txt file.
PlotReynolds: a method for plotting reynolds number for a single mesh. (Requires matplotlib package)
WriteReynoldsOutput: a method for writing reynolds number output values for a specific mesh in a .txt file.
#Pressure Methods:
PlotPressure: a method for plotting mean pressure for a single mesh. (Requires matplotlib package)
PlotPressureTwo: a method for plotting pressures for a couple of meshes. (Requires matplotlib package)
PlotPressureComparative: a method for plotting brachial, radial and ulnar mean pressure. (Requires matplotlib package)
GetPressureSignal: a method for returning pressure signal for specific mesh.
PlotPressureDrop : a method for plotting pressure drop for specific mesh. (Requires matplotlib package)
WritePressureInput: a method for writing pressure input values for a specific mesh in a .txt file.
WritePressureOutput: a method for writing pressure output values for a specific mesh in a .txt file.
#Wall Shear Stress Methods:
PlotPWSS: a method for plotting mean WSS(Poiseuille) for a single mesh. (Requires matplotlib package)
PlotPWSSComparative: a method for plotting brachial, radial and ulnar mean WSS (Poiseuille). (Requires matplotlib package)
GetPWSSSignal: a method for returning WSS signal(Poiseuille) for specific mesh.
PlotWSS: a method for plotting mean WSS for a single mesh. (Requires matplotlib package)
GetWSSSignal: a method for returning WSS signal for specific mesh.
WriteWSSOutput: a method for writing WSS output values for a specific mesh in a .txt file.
#Other Methods:
PulseWaveVelocity: a method for computing Pulse Wave Velocity(m/s).
If SuperEdge2 is specified, PWV is computed between first and second superedge,
otherwise PWV is computed over a single superedge.
'''
def __init__(self):
'''
Constructor
'''
self.NetworkGraph = None
self.NetworkMesh = None
self.SimulationContext = None
self.DofMap = None
self.Solutions = None
self.t = None
self.TimeStep = None
self.Period = None
self.CardiacFreq = None
self.Cycles = None
self.images = None
self.dayFlow = {} #{element.Id:Q}
self.dayWssP = {} #{element.Id:taoPeak}
self.dayPressure = {} #{element.Id:pressure}
self.dayDiameter = {} #{element.Id:diameter}
self.flowDirection = {'(+)':"from node1 to node2", '(-)':"from node2 to node1"} #Flow direction is assumed positive if flow goes from node1 to node2.
def SetNetworkGraph(self,networkGraph):
'''
Setting NetworkMesh
'''
self.NetworkGraph = networkGraph
def SetNetworkMesh(self,networkMesh):
'''
Setting NetworkMesh
'''
self.NetworkMesh = networkMesh
self.DofMap = DofMap()
self.DofMap.SetNetworkMesh(networkMesh)
self.DofMap.Build()
def SetSimulationContext(self, simulationContext):
'''
Setting SimulationContext
'''
self.SimulationContext = simulationContext
try:
self.TimeStep = simulationContext.Context['timestep']
except KeyError:
print "Error, Please set timestep in Simulation Context XML File"
raise
try:
self.Period = self.SimulationContext.Context['period']
self.CardiacFreq = int(self.Period/self.TimeStep)
except KeyError:
print "Error, Please set period in Simulation Context XML File"
raise
try:
self.Cycles = self.SimulationContext.Context['cycles']
except KeyError:
print "Error, Please set cycles number in Simulation Context XML File"
raise
self.t = linspace(self.TimeStep,self.Period,self.CardiacFreq)
def SetSolutions(self, solutions):
'''
Setting Solutions
'''
self.Solutions = solutions
def SetImagesPath(self, imagDict):
'''
Setting images directory
'''
for name, path in imagDict.iteritems():
if name == 'im':
self.images = path
self.f_images = path
self.p_images = path
self.w_images = path
for name, path in imagDict.iteritems():
if name == 'f':
self.f_images = path
if name == 'p':
self.p_images = path
if name == 'w':
self.w_images = path
#INPUT GNUID
def GetGnuidInformation(self, PatientId, mesh_radius):
'''This method provides information to be used as Gnuid input.'''
ro = self.SimulationContext.Context['blood_density']/1000
mu = self.SimulationContext.Context['dynamic_viscosity']*10
period_pyns = self.SimulationContext.Context['period']
frequency_pyns = 1./period_pyns
#find mesh
for element in self.NetworkMesh.Elements:
if element.Type == 'Anastomosis':
anastomosis = element
prox_artery = anastomosis.Proximal
dofs = prox_artery.GetPoiseuilleDofs()
prox_artery_p1 = self.Solutions[(self.DofMap.DofMap[prox_artery.Id, dofs[0]]),self.CardiacFreq*(self.Cycles-1):] #pressure [Pa]
prox_artery_p2 = self.Solutions[(self.DofMap.DofMap[prox_artery.Id, dofs[1]]),self.CardiacFreq*(self.Cycles-1):] #pressure [Pa]
prox_artery_q = mean(((prox_artery_p1-prox_artery_p2)/prox_artery.R))*6e7 #flow [mL/min]
prox_artery_radius = (max(prox_artery.Radius))*100 # radius [cm]
dist_artery = anastomosis.Distal
dofs = dist_artery.GetPoiseuilleDofs()
dist_artery_p1 = self.Solutions[(self.DofMap.DofMap[dist_artery.Id, dofs[0]]),self.CardiacFreq*(self.Cycles-1):] #pressure [Pa]
dist_artery_p2 = self.Solutions[(self.DofMap.DofMap[dist_artery.Id, dofs[1]]),self.CardiacFreq*(self.Cycles-1):] #pressure [Pa]
dist_artery_q = mean(((dist_artery_p1-dist_artery_p2)/dist_artery.R))*6e7 #flow [mL/min]
prox_artery_mass_flow = (prox_artery_q * ro)/60 #mass flow [g/s]
dist_artery_mass_flow = (dist_artery_q * ro)/60 #mass flow [g/s]
womersley = prox_artery_radius*sqrt((2*pi*frequency_pyns*ro)/mu) #womersley number
gnuid_frequency = ((womersley**2)*mu)/((float(mesh_radius)**2)*2*pi*ro) #frequency for gnuid
gnuid_period = 1./gnuid_frequency #period for gnuid
gnuid_scaling_factor = dist_artery_mass_flow/prox_artery_mass_flow #gnuid scaling factor
txtpath = 'Results/' + PatientId + '/gnuid_parameters.txt'
text_file = open(txtpath, "w")
text_file.write("GNUID Parameters\n")
text_file.write("Proximal artery mass flow " + str(prox_artery_mass_flow) + "\n")
text_file.write("Distal artery mass flow " + str(dist_artery_mass_flow) + "\n")
text_file.write("Womersley number " + str(womersley) + "\n")
text_file.write("Blood Density " + str(ro) + "\n")
text_file.write("Blood Viscosity " + str(mu) + "\n")
text_file.write("Gnuid frequency " + str(gnuid_frequency) + "\n")
text_file.write("Gnuid period " + str(gnuid_period) + "\n")
text_file.write("Gnuid scaling factor " + str(gnuid_scaling_factor) + "\n")
text_file.close()
# JSON METHODS
def WriteJsonInfo(self, days, elements, PatientId):
'''
'''
info = {}
info['time'] = []
info['elements'] = []
if days > 0:
info['adaptation']=True
else:
info['adaptation']=False
for d in range(-1,days+1):
if d >0:
info['time'].append(d*10)
else:
info['time'].append(d)
info['time'].sort()
for el in elements:
if el.Type == 'WavePropagation' or el.Type == 'Resistance':
info['elements'].append(el.Name)
info['elements'].sort()
path = 'Results/' + PatientId + '/json/info.json'
f = open(path,'w')
dump(info, f)
f.close()
def WriteJson(self, meshid, time, excludeWss, PatientId):
'''
This method writes a json file for each mesh.
'''
meshInfo = {}
meshid = str(meshid)
for element in self.NetworkMesh.Elements:
if element.Id == meshid:
dofs = element.GetPoiseuilleDofs()
p1 = self.Solutions[(self.DofMap.DofMap[meshid, dofs[0]]),self.CardiacFreq*(self.Cycles-1):]
p2 = self.Solutions[(self.DofMap.DofMap[meshid, dofs[1]]),self.CardiacFreq*(self.Cycles-1):]
Flow = (p1-p2)/element.R
Wss = []
Reynolds = []
elName = element.Name
meshInfo['meshId']=str(meshid)
meshInfo['name']=str(elName)
meshInfo['mean_pressure']=str(round(mean(p1/133.32),2))+' mmHg'
meshInfo['min_pressure'] = str(0)
min_p = round(min(p1/133.32),2)
if min_p < 0:
meshInfo['min_pressure'] = str(min_p)
meshInfo['mean_flow']=str(round(mean(Flow*6e7),2))+' mL/min'
meshInfo['min_flow'] = str(0)
min_q = round(min(Flow*6e7),2)
if min_q < 0:
meshInfo['min_flow'] = str(min_q)
meshInfo['items'] = []
timeValues = {}
timeValues['flow'] = []
timeValues['pressure'] = []
self.dayFlow[element.Name] = (round(mean(Flow*6e7),1))
self.dayPressure[element.Name] = (round(mean(p1/133.32),1))
if element.Type != "Resistance":
Radius = element.Radius
Reynolds = (2.0*Flow*self.SimulationContext.Context['blood_density'])/(pi*max(Radius)*self.SimulationContext.Context['dynamic_viscosity'])
if excludeWss is False:
Wss = self.GetWSSSignal(element)
tWss = linspace(0, self.Period, len(Wss))
meshInfo['length']=str(round(element.Length*1e2,2))+' cm'
meshInfo['diameter_min']=str(round((min(element.Radius)*2e3),2))+' mm'
meshInfo['diameter_max']=str(round((max(element.Radius)*2e3),2))+' mm'
if excludeWss is False:
meshInfo['mean_wss']=str(round(mean(Wss*10),2))+' dynes/cm<sup>2</sup>'
meshInfo['min_wss'] = str(0)
min_wss = round(min(Wss*10),2)
if min_wss < 0:
meshInfo['min_wss'] = str(min_wss)
meshInfo['mean_re']=str(round(mean(Reynolds),1))
meshInfo['min_re'] = str(0)
min_re = round(min(Reynolds),1)
if min_re < 0:
meshInfo['min_re'] = str(min_re)
timeValues['wss'] = []
timeValues['re'] = []
if excludeWss is False:
self.dayWssP[element.Name] = (round(max(Wss*10),2))
try:
self.dayDiameter[element.Name] = (round(element.dayRadius[time][0]*2e3,2))
except:
self.dayDiameter[element.Name] = (round(element.Radius[0]*2e3,2))
i=0
for q in Flow:
timeValues['flow'].append([self.t[i],(round(q*6e7,2))])
i+=1
i=0
for p in p1:
timeValues['pressure'].append([self.t[i],(round(p/133.32,2))])
i+=1
if excludeWss is False:
i=0
for w in Wss:
timeValues['wss'].append([tWss[i],(round(w*10,2))])
i+=1
i=0
for re in Reynolds:
timeValues['re'].append([self.t[i],(round(re,2))])
i+=1
meshInfo['items'].append(timeValues)
if time > 0:
path = 'Results/' + PatientId + '/json/'+str(time*10)+'_'+str(elName)+'.json'
else:
path = 'Results/' + PatientId + '/json/'+str(time)+'_'+str(elName)+'.json'
f = open(path,'w')
dump(meshInfo, f)
f.close()
def WriteJsonAdapt(self, adaptation, PatientId):
'''
If adaptation algorithm is active, this method
will write a json file for each mesh including
information about vessel adaptation.
'''
meshInfo = {}
for element in self.NetworkMesh.Elements:
if element.Type == 'WavePropagation':
elName = element.Name
meshInfo['meshId']=str(element.Id)
meshInfo['name']=str(elName)
meshInfo['items'] = []
timeValues = {}
timeValues['flow'] = []
timeValues['pressure'] = []
timeValues['wssP'] = []
timeValues['diameter'] = []
for day,sol in adaptation.solutions.iteritems():
if day == -1:
try:
timeValues['flow'].append([day,sol.dayFlow[element.Name]])
timeValues['pressure'].append([day,sol.dayPressure[element.Name]])
timeValues['wssP'].append([day,sol.dayWssP[element.Name]])
timeValues['diameter'].append([day,sol.dayDiameter[element.Name]])
except KeyError:
pass
if day != -1:
timeValues['flow'].append([day*10,sol.dayFlow[element.Name]])
timeValues['pressure'].append([day*10,sol.dayPressure[element.Name]])
timeValues['wssP'].append([day*10,sol.dayWssP[element.Name]])
timeValues['diameter'].append([day*10,sol.dayDiameter[element.Name]])
timeValues['flow'].sort()
min_q = 0
for q in timeValues['flow']:
if q[1] < min_q:
min_q = q[1]
meshInfo['min_q'] = str(min_q)
timeValues['pressure'].sort()
timeValues['wssP'].sort()
timeValues['diameter'].sort()
meshInfo['items'].append(timeValues)
path = 'Results/' + PatientId + '/json/adapt_'+str(elName)+'.json'
f = open(path,'w')
dump(meshInfo, f)
f.close()
# GENERAL METHODS
def PlotBrachial(self):
'''
This method plots Brachial flows, pressure
and wss (for each segment) in the same figure.
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close
except ImportError:
MatPlotLibError()
colourvector = ['r', 'b', 'g', 'c', 'm', 'y', 'k']
indexcolour = 0
for ent, el in self.NetworkMesh.Entities.iteritems():
if ent.Id is not None and ent.Id.find('rachial') != -1:
for element in el:
dofs = element.GetPoiseuilleDofs()
Flow = (self.Solutions[(self.DofMap.DofMap[element.Id, dofs[0]]),self.CardiacFreq*(self.Cycles-1):] - self.Solutions[(self.DofMap.DofMap[element.Id, dofs[1]]),self.CardiacFreq*(self.Cycles-1):])/element.R
PressureIN = (self.Solutions[(self.DofMap.DofMap[element.Id, 0]),self.CardiacFreq*(self.Cycles-1):])
WSSPoiseuille = ((4.0*element.eta)/pi) * (Flow/mean(element.Radius)**3)
print "Name: ", element.Name, " PressureIN(mmHg): ", mean(PressureIN)/133.3223684211, " MeanFlow(mL/min): ", mean(Flow)*6.0e7, " MeanWSS(Pa): ", mean(WSSPoiseuille)
plot(self.t, Flow*6e7, colourvector[indexcolour],linewidth = 3, label = 'Flow '+element.Name)
xlabel('Time ($s$)')
ylabel('Flow ($mL/min$)')
title ('Brachial Flow')
legend()
if indexcolour == 6:
indexcolour = 0
else:
indexcolour+=1
savefig(self.images+'brachial_flow.png')
close()
indexcolour = 0
for element in el:
dofs = element.GetPoiseuilleDofs()
PressureIN = (self.Solutions[(self.DofMap.DofMap[element.Id, 0]),self.CardiacFreq*(self.Cycles-1):])/133.3223684211
plot(self.t, PressureIN, colourvector[indexcolour],linewidth = 3, label = 'Pressure '+element.Name)
xlabel('Time ($s$)')
ylabel('Pressure ($mmHG$)')
title ('Brachial Pressure')
legend()
if indexcolour == 6:
indexcolour = 0
else:
indexcolour+=1
savefig(self.images+'brachial_pressure.png')
close()
indexcolour = 0
def PlotRadial(self):
'''
This method plots Radial flows, pressure
and wss (for each segment) in the same figure.
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close
except ImportError:
MatPlotLibError()
colourvector = ['r', 'b', 'g', 'c', 'm', 'y', 'k']
indexcolour = 0
for ent, el in self.NetworkMesh.Entities.iteritems():
if ent.Id is not None and ent.Id.find('radial') != -1:
for element in el:
dofs = element.GetPoiseuilleDofs()
Flow = (self.Solutions[(self.DofMap.DofMap[element.Id, dofs[0]]),self.CardiacFreq*(self.Cycles-1):] - self.Solutions[(self.DofMap.DofMap[element.Id, dofs[1]]),self.CardiacFreq*(self.Cycles-1):])/element.R
PressureIN = (self.Solutions[(self.DofMap.DofMap[element.Id, 0]),self.CardiacFreq*(self.Cycles-1):])
WSSPoiseuille = ((4.0*element.eta)/pi) * (Flow/mean(element.Radius)**3)
print "Name: ", element.Name, " PressureIN(mmHg): ", mean(PressureIN)/133.3223684211, " MeanFlow(mL/min): ", mean(Flow)*6.0e7, " MeanWSS(Pa): ", mean(WSSPoiseuille)
plot(self.t, Flow*6e7, colourvector[indexcolour],linewidth = 3, label = 'Flow '+element.Name)
xlabel('Time ($s$)')
ylabel('Flow ($mL/min$)')
title ('Radial Flow')
legend()
if indexcolour == 6:
indexcolour = 0
else:
indexcolour+=1
savefig(self.images+'radial_flow.png')
close()
indexcolour = 0
for element in el:
dofs = element.GetPoiseuilleDofs()
PressureIN = (self.Solutions[(self.DofMap.DofMap[element.Id, 0]),self.CardiacFreq*(self.Cycles-1):])/133.3223684211
plot(self.t, PressureIN, colourvector[indexcolour],linewidth = 3, label = 'Pressure '+element.Name)
xlabel('Time ($s$)')
ylabel('Pressure ($mmHG$)')
title ('Radial Pressure')
legend()
if indexcolour == 6:
indexcolour = 0
else:
indexcolour+=1
savefig(self.images+'radial_pressure.png')
close()
indexcolour = 0
def PlotCephalic(self):
'''
This method plots Cephalic flows, pressure
and wss (for each segment) in the same figure.
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close
except ImportError:
MatPlotLibError()
colourvector = ['r', 'b', 'g', 'c', 'm', 'y', 'k']
indexcolour = 0
for ent, el in self.NetworkMesh.Entities.iteritems():
if ent.Id is not None and ent.Id.find('cephalic') != -1:
for element in el:
dofs = element.GetPoiseuilleDofs()
Flow = (self.Solutions[(self.DofMap.DofMap[element.Id, dofs[0]]),self.CardiacFreq*(self.Cycles-1):] - self.Solutions[(self.DofMap.DofMap[element.Id, dofs[1]]),self.CardiacFreq*(self.Cycles-1):])/element.R
PressureIN = (self.Solutions[(self.DofMap.DofMap[element.Id, 0]),self.CardiacFreq*(self.Cycles-1):])
WSSPoiseuille = ((4.0*element.eta)/pi) * (Flow/mean(element.Radius)**3)
print "Name: ", element.Name, " PressureIN(mmHg): ", mean(PressureIN)/133.3223684211, " MeanFlow(mL/min): ", mean(Flow)*6.0e7, " MeanWSS(Pa): ", mean(WSSPoiseuille)
plot(self.t, Flow*6e7, colourvector[indexcolour],linewidth = 3, label = element.Name)
xlabel('Time ($s$)')
ylabel('Flow ($mL/min$)')
title ('Cephalic Flow')
legend(loc=0)
if indexcolour == 6:
indexcolour = 0
else:
indexcolour+=1
savefig(self.images+'cephalic_flow.png')
close()
indexcolour = 0
for element in el:
dofs = element.GetPoiseuilleDofs()
PressureIN = (self.Solutions[(self.DofMap.DofMap[element.Id, 0]),self.CardiacFreq*(self.Cycles-1):])/133.3223684211
plot(self.t, PressureIN, colourvector[indexcolour],linewidth = 3, label = 'Pressure '+element.Name)
xlabel('Time ($s$)')
ylabel('Pressure ($mmHG$)')
title ('Cephalic Pressure')
legend()
if indexcolour == 6:
indexcolour = 0
else:
indexcolour+=1
savefig(self.images+'cephalic_pressure.png')
close()
indexcolour = 0
# FLOW METHODS
def GetInflow(self, flow):
'''
This method plots inflow function
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close
except ImportError:
MatPlotLibError()
t = linspace(0.0,self.Period+self.TimeStep,self.CardiacFreq).reshape((1,ceil(self.Period/self.TimeStep+1.0)))
plot(t[0,:], flow[0,:]*6e7, 'r-',linewidth = 3, label = 'Inlet Flow') #red line
xlabel('Time ($s$)')
ylabel('Flow ($mL/min$)')
title ('InFlow: '+str(mean(flow)*6.0e7)+' $mL/min$')
legend()
savefig(self.images+'inflow.png')
close()
def PlotDaysBrachial(self, wdir, adaptation):
'''
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, savefig, close, ylim
except ImportError:
MatPlotLibError()
Flow = {-1:self.SimulationContext.Context['brachial_flow']}
Diameter = {}
t = [-1]
x = 0
yFlows=[]
yDiams=[]
for el in self.NetworkMesh.Elements:
if el.Name == 'brachial_prox_1':
for day,sol in adaptation.solutions.iteritems():
if day != -1:
Flow.update({day:sol.dayFlow[el.Id]})
t.append(x)
x+=1
try:
Diameter.update({day:el.dayRadius[day][0]*2e3})
except:
Diameter.update({day:el.Radius[0]*2e3})
Diameter[-1]=Diameter[0]
tPlot = []
for day in sorted(t):
yFlows.append(Flow[day])
yDiams.append(Diameter[day])
tPlot.append(day*10)
plot(tPlot,yDiams,marker='o', linestyle='-',linewidth = 2)
minY = 0
ylim(ymin=minY)
xlabel('Time ($days$)')
ylabel('Diameter ($mm$)')
brachDiam = wdir+'/Brachial_days_diam.png'
savefig(wdir+'/Brachial_days_diam.png')
close()
plot(tPlot,yFlows,marker='o', linestyle='-',linewidth = 2)
ylim(ymin=minY)
xlabel('Time ($days$)')
ylabel('Flow ($mL/min$)')
brachFlow = wdir+'/Brachial_days_flow.png'
savefig(wdir+'/Brachial_days_flow.png')
close()
meanBrachFlow = Flow[4]
return brachDiam, brachFlow, meanBrachFlow
def GetDistalPressure(self, adaptation):
'''
This method returns distal pressure in the index finger (mmHg)
'''
for element in self.NetworkMesh.Elements:
if element.Name == 'index_finger':
for day,sol in adaptation.solutions.iteritems():
if day == 4:
meshid = element.Id
dofs = element.GetPoiseuilleDofs()
distalPressure = mean(self.Solutions[(self.DofMap.DofMap[meshid, dofs[1]]),self.CardiacFreq*(self.Cycles-1):])
return round(distalPressure/133.32,2)
def PlotDistalPressure(self, wdir, distalPressures):
'''
'''
try:
from matplotlib.pyplot import plot, savefig, close, ylim, figure
except ImportError:
MatPlotLibError()
pressure = []
ind = arange(4)
pos = arange(4)
width = 0.5
for va, p in distalPressures.iteritems():
for x in ind:
if va == x:
pressure.append(p)
fig = figure()
ax = fig.add_subplot(111)
rects = ax.bar(0.2+ind, pressure, width, color='c')
ax.set_title('Distal pressure prediction in different AVFs')
ax.set_ylabel('Index finger pressure at 40 days ($mmHg$)')
ax.set_xticks(0.45+pos)
ax.set_xticklabels( ('RCEE', 'RCES', 'BCES', 'BBES') )
plot([0,4], [60,60],'--', color='k', linewidth=2 )
maxY = max(pressure)
maxY+=0.02*maxY
ylim(ymax=maxY)
pressureImage = wdir+'/distalPressure.png'
savefig(wdir+'/distalPressure.png')
close()
return pressureImage
def Compare(self, wdir, compare):
'''
'''
try:
from matplotlib.pyplot import plot, savefig, close, ylim, figure
except ImportError:
MatPlotLibError()
flow = []
std = []
ind = arange(4)
pos = arange(4)
width = 0.5
for va, q in compare.iteritems():
for x in ind:
if va == x:
flow.append(q)
std.append(q*0.2)
fig = figure()
ax = fig.add_subplot(111)
rects = ax.bar(0.2+ind, flow, width, color='c', yerr = std, ecolor='r')
ax.set_title('Comparing flow volume in different AVFs')
ax.set_ylabel('Brachial artery flow volume at 40 days ($mL/min$)')
ax.set_xticks(0.45+pos)
ax.set_xticklabels( ('RCEE', 'RCES', 'BCES', 'BBES') )
plot([0,2], [400,400],'--', color='k', linewidth=2 )
maxY = max(flow)+max(std)
maxY+=0.02*maxY
ylim(ymax=maxY)
compareImage = wdir+'/compare.png'
savefig(wdir+'/compare.png')
close()
return compareImage
def Plots(self, wdir, day, name):
'''
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close, ylim
except ImportError:
MatPlotLibError()
timeImages = []
for element in self.NetworkMesh.Elements:
if element.Name == name:
meshid = element.Id
el = element
dofs = element.GetPoiseuilleDofs()
p1 = self.Solutions[(self.DofMap.DofMap[meshid, dofs[0]]),self.CardiacFreq*(self.Cycles-1):]
p2 = self.Solutions[(self.DofMap.DofMap[meshid, dofs[1]]),self.CardiacFreq*(self.Cycles-1):]
if mean(p1)>=mean(p2):
flowDirection = self.flowDirection['(+)']
Flow = (p1-p2)/element.R
else:
flowDirection = self.flowDirection['(-)']
Flow = (p2-p1)/element.R
self.dayFlow[meshid] = (round(mean(Flow*6e7),1))
plot(self.t, Flow*6e7, 'r-',linewidth = 3, label = 'Volumetric flow rate') #red line
minY = 0
for q in Flow*6e7:
if q < minY:
minY = q
if minY != 0:
plot(self.t, zeros(len(Flow)),':',linewidth = 1)
ylim(ymin=minY)
xlabel('Time ($s$)')
ylabel('Volumetric flow rate ($mL/min$)')
if flowDirection == self.flowDirection['(+)']:
title ('Flow (+)'+' peak:'+str(round(max(Flow*6e7),1))+' mean:'+str(round(mean(Flow*6e7),1))+' min:'+str(round(min(Flow*6e7),1)))
if flowDirection == self.flowDirection['(-)']:
title ('Flow (-)'+' peak:'+str(round(max(Flow*6e7),1))+' mean:'+str(round(mean(Flow*6e7),1))+' min:'+str(round(min(Flow*6e7),1)))
legend()
if name.__contains__('brachial'):
timeImages.append(wdir+'/%s_brachflow.png' % day)
savefig(wdir+'/%s_brachflow.png' % day)
close()
if name.__contains__('radial'):
timeImages.append(wdir+'/%s_radflow.png' % day)
savefig(wdir+'/%s_radflow.png' % day)
close()
plot(self.t, p1/133.32, 'b-', linewidth = 3, label = 'Pressure Signal') #blue line
minY = 0
for p in p1/133.32:
if p < minY:
minY = p
if minY != 0:
plot(self.t, zeros(len(p1)),':',linewidth = 1)
ylim(ymin=minY)
xlabel('Time ($s$)')
ylabel('Pressure ($mmHg$)')
title ('Pressure'+' peak:'+str(round(max(p1/133.32),1))+' mean:'+str(round(mean(p1/133.32),1))+' min:'+str(round(min(p1/133.32),1)))
legend()
if name.__contains__('brachial'):
timeImages.append(wdir+'/%s_brachpressure.png' % day)
savefig(wdir+'/%s_brachpressure.png' % day)
close()
if name.__contains__('radial'):
timeImages.append(wdir+'/%s_radpressure.png' % day)
savefig(wdir+'/%s_radpressure.png' % day)
close()
inverseWomersley = InverseWomersley()
inverseWomersley.SetSimulationContext(self.SimulationContext)
inverseWomersley.SetNetworkMesh(self.NetworkMesh)
inverseWomersley.SetFlowSignal(self.GetFlowSignal(el))
inverseWomersley.GetTaoFromQ(el)
tplot = linspace(0, inverseWomersley.tPeriod, len(inverseWomersley.Tauplot))
plot(tplot, inverseWomersley.Tauplot,'g-',linewidth = 3, label = 'WSS')
minY = 0
for w in inverseWomersley.Tauplot:
if w < minY:
minY = w
if minY != 0:
plot(tplot, zeros(len(inverseWomersley.Tauplot)),':',linewidth = 1)
ylim(ymin=minY)
xlabel('Time ($s$)')
ylabel('Wall shear stress ($dyne/cm^2$)')
title ('Wss'+' peak:'+str(round(max(inverseWomersley.Tauplot),1))+' mean:'+str(round(mean(inverseWomersley.Tauplot),1))+' min:'+str(round(min(inverseWomersley.Tauplot),1)))
legend()
if name.__contains__('brachial'):
timeImages.append(wdir+'/%s_brachwss.png' % day)
savefig(wdir+'/%s_brachwss.png' % day)
close()
if name.__contains__('radial'):
timeImages.append(wdir+'/%s_radwss.png' % day)
savefig(wdir+'/%s_radwss.png' % day)
close()
return timeImages
def PlotDaysRadial(self, wdir, adaptation):
'''
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, savefig, close, ylim
except ImportError:
MatPlotLibError()
Flow = {-1:self.SimulationContext.Context['radial_flow']}
Diameter = {}
t = [-1]
x = 0
yFlows=[]
yDiams=[]
for el in self.NetworkMesh.Elements:
if el.Name == 'radial_prox_3':
for day,sol in adaptation.solutions.iteritems():
if day != -1:
Flow.update({day:sol.dayFlow[el.Id]})
t.append(x)
x+=1
try:
Diameter.update({day:el.dayRadius[day][0]*2e3})
except:
Diameter.update({day:el.Radius[0]*2e3})
Diameter[-1]=Diameter[0]
tPlot = []
for day in sorted(t):
yFlows.append(Flow[day])
yDiams.append(Diameter[day])
tPlot.append(day*10)
minY = 0
plot(tPlot,yDiams,marker='o', linestyle='-',linewidth = 2)
ylim(ymin=minY)
xlabel('Time ($days$)')
ylabel('Diameter ($mm$)')
radDiam = wdir+'/Radial_days_diam.png'
savefig(wdir+'/Radial_days_diam.png')
close()
plot(tPlot,yFlows,marker='o', linestyle='-',linewidth = 2)
ylim(ymin=minY)
xlabel('Time ($days$)')
ylabel('Flow ($mL/min$)')
radFlow = wdir+'/Radial_days_flow.png'
savefig(wdir+'/Radial_days_flow.png')
close()
return radDiam, radFlow
def PlotFlow(self, meshid):
'''
This method plots mean flow for a single mesh.
Flow volume is considered as absolute value.
Direction of the flow is assumed + if goes from node1 to node2. Instead
flowDirection is assumed to be -.
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close, ylim
except ImportError:
MatPlotLibError()
meshid = str(meshid)
for element in self.NetworkMesh.Elements:
if element.Id == meshid:
name = self.NetworkGraph.Edges[self.NetworkMesh.MeshToGraph[meshid]].Name
dofs = element.GetPoiseuilleDofs()
p1 = self.Solutions[(self.DofMap.DofMap[meshid, dofs[0]]),self.CardiacFreq*(self.Cycles-1):]
p2 = self.Solutions[(self.DofMap.DofMap[meshid, dofs[1]]),self.CardiacFreq*(self.Cycles-1):]
if mean(p1)>=mean(p2):
flowDirection = self.flowDirection['(+)']
Flow = (p1-p2)/element.R
else:
flowDirection = self.flowDirection['(-)']
Flow = (p2-p1)/element.R
print "Flow, MeshId ", element.Id, ' ', element.Name, " = " , mean(Flow)*6e7, "mL/min ", flowDirection
self.dayFlow[meshid] = (round(mean(Flow*6e7),1))
plot(self.t, Flow*6e7, 'r-',linewidth = 3, label = 'Flow Output') #red line
minY = 0
for q in Flow*6e7:
if q < minY:
minY = q
if minY != 0:
plot(self.t, zeros(len(Flow)),':',linewidth = 1)
ylim(ymin=minY)
xlabel('Time ($s$)')
ylabel('Volumetric flow rate ($mL/min$)')
if flowDirection == self.flowDirection['(+)']:
title ('Flow (+)'+' peak:'+str(round(max(Flow*6e7),1))+' mean:'+str(round(mean(Flow*6e7),1))+' min:'+str(round(min(Flow*6e7),1)))
if flowDirection == self.flowDirection['(-)']:
title ('Flow (-)'+' peak:'+str(round(max(Flow*6e7),1))+' mean:'+str(round(mean(Flow*6e7),1))+' min:'+str(round(min(Flow*6e7),1)))
legend()
savefig(self.f_images + meshid + '_' + name +'_flow.png')
close()
def PlotVelocity(self, meshid):
'''
This method plots mean flow for a single mesh
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close
except ImportError:
MatPlotLibError()
meshid = str(meshid)
for element in self.NetworkMesh.Elements:
if element.Id == meshid:
name = self.NetworkGraph.Edges[self.NetworkMesh.MeshToGraph[meshid]].Name
dofs = element.GetPoiseuilleDofs()
p1 = self.Solutions[(self.DofMap.DofMap[meshid, dofs[0]]),self.CardiacFreq*(self.Cycles-1):]
p2 = self.Solutions[(self.DofMap.DofMap[meshid, dofs[1]]),self.CardiacFreq*(self.Cycles-1):]
if mean(p1)>=mean(p2):
flowDirection = self.flowDirection['(+)']
Flow = (p1-p2)/element.R
else:
flowDirection = self.flowDirection['(-)']
Flow = (p2-p1)/element.R
Radius = mean(element.Radius)
print element.Name, Radius
Velocity = Flow/(pi*Radius**2)
if flowDirection == self.flowDirection['(+)']:
plot(self.t, Velocity, 'r-',linewidth = 3, label = 'Velocity (+)') #red line
if flowDirection == self.flowDirection['(-)']:
plot(self.t, Velocity, 'r-',linewidth = 3, label = 'Velocity (-)') #red line
xlabel('Time ($s$)')
ylabel('Velocity ($m^3/s$)')
title ('Velocity')
legend()
savefig(self.images + meshid + '_' + name +'_vel.png')
close()
def PlotFlowComparative(self):
'''
This method plots brachial, radial and ulnar mean flow.
If cycle is not specified, default cycle is the last one
'''
try:
from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close
except ImportError:
MatPlotLibError()
FlowBrachial = 0
FlowRadial = 0
FlowUlnar = 0
i = 0
j = 0
k = 0
for element in self.NetworkMesh.Elements:
if element.Type is not 'Windkessel' and element.Name.find('brachial') != -1:
dofs = element.GetPoiseuilleDofs()
p1 = self.Solutions[(self.DofMap.DofMap[element.Id, dofs[0]]),self.CardiacFreq*(self.Cycles-1):]
p2 = self.Solutions[(self.DofMap.DofMap[element.Id, dofs[1]]),self.CardiacFreq*(self.Cycles-1):]
if mean(p1)>=mean(p2):
FlowBrachial += (p1-p2)/element.R
else:
FlowBrachial += (p2-p1)/element.R
i += 1
if element.Type is not 'Windkessel' and element.Name.find('radial') != -1:
dofs = element.GetPoiseuilleDofs()
p1 = self.Solutions[(self.DofMap.DofMap[element.Id, dofs[0]]),self.CardiacFreq*(self.Cycles-1):]
p2 = self.Solutions[(self.DofMap.DofMap[element.Id, dofs[1]]),self.CardiacFreq*(self.Cycles-1):]
if mean(p1)>=mean(p2):
FlowRadial += (p1-p2)/element.R
else:
FlowRadial += (p2-p1)/element.R
j += 1
if element.Type is not 'Windkessel' and element.Name.find('ulnar') != -1:
dofs = element.GetPoiseuilleDofs()
p1 = self.Solutions[(self.DofMap.DofMap[element.Id, dofs[0]]),self.CardiacFreq*(self.Cycles-1):]
p2 = self.Solutions[(self.DofMap.DofMap[element.Id, dofs[1]]),self.CardiacFreq*(self.Cycles-1):]
if mean(p1)>=mean(p2):
FlowUlnar += (p1-p2)/element.R
else:
FlowUlnar += (p2-p1)/element.R
k += 1
if i != 0:
FlowBrachial = (FlowBrachial*6e7)/i
print "Brachial Flow = ", mean(FlowBrachial), "mL/min"
plot(self.t, FlowBrachial, 'r-', linewidth = 3, label = 'brachial') #red line
if i == 0:
FlowBrachial = 0
print "There isn't any element named brachial, check your network xml file"
if j != 0:
FlowRadial = (FlowRadial*6e7)/j
print "Radial Flow = ", mean(FlowRadial), "mL/min"
plot(self.t, FlowRadial, 'b-', linewidth = 3, label = 'radial') #blue line
if j == 0:
FlowRadial = 0