-
Notifications
You must be signed in to change notification settings - Fork 2
/
CT_coronary_automated_tuning.py
1995 lines (1707 loc) · 76.2 KB
/
CT_coronary_automated_tuning.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from time import sleep
import vtk
import os
import glob
import sys
import time
import numpy as np
import math
from scipy.optimize import minimize
pConv = 1333.34
# ******************* DEFINE USER INPUTS IN THIS BLOCK ************************
# ** Patient clinical information (if not known, indicate 'NONE')
heart_rate = 60 #BPM
Pao_min = 89.8 # mmHg
Pao_max = 151.3 # mmHg
strokeVol = 80.85 # mL
ejectFract = 0.69
sys_cor_split= 6.37 #The fraction of cardiac output to all coronary arteries
meanPressure = (0.333)*Pao_max + (0.667)*Pao_min # mmHg
Ppul_mean = 14.0 # mmHg
Qla_ratio = 'None' #1.07 # Ratio of 'early' to 'late' flows into LV (i.e. E/A wave)
mit_valve = 'None' #0.763 #0.56 # Fraction of heart cycle that mitral valve is open for
aor_valve = 'None' #0.311 #0.39 # Fraction of heart cycle that aortic valve is open for
pul_valve = 'None' #0.377 #0.374 # Fraction of heart cycle that pulmonary valve is open for
Pra_mean = 'None' #3.0 # mmHg - IVC right atrial mean pressure
meanFlow = strokeVol*(float(heart_rate)/60.0) # mL/s
Cam_scale = 0.89
Ca_scale = 0.11
Crcr_estim = 50e-6 #compliance of the aorta (estimate from 3ewk)
# ************************* Left and Right Coronary Split *******************
#Write file to store flow Split data
Left_Cor_split_assigned=70
Right_Cor_split_assigned=100-Left_Cor_split_assigned
f_l=(sys_cor_split/100.)*(Left_Cor_split_assigned/100.)
f_r=(sys_cor_split/100.)*(Right_Cor_split_assigned/100.)
Left_Cor_split_computed=0 #Don't touch
Aor_Cor_split_computed=0 #Don't touch
#Write the data to a file
Flow_split_file=open("LeftRightFlowSplit.dat",'w')
Flow_split_file.write("Iteration AortaCoronaryAssigned AortaCoronaryMeasured LeftSplitAssigned LeftSplitMeasured LeftResistance RightResistance\n")
Flow_split_file.close()
# *********************** Coronary Flow Split ************************
splitting_scheme="owais"
if splitting_scheme=="justin":sys_cor_split = 4.0
if splitting_scheme=="owais": sys_cor_split = (f_l+f_r)*100
# *************************** SOLVER PARAMETERS *************************
N_timesteps=200
N_cycles=3
# ** FSI parameters
UNIFORM_WALL_PROPERTIES = False
# For uniform wall properties only
deformable_Evw=10000000
deformable_thickness=0.05
# For variable wall properties only
deformable_aortic_E = 7000000
deformable_coronary_E = 11500000
deformable_graft_E = 50000000
deformable_lima_E = 7000000
# For all deformable simulations
deformable_nuvw=0.5
deformable_density=1.0
deformable_kcons=0.833333
deformable_pressure=119990
# ** Mesh information
WORKING_DIRECTORY = os.getcwd()
MESH_SURFACES_PATH = os.getcwd()+"/mesh-complete/mesh-surfaces"
aorBranchTag = 'aorta'
lcaBranchTag = 'lca'
lcxBranchTag = 'lcx'
rcaBranchTag = 'rca'
inflowTag = 'inflow'
# Remove the cap tags if present
CapFileNames=glob.glob(MESH_SURFACES_PATH+"/cap_*.vtp")
for CapFileName in CapFileNames:
os.system("mv %s %s"%(CapFileName, CapFileName.replace("cap_","")))
# ** Executables and file paths
GCODE_BINARY_DIR = '/home/k/khanmu11/khanmu11/Softwares/0DSolver/lpnbin/'
PRESOLVER_PATH = '/home/k/khanmu11/ana/Softwares/svSolver/BuildWithMake/Bin/svpre.exe'
POST_SOLVER_PATH = '/home/k/khanmu11/ana/Softwares/svSolver/BuildWithMake/Bin/svpost.exe'
# ** Cluster settings
FLOWSOLVER_NODES = 4
PROCESSORS=40
BATCH_COMMAND = "sbatch"
RUN_COMMAND = 'srun' # usually defined inside your batch scripts
OPT_SCRIPT = "Niagara_OPT_script"
DREAM_SCRIPT = "Niagara_DREAM_script"
SOLVER_SCRIPT = "Niagara_flowsolver_script"
RES_OPT_SCRIPT = "Niagara_optimize_surr_res_script"
COM_OPT_SCRIPT = "Niagara_optimize_surr_com_script"
# ** Other tuning settings
USER_EMAIL_ADDRESS = '[email protected]'
USE_OPTIMIZATION = True
LOG_SCALE = 0.0001
NUM_RESTARTS = 50
MAX_ITER = 200
# ************************ USER INPUTS END HERE *******************************
if(GCODE_BINARY_DIR[-1:] is not '/'):
GCODE_BINARY_DIR = GCODE_BINARY_DIR + '/'
SURROGATE_COMMAND = GCODE_BINARY_DIR + 'bin/runCoronaryModel'
SURROGATE_OUTPUTS_PATH = 'outputTargets.out'
SOLVER_INPUT_PATH = 'solver.inp'
CORONARY_MODEL_PATH = 'coronaryModel.txt'
THREE_D_RESULTS_PATH = 'AllData'
#-------------------------------------------------------------------------------
def readVTPFile( file_in ):
reader = vtk.vtkXMLPolyDataReader()
reader.SetFileName(file_in)
reader.Update()
poly = reader.GetOutput()
return poly
#-------------------------------------------------------------------------------
def findVTPArea( file_in ):
reader = vtk.vtkXMLPolyDataReader()
reader.SetFileName(file_in)
reader.Update()
poly = reader.GetOutputPort()
masser = vtk.vtkMassProperties()
masser.SetInputConnection(poly)
masser.Update()
return masser.GetSurfaceArea()
#-------------------------------------------------------------------------------
def findVTPMassCenter( file_in ):
reader = vtk.vtkXMLPolyDataReader()
reader.SetFileName(file_in)
reader.Update()
poly = reader.GetOutput()
num_points = poly.GetNumberOfPoints()
x_list = []
y_list = []
z_list = []
for i in range(num_points):
x_list.append(float(poly.GetPoints().GetPoint(i)[0]))
y_list.append(float(poly.GetPoints().GetPoint(i)[1]))
z_list.append(float(poly.GetPoints().GetPoint(i)[2]))
return (np.average(x_list), np.average(y_list), np.average(z_list))
#-------------------------------------------------------------------------------
def runScript_base(scriptName, jobName, time, nodes, procs):
scriptFile = open(str(scriptName), 'w')
scriptFile.write('#!/bin/bash\n\n')
scriptFile.write('# Name of your job\n')
scriptFile.write('#SBATCH --job-name='+str(jobName)+'\n')
scriptFile.write('#SBATCH --partition=debug\n\n')
scriptFile.write('# Specify the name of the output file. The %j specifies the job ID\n')
scriptFile.write('#SBATCH --output='+str(jobName)+'.o%j\n\n')
scriptFile.write('# Specify the name of the error file. The %j specifies the job ID\n')
scriptFile.write('#SBATCH --error='+str(jobName)+'.e%j\n\n')
scriptFile.write('# The walltime you require for your job\n')
scriptFile.write('#SBATCH --time='+str(time)+':00:00\n\n')
scriptFile.write('# Job priority. Leave as normal for now\n')
scriptFile.write('#SBATCH --qos=normal\n\n')
scriptFile.write('# Number of nodes are you requesting for your job. You can have 40 processors per node\n')
scriptFile.write('#SBATCH --nodes='+str(nodes)+'\n\n')
scriptFile.write('# Number of processors per node\n')
scriptFile.write('#SBATCH --ntasks-per-node='+str(procs)+'\n\n')
scriptFile.write('# Send an email to this address when your job starts and finishes\n')
scriptFile.write('#SBATCH --mail-user='+str(USER_EMAIL_ADDRESS)+'\n')
scriptFile.write('#SBATCH --mail-type=begin\n')
scriptFile.write('#SBATCH --mail-type=end\n\n')
scriptFile.write('# Name of the executable you want to run on the cluster\n')
scriptFile.write("module purge; module load cmake lsb-release intelpython3/2019u4 gcc/8.3.0 openmpi/4.0.1 vtk/9.0.1\n")
scriptFile.close()
#-------------------------------------------------------------------------------
def makeNM_script():
runScript_base(OPT_SCRIPT, 'NM_cor', 1, 1, 1)
NM_script = open(OPT_SCRIPT, 'a')
NM_script.write('\n')
NM_script.write(RUN_COMMAND + ' ' + GCODE_BINARY_DIR + 'bin/tuneModel_NM 0 coronary.csv 2 coronaryParams.txt\n')
NM_script.close()
#-------------------------------------------------------------------------------
def makeFlowsolver_script():
runScript_base(SOLVER_SCRIPT, 'svFlowsolver', 1, FLOWSOLVER_NODES, PROCESSORS)
flow_script = open(SOLVER_SCRIPT, 'a')
flow_script.write('\n')
flow_script.write(RUN_COMMAND + ' /home/k/khanmu11/ana/Softwares/svSolver/BuildWithMake/Bin/svsolver-openmpi.exe\n')
flow_script.close()
#-------------------------------------------------------------------------------
def makeSurrResOpt_script():
runScript_base(RES_OPT_SCRIPT, 'SUR_OPT', 1, 1, 1)
opt_script = open(RES_OPT_SCRIPT, 'a')
opt_script.write('\n')
opt_script.write(RUN_COMMAND + ' python optimizeSurrogateRes.py\n')
opt_script.close()
#-------------------------------------------------------------------------------
def makeSurrComOpt_script():
runScript_base(COM_OPT_SCRIPT, 'SUR_OPT', 1, 1, 1)
opt_script = open(COM_OPT_SCRIPT, 'a')
opt_script.write('\n')
opt_script.write(RUN_COMMAND + ' python optimizeSurrogateCom.py\n')
opt_script.close()
#-------------------------------------------------------------------------------
def runNM_OPT():
print("\n** Running Nelder-Mead Optimization\n")
#command_string = BATCH_COMMAND + ' ' + OPT_SCRIPT ############## MOK Changed for Niagara
command_string = GCODE_BINARY_DIR + 'bin/tuneModel_NM 0 coronary.csv 2 coronaryParams.txt'
print(command_string)
os.system(command_string)
#-------------------------------------------------------------------------------
def runDREAM_MCMC():
print("\n** Running DREAM Parallel MCMC\n")
command_string = BATCH_COMMAND + ' ' + DREAM_SCRIPT
print(command_string)
os.system(command_string)
#-------------------------------------------------------------------------------
def run3D_SIM():
print("\n** Starting 3D SimVascular Simulation\n")
command_string = BATCH_COMMAND + ' ' + SOLVER_SCRIPT
print(command_string)
os.system(command_string)
#-------------------------------------------------------------------------------
def runSurrogateSim():
print("** Running surrogate simulation")
command_string = SURROGATE_COMMAND
print(command_string)
os.system(command_string)
output_file = open(SURROGATE_OUTPUTS_PATH, 'r')
surr_results = []
for line in output_file:
elements = line.split()
if(len(elements) == 0):
continue;
res = elements[0]
if(res == 'PaoMin' or res == 'PaoMax' or res == 'PaoMean'
or res == 'AorCorSplit' or res == 'AbsQin' or res == 'LCorMaxRatio'
or res == 'LCorTotRatio' or res == 'LThirdFF' or res == 'LHalfFF'
or res == 'RCorMaxRatio' or res == 'RCorTotRatio'
or res == 'RThirdFF' or res == 'RHalfFF'):
surr_results.append(float(elements[2]))
output_file.close()
return surr_results
#-------------------------------------------------------------------------------
def runSurrogateResOptimization():
print('\n** Optimizing surrogate resistances using Nelder-Mead\n')
#command_string = BATCH_COMMAND + ' ' + RES_OPT_SCRIPT
command_string = "python optimizeSurrogateRes.py"
print(command_string)
os.system(command_string)
#-------------------------------------------------------------------------------
def runSurrogateComplianceOptimization():
print('\n** Optimizing surrogate compliance using Nelder-Mead\n')
##command_string = BATCH_COMMAND + ' ' + COM_OPT_SCRIPT
command_string = "python optimizeSurrogateCom.py"
print(command_string)
os.system(command_string)
#-------------------------------------------------------------------------------
def getLL_params():
standard_devs = []
weights = []
standard_devs.append(5.0) # PaoMin
standard_devs.append(5.0) # PaoMax
standard_devs.append(5.0) # PaoMean
standard_devs.append(0.05) # AorCorSplit
standard_devs.append(5.0) # AbsQin
standard_devs.append(0.8) # LCorMaxRatio
standard_devs.append(2.5337) # LCorTotRatio
standard_devs.append(0.02) # LThirdFF
standard_devs.append(0.03) # LHalfFF
standard_devs.append(0.3) # RCorMaxRatio
standard_devs.append(1.0816) # RCorTotRatio
standard_devs.append(0.07) # RThirdFF
standard_devs.append(0.07) # RHalfFF
weights.append(3.0) # PaoMin
weights.append(3.0) # PaoMax
weights.append(3.0) # PaoMean
weights.append(5.0) # AorCorSplit MOK: Previously 1.0
weights.append(5.0) # AbsQin
weights.append(2.5) # LCorMaxRatio
weights.append(2.5) # LCorTotRatio
weights.append(2.5) # LThirdFF
weights.append(2.5) # LHalfFF
weights.append(2.5) # RCorMaxRatio
weights.append(2.5) # RCorTotRatio
weights.append(2.5) # RThirdFF
weights.append(2.5) # RHalfFF
"""standard_devs.append(8.0) # PaoMin
standard_devs.append(12.0) # PaoMax
standard_devs.append(9.6) # PaoMean
standard_devs.append(0.05) # AorCorSplit
standard_devs.append(9.0) # AbsQin
standard_devs.append(0.8) # LCorMaxRatio
standard_devs.append(2.5337) # LCorTotRatio
standard_devs.append(0.02) # LThirdFF
standard_devs.append(0.03) # LHalfFF
standard_devs.append(0.3) # RCorMaxRatio
standard_devs.append(1.0816) # RCorTotRatio
standard_devs.append(0.07) # RThirdFF
standard_devs.append(0.07) # RHalfFF
weights.append(0.5) # PaoMin
weights.append(0.25) # PaoMax
weights.append(1.0) # PaoMean
weights.append(1.0) # AorCorSplit MOK: Previously 1.0
weights.append(0.25) # AbsQin
weights.append(5.0) # LCorMaxRatio
weights.append(5.0) # LCorTotRatio
weights.append(5.0) # LThirdFF
weights.append(5.0) # LHalfFF
weights.append(5.0) # RCorMaxRatio
weights.append(5.0) # RCorTotRatio
weights.append(5.0) # RThirdFF
weights.append(5.0) # RHalfFF"""
return standard_devs, weights
#-------------------------------------------------------------------------------
def makeCoronaryBaseModel():
filelist = glob.glob('*')
if(not 'coronaryModel_base.txt' in filelist):
os.system('cp coronaryModel.txt coronaryModel_base.txt')
#-------------------------------------------------------------------------------
def getSurrogateResistances():
model_name = 'coronaryModel.txt'
model_file = open(model_name, 'r')
resistances = []
for line in model_file:
elements = line.split(',')
if(elements[0] == 'SurrogateRes'):
for i in range(1, len(elements)):
if(not elements[i] == '\n'):
resistances.append(float(elements[i]))
model_file.close()
return resistances
#-------------------------------------------------------------------------------
def getSurrogateCompliance():
model_name = 'coronaryModel.txt'
model_file = open(model_name, 'r')
resistances = []
for line in model_file:
elements = line.split(',')
if(elements[0] == 'Csurr'):
for i in range(1, len(elements)):
if(not elements[i] == '\n'):
resistances.append(float(elements[i]))
model_file.close()
return resistances
#-------------------------------------------------------------------------------
def updateSurrogateCompliance(new_compliances):
base_name = 'coronaryModel_base.txt'
model_name = 'coronaryModel.txt'
base_file = open(base_name, 'r')
model_file = open(model_name, 'w')
for line in base_file:
elements = line.split(',')
if(elements[0] == 'Csurr'):
model_file.write('Csurr,')
for i in range(len(new_compliances)):
model_file.write('{0:.6f},'.format(new_compliances[i]))
model_file.write('\n')
else:
model_file.write(line)
base_file.close()
model_file.close()
#-------------------------------------------------------------------------------
def updateSurrogateResistances(new_resistances):
base_name = 'coronaryModel_base.txt'
model_name = 'coronaryModel.txt'
base_file = open(base_name, 'r')
model_file = open(model_name, 'w')
for line in base_file:
elements = line.split(',')
if(elements[0] == 'SurrogateRes'):
model_file.write('SurrogateRes,')
for i in range(len(new_resistances)):
model_file.write('{0:.6f},'.format(new_resistances[i]))
model_file.write('\n')
else:
model_file.write(line)
base_file.close()
model_file.close()
#-------------------------------------------------------------------------------
def post_process_3D_results(all_data_path):
#Define global variables
global Left_Cor_split_computed
global Aor_Cor_split_computed
total_steps = -1
single_cycle = -1
step_size_3D = -1
solver_file = open(SOLVER_INPUT_PATH, 'r')
for line in solver_file:
line_split = line.split()
if(len(line_split) > 2):
if(line_split[2] == 'Timesteps:'):
total_steps = int(line_split[3])
if(len(line_split) > 1):
if(line_split[1] == 'Step'):
step_size_3D = float(line_split[3])
solver_file.close()
if(total_steps == -1 or step_size_3D == -1):
print('Error: Could not process solver.inp. Please ensure that it is formatted correctly')
exit(1)
model_file = open(CORONARY_MODEL_PATH, 'r')
line = model_file.readline()
elements = line.split(',')
nCOR_l = int(elements[0])
nCOR_r = int(elements[1])
nRCR = int(elements[2])
Tc = float(elements[3])
model_file.close()
nUnknowns = 2*(nCOR_l + nCOR_r) + nRCR + 10
nFaces = nCOR_l + nCOR_r + nRCR
single_cycle = int(round(float(Tc/step_size_3D)/10.0)*10.0)
all_data_file = open(all_data_path, 'r')
line = all_data_file.readline()
elements = line.split()
AllData = np.zeros((total_steps, len(elements)))
count = 0
for el in elements:
AllData[0, count] = float(el)
count = count + 1
outer_count = 1
for line in all_data_file:
elements = line.split()
count = 0
for el in elements:
AllData[outer_count, count] = float(el)
count = count+1
outer_count = outer_count + 1
all_data_file.close()
auxStart = nUnknowns
rcr_st = auxStart + 4
l_cor_st = rcr_st + nRCR
r_cor_st = l_cor_st + nCOR_l
ao_valve = auxStart + nFaces + 12
mit_valve = auxStart + nFaces + 11
tri_valve = auxStart + nFaces + 13
pulm_valve = auxStart + nFaces + 14
# Begin post-processing of 3D results here
# SUM RCR FLUX
temp = 0.0
Q_rcr = 0.0
for loopA in range(nRCR):
temp = np.trapz(AllData[total_steps - single_cycle : total_steps, loopA+rcr_st], x=AllData[total_steps - single_cycle : total_steps, auxStart])
Q_rcr = Q_rcr + temp
# SUM LEFT CORONARY FLUX
Q_lcor = 0.0
for loopA in range(nCOR_l):
temp = np.trapz(AllData[total_steps - single_cycle : total_steps, loopA+l_cor_st], x=AllData[total_steps - single_cycle : total_steps, auxStart])
Q_lcor = Q_lcor + temp
# INTEGRATE LEFT MAIN FLOW
lmain_flow = np.trapz(AllData[total_steps - single_cycle : total_steps, l_cor_st], x=AllData[total_steps - single_cycle : total_steps, auxStart])
# SUM RIGHT CORONARY FLUX
Q_rcor = 0.0
for loopA in range(nCOR_r):
temp = np.trapz(AllData[total_steps - single_cycle : total_steps, loopA+r_cor_st], x=AllData[total_steps - single_cycle : total_steps, auxStart])
Q_rcor = Q_rcor + temp
# INTEGRATE RIGHT MAIN FLOW
rmain_flow = np.trapz(AllData[total_steps - single_cycle : total_steps, r_cor_st], x=AllData[total_steps - single_cycle : total_steps, auxStart])
# FIND THE END OF SYSTOLE
systole_end = int((total_steps - single_cycle)/2) - 1
for i in range(total_steps - single_cycle - 1, total_steps-1):
if(AllData[i, ao_valve] > 0.0 and AllData[i+1, ao_valve] == 0.0):
systole_end = i
break
# FIND THE START OF SYSTOLE
systole_start = total_steps - single_cycle - 1
for i in range(total_steps - single_cycle - 1, total_steps - 1):
if(AllData[i, ao_valve] == 0.0 and AllData[i+1, ao_valve] > 0.0):
systole_start = i
break
ao_open = systole_start
# FIND WHEN THE MITRAL VALVE OPENS
mit_open = total_steps - single_cycle - 1
for i in range(total_steps - single_cycle - 1, total_steps - 1):
if(AllData[i, mit_valve] == 0.0 and AllData[i+1, mit_valve] > 0.0):
mit_open = i
break
mit_half = int( round((mit_open + total_steps)/2.0) )
aor_half = int( round((ao_open + systole_end)/2.0) )
# CALCULATE MAX AND TOTAL CORONARY FLOW DURING SYSTOLE
l_cor_qmax_s = np.amax( AllData[systole_start : systole_end, l_cor_st] )
l_cor_qtot_s = np.trapz(AllData[systole_start : systole_end, l_cor_st], x=AllData[systole_start : systole_end, auxStart])
r_cor_qmax_s = np.amax( AllData[systole_start : systole_end, r_cor_st] )
r_cor_qtot_s = np.trapz(AllData[systole_start : systole_end, r_cor_st], x=AllData[systole_start : systole_end, auxStart])
# CALCULATE MAX AND TOTAL CORONARY FLOW DURING DIASTOLE
l_cor_qmax_d = max( np.amax( AllData[systole_end : total_steps, l_cor_st] ), np.amax( AllData[total_steps - single_cycle - 1 : systole_start, l_cor_st] ) )
l_cor_qtot_d = np.trapz(AllData[systole_end : total_steps, l_cor_st], x=AllData[systole_end : total_steps, auxStart]) + np.trapz(AllData[total_steps - single_cycle - 1 : systole_start, l_cor_st], x=AllData[total_steps - single_cycle - 1 : systole_start, auxStart])
r_cor_qmax_d = max( np.amax( AllData[systole_end : total_steps, r_cor_st] ), np.amax( AllData[total_steps - single_cycle - 1 : systole_start, r_cor_st] ) )
r_cor_qtot_d = np.trapz(AllData[systole_end : total_steps, r_cor_st], x=AllData[systole_end : total_steps, auxStart]) + np.trapz(AllData[total_steps - single_cycle - 1 : systole_start, r_cor_st], x=AllData[total_steps - single_cycle - 1 : systole_start, auxStart])
# CALCULATE RATIOS (DIASTOLE TO SYSTOLE)
l_cor_max_ratio = l_cor_qmax_d/l_cor_qmax_s
l_cor_tot_ratio = l_cor_qtot_d/l_cor_qtot_s
r_cor_max_ratio = r_cor_qmax_d/r_cor_qmax_s
r_cor_tot_ratio = r_cor_qtot_d/r_cor_qtot_s
# CALCULATE THE 1/3 FF AND 1/2 FF
thirdCyc = int( round(single_cycle/3) )
halfCyc = int( round(single_cycle/2) )
if(systole_end+thirdCyc-1 < total_steps):
r_third_FF = np.trapz( AllData[systole_end-1 : systole_end+thirdCyc, r_cor_st], x=AllData[systole_end-1 : systole_end+thirdCyc, auxStart] )/rmain_flow
l_third_FF = np.trapz( AllData[systole_end-1 : systole_end+thirdCyc, l_cor_st], x=AllData[systole_end-1 : systole_end+thirdCyc, auxStart] )/lmain_flow
else:
r_third_FF = 0.0
l_third_FF = 0.0
if(systole_end+halfCyc-1 < total_steps):
r_half_FF = np.trapz( AllData[systole_end-1 : systole_end+halfCyc, r_cor_st], x=AllData[systole_end-1 : systole_end+halfCyc, auxStart] )/rmain_flow
l_half_FF = np.trapz( AllData[systole_end-1 : systole_end+halfCyc, l_cor_st], x=AllData[systole_end-1 : systole_end+halfCyc, auxStart] )/lmain_flow
else:
r_half_FF = 0.0
l_half_FF = 0.0
# COMPUTE OUTPUT QUANTITIES
Qinlet = np.trapz( AllData[total_steps - single_cycle - 1 : total_steps, nUnknowns + nFaces + 4], x=AllData[total_steps - single_cycle - 1 : total_steps, auxStart] )
Aor_Cor_split = ( (Q_lcor + Q_rcor) / (Q_lcor + Q_rcor + Q_rcr) ) * 100.0
Aor_Cor_split_computed=Aor_Cor_split
#Aor_Cor_split = ( (Q_lcor) / (Q_lcor + Q_rcor + Q_rcr) ) * 100.0
Left_Cor_split = ( (Q_lcor) / (Q_lcor + Q_rcor))*100.0
Left_Cor_split_computed=Left_Cor_split
Pao_max = np.amax( AllData[total_steps - single_cycle - 1 : total_steps, 9] )
Pao_min = np.amin( AllData[total_steps - single_cycle - 1 : total_steps, 9] )
Pao_mean = np.mean( AllData[total_steps - single_cycle - 1 : total_steps, 9] )
Ppul_mean = np.mean( AllData[total_steps - single_cycle - 1 : total_steps, 4] )
EF_LV = ( np.amax( AllData[total_steps - single_cycle - 1 : total_steps, 7] ) - np.amin( AllData[total_steps - single_cycle - 1 : total_steps, 7] ) ) / np.amax( AllData[total_steps - single_cycle - 1 : total_steps, 7] )
Prv_Pra = np.amax( AllData[total_steps - single_cycle - 1 : total_steps, auxStart + 7 + nFaces] ) - np.amax( AllData[total_steps - single_cycle - 1 : total_steps, auxStart + 9 + nFaces] )
Ppul_Prv = np.amax( AllData[total_steps - single_cycle - 1 : total_steps, auxStart + 7 + nFaces] ) - np.amax( AllData[total_steps - single_cycle - 1 : total_steps, 4] )
mit_valve_time = float(np.sum( AllData[total_steps - single_cycle - 1 : total_steps, mit_valve] )) / float(single_cycle)
aor_valve_time = float(np.sum( AllData[total_steps - single_cycle - 1 : total_steps, ao_valve] )) / float(single_cycle)
pul_valve_time = float(np.sum( AllData[total_steps - single_cycle - 1 : total_steps, pulm_valve] )) / float(single_cycle)
Qla_ratio = np.amax( AllData[mit_open-1 : mit_half, 6] ) / np.amax( AllData[ mit_half-1 : total_steps, 6] )
Pra_mean = np.mean( AllData[total_steps - single_cycle - 1: total_steps, auxStart + 9 + nFaces] )
if(r_cor_max_ratio < 0 or l_cor_max_ratio < 0 or r_cor_tot_ratio < 0 or l_cor_tot_ratio < 0):
r_cor_max_ratio = 9001.0
l_cor_max_ratio = 9001.0
r_cor_tot_ratio = 9001.0
l_cor_tot_ratio = 9001.0
# COMPUTE CONVERGENCE QUANTITIES
# PRINT RESULT
print("** PaoMin: \t{0:.2f}".format(Pao_min))
print("** PaoMax: \t{0:.2f}".format(Pao_max))
print("** PaoMean: \t{0:.2f}".format(Pao_mean))
print("** Aor_Cor_Split: \t{0:.2f}".format(Aor_Cor_split))
print("** Left_Cor_Split: \t{0:.2f}".format(Left_Cor_split))
print("** Qinlet: \t{0:.2f}".format(abs(Qinlet)))
print("** EF_LV: \t\t{0:.2f}".format(EF_LV))
print("** Qla_ratio: \t{0:.2f}".format(Qla_ratio))
print("** mit_valve: \t{0:.2f}".format(mit_valve_time))
print("** aor_valve: \t{0:.2f}".format(aor_valve_time))
print("** pul_valve: \t{0:.2f}".format(pul_valve_time))
print("** Pra-mean: \t{0:.2f}".format(Pra_mean))
print("** lcor_max: \t{0:.3f}".format(l_cor_max_ratio))
print("** lcor_tot: \t{0:.3f}".format(l_cor_tot_ratio))
print("** lcor_third: \t{0:.3f}".format(l_third_FF))
print("** lcor_half: \t{0:.3f}".format(l_half_FF))
print("** rcor_max: \t{0:.3f}".format(r_cor_max_ratio))
print("** rcor_tot: \t{0:.3f}".format(r_cor_tot_ratio))
print("** rcor_third: \t{0:.3f}".format(r_third_FF))
print("** rcor_half: \t{0:.3f}".format(r_half_FF))
results = [Pao_min, Pao_max, Pao_mean, Aor_Cor_split, abs(Qinlet),
l_cor_max_ratio, l_cor_tot_ratio, l_third_FF, l_half_FF, r_cor_max_ratio,
r_cor_tot_ratio, r_third_FF, r_half_FF]
return results
#-------------------------------------------------------------------------------
def evalCoronaryLL_resistance_only(resistances):
LL = 0.0
for res in resistances:
LL = LL - LOG_SCALE * np.log(res)
updateSurrogateResistances(resistances)
surr_results = runSurrogateSim()
true_results = post_process_3D_results('AllData')
standard_devs, weights = getLL_params()
for i in range(len(surr_results)):
LL = LL + 0.5 * (true_results[i] -
surr_results[i])**2 / (standard_devs[i]**2 * weights[i])
print('LL: {0:.6f}'.format(LL))
return LL
#-------------------------------------------------------------------------------
def evalCoronaryLL_compliance_only(compliance):
LL = 0.0
for com in compliance:
LL = LL - LOG_SCALE * np.log(com)
updateSurrogateCompliance(compliance)
# Need to get data for inflow waveform too!
surr_results = runSurrogateSim()
true_results = post_process_3D_results('AllData')
standard_devs, weights = getLL_params()
for i in range(len(surr_results)):
LL = LL + 0.5 * (true_results[i] - surr_results[i])**2 / (standard_devs[i]**2 * weights[i])
print('LL: {0:.6f}'.format(LL))
return LL
#-------------------------------------------------------------------------------
def optimizeSurrogateResistances():
resistances = np.array(getSurrogateResistances())
for i in range(NUM_RESTARTS):
print('\n **** STARTING NM ITERATION {0}/{1} ***** \n'.format(i, NUM_RESTARTS))
optimized_resistances = minimize(evalCoronaryLL_resistance_only, resistances, method='nelder-mead',
options={'xtol': 1e-8, 'disp': True, 'maxiter': MAX_ITER})
resistances = optimized_resistances.x
print(optimized_resistances.x)
updateSurrogateResistances(optimized_resistances.x)
return optimized_resistances.x
#-------------------------------------------------------------------------------
def optimizeSurrogateCompliance():
surrogate_compliance = np.array(getSurrogateCompliance())
for i in range(NUM_RESTARTS):
print('\n **** STARTING NM ITERATION {0}/{1} ***** \n'.format(i, NUM_RESTARTS))
optimized_compliance = minimize(evalCoronaryLL_compliance_only, surrogate_compliance, method='nelder-mead', options={'xtol':1e-8, 'disp': True, 'maxiter': MAX_ITER})
surrogate_compliance = optimized_compliance.x
print(optimized_compliance.x)
updateSurrogateCompliance(optimized_compliance.x)
return optimized_compliance.x
#-------------------------------------------------------------------------------
def coronaryTuningIteration(count, rigidFlag):
if(rigidFlag and count == 3):
return
if(not rigidFlag and count == 3):
return
if(USE_OPTIMIZATION):
end_name = "NM_fin.txt"
param_name = "optParams.txt"
if(not os.path.isfile(end_name)):
runNM_OPT()
'''# Check for weird Sherlock error where memory writing fails
time.sleep(180)
error_file = glob.glob('*.e*')
sim_start = False
if(len(error_file) != 0 and os.stat(error_file[0]).st_size == 0.0):
sim_start = True
restart_counter = 0
while(not sim_start):
output_file = glob.glob('*.o*')
error_file = glob.glob('*.e*')
if(len(error_file) == 0):
print('** Tuning still in the queue. Waiting...')
time.sleep(600)
elif(os.stat(error_file[0]).st_size != 0.0):
if(restart_counter > 4):
print('Too many retries submitting the job. Aborting.')
sys.exit(0)
print('** Sherlock error writing files. Submitting job again...\n')
command_string = "rm -r " + output_file[0] + " " + error_file[0] + " " + sim_folder
print(command_string)
os.system(command_string)
runNM_OPT()
time.sleep(300)
restart_counter = restart_counter + 1
else:
sim_start = True'''
else: # Using DREAM MCMC
runDREAM_MCMC()
end_name = "bestParams.txt"
param_name = end_name
# Check for weird Sherlock error where memory writing fails
time.sleep(180)
error_file = glob.glob('*.e*')
sim_start = False
if(len(error_file) != 0 and os.stat(error_file[0]).st_size == 0.0):
sim_start = True
restart_counter = 0
while(not sim_start):
output_file = glob.glob('*.o*')
error_file = glob.glob('*.e*')
if(len(error_file) == 0):
print('** Tuning still in the queue. Waiting...')
time.sleep(600)
elif(os.stat(error_file[0]).st_size != 0.0):
if(restart_counter > 4):
print('Too many retries submitting the job. Aborting.')
sys.exit(0)
print('** Sherlock error writing files. Submitting job again...\n')
command_string = "rm -r " + output_file[0] + " " + error_file[0] + " " + sim_folder
print(command_string)
os.system(command_string)
runDREAM_MCMC()
time.sleep(300)
restart_counter = restart_counter + 1
else:
sim_start = True
# Wait for optimization or DREAM to finish
#print('\n** Waiting for tuning round ' + str(count) + ' to finish...\n')
#while(not os.path.isfile(end_name)):
# time.sleep(60);
print('** Tuning complete!\n')
command_string = "rm " + end_name
print(command_string)
os.system(command_string)
print('\n** Transforming parameter file to coronaryParams.txt\n')
command_string = "cp " + param_name + " coronaryParams.txt"
print(command_string)
os.system(command_string)
if(rigidFlag):
folder_name = "Rigid_tuning_" + str(count)
else:
folder_name = 'FSI_tuning_' + str(count)
print("\n** Cleaning up tuning files and saving them in: " + folder_name + '\n')
if(not os.path.isdir(folder_name)):
command_string = "mkdir " + folder_name
print(command_string)
os.system(command_string)
command_string = "mv optParams.txt optValue.txt outputTargets.out " + folder_name
print(command_string)
os.system(command_string)
'''output_file = glob.glob('*.o*')
error_file = glob.glob('*.e*')
command_string = "mv " + output_file[0] + " " + error_file[0] + " " + folder_name
print(command_string)
os.system(command_string)''' ########### MOK Changed for Niagara
# Now, all files should be ready to run a 3D simulation, so just call the flowsolver script!
procs_list = glob.glob('*-procs_*')
if(len(procs_list) == 0):
run3D_SIM()
# NEED FLAG HERE TO DETERMINE STOP OF 3D SIMULATION
total_steps = N_timesteps*N_cycles
procs_list = glob.glob('%d-procs_case'%(int(FLOWSOLVER_NODES*PROCESSORS)))
print('\n** Waiting for simulation job to launch...\n')
#Check to see if the simulation has started by finding the results folder
while(len(procs_list) == 0):
time.sleep(180)
procs_list = glob.glob('%d-procs_case'%(int(FLOWSOLVER_NODES*PROCESSORS)))
print('\n** Waiting for simulation job to launch...\n')
sim_folder = '%d-procs_case'%(int(FLOWSOLVER_NODES*PROCESSORS))
print('\n** Simulation has launched! Waiting for simulation to finish...\n')
#Check to see if the AllData file has been written inside the results folder
AllData_file=glob.glob('%d-procs_case/AllData'%(int(FLOWSOLVER_NODES*PROCESSORS)))
while(len(AllData_file) == 0):
time.sleep(180)
AllData_file = glob.glob('%d-procs_case/AllData'%(int(FLOWSOLVER_NODES*PROCESSORS)))
print('\n** AllData file has been written...\n')
#Check to see if the Simulation is finished
sim_finished = False
while(not sim_finished):
time.sleep(100)
AllData_check = open(sim_folder + '/AllData', 'r')
counter = 0
for line in AllData_check:
counter = counter + 1
print ("------- Finished %d of %d timesteps"%(counter,total_steps))
AllData_check.close()
if(counter == total_steps):
sim_finished = True
print('** Simulation has finished! Moving on to post processing...\n')
# First, copy the 3D results AllData to the current direction
AllData_location = sim_folder + '/AllData'
command_string = 'cp ' + AllData_location + ' .'
print(command_string)
os.system(command_string)
# Make a base copy of coronaryModel
makeCoronaryBaseModel()
# After running 3D sim, check to see if the results match the surrogate
# results. If they do, then break out of this function
if(rigidFlag):
surrogate_resistances = np.array(getSurrogateResistances())
LL = evalCoronaryLL_resistance_only(surrogate_resistances)
if(abs(LL) < 2.0):
print('\n** Rigid tuning has converged! Cleaning up files...\n')
output_file = glob.glob('*.o*')
error_file = glob.glob('*.e*')
command_string = "mv AllData " + output_file[0] + " " + error_file[0] + " " + folder_name
print(command_string)
os.system(command_string)
return
else:
surrogate_compliance = getSurrogateCompliance()
LL = evalCoronaryLL_compliance_only(surrogate_compliance)
if(abs(LL) < 2.0):
print('\n** FSI tuning has converged! Cleaning up files...\n')
output_file = glob.glob('*.o*')
error_file = glob.glob('*.e*')
command_string = "mv AllData " + output_file[0] + " " + error_file[0] + " " + folder_name
print(command_string)
os.system(command_string)
return
# Move 3D simulation files out of the folder before optimizing surrogate
output_file = glob.glob('*.o*')
error_file = glob.glob('*.e*')
command_string = "mv " + output_file[0] + " " + error_file[0] + " " + folder_name
print(command_string)
os.system(command_string)
# Now optimize coronary surrogate resistances
if(rigidFlag):
runSurrogateResOptimization()
end_name = "surr_res_fin.txt"
### Check for weird Sherlock error where memory writing fails
##time.sleep(180)
##error_file = glob.glob('*.e*')
##sim_start = False
##if(len(error_file) != 0 and os.stat(error_file[0]).st_size == 0.0):
## sim_start = True
##restart_counter = 0
##while(not sim_start):
## output_file = glob.glob('*.o*')
## error_file = glob.glob('*.e*')
## if(len(error_file) == 0):
## print('** Simulation still in the queue. Waiting...')
## time.sleep(600)
## elif(os.stat(error_file[0]).st_size != 0.0):
## if(restart_counter > 4):
## print('Too many retries submitting the job. Aborting.')
## sys.exit(0)
## print('** Sherlock error writing files. Submitting job again...\n')
## command_string = "rm -r " + output_file[0] + " " + error_file[0] + " " + sim_folder
## print(command_string)
## os.system(command_string)
## runSurrogateResOptimization()
## time.sleep(300)
## restart_counter = restart_counter + 1
## else:
## sim_start = True
else:
runSurrogateComplianceOptimization()
end_name = "surr_com_fin.txt"
### Check for weird Sherlock error where memory writing fails
##time.sleep(180)
##error_file = glob.glob('*.e*')
##sim_start = False
##if(len(error_file) != 0 and os.stat(error_file[0]).st_size == 0.0):
## sim_start = True
##restart_counter = 0
##while(not sim_start):
## output_file = glob.glob('*.o*')
## error_file = glob.glob('*.e*')
## if(len(error_file) == 0):
## print('** Simulation still in the queue. Waiting...')
## time.sleep(600)
## elif(os.stat(error_file[0]).st_size != 0.0):
## if(restart_counter > 4):
## print('Too many retries submitting the job. Aborting.')
## sys.exit(0)
## print('** Sherlock error writing files. Submitting job again...\n')
## command_string = "rm -r " + output_file[0] + " " + error_file[0] + " " + sim_folder
## print(command_string)
## os.system(command_string)
## runSurrogateComplianceOptimization()
## time.sleep(300)
## restart_counter = restart_counter + 1
## else:
## sim_start = True
### Wait for optimization or DREAM to finish
##print('\n** Waiting for surrogate optimization round ' + str(count) + ' to finish...\n')
##while(not os.path.isfile(end_name)):
## time.sleep(60);
##print('** Surrogate optimization complete!\n')
##command_string = "rm " + end_name
##print(command_string)
##os.system(command_string)
# Clean up files and get ready for the next iteration
if(count < 2):
print('\n** Moving simulation files to ' + folder_name + '\n')
command_string = 'mv ' + sim_folder + ' ' + folder_name
print(command_string)
os.system(command_string)
##output_file = glob.glob('*.o*')
##error_file = glob.glob('*.e*')
##command_string = "mv AllData " + output_file[0] + " " + error_file[0] + " " + folder_name
command_string = "mv AllData " + folder_name
print(command_string)
os.system(command_string)
# Recursively call this function again until rigid tuning satisfied
coronaryTuningIteration(count+1, rigidFlag)
#-------------------------------------------------------------------------------
def rigidPresolve():
input_path = MESH_SURFACES_PATH
if(input_path[-1:] is not '/'):
input_path = input_path + '/'
if(input_path[-1:] is not '*'):
input_path = input_path + '*'
Tc = 60.0/heart_rate
filelist_raw = glob.glob(input_path)
filelist_raw.sort()
filelist = []
for trial in filelist_raw: