Cardiovascular.cpp 109 KB
Newer Older
Aaron Bray's avatar
Aaron Bray committed
1
2
/* Distributed under the Apache License, Version 2.0.
   See accompanying NOTICE file for details.*/
Aaron Bray's avatar
Aaron Bray committed
3
4

#include "stdafx.h"
5
6
7
8
9
#include "physiology/Cardiovascular.h"
#include "physiology/Saturation.h"
#include "controller/Circuits.h"
#include "controller/Compartments.h"
#include "controller/Substances.h"
10
11
#include "PulseConfiguration.h"
// Conditions
12
#include "engine/SEConditionManager.h"
13
14
15
16
17
#include "patient/conditions/SEChronicAnemia.h"
#include "patient/conditions/SEChronicHeartFailure.h"
#include "patient/conditions/SEChronicPericardialEffusion.h"
#include "patient/conditions/SEChronicRenalStenosis.h"
// Actions
18
19
#include "engine/SEActionManager.h"
#include "engine/SEPatientActionCollection.h"
20
21
22
23
24
25
26
27
28
29
30
#include "patient/actions/SEBrainInjury.h"
#include "patient/actions/SEChestCompressionForce.h"
#include "patient/actions/SEChestCompressionForceScale.h"
#include "patient/actions/SEHemorrhage.h"
#include "patient/actions/SEPericardialEffusion.h"
// Dependent Systems
#include "system/physiology/SEBloodChemistrySystem.h"
#include "system/physiology/SEDrugSystem.h"
#include "system/physiology/SEEnergySystem.h"
#include "system/physiology/SENervousSystem.h"
// CDM
Aaron Bray's avatar
Aaron Bray committed
31
#include "patient/SEPatient.h"
32
#include "engine/SEEventManager.h"
33
34
#include "substance/SESubstance.h"
#include "substance/SESubstanceTransport.h"
Aaron Bray's avatar
Aaron Bray committed
35
#include "circuit/fluid/SEFluidCircuit.h"
36
#include "circuit/fluid/SEFluidCircuitCalculator.h"
Aaron Bray's avatar
Aaron Bray committed
37
#include "compartment/fluid/SELiquidCompartmentGraph.h"
38
#include "compartment/fluid/SEGasCompartment.h"
Aaron Bray's avatar
Aaron Bray committed
39
40
41
42
43
44
#include "compartment/substances/SELiquidSubstanceQuantity.h"
#include "properties/SEScalar0To1.h"
#include "properties/SEScalarPressure.h"
#include "properties/SEScalarFrequency.h"
#include "properties/SEScalarMass.h"
#include "properties/SEScalarMassPerVolume.h"
45
#include "properties/SEScalar0To1.h"
Aaron Bray's avatar
Aaron Bray committed
46
47
48
49
#include "properties/SEScalarForce.h"
#include "properties/SEScalarElectricPotential.h"
#include "properties/SEScalarTime.h"
#include "properties/SEScalarPressurePerVolume.h"
50
#include "properties/SEScalarPressureTimePerVolume.h"
Aaron Bray's avatar
Aaron Bray committed
51
52
53
#include "properties/SEScalarPower.h"
#include "properties/SEScalarTemperature.h"
#include "properties/SEScalarAmountPerVolume.h"
54
55
56
#include "properties/SEScalarVolume.h"
#include "properties/SEScalarVolumePerTime.h"
#include "properties/SEScalarVolumePerPressure.h"
Aaron Bray's avatar
Aaron Bray committed
57
58
59
#include "properties/SEScalarVolumePerTimeArea.h"
#include "properties/SEScalarArea.h"
#include "properties/SEScalarPressureTimePerVolumeArea.h"
60
#include "properties/SERunningAverage.h"
61
#include "utils/DataTrack.h"
Aaron Bray's avatar
Aaron Bray committed
62

63
Cardiovascular::Cardiovascular(PulseController& data) : SECardiovascularSystem(data.GetLogger()), m_data(data)
Aaron Bray's avatar
Aaron Bray committed
64
65
{
  m_TuningFile = "";
66
  m_transporter = new SELiquidTransporter(VolumePerTimeUnit::mL_Per_s, VolumeUnit::mL, MassUnit::ug, MassPerVolumeUnit::ug_Per_mL, data.GetLogger());
67
  m_circuitCalculator = new SEFluidCircuitCalculator(VolumePerPressureUnit::mL_Per_mmHg, VolumePerTimeUnit::mL_Per_s, PressureTimeSquaredPerVolumeUnit::mmHg_s2_Per_mL, PressureUnit::mmHg, VolumeUnit::mL, PressureTimePerVolumeUnit::mmHg_s_Per_mL, data.GetLogger());
68
69
70
71
72
73
74
75
  m_CardiacCycleArterialPressure_mmHg = new SERunningAverage();
  m_CardiacCycleArterialCO2PartialPressure_mmHg = new SERunningAverage();
  m_CardiacCyclePulmonaryCapillariesWedgePressure_mmHg = new SERunningAverage();
  m_CardiacCyclePulmonaryCapillariesFlow_mL_Per_s = new SERunningAverage();
  m_CardiacCyclePulmonaryShuntFlow_mL_Per_s = new SERunningAverage();
  m_CardiacCyclePulmonaryArteryPressure_mmHg = new SERunningAverage();
  m_CardiacCycleCentralVenousPressure_mmHg = new SERunningAverage();
  m_CardiacCycleSkinFlow_mL_Per_s = new SERunningAverage();
Aaron Bray's avatar
Aaron Bray committed
76
  Clear();
Aaron Bray's avatar
Aaron Bray committed
77
78
79
80
81
}

Cardiovascular::~Cardiovascular()
{
  Clear();
82
83
84
85
86
87
88
89
90
91
  delete m_transporter;
  delete m_circuitCalculator;
  delete m_CardiacCycleArterialPressure_mmHg;
  delete m_CardiacCycleArterialCO2PartialPressure_mmHg;
  delete m_CardiacCyclePulmonaryCapillariesWedgePressure_mmHg;
  delete m_CardiacCyclePulmonaryCapillariesFlow_mL_Per_s;
  delete m_CardiacCyclePulmonaryShuntFlow_mL_Per_s;
  delete m_CardiacCyclePulmonaryArteryPressure_mmHg;
  delete m_CardiacCycleCentralVenousPressure_mmHg;
  delete m_CardiacCycleSkinFlow_mL_Per_s;
Aaron Bray's avatar
Aaron Bray committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
}

void Cardiovascular::Clear()
{
  SECardiovascularSystem::Clear();

  m_CirculatoryCircuit = nullptr;
  m_CirculatoryGraph = nullptr;

  m_AortaCompliance = nullptr;
  m_AortaResistance = nullptr;
  m_VenaCavaCompliance = nullptr;
  m_RightHeartResistance = nullptr;

  m_MainPulmonaryArteries = nullptr;
  m_LeftHeart2 = nullptr;

  m_LeftPulmonaryArteriesToVeins = nullptr;
  m_LeftPulmonaryArteriesToCapillaries = nullptr;
  m_RightPulmonaryArteriesToVeins = nullptr;
  m_RightPulmonaryArteriesToCapillaries = nullptr;

114
  m_InternalHemorrhageToAorta = nullptr;
Aaron Bray's avatar
Aaron Bray committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  m_pAortaToBone = nullptr;
  m_pAortaToBrain = nullptr;
  m_pBrainToVenaCava = nullptr;
  m_pAortaToLiver = nullptr;
  m_pAortaToLeftKidney = nullptr;
  m_pAortaToLargeIntestine = nullptr;
  m_pAortaToMuscle = nullptr;
  m_pMuscleToVenaCava = nullptr;
  m_pAortaToMyocardium = nullptr;
  m_pMyocardiumToVenaCava = nullptr;
  m_pAortaToRightKidney = nullptr;
  m_pAortaToSkin = nullptr;
  m_pAortaToSmallIntestine = nullptr;
  m_pAortaToSplanchnic = nullptr;
  m_pAortaToSpleen = nullptr;

131
132
133
  m_pGndToAbdominalCavity = nullptr;
  m_pAbdominalCavityToGnd = nullptr;

Aaron Bray's avatar
Aaron Bray committed
134
135
136
137
138
139
140
141
142
143
144
145
146
  m_pGndToPericardium = nullptr;
  m_pPericardiumToGnd = nullptr;
  m_pRightHeartToGnd = nullptr;
  m_pRightHeart = nullptr;
  m_pLeftHeartToGnd = nullptr;
  m_pLeftHeart = nullptr;
  m_LeftHeartToAorta = nullptr;

  m_leftRenalArteryPath = nullptr;
  m_rightRenalArteryPath = nullptr;

  m_Aorta = nullptr;
  m_AortaCO2 = nullptr;
147
  m_Groundcmpt = nullptr;
Aaron Bray's avatar
Aaron Bray committed
148
149
150
151
152
153
154
155
156
157
  m_LeftHeart = nullptr;
  m_LeftPulmonaryCapillaries = nullptr;
  m_LeftPulmonaryArteries = nullptr;
  m_LeftPulmonaryVeins = nullptr;
  m_Pericardium = nullptr;
  m_RightHeart = nullptr;
  m_RightPulmonaryCapillaries = nullptr;
  m_RightPulmonaryArteries = nullptr;
  m_RightPulmonaryVeins = nullptr;
  m_VenaCava = nullptr;
158
  m_AbdominalCavity = nullptr;
Aaron Bray's avatar
Aaron Bray committed
159

160
161
162
  m_leftPleuralCavity = nullptr;
  m_rightPleuralCavity = nullptr;

163
164
165
166
167
168
169
170
  m_CardiacCycleArterialPressure_mmHg->Clear();
  m_CardiacCycleArterialCO2PartialPressure_mmHg->Clear();
  m_CardiacCyclePulmonaryCapillariesWedgePressure_mmHg->Clear();
  m_CardiacCyclePulmonaryCapillariesFlow_mL_Per_s->Clear();
  m_CardiacCyclePulmonaryShuntFlow_mL_Per_s->Clear();
  m_CardiacCyclePulmonaryArteryPressure_mmHg->Clear();
  m_CardiacCycleCentralVenousPressure_mmHg->Clear();
  m_CardiacCycleSkinFlow_mL_Per_s->Clear();
171
172
173
174
175
176

  m_HemorrhageLinks.clear();
  m_HemorrhagePaths.clear();

  m_InternalHemorrhageLinks.clear();
  m_InternalHemorrhagePaths.clear();
Aaron Bray's avatar
Aaron Bray committed
177
178
179
180
181
182
183
184
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Initializes system properties.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::Initialize()
{
185
  PulseSystem::Initialize();
Aaron Bray's avatar
Aaron Bray committed
186

187
  m_HeartRhythm = eHeartRhythm::NormalSinus;
Aaron Bray's avatar
Aaron Bray committed
188
189
190
191
192
193
194
195
196
197

  m_StartSystole = true;
  m_HeartFlowDetected = false;
  m_CardiacCyclePeriod_s = 0.8; //seconds per beat
  m_CardiacCycleDiastolicVolume_mL = 0.0;
  m_CardiacCycleStrokeVolume_mL = 0;
  m_CurrentCardiacCycleDuration_s = 0;

  //Heart Elastance Parameters
  m_LeftHeartElastance_mmHg_Per_mL = 0.0;
198
199
  m_LeftHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetLeftHeartElastanceMaximum(PressurePerVolumeUnit::mmHg_Per_mL);
  m_LeftHeartElastanceMin_mmHg_Per_mL = m_data.GetConfiguration().GetLeftHeartElastanceMinimum(PressurePerVolumeUnit::mmHg_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
200
201
  m_LeftHeartElastanceModifier = 1.0; //Utilized for reducing the maximum elastance to represent left ventricular systolic dysfunction
  m_RightHeartElastance_mmHg_Per_mL = 0.0;
202
203
  m_RightHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetRightHeartElastanceMaximum(PressurePerVolumeUnit::mmHg_Per_mL);
  m_RightHeartElastanceMin_mmHg_Per_mL = m_data.GetConfiguration().GetRightHeartElastanceMinimum(PressurePerVolumeUnit::mmHg_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
204
205
206
207
208
209
210
211
  
  // CPR and Cardiac Arrest control
  m_EnterCardiacArrest = false;
  m_CompressionTime_s = 0.0;
  m_CompressionRatio = 0.0;
  m_CompressionPeriod_s = 0.0;

  //Initialize system data based on patient file inputs
212
213
214
  GetBloodVolume().Set(m_data.GetCurrentPatient().GetBloodVolumeBaseline());
  m_CardiacCycleAortaPressureHigh_mmHg = m_data.GetCurrentPatient().GetSystolicArterialPressureBaseline(PressureUnit::mmHg);
  m_CardiacCycleAortaPressureLow_mmHg = m_data.GetCurrentPatient().GetDiastolicArterialPressureBaseline(PressureUnit::mmHg);
Aaron Bray's avatar
Aaron Bray committed
215
  GetMeanArterialPressure().SetValue((2. / 3.*m_CardiacCycleAortaPressureLow_mmHg) + (1. / 3.*m_CardiacCycleAortaPressureHigh_mmHg), PressureUnit::mmHg);
216
  m_CardiacCycleArterialPressure_mmHg->Sample(GetMeanArterialPressure().GetValue(PressureUnit::mmHg));
Aaron Bray's avatar
Aaron Bray committed
217
218
219
  m_CardiacCyclePulmonaryArteryPressureHigh_mmHg = 26;
  m_CardiacCyclePulmonaryArteryPressureLow_mmHg = 9;
  GetPulmonaryMeanArterialPressure().SetValue(15, PressureUnit::mmHg);
220
  GetHeartRate().Set(m_data.GetCurrentPatient().GetHeartRateBaseline());
Aaron Bray's avatar
Aaron Bray committed
221
222
223
224
  RecordAndResetCardiacCycle();  
  
  // Set system data based on physiology norms
  GetMeanCentralVenousPressure().SetValue(5.0, PressureUnit::mmHg);
225
  m_CardiacCycleArterialCO2PartialPressure_mmHg->Sample(60.0);
Aaron Bray's avatar
Aaron Bray committed
226
227
228
229
230
231
232
233
234
235
236
237
238
239
  m_LastCardiacCycleMeanArterialCO2PartialPressure_mmHg = 60.0;
  GetMeanArterialCarbonDioxidePartialPressure().SetValue(60, PressureUnit::mmHg);
  GetMeanArterialCarbonDioxidePartialPressureDelta().SetValue(0.0, PressureUnit::mmHg);
  GetPulmonaryCapillariesWedgePressure().SetValue(0, PressureUnit::mmHg);
  GetPulmonaryMeanArterialPressure().SetValue(90, PressureUnit::mmHg);
  GetPulmonaryArterialPressure().SetValue(90, PressureUnit::mmHg);
  GetPulmonaryMeanCapillaryFlow().SetValue(0, VolumePerTimeUnit::mL_Per_s);
  GetPulmonaryMeanShuntFlow().SetValue(0, VolumePerTimeUnit::mL_Per_s);

  GetMeanSkinFlow().SetValue(0, VolumePerTimeUnit::mL_Per_s);
  GetCardiacOutput().SetValue(5600, VolumePerTimeUnit::mL_Per_min);
  GetHeartStrokeVolume().SetValue(78, VolumeUnit::mL);
  GetHeartEjectionFraction().SetValue(0.55);
  GetCardiacIndex().SetValue(3.0, VolumePerTimeAreaUnit::mL_Per_min_m2);
240
  GetPulmonaryVascularResistance().SetValue(0.14, PressureTimePerVolumeUnit::mmHg_min_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
241
242
243
244
245
246
247
  GetPulmonaryVascularResistanceIndex().SetValue(0.082, PressureTimePerVolumeAreaUnit::mmHg_min_Per_mL_m2);

  m_CurrentCardiacCycleTime_s = 0.0;

  CalculateHeartElastance();

  double systemicVascularResistance_mmHg_s_Per_mL = (GetMeanArterialPressure().GetValue(PressureUnit::mmHg) - GetMeanCentralVenousPressure().GetValue(PressureUnit::mmHg)) / GetCardiacOutput().GetValue(VolumePerTimeUnit::mL_Per_s);
248
  GetSystemicVascularResistance().SetValue(systemicVascularResistance_mmHg_s_Per_mL, PressureTimePerVolumeUnit::mmHg_s_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
249
250
251
  // This is not part of stabilization due to not knowing when we hit the patient parameters with a circuit configuration
  TuneCircuit();
  systemicVascularResistance_mmHg_s_Per_mL = (GetMeanArterialPressure().GetValue(PressureUnit::mmHg) - GetMeanCentralVenousPressure().GetValue(PressureUnit::mmHg)) / GetCardiacOutput().GetValue(VolumePerTimeUnit::mL_Per_s);
252
253
254
  GetSystemicVascularResistance().SetValue(systemicVascularResistance_mmHg_s_Per_mL, PressureTimePerVolumeUnit::mmHg_s_Per_mL);
  m_LeftHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetLeftHeartElastanceMaximum(PressurePerVolumeUnit::mmHg_Per_mL);
  m_RightHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetRightHeartElastanceMaximum(PressurePerVolumeUnit::mmHg_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Initializes parameters for Cardiovascular Class
///
///  \details
///   Initializes member variables and system level values on the common data model.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::SetUp()
{
  m_dT_s = m_data.GetTimeStep().GetValue(TimeUnit::s);
  m_minIndividialSystemicResistance__mmHg_s_Per_mL = 0.1;

  //Circuits
  m_CirculatoryCircuit = &m_data.GetCircuits().GetActiveCardiovascularCircuit();
  m_CirculatoryGraph = &m_data.GetCompartments().GetActiveCardiovascularGraph();
272
  //Compartments
Aaron Bray's avatar
Aaron Bray committed
273
  m_Aorta = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::Aorta);
Aaron Bray's avatar
Aaron Bray committed
274
  m_AortaCO2 = m_Aorta->GetSubstanceQuantity(m_data.GetSubstances().GetCO2());
Aaron Bray's avatar
Aaron Bray committed
275
  m_Brain = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::Brain);
276
  m_Groundcmpt = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::Ground);
Aaron Bray's avatar
Aaron Bray committed
277
278
279
280
281
282
283
284
285
286
  m_LeftPulmonaryArteries = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::LeftPulmonaryArteries);
  m_RightPulmonaryArteries = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::RightPulmonaryArteries);
  m_LeftPulmonaryVeins = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::LeftPulmonaryVeins);
  m_RightPulmonaryVeins = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::RightPulmonaryVeins);
  m_LeftPulmonaryCapillaries = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::LeftPulmonaryCapillaries);
  m_RightPulmonaryCapillaries = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::RightPulmonaryCapillaries);
  m_VenaCava = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::VenaCava);
  m_Pericardium = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::Pericardium);
  m_LeftHeart = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::LeftHeart);
  m_RightHeart = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::RightHeart);
287
  m_AbdominalCavity = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::AbdominalCavity);
288
289
290
  //Respiratory Compartments
  m_leftPleuralCavity = m_data.GetCompartments().GetGasCompartment(pulse::PulmonaryCompartment::LeftPleuralCavity);
  m_rightPleuralCavity = m_data.GetCompartments().GetGasCompartment(pulse::PulmonaryCompartment::RightPleuralCavity);
Aaron Bray's avatar
Aaron Bray committed
291
  //Nodes
Aaron Bray's avatar
Aaron Bray committed
292
293
  m_MainPulmonaryArteries = m_CirculatoryCircuit->GetNode(pulse::CardiovascularNode::MainPulmonaryArteries);
  m_LeftHeart2 = m_CirculatoryCircuit->GetNode(pulse::CardiovascularNode::LeftHeart2);
294
  m_Ground = m_CirculatoryCircuit->GetNode(pulse::CardiovascularNode::Ground);
Aaron Bray's avatar
Aaron Bray committed
295
  //Paths
Aaron Bray's avatar
Aaron Bray committed
296
297
298
299
300
  m_LeftPulmonaryArteriesToVeins = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::LeftPulmonaryArteriesToLeftPulmonaryVeins);
  m_LeftPulmonaryArteriesToCapillaries = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::LeftPulmonaryArteriesToLeftPulmonaryCapillaries);
  m_RightPulmonaryArteriesToVeins = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::RightPulmonaryArteriesToRightPulmonaryVeins);
  m_RightPulmonaryArteriesToCapillaries = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::RightPulmonaryArteriesToRightPulmonaryCapillaries);

301
  m_InternalHemorrhageToAorta = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::GroundToAorta4);
Aaron Bray's avatar
Aaron Bray committed
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
  m_pAortaToBone = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToBone1);
  m_pAortaToBrain = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToBrain1);
  m_pBrainToVenaCava = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Brain1ToBrain2);
  m_pAortaToLiver = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToLiver1);
  m_pAortaToLeftKidney = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToLeftKidney1);
  m_pAortaToLargeIntestine = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToLargeIntestine);
  m_pAortaToMuscle = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToMuscle1);
  m_pMuscleToVenaCava = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Muscle1ToMuscle2);
  m_pAortaToMyocardium = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToMyocardium1);
  m_pMyocardiumToVenaCava = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Myocardium1ToMyocardium2);
  m_pAortaToRightKidney = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToRightKidney1);
  m_pAortaToSkin = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToSkin1);
  m_pAortaToSmallIntestine = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToSmallIntestine);
  m_pAortaToSplanchnic = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToSplanchnic);
  m_pAortaToSpleen = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToSpleen);

  m_pBrainResistanceDownstream = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Brain1ToBrain2);
  m_pBrainResistanceUpstream = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToBrain1);

321
322
323
  m_pGndToAbdominalCavity = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::GroundToAbdominalCavity1);
  m_pAbdominalCavityToGnd = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::AbdominalCavity1ToGround);

Aaron Bray's avatar
Aaron Bray committed
324
325
326
327
328
329
330
  m_pGndToPericardium = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::GroundToPericardium1);
  m_pPericardiumToGnd = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Pericardium1ToGround);
  m_pRightHeartToGnd = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::RightHeart3ToGround);
  m_pRightHeart = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::RightHeart1ToRightHeart3);
  m_pLeftHeartToGnd = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::LeftHeart3ToGround);
  m_pLeftHeart = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::LeftHeart1ToLeftHeart3);
  m_LeftHeartToAorta = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::LeftHeart1ToAorta2);
Aaron Bray's avatar
Aaron Bray committed
331
332

  /// \todo We are assuming that the complex renal system is connected. Make it agnostic.
Aaron Bray's avatar
Aaron Bray committed
333
334
  m_leftRenalArteryPath = m_CirculatoryCircuit->GetPath(pulse::RenalPath::LeftRenalArteryToAfferentArteriole);
  m_rightRenalArteryPath = m_CirculatoryCircuit->GetPath(pulse::RenalPath::RightRenalArteryToAfferentArteriole);
Aaron Bray's avatar
Aaron Bray committed
335
336
337
338

  m_systemicResistancePaths.clear();
  m_systemicCompliancePaths.clear();
  std::vector<SEFluidCircuitNode*> venousNodes;
Aaron Bray's avatar
Aaron Bray committed
339
  SEFluidCircuitNode* aorta = m_CirculatoryCircuit->GetNode(pulse::CardiovascularNode::Aorta1);
Aaron Bray's avatar
Aaron Bray committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
  for (SEFluidCircuitPath* path : m_CirculatoryCircuit->GetPaths())
  {
    if (&path->GetSourceNode() == aorta && path->HasResistanceBaseline())
    {
      m_systemicResistancePaths.push_back(path);
      venousNodes.push_back(&path->GetTargetNode());
    }
  }
  for (SEFluidCircuitPath* path : m_CirculatoryCircuit->GetPaths())
  {
    for (SEFluidCircuitNode* node : venousNodes)
    {
      if (&path->GetSourceNode() == node)
      {
        if (path->HasResistanceBaseline())
          m_systemicResistancePaths.push_back(path);
        if (path->HasComplianceBaseline())
          m_systemicCompliancePaths.push_back(path);
        break;
      }
    }
  }
  // Add the portal vein!
Aaron Bray's avatar
Aaron Bray committed
363
  SEFluidCircuitPath* p = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::PortalVeinToLiver1);
Aaron Bray's avatar
Aaron Bray committed
364
365
  if (!Contains(m_systemicResistancePaths, (*p)))
    m_systemicResistancePaths.push_back(p);
366
  m_AortaCompliance = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToAorta4);
Aaron Bray's avatar
Aaron Bray committed
367
368
369
  m_AortaResistance = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta3ToAorta1);
  m_VenaCavaCompliance = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::VenaCavaToGround);
  m_RightHeartResistance = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::VenaCavaToRightHeart2);
Aaron Bray's avatar
Aaron Bray committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Cardiovascular system at steady state
///
/// \details
/// Initializes Cardiovascular conditions if any are present.
///  <UL>
///   <LI>Anemia</LI>
///   <LI>Renal Stenosis</LI>
///   <LI>Heart Failure</LI>
///   <LI>Pericardial Effusion</LI>
///  </UL>
///
//--------------------------------------------------------------------------------------------------
void Cardiovascular::AtSteadyState()
{
388
389
390
391
  m_data.GetCurrentPatient().GetHeartRateBaseline().Set(GetHeartRate());
  m_data.GetCurrentPatient().GetDiastolicArterialPressureBaseline().Set(GetDiastolicArterialPressure());
  m_data.GetCurrentPatient().GetSystolicArterialPressureBaseline().Set(GetSystolicArterialPressure());
  m_data.GetCurrentPatient().GetMeanArterialPressureBaseline().Set(GetMeanArterialPressure());
Aaron Bray's avatar
Aaron Bray committed
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

  std::string typeString = "Initial Stabilization Homeostasis: ";
  if (m_data.GetState() == EngineState::AtSecondaryStableState)
    typeString = "Secondary Stabilization Homeostasis: ";

  m_ss << typeString << "Patient heart rate = " << GetHeartRate();
  Info(m_ss);
  m_ss << typeString << "Patient diastolic arterial pressure = " << GetDiastolicArterialPressure();
  Info(m_ss);
  m_ss << typeString << "Patient systolic arterial pressure = " << GetSystolicArterialPressure();
  Info(m_ss);
  m_ss << typeString << "Patient mean arterial pressure = " << GetMeanArterialPressure();
  Info(m_ss);

  if (m_data.GetState() == EngineState::AtInitialStableState)
  {// At Resting State, apply conditions if we have them
    if (m_data.GetConditions().HasChronicAnemia())
      ChronicAnemia();
    if (m_data.GetConditions().HasChronicRenalStenosis())
      ChronicRenalStenosis();
    if (m_data.GetConditions().HasChronicVentricularSystolicDysfunction())
      ChronicHeartFailure();
    if (m_data.GetConditions().HasChronicPericardialEffusion())
      ChronicPericardialEffusion();
  }

418
419
  m_LeftHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetLeftHeartElastanceMaximum(PressurePerVolumeUnit::mmHg_Per_mL);
  m_RightHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetRightHeartElastanceMaximum(PressurePerVolumeUnit::mmHg_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Establishes the anemia condition by removing hemoglobin and reducing blood viscosity (simulated by vascular resistance reduction).
///
/// \details
/// We are modeling iron deficiency anemia as a chronic reduction in hemoglobin in the blood as well as
/// a reduction in the cardiovascular resistances to lower the systemic vascular resistance that is
/// seen with the reduced viscosity. The oxygen carrying capacity of the blood is reduced due to the
/// decrease in hemoglobin content.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::ChronicAnemia()
{
  SEChronicAnemia* anemia = m_data.GetConditions().GetChronicAnemia();
  double rf = anemia->GetReductionFactor().GetValue();

  // Maximum 30% reduction
  if (rf > 0.3)
  {
    /// \error if too much hemoglobin is removed, we will no longer meet validation, so set to maximum amount that can be removed.
441
    Error("Cannot remove more than 30% of hemoglobin in anemia in the Pulse Engine. Setting value to 30% and continuing.", "Cardiovascular::Anemia");
Aaron Bray's avatar
Aaron Bray committed
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
    rf = 0.3;
  }
  // Empirical resistance modification
  double viscousModifier = 1.0 - (0.15*rf);

  std::vector<SESubstance*> hemoglobinSubs;
  hemoglobinSubs.push_back(&m_data.GetSubstances().GetHb());
  hemoglobinSubs.push_back(&m_data.GetSubstances().GetHbO2());
  hemoglobinSubs.push_back(&m_data.GetSubstances().GetHbCO2());
  hemoglobinSubs.push_back(&m_data.GetSubstances().GetHbO2CO2());

  double newMass_g;
  SELiquidSubstanceQuantity* subQ;
  // Reduce all hemoglobin mass in all compartments
  for (SELiquidCompartment* cmpt : m_data.GetCompartments().GetVascularLeafCompartments())
  {
    if (!cmpt->HasVolume())
      continue;

    for (SESubstance* subst : hemoglobinSubs)
    {
      subQ = cmpt->GetSubstanceQuantity(*subst);
      newMass_g = subQ->GetMass(MassUnit::g)*(1 - rf);
      subQ->GetMass().SetValue(newMass_g, MassUnit::g);
      subQ->Balance(BalanceLiquidBy::Mass);
    }
  }

  // Only the cardiovascular paths are adjusted. This is obviously an inconsistency, but 
  // other vascular paths may contain non-blood fluids for which viscosity is unaffected by
  // anemia. This gets us close enough.
  for (SEFluidCircuitPath* path : m_data.GetCircuits().GetCardiovascularCircuit().GetPaths())
  {
    if (path->HasResistanceBaseline())
    {
477
    path->GetResistanceBaseline().SetValue(path->GetResistanceBaseline(PressureTimePerVolumeUnit::mmHg_s_Per_mL)*viscousModifier, PressureTimePerVolumeUnit::mmHg_s_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
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
    }   
  }
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Establishes the chronic heart failure condition.
///
/// \details
/// Heart failure is a chronic condition that is modeled by a permanent
/// reduction in the left heart contractility. The user may scale the severity of this action
/// with a fraction from 0 to 1, with 0 being non-existent to 1 being severe heart failure.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::ChronicHeartFailure()
{
  //Decrease left heart contractility
  m_LeftHeartElastanceModifier = 0.27;
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Establishes the pericardial effusion condition.
///
/// \details
/// Pericardial effusion can be either chronic (slow) or acute (fast).
/// Chronic effusion will eventually lead to tamponade, acute effusion leads
/// immediately to tamponade and imminent death. The chronic effusion parameters 
505
/// are set in the Pulse engine so that life-threatening tamponade will occur 
Aaron Bray's avatar
Aaron Bray committed
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
///  in about 30 minutes after the insult.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::ChronicPericardialEffusion()
{
  double deltaVolume_mL = m_data.GetConditions().GetChronicPericardialEffusion()->GetAccumulatedVolume().GetValue(VolumeUnit::mL);
  if (deltaVolume_mL > 1000.0)
  {
    Error("Cannot specify volume accumulation greater than 1000 mL. Accumulated volume is now set at 1000 mL.");
    /// \error Cannot specify volume accumulation greater than 1000 mL. Accumulated volume is now set at 1000 mL.
    deltaVolume_mL = 1000.0;
  }
  else if (deltaVolume_mL < 0.0)
  {
    Error("Cannot specify volume accumulation less than 0 mL. Accumulated volume is now set at 0 mL.");
    /// \error Cannot specify volume accumulation less than 0 mL. Accumulated volume is now set at 0 mL.
    deltaVolume_mL = 0.0;
  }

  //Just throw this all on at once
  //Only do this for a single time-step!
  m_pGndToPericardium->GetNextFlowSource().SetValue(deltaVolume_mL / m_dT_s, VolumePerTimeUnit::mL_Per_s);
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Establishes the renal stenosis condition in one or both of the renal arteries.
///
/// \details
/// Stenosed renal arteries are slightly occluded, which increases the resistance from the aorta to the kidney.
/// This is implemented as a condition, which specifies what percent of the artery is occluded and which artery
/// or arteries are being affected. 
//--------------------------------------------------------------------------------------------------
void Cardiovascular::ChronicRenalStenosis()
{
  ///\todo move this to CV
  double LeftOcclusionFraction = m_data.GetConditions().GetChronicRenalStenosis()->GetLeftKidneySeverity().GetValue();
  double RightOcclusionFraction = m_data.GetConditions().GetChronicRenalStenosis()->GetRightKidneySeverity().GetValue();

  if (LeftOcclusionFraction < 0.0)
  {
    /// \error Cannot specify left occlusion fraction less than zero
    Error("Cannot specify left occlusion fraction less than zero. Renal resistances remain unchanged."); //Specify resistance is the same in error
    return;
  }

  if (RightOcclusionFraction < 0.0)
  {
    /// \error Cannot specify right occlusion fraction less than zero
    Error("Cannot specify right occlusion fraction less than zero. Renal resistances remain unchanged.");
    return;
  }

  if (LeftOcclusionFraction > 1.0)
  {
    /// \error Cannot specify left occlusion fraction greater than one
    Error("Cannot specify left occlusion fraction greater than one. Renal resistances remain unchanged.");
    return;
  }

  if (RightOcclusionFraction > 1.0)
  {
    /// \error Cannot specify right occlusion fraction greater than one
    Error("Cannot specify right occlusion fraction greater than  one. Renal resistances remain unchanged.");
    return;
  }

572
  //Aorta1ToAfferentArteriole paths are equivalent to the renal artery in Pulse. Resistance increases on these paths to represent renal arterial stenosis
573
574
  double currentLeftResistance_mmHg_s_Per_mL = m_leftRenalArteryPath->GetResistanceBaseline(PressureTimePerVolumeUnit::mmHg_s_Per_mL);
  double currentRightResistance_mmHg_s_Per_mL = m_rightRenalArteryPath->GetResistanceBaseline(PressureTimePerVolumeUnit::mmHg_s_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
575
576
577
578

  //The base resistance is a tuned parameter that allows for adequate flow reduction to the kidneys with the logarithmic functional form chosen
  double baseResistance_mmHg_s_Per_mL = 10.0;
  //Open resistance indicates a completely occluded artery. This value is 100 mmHg/mL/s for the cardiovascular circuit.
579
  double openResistance_mmHg_s_Per_mL = m_data.GetConfiguration().GetCardiovascularOpenResistance(PressureTimePerVolumeUnit::mmHg_s_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
580

581
582
  double newLeftResistance_mmHg_s_Per_mL = GeneralMath::ExponentialDecayFunction(baseResistance_mmHg_s_Per_mL, openResistance_mmHg_s_Per_mL, currentLeftResistance_mmHg_s_Per_mL, LeftOcclusionFraction);
  double newRightResistance_mmHg_s_Per_mL = GeneralMath::ExponentialDecayFunction(baseResistance_mmHg_s_Per_mL, openResistance_mmHg_s_Per_mL, currentRightResistance_mmHg_s_Per_mL, RightOcclusionFraction);
Aaron Bray's avatar
Aaron Bray committed
583

584
585
  m_leftRenalArteryPath->GetResistanceBaseline().SetValue(newLeftResistance_mmHg_s_Per_mL, PressureTimePerVolumeUnit::mmHg_s_Per_mL);
  m_rightRenalArteryPath->GetResistanceBaseline().SetValue(newRightResistance_mmHg_s_Per_mL, PressureTimePerVolumeUnit::mmHg_s_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Preprocess prepares the cardiovascular system for the circuit solver
///
/// \details
/// This function calculates the appropriate modifications to the cardiovascular
/// circuit for the time within the cardiac cycle and it processes the actions on the 
/// cardiovascular system.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::PreProcess()
{
  // Locate the cardiac cycle in time (systole, diastole)
  // and do the appropriate calculations based on the time location.
  HeartDriver();
  ProcessActions();
603
  UpdateHeartRhythm();
604
  CalculatePleuralCavityVenousEffects();
Aaron Bray's avatar
Aaron Bray committed
605
606
607
608
609
610
611
612
613
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Process solves the cardiovascular circuit
///
/// \details
/// Modifications to the cardiovascular system are made during the preprocess
/// step of the cardiovascular and other systems. The new state of the circuit 
614
615
/// is solved using %Pulse @ref CircuitMethodology. Advective substance transport
/// is computed using the %Pulse @ref SubstanceTransportMethodology.
Aaron Bray's avatar
Aaron Bray committed
616
617
618
619
620
/// Finally, vitals sign data is computed and system data is populated in the 
/// CalculateVitalSigns method.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::Process()
{
621
622
  m_circuitCalculator->Process(*m_CirculatoryCircuit, m_dT_s);
  m_transporter->Transport(*m_CirculatoryGraph, m_dT_s);
Aaron Bray's avatar
Aaron Bray committed
623
624
625
626
627
628
629
630
631
632
633
634
  CalculateVitalSigns();
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Update the cardiovascular circuit
///
/// \details
/// The current time-step's circuit solution is set to the next time-step when it is passed to PostProcess.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::PostProcess()
{
635
  m_circuitCalculator->PostProcess(*m_CirculatoryCircuit);
Aaron Bray's avatar
Aaron Bray committed
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
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// CalculateVitalSigns computes and/or updates cardiovascular system level data
///
/// \details
/// Calculate vital signs obtains the pressures in the aorta, pulmonary arteries, pulmonary veins and vena cava. 
/// Waveform data for the system, such as arterial pressure, is set every at every time slice. Mean data, such
/// as mean arterial pressure, is set using a running average. Data that are more useful filtered are also set
/// from a running mean. 
/// Several events and irreversible states are detected and set by this method.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::CalculateVitalSigns()
{
  // Grab data from the circuit in order to calculate a running mean
  double AortaNodePressure_mmHg = m_Aorta->GetPressure(PressureUnit::mmHg);
  double AortaNodeCO2PartialPressure_mmHg = m_AortaCO2 == nullptr ? 0 : m_AortaCO2->GetPartialPressure(PressureUnit::mmHg); // This is here so we can Tune circuit w/o substances
  double LeftPulmonaryArteryVolume_mL = m_LeftPulmonaryArteries->GetVolume(VolumeUnit::mL);
  double RightPulmonaryArteryVolume_mL = m_RightPulmonaryArteries->GetVolume(VolumeUnit::mL);
  double TotalPulmonaryArteryVolume_mL = LeftPulmonaryArteryVolume_mL + RightPulmonaryArteryVolume_mL;
  double LeftPulmonaryArteryPressure_mmHg = m_LeftPulmonaryArteries->GetPressure(PressureUnit::mmHg);
  double RightPulmonaryArteryPressure_mmHg = m_RightPulmonaryArteries->GetPressure(PressureUnit::mmHg);

  double LeftPulmonaryVeinVolume_mL = m_LeftPulmonaryVeins->GetVolume(VolumeUnit::mL);
  double RightPulmonaryVeinVolume_mL = m_RightPulmonaryVeins->GetVolume(VolumeUnit::mL);
  double TotalPulmonaryVeinVolume_mL = LeftPulmonaryVeinVolume_mL + RightPulmonaryVeinVolume_mL;
  double LeftPulmonaryVeinPressure_mmHg = m_LeftPulmonaryVeins->GetPressure(PressureUnit::mmHg);
  double RightPulmonaryVeinPressure_mmHg = m_RightPulmonaryVeins->GetPressure(PressureUnit::mmHg);

  double PulmonaryArteryNodePressure_mmHg = (LeftPulmonaryArteryVolume_mL*LeftPulmonaryArteryPressure_mmHg + RightPulmonaryArteryVolume_mL*RightPulmonaryArteryPressure_mmHg) / TotalPulmonaryArteryVolume_mL;
  double PulmVeinNodePressure_mmHg = (LeftPulmonaryVeinVolume_mL*LeftPulmonaryVeinPressure_mmHg + RightPulmonaryVeinVolume_mL*RightPulmonaryVeinPressure_mmHg) / TotalPulmonaryVeinVolume_mL;
  double PulmCapFlow_mL_Per_s = m_LeftPulmonaryArteriesToCapillaries->GetNextFlow(VolumePerTimeUnit::mL_Per_s)
    + m_RightPulmonaryArteriesToCapillaries->GetNextFlow(VolumePerTimeUnit::mL_Per_s);
  double PulmShuntFlow_mL_Per_s = m_LeftPulmonaryArteriesToVeins->GetNextFlow(VolumePerTimeUnit::mL_Per_s)
    + m_RightPulmonaryArteriesToVeins->GetNextFlow(VolumePerTimeUnit::mL_Per_s);

  double VenaCavaPressure_mmHg = m_VenaCava->GetPressure(PressureUnit::mmHg);

  double SkinFlow_mL_Per_s = m_pAortaToSkin->GetNextFlow(VolumePerTimeUnit::mL_Per_s);
  double LHeartFlow_mL_Per_s = m_LeftHeartToAorta->GetNextFlow(VolumePerTimeUnit::mL_Per_s);
  double LHeartVolume_mL = m_LeftHeart->GetVolume(VolumeUnit::mL);

  double muscleFlow_mL_Per_s = m_pAortaToMuscle->GetNextFlow(VolumePerTimeUnit::mL_Per_s);

  double gutFlow_mL_Per_s = m_pAortaToLargeIntestine->GetNextFlow(VolumePerTimeUnit::mL_Per_s) +
    m_pAortaToSmallIntestine->GetNextFlow(VolumePerTimeUnit::mL_Per_s) +
    m_pAortaToSplanchnic->GetNextFlow(VolumePerTimeUnit::mL_Per_s);

  // Calculate heart rate - Threshold of 0.1 is empirically determined. Approximate zero makes it too noisy.
  m_CurrentCardiacCycleDuration_s += m_dT_s;
  if (LHeartFlow_mL_Per_s > 0.1 && !m_HeartFlowDetected)
  {
    m_HeartFlowDetected = true;
    CalculateHeartRate();
    RecordAndResetCardiacCycle();
  }
  if (LHeartFlow_mL_Per_s < 0.1 && m_HeartFlowDetected)
    m_HeartFlowDetected = false;

  // Record high and low values to compute for systolic and diastolic pressures:
  if (AortaNodePressure_mmHg > m_CardiacCycleAortaPressureHigh_mmHg)
    m_CardiacCycleAortaPressureHigh_mmHg = AortaNodePressure_mmHg;  
  if (AortaNodePressure_mmHg < m_CardiacCycleAortaPressureLow_mmHg)
    m_CardiacCycleAortaPressureLow_mmHg = AortaNodePressure_mmHg;  
  if (PulmonaryArteryNodePressure_mmHg > m_CardiacCyclePulmonaryArteryPressureHigh_mmHg)
    m_CardiacCyclePulmonaryArteryPressureHigh_mmHg = PulmonaryArteryNodePressure_mmHg;
  if (PulmonaryArteryNodePressure_mmHg < m_CardiacCyclePulmonaryArteryPressureLow_mmHg)
    m_CardiacCyclePulmonaryArteryPressureLow_mmHg = PulmonaryArteryNodePressure_mmHg;

  // Get Max of Left Ventricle Volume over the course of a heart beat for end diastolic volume
  if (LHeartVolume_mL > m_CardiacCycleDiastolicVolume_mL)
    m_CardiacCycleDiastolicVolume_mL = LHeartVolume_mL;

  // Increment stroke volume. Get samples for running means
  m_CardiacCycleStrokeVolume_mL += LHeartFlow_mL_Per_s*m_dT_s;
712
713
714
715
716
717
718
719
  m_CardiacCycleArterialPressure_mmHg->Sample(AortaNodePressure_mmHg);
  m_CardiacCycleArterialCO2PartialPressure_mmHg->Sample(AortaNodeCO2PartialPressure_mmHg);
  m_CardiacCyclePulmonaryCapillariesWedgePressure_mmHg->Sample(PulmVeinNodePressure_mmHg);
  m_CardiacCyclePulmonaryCapillariesFlow_mL_Per_s->Sample(PulmCapFlow_mL_Per_s);
  m_CardiacCyclePulmonaryShuntFlow_mL_Per_s->Sample(PulmShuntFlow_mL_Per_s);
  m_CardiacCyclePulmonaryArteryPressure_mmHg->Sample(PulmonaryArteryNodePressure_mmHg);
  m_CardiacCycleCentralVenousPressure_mmHg->Sample(VenaCavaPressure_mmHg);
  m_CardiacCycleSkinFlow_mL_Per_s->Sample(SkinFlow_mL_Per_s);
Aaron Bray's avatar
Aaron Bray committed
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

  /// \todo Make sure irreversible state is hit before we get here.
  if (m_CardiacCycleAortaPressureLow_mmHg < -2.0)
  {
    Fatal("Diastolic pressure has fallen below zero.");
    /// \error Fatal: Diastolic pressure has fallen below -2
  }
  if (m_CardiacCycleAortaPressureHigh_mmHg > 700.0)
  {
    Fatal("Systolic pressure has exceeded physiologic range.");
    /// \error Fatal: Systolic pressure has exceeded 700
  }

  // Pressures\Flows from circuit
  GetArterialPressure().SetValue(AortaNodePressure_mmHg, PressureUnit::mmHg);
  GetPulmonaryArterialPressure().SetValue(PulmonaryArteryNodePressure_mmHg, PressureUnit::mmHg);
  GetCentralVenousPressure().SetValue(VenaCavaPressure_mmHg, PressureUnit::mmHg);
  GetCerebralBloodFlow().Set(m_Brain->GetInFlow());
  GetIntracranialPressure().Set(m_Brain->GetPressure());
  GetCerebralPerfusionPressure().SetValue(GetMeanArterialPressure(PressureUnit::mmHg) - GetIntracranialPressure(PressureUnit::mmHg), PressureUnit::mmHg);

  if (m_data.GetState() > EngineState::InitialStabilization)
  {// Don't throw events if we are initializing

  // Check for hypovolemic shock
  /// \event Patient: Hypovolemic Shock: blood volume below 65% of its normal value
746
    if (GetBloodVolume().GetValue(VolumeUnit::mL) <= (m_data.GetConfiguration().GetMinimumBloodVolumeFraction()* m_data.GetCurrentPatient().GetBloodVolumeBaseline(VolumeUnit::mL)))
Aaron Bray's avatar
Aaron Bray committed
747
    {
748
      m_data.GetEvents().SetEvent(eEvent::HypovolemicShock, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
749
750
751

      /// \event Patient: blood loss below 50%, irreversible state enacted 
      // @cite Gutierrez2004HemorrhagicShock
752
      double hypovolemicShock = 0.5*m_data.GetCurrentPatient().GetBloodVolumeBaseline(VolumeUnit::mL);
Aaron Bray's avatar
Aaron Bray committed
753
754
755
756
757
      if (GetBloodVolume().GetValue(VolumeUnit::mL) <= hypovolemicShock)
      {
        m_ss << "Over half the patients blood volume has been lost. The patient is now in an irreversible state.";
        Warning(m_ss);
        /// \irreversible Over half the patients blood volume has been lost.
758
        m_data.GetEvents().SetEvent(eEvent::IrreversibleState, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
759
760
761
762
      }
    }
    else
    {
763
      m_data.GetEvents().SetEvent(eEvent::HypovolemicShock, false, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
764
765
766
767
768
769
770
771
772
    }

    //Check for cardiogenic shock
    if (GetCardiacIndex().GetValue(VolumePerTimeAreaUnit::L_Per_min_m2) < 2.2 &&
      GetSystolicArterialPressure(PressureUnit::mmHg) < 90.0 &&
      GetPulmonaryCapillariesWedgePressure(PressureUnit::mmHg) > 15.0)
    {
      /// \event Patient: Cardiogenic Shock: Cardiac Index has fallen below 2.2 L/min-m^2, Systolic Arterial Pressure is below 90 mmHg, and Pulmonary Capillary Wedge Pressure is above 15.0.
      /// \cite dhakam2008review
773
      m_data.GetEvents().SetEvent(eEvent::CardiogenicShock, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
774
775
776
    }
    else
    {
777
      m_data.GetEvents().SetEvent(eEvent::CardiogenicShock, false, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
778
779
780
781
782
    }

    //Check for Tachycardia, Bradycardia, and asystole
    /// \event Patient: Tachycardia: heart rate exceeds 100 beats per minute.  This state is alleviated if it decreases below 90.
    if (GetHeartRate().GetValue(FrequencyUnit::Per_min) < 90)
783
      m_data.GetEvents().SetEvent(eEvent::Tachycardia, false, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
784
    if (GetHeartRate().GetValue(FrequencyUnit::Per_min) > 100)
785
      m_data.GetEvents().SetEvent(eEvent::Tachycardia, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
786
787
    /// \event Patient: Bradycardia: heart rate falls below 60 beats per minute.  This state is alleviated if it increases above 65.
    if (GetHeartRate().GetValue(FrequencyUnit::Per_min) < 60)
788
      m_data.GetEvents().SetEvent(eEvent::Bradycardia, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
789
    if (GetHeartRate().GetValue(FrequencyUnit::Per_min) > 65)
790
      m_data.GetEvents().SetEvent(eEvent::Bradycardia, false, m_data.GetSimulationTime());
791
    if (GetHeartRate().GetValue(FrequencyUnit::Per_min) == 0 || m_data.GetActions().GetPatientActions().HasCardiacArrest())
Aaron Bray's avatar
Aaron Bray committed
792
    {
793
      m_data.GetEvents().SetEvent(eEvent::Asystole, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
794
    }
795
    else
Aaron Bray's avatar
Aaron Bray committed
796
    {
797
      m_data.GetEvents().SetEvent(eEvent::Asystole, false, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
798
799
800
801
    }
  }

  // Irreversible state if asystole persists.
802
  if (GetHeartRhythm() == eHeartRhythm::Asystolic)
Aaron Bray's avatar
Aaron Bray committed
803
804
  {
    /// \event Patient: Irreversible State: heart has been in asystole for over 45 min:
805
    if (m_data.GetEvents().GetEventDuration(eEvent::Asystole, TimeUnit::s) > 2700.0) // \cite: Zijlmans2002EpilepticSeizuresAsystole
Aaron Bray's avatar
Aaron Bray committed
806
    {
807
      m_ss << "Asystole has occurred for " << m_data.GetEvents().GetEventDuration(eEvent::Asystole, TimeUnit::s) << " seconds, patient is in irreversible state.";
Aaron Bray's avatar
Aaron Bray committed
808
809
      Warning(m_ss);
      /// \irreversible Heart has been in asystole for over 45 min
810
      m_data.GetEvents().SetEvent(eEvent::IrreversibleState, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
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
    }
  }

  // Compute blood volume
  double blood_mL = 0;
  for (SELiquidCompartment* cmpt : m_data.GetCompartments().GetVascularLeafCompartments())
  {
    if (cmpt->HasVolume() && cmpt != m_Pericardium) //Don't include pericardium
    {
      blood_mL += cmpt->GetVolume(VolumeUnit::mL);
    }
  }
  GetBloodVolume().SetValue(blood_mL, VolumeUnit::mL);
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Sets the systolic and diastolic pressures.
///
/// \details
/// The systemic arterial and pulmonary arterial systolic and diastolic pressures are set here. 
/// The variables used to track the maximum and minimum pressures are then reset for the next cardiac cycle.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::RecordAndResetCardiacCycle()
{
  GetSystolicArterialPressure().SetValue(m_CardiacCycleAortaPressureHigh_mmHg, PressureUnit::mmHg);
  GetDiastolicArterialPressure().SetValue(m_CardiacCycleAortaPressureLow_mmHg, PressureUnit::mmHg);
  GetPulmonarySystolicArterialPressure().SetValue(m_CardiacCyclePulmonaryArteryPressureHigh_mmHg, PressureUnit::mmHg);
  GetPulmonaryDiastolicArterialPressure().SetValue(m_CardiacCyclePulmonaryArteryPressureLow_mmHg, PressureUnit::mmHg);
  GetPulsePressure().SetValue(m_CardiacCycleAortaPressureHigh_mmHg - m_CardiacCycleAortaPressureLow_mmHg, PressureUnit::mmHg);  

  m_data.GetCardiovascular().GetHeartStrokeVolume().SetValue(m_CardiacCycleStrokeVolume_mL, VolumeUnit::mL);
  double ejectionFraction = 0.;
  if (m_CardiacCycleDiastolicVolume_mL > ZERO_APPROX)
    ejectionFraction = m_CardiacCycleStrokeVolume_mL / m_CardiacCycleDiastolicVolume_mL;
  GetHeartEjectionFraction().SetValue(ejectionFraction);
  GetCardiacOutput().SetValue(m_CardiacCycleStrokeVolume_mL * GetHeartRate().GetValue(FrequencyUnit::Per_min), VolumePerTimeUnit::mL_Per_min);
848
  GetCardiacIndex().SetValue(GetCardiacOutput().GetValue(VolumePerTimeUnit::mL_Per_min) / m_data.GetCurrentPatient().GetSkinSurfaceArea(AreaUnit::m2), VolumePerTimeAreaUnit::mL_Per_min_m2);
Aaron Bray's avatar
Aaron Bray committed
849
850
851

  // Running means
  // Mean Arterial Pressure
852
  GetMeanArterialPressure().SetValue(m_CardiacCycleArterialPressure_mmHg->Value(), PressureUnit::mmHg);
853
  m_CardiacCycleArterialPressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
854
  // Mean Aterial CO2 Partial Pressure
855
  GetMeanArterialCarbonDioxidePartialPressure().SetValue(m_CardiacCycleArterialCO2PartialPressure_mmHg->Value(), PressureUnit::mmHg);
Aaron Bray's avatar
Aaron Bray committed
856
  // Mean Aterial CO2 Partial Pressure Delta
857
858
  GetMeanArterialCarbonDioxidePartialPressureDelta().SetValue(m_CardiacCycleArterialCO2PartialPressure_mmHg->Value() - m_LastCardiacCycleMeanArterialCO2PartialPressure_mmHg, PressureUnit::mmHg);
  m_LastCardiacCycleMeanArterialCO2PartialPressure_mmHg = m_CardiacCycleArterialCO2PartialPressure_mmHg->Value();
859
  m_CardiacCycleArterialCO2PartialPressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
860
  // Pulmonary Capillary Wedge Pressure
861
  GetPulmonaryCapillariesWedgePressure().SetValue(m_CardiacCyclePulmonaryCapillariesWedgePressure_mmHg->Value(), PressureUnit::mmHg);
862
  m_CardiacCyclePulmonaryCapillariesWedgePressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
863
  // Pulmonary Capillary Mean Flow
864
  GetPulmonaryMeanCapillaryFlow().SetValue(m_CardiacCyclePulmonaryCapillariesFlow_mL_Per_s->Value(), VolumePerTimeUnit::mL_Per_s);
865
  m_CardiacCyclePulmonaryCapillariesFlow_mL_Per_s->Clear();
Aaron Bray's avatar
Aaron Bray committed
866
  // Pulmonary Shunt Mean Flow
867
  GetPulmonaryMeanShuntFlow().SetValue(m_CardiacCyclePulmonaryShuntFlow_mL_Per_s->Value(), VolumePerTimeUnit::mL_Per_s);
868
  m_CardiacCyclePulmonaryShuntFlow_mL_Per_s->Clear();
Aaron Bray's avatar
Aaron Bray committed
869
  // Mean Pulmonary Artery Pressure
870
  GetPulmonaryMeanArterialPressure().SetValue(m_CardiacCyclePulmonaryArteryPressure_mmHg->Value(), PressureUnit::mmHg);
871
  m_CardiacCyclePulmonaryArteryPressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
872
  // Mean Central Venous Pressure
873
  GetMeanCentralVenousPressure().SetValue(m_CardiacCycleCentralVenousPressure_mmHg->Value(), PressureUnit::mmHg);
874
  m_CardiacCycleCentralVenousPressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
875
  // Mean Skin Flow
876
  GetMeanSkinFlow().SetValue(m_CardiacCycleSkinFlow_mL_Per_s->Value(), VolumePerTimeUnit::mL_Per_s);
877
  m_CardiacCycleSkinFlow_mL_Per_s->Clear();
Aaron Bray's avatar
Aaron Bray committed
878
879

  // Computed systemic Vascular Resistance
880
  double cardiacOutput_mL_Per_s = GetCardiacOutput().GetValue(VolumePerTimeUnit::mL_Per_s);
Aaron Bray's avatar
Aaron Bray committed
881
  double systemicVascularResistance_mmHg_s_Per_mL = 0.0;
882
883
  if (cardiacOutput_mL_Per_s > ZERO_APPROX)
    systemicVascularResistance_mmHg_s_Per_mL = (GetMeanArterialPressure().GetValue(PressureUnit::mmHg) - GetMeanCentralVenousPressure().GetValue(PressureUnit::mmHg)) / cardiacOutput_mL_Per_s;
884
  GetSystemicVascularResistance().SetValue(systemicVascularResistance_mmHg_s_Per_mL, PressureTimePerVolumeUnit::mmHg_s_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
885
886

  // Computed pulmonary Vascular Resistances
887
  if (cardiacOutput_mL_Per_s == 0.0)
Aaron Bray's avatar
Aaron Bray committed
888
  {
889
    GetPulmonaryVascularResistance().SetValue(0.0, PressureTimePerVolumeUnit::mmHg_min_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
890
891
892
893
    GetPulmonaryVascularResistanceIndex().SetValue(0.0, PressureTimePerVolumeAreaUnit::mmHg_min_Per_mL_m2);
  }
  else
  {
894
895
	//(Mean arteral pressure - mean pulmonary wedge pressure)/Cardiac output
	  double PulmonaryPressureDrop_mmHg = GetPulmonaryMeanArterialPressure(PressureUnit::mmHg) - GetPulmonaryCapillariesWedgePressure(PressureUnit::mmHg);
896
    GetPulmonaryVascularResistance().SetValue(PulmonaryPressureDrop_mmHg / cardiacOutput_mL_Per_s, PressureTimePerVolumeUnit::mmHg_s_Per_mL);
897
898
899
	
    //Mean arteral pressure - mean pulmonary wedge pressure)/Cardiac index where cardiac index is cardiac output / body surface area
	GetPulmonaryVascularResistanceIndex().SetValue(PulmonaryPressureDrop_mmHg / GetCardiacIndex(VolumePerTimeAreaUnit::mL_Per_s_m2), PressureTimePerVolumeAreaUnit::mmHg_s_Per_mL_m2);
Aaron Bray's avatar
Aaron Bray committed
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
  }  
  
  m_CardiacCycleAortaPressureHigh_mmHg = 0.0;
  m_CardiacCycleAortaPressureLow_mmHg = 10000.0;
  m_CardiacCyclePulmonaryArteryPressureHigh_mmHg = 0.0;
  m_CardiacCyclePulmonaryArteryPressureLow_mmHg = 10000.0;
  m_CardiacCycleDiastolicVolume_mL = 0;
  m_CardiacCycleStrokeVolume_mL = 0;
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Holds the action methods for the cardiovascular system.
///
/// \details
/// This method holds the actions for the CV system so that only one
/// method need be called in preprocess.
/// <ul>
///   <li> Hemorrhage </li>
///   <li> Pericardial Effusion </li>
///   <li> CPR </li>
///   <li> CardiacArrest </li>
/// </ul>
//--------------------------------------------------------------------------------------------------
void Cardiovascular::ProcessActions()
{
  TraumaticBrainInjury();
  Hemorrhage();
  PericardialEffusion();
  CPR();
  CardiacArrest();
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// The traumatic brain injury action increases flow resistance in the brain
///
/// \details
/// The user may specify a brain injury of varying severity to apply during runtime. The brain resistance
/// is scaled based on severity, which impacts flow and pressure in the brain, simulating the effects of
/// a non-localized brain injury.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::TraumaticBrainInjury()
{
  if (!m_data.GetActions().GetPatientActions().HasBrainInjury())
    return;

  //Grab info about the injury
  SEBrainInjury* b = m_data.GetActions().GetPatientActions().GetBrainInjury();
  double severity = b->GetSeverity().GetValue();

  //Interpolate linearly between multipliers of 1 (for severity of 0) to max (for severity of 1)
  //These multipliers are chosen to result in ICP > 25 mmHg and CBF < 1.8 mL/s
  double usMult = GeneralMath::LinearInterpolator(0, 1, 1, 4.775, severity);
  double dsMult = GeneralMath::LinearInterpolator(0, 1, 1, 30.409, severity);

956
957
  m_pBrainResistanceDownstream->GetNextResistance().SetValue(dsMult * m_pBrainResistanceDownstream->GetResistanceBaseline().GetValue(PressureTimePerVolumeUnit::mmHg_s_Per_mL), PressureTimePerVolumeUnit::mmHg_s_Per_mL);
  m_pBrainResistanceUpstream->GetNextResistance().SetValue(usMult * m_pBrainResistanceUpstream->GetResistanceBaseline().GetValue(PressureTimePerVolumeUnit::mmHg_s_Per_mL), PressureTimePerVolumeUnit::mmHg_s_Per_mL);
Aaron Bray's avatar
Aaron Bray committed
958
959
960
961
962
963
964
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// The hemorrhage function simulates bleeding from a specified compartment
///
/// \details
965
/// The user may specify multiple bleeds across the anatomical compartments. The Model creates a 
966
967
968
/// separate bleeding path for each node in each anatomical compartment by volume-weighting the 
/// flow. Hemorrhage calls for a compartment that already contains a hemorrhage will be overwritten 
/// with the new value. Compartments can overlap.
Aaron Bray's avatar
Aaron Bray committed
969
970
971
972
//--------------------------------------------------------------------------------------------------
void Cardiovascular::Hemorrhage()
{
  /// \todo Enforce limits and remove fatal errors.
973

974
975
976
  //Set all hemorrhage flows to zero, so:
  // - We can increment for overlapping compartments
  // - We know to remove ones that are turned off
977
  for (unsigned int hIter = 0; hIter < m_HemorrhagePaths.size(); hIter++)
978
  {
979
    m_HemorrhagePaths.at(hIter)->GetNextFlowSource().SetValue(0.0, VolumePerTimeUnit::mL_Per_s);
980
  }
981

Aaron Bray's avatar
Aaron Bray committed
982
  SEHemorrhage* h;
983
  double TotalLossRate_mL_Per_s = 0.0;
984
  double internal_rate_mL_Per_s = 0.0;
985
  std::vector<SEHemorrhage*> invalid_hemorrhages;
Aaron Bray's avatar
Aaron Bray committed
986
987
988
989
  const std::map <std::string, SEHemorrhage*> & hems = m_data.GetActions().GetPatientActions().GetHemorrhages();
  for (auto hem : hems)
  {
    h = hem.second;
990
    double rate_mL_Per_s = h->GetRate().GetValue(VolumePerTimeUnit::mL_Per_s);
991
992
    // Allow shorthand naming
    SELiquidCompartment* compartment = m_data.GetCompartments().GetCardiovascularGraph().GetCompartment(h->GetCompartment());
993
994
995
996
997
998
999
1000
1001
1002
1003
    if (compartment == nullptr)
    {
      h->SetCompartment(h->GetCompartment() + "Vasculature");
      compartment = m_data.GetCompartments().GetCardiovascularGraph().GetCompartment(h->GetCompartment());
    }
    if (compartment == nullptr)
    {
      Error("Removing invalid Hemorrhage due to unsupported compartment : " + h->GetCompartment());
      invalid_hemorrhages.push_back(h);
      continue;
    }
1004

1005
    /// \error Error: Bleeding rate cannot exceed cardiac output
1006
    if (rate_mL_Per_s > GetCardiacOutput().GetValue(VolumePerTimeUnit::mL_Per_s))
1007
    {
Aaron Bray's avatar
Aaron Bray committed
1008
1009
      m_ss << "Cannot have bleeding rate greater than cardiac output. \n\tCurrent cardiac output is: " << GetCardiacOutput()
        << "\n\tAnd specified bleeding rate is: " << h->GetRate();
1010
1011
1012
      Error(m_ss);
      invalid_hemorrhages.push_back(h);
      continue;
Aaron Bray's avatar
Aaron Bray committed
1013
    }
1014
    /// \error Error: Bleeding rate cannot be less than zero
1015
    if (rate_mL_Per_s < 0)
Aaron Bray's avatar
Aaron Bray committed
1016
1017
    {
      m_ss << "Cannot specify bleeding less than 0";
1018
1019
1020
      Error(m_ss);
      invalid_hemorrhages.push_back(h);
      continue;
Aaron Bray's avatar
Aaron Bray committed
1021
    }
1022
    /// \error Error: Bleeding must be from a vascular compartment
1023
1024
    if (!compartment)
    {
1025
1026
1027
1028
      m_ss << "Cannot hemorrhage from compartment "+h->GetComment()+", must be a valid vascular compartment";
      Error(m_ss);
      invalid_hemorrhages.push_back(h);
      continue;
1029
    }
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
    if (h->GetType() == eHemorrhage_Type::Internal)
    {
      SELiquidCompartment* abdomenCompartment = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::Abdomen);
      if (!abdomenCompartment->HasChild(compartment->GetName()))
      {
        m_ss << "Internal Hemorrhage is only supported for the abdominal region, including the right and left kidneys, liver, spleen, splanchnic, and small and large intestine vascular compartments.";
        Error(m_ss);
        invalid_hemorrhages.push_back(h);
        continue;
      }
    }
1041
    else //(h->GetType() == eHemorrhage_Type::External)
1042
1043
1044
    {
      //Only mass is merely transfered if it is an internal bleed
      TotalLossRate_mL_Per_s += rate_mL_Per_s;
1045
    }
1046

1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
    //Get all circuit nodes in this compartment
    std::vector<SEFluidCircuitNode*> nodes;
    nodes.insert(nodes.end(), compartment->GetNodeMapping().GetNodes().begin(), compartment->GetNodeMapping().GetNodes().end());
    for (unsigned int leafIter = 0; leafIter < compartment->GetLeaves().size(); leafIter++)
    {
      SELiquidCompartment* leaf = compartment->GetLeaves().at(leafIter);
      nodes.insert(nodes.end(), leaf->GetNodeMapping().GetNodes().begin(), leaf->GetNodeMapping().GetNodes().end());
    }

    unsigned int nodesIter = 0;
1057
1058
    unsigned int nodesWithVolume = 0;
    double totalVolume_mL = 0.0;
1059
    while (nodesIter < nodes.size())
1060
    {
1061
      SEFluidCircuitNode* node = nodes.at(nodesIter);
1062
      //Only use nodes that are part of the Circulatory circuit
1063
1064
1065
1066
1067
1068
1069
      if (std::find(m_CirculatoryCircuit->GetNodes().begin(), m_CirculatoryCircuit->GetNodes().end(), node) == m_CirculatoryCircuit->GetNodes().end())
      {
        //Not in circuit
        nodes.erase(nodes.begin() + nodesIter);
        continue;
      }

1070
1071
1072
1073
1074
      if (node->HasNextVolume())
      {
        nodesWithVolume++;
        totalVolume_mL += node->GetNextVolume(VolumeUnit::mL);
      }
1075
1076

      nodesIter++;
1077
    }
1078
1079
1080
1081

    /// \error Fatal: Bleeding must come from nodes in the circultatory circuit
    if (nodes.size() == 0)
    {
1082
      /// \error Error: Hemorrhage compartments must have nodes in the circulatory circuit
1083
      m_ss << "Hemorrhage compartments must have nodes in the circulatory circuit";
1084
1085
1086
      Error(m_ss);
      invalid_hemorrhages.push_back(h);
      continue;
1087
1088
1089
    }

    //Update the circuit to remove blood from the specified compartment
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
    for (auto node : nodes)
    {
      //Weight the flow sink value by node volume
      double thisNodeRate_mL_Per_s = 0.0;
      if (nodesWithVolume == 0)
      {
        //No nodes have volume, so evenly distribute
        thisNodeRate_mL_Per_s = rate_mL_Per_s / double(nodes.size());
      }
      else if (!node->HasNextVolume())
      {
        //Some nodes have volume, but not this one, so move on
        continue;
      }
      else
      {
        //This node has volume
        thisNodeRate_mL_Per_s = rate_mL_Per_s * node->GetNextVolume(VolumeUnit::mL) / totalVolume_mL;
      }

      //Check if we've already been hemorrhaging here
      SEFluidCircuitPath* hemorrhagePath;
      bool pathFound = false;
1113
      for (unsigned int hIter = 0; hIter < m_HemorrhagePaths.size(); hIter++)
1114
      {
1115
        hemorrhagePath = m_HemorrhagePaths.at(hIter);
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
        if (&(hemorrhagePath->GetSourceNode()) == node)
        {
          pathFound = true;
          break;
        }
      }

      if (pathFound)
      {
        //Update the existing bleed path
1126
1127
        //Increment value to allow overlapping compartments
        hemorrhagePath->GetNextFlowSource().IncrementValue(thisNodeRate_mL_Per_s, VolumePerTimeUnit::mL_Per_s);
1128
1129
1130
1131
1132
      }
      else
      {
        //Add bleed path for fluid mechanics
        SEFluidCircuitPath& newHemorrhagePath = m_CirculatoryCircuit->CreatePath(*node, *m_Ground, node->GetName() + "Hemorrhage");
1133
1134
        //Increment value to allow overlapping compartments
        newHemorrhagePath.GetNextFlowSource().IncrementValue(thisNodeRate_mL_Per_s, VolumePerTimeUnit::mL_Per_s);
1135
1136
1137
        m_CirculatoryCircuit->StateChange();

        //Add bleed link for transport
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
        //Find the source compartment (may be a leaf) to make the graph work (i.e., to transport)
        SELiquidCompartment* sourceCompartment;
        if (std::find(compartment->GetNodeMapping().GetNodes().begin(), compartment->GetNodeMapping().GetNodes().end(), node) != compartment->GetNodeMapping().GetNodes().end())
        {
          sourceCompartment = compartment;
        }
        else
        {
          for (unsigned int leafIter = 0; leafIter < compartment->GetLeaves().size(); leafIter++)
          {
            SELiquidCompartment* leaf = compartment->GetLeaves().at(leafIter);
            if (std::find(leaf->GetNodeMapping().GetNodes().begin(), leaf->GetNodeMapping().GetNodes().end(), node) != leaf->GetNodeMapping().GetNodes().end())
            {
              sourceCompartment = leaf;
              break;
            }
          }
1155
        }
1156
1157

        SELiquidCompartmentLink& newHemorrhageLink = m_data.GetCompartments().CreateLiquidLink(*sourceCompartment, *m_Groundcmpt, compartment->GetName() + "Hemorrhage");
1158
1159
        newHemorrhageLink.MapPath(newHemorrhagePath);
        m_CirculatoryGraph->AddLink(newHemorrhageLink);
1160
        m_data.GetCompartments().StateChange();
1161
1162

        //Add to local lists
1163
1164
        m_HemorrhagePaths.push_back(&newHemorrhagePath);
        m_HemorrhageLinks.push_back(&newHemorrhageLink);
1165
1166
1167
1168
1169
        if (h->GetType() == eHemorrhage_Type::Internal)
        {
          m_InternalHemorrhagePaths.push_back(&newHemorrhagePath);
          m_InternalHemorrhageLinks.push_back(&newHemorrhageLink);
        }
1170
1171
      }
    }
1172

1173
1174
1175
1176
1177
1178
    //total the internal hemorrhage flow rate and apply it to the abdominal cavity path
    for (auto hemorrhage : m_InternalHemorrhagePaths)
    {
      internal_rate_mL_Per_s += hemorrhage->GetNextFlowSource().GetValue(VolumePerTimeUnit::mL_Per_s);
    }
    m_pGndToAbdominalCavity->GetNextFlowSource().SetValue(internal_rate_mL_Per_s, VolumePerTimeUnit::mL_Per_s);
Aaron Bray's avatar
Aaron Bray committed
1179
  }
1180

1181
1182
1183
1184
  // Remove any invalid hemorrhages
  for (SEHemorrhage* h : invalid_hemorrhages)
    m_data.GetActions().GetPatientActions().RemoveHemorrhage(h->GetCompartment());

1185
1186
1187
  //Remove hemorrhage elements that aren't being used
  //Make sure to do this even if no hemorrhage action, since it's needed when removed
  unsigned int hIter = 0;
1188
  while (hIter < m_HemorrhagePaths.size())
1189
  {
1190
    if (m_HemorrhagePaths.at(hIter)->GetNextFlowSource(VolumePerTimeUnit::mL_Per_s) == 0.0)
1191
    {
1192
      m_CirculatoryCircuit->RemovePath(*m_HemorrhagePaths.at(hIter));
1193
      m_HemorrhagePaths.erase(m_HemorrhagePaths.begin() + hIter);
1194
1195
      m_CirculatoryCircuit->StateChange();

1196
1197
      m_CirculatoryGraph->RemoveLink(*m_HemorrhageLinks.at(hIter));
      m_HemorrhageLinks.erase(m_HemorrhageLinks.begin() + hIter);
1198
      m_CirculatoryGraph->StateChange();
1199

1200
1201
1202
1203
1204
      continue;
    }
    hIter++;
  }

1205
1206
1207
  //Update abdominal cavity compliance
  double abdominalBloodVolume = m_AbdominalCavity->GetVolume().GetValue(VolumeUnit::mL);
  double compliance_mL_Per_mmHg = 0;
1208
  double complianceCurveExponent = 0.55;
1209
  //Variable compliance calculation
1210
  compliance_mL_Per_mmHg = pow(abdominalBloodVolume, complianceCurveExponent);
1211
  m_pAbdominalCavityToGnd->GetComplianceBaseline().SetValue(compliance_mL_Per_mmHg, VolumePerPressureUnit::mL_Per_mmHg);
1212

1213
1214
1215
  //Effect the Aorta with internal hemorrhages
  InternalHemorrhagePressureApplication();

Aaron Bray's avatar
Aaron Bray committed
1216
1217
1218
  if (TotalLossRate_mL_Per_s == 0)
    return;

1219
  //Update the patient's mass
Aaron Bray's avatar
Aaron Bray committed
1220
  double bloodDensity_kg_Per_mL = m_data.GetBloodChemistry().GetBloodDensity(MassPerVolumeUnit::kg_Per_mL);
1221
  double massLost_kg = (TotalLossRate_mL_Per_s - internal_rate_mL_Per_s)*bloodDensity_kg_Per_mL*m_dT_s;
1222
  double patientMass_kg = m_data.GetCurrentPatient().GetWeight(MassUnit::kg);
Aaron Bray's avatar
Aaron Bray committed
1223
1224
  patientMass_kg -= massLost_kg;

1225
  m_data.GetCurrentPatient().GetWeight().SetValue(patientMass_kg, MassUnit::kg);
Aaron Bray's avatar
Aaron Bray committed
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// The function initiates a flow source on the pericardium. It is used by both the action and condition.
///
/// \details
/// The pericardial effusion action may be called during run time. It initiates a flow source on the pericardium
/// which leads to increased pericardium volume. As the volume increases, a pressure source is applied to
/// the left and right heart nodes, simulating the restriction of the swelling pericardium.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::PericardialEffusion()
{
  //We need to do this here because the circuit needs to be processed to modify the compliance pressure based on the volume change
  if ( m_data.GetConditions().HasChronicPericardialEffusion() &&
      !m_data.GetActions().GetPatientActions().HasPericardialEffusion())
  {
    PericardialEffusionPressureApplication();
  }

  if (!m_data.GetActions().GetPatientActions().HasPericardialEffusion())
    return;

  double complianceSlopeParameter = 0.0;
  double complianceCurveParameter = 0.0;
  double flowToPericardium_mL_per_s = 0.0;
  double flowCubed_mL3_Per_s3 = 0.0;
  double compliance_mL_Per_mmHg = 0.0;
  double intrapericardialVolume_mL = m_Pericardium->GetVolume(VolumeUnit::mL);
  double intrapericardialPressure_mmHg = m_Pericardium->GetPressure(PressureUnit::mmHg);

  double effusionRate_mL_Per_s = m_data.GetActions().GetPatientActions().GetPericardialEffusion()->GetEffusionRate().GetValue(VolumePerTimeUnit::mL_Per_s);
  if (effusionRate_mL_Per_s <= 0.1 && effusionRate_mL_Per_s > 0.0)
  {
    //Slow effusion
    complianceSlopeParameter = 0.4;
    complianceCurveParameter = 0.55;
  }
  else if (effusionRate_mL_Per_s > 0.1 && effusionRate_mL_Per_s < 1.0)
  {
    complianceSlopeParameter = 50;
    complianceCurveParameter = 0.1;
  }
  else if (effusionRate_mL_Per_s > 1.0)
  {
    Error("Effusion rate is out of physiologic bounds. Effusion rate is reset to 1.0 milliliters per second.");
    /// \error Effusion rate is out of physiologic bounds. Effusion rate is reset to 1.0 milliliters per second.
    effusionRate_mL_Per_s = 1.0;
    complianceSlopeParameter = 50;
    complianceCurveParameter = 0.1;
  }
  else if (effusionRate_mL_Per_s < 0.0)
  {
    Error("Cannot specify effusion rate less than zero. Effusion rate is now set to 0.0.");
    /// \error Cannot specify effusion rate less than zero. Effusion rate is now set to 0.0.
    effusionRate_mL_Per_s = 0.0;
    complianceSlopeParameter = 0.4;
    complianceCurveParameter = 0.55;
  }

  m_pGndToPericardium->GetNextFlowSource().SetValue(effusionRate_mL_Per_s, VolumePerTimeUnit::mL_Per_s);
  flowToPericardium_mL_per_s = m_pGndToPericardium->GetNextFlow(VolumePerTimeUnit::mL_Per_s);
  flowCubed_mL3_Per_s3 = flowToPericardium_mL_per_s*flowToPericardium_mL_per_s*flowToPericardium_mL_per_s;

  //Variable compliance calculation
  if (flowCubed_mL3_Per_s3 < 0.0001)
  {
1293
    compliance_mL_Per_mmHg = m_pPericardiumToGnd->GetNextCompliance().GetValue(VolumePerPressureUnit::mL_Per_mmHg);
Aaron Bray's avatar
Aaron Bray committed
1294
1295
1296
1297
1298
1299
  }
  else
  {
    compliance_mL_Per_mmHg = complianceSlopeParameter / flowCubed_mL3_Per_s3 - complianceCurveParameter*intrapericardialVolume_mL;
  }

1300
  m_pPericardiumToGnd->GetNextCompliance().SetValue(compliance_mL_Per_mmHg, VolumePerPressureUnit::mL_Per_mmHg);
Aaron Bray's avatar
Aaron Bray committed
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346

  PericardialEffusionPressureApplication();
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// The CPR function controls the force applied during a chest compression action.
///
/// \details
/// The user may apply a chest compression to continue blood circulation if the heart no longer has an effective rhythm.
/// The compression can either be defined by an explicit force or by a fraction of the maximum allowable force. 
/// If the compression input is a force scale then the method controls the shape of the force pulse and converts the force
/// pressure for application to the heart. 
/// If the compression input is force, then the raw force is converted to pressure and applied to
/// the heart. The pressure is applied at the pressure source on the LeftHeart3ToGround and 
/// RightHeart3ToGround paths in the cardiovascular circuit.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::CPR()
{
  // If a compression has started, finish it.
  if (m_CompressionRatio > 0.0)
  {
    if (m_data.GetActions().GetPatientActions().HasChestCompressionForceScale()) 
    {
      Warning("Attempt to start a new compression during a previous compression. Allow more time between compressions or shorten the compression period.");
      m_data.GetActions().GetPatientActions().RemoveChestCompression();
      return;
    }

    if (m_data.GetActions().GetPatientActions().HasChestCompressionForce())
    {
      Warning("Attempt to switch to explicit force from force scale during CPR compression. CPR actions will be ignored until current compression ends.");
      m_data.GetActions().GetPatientActions().RemoveChestCompression();
      return;
    }

    CalculateAndSetCPRcompressionForce();
    return;
  }
  // If there is no chest compression action and we are not currently compressing, return to ProcessActions
  if (!m_data.GetActions().GetPatientActions().HasChestCompression())
    return;

  // Call for chest compression with an effective heart rhythm
  // In the future we may allow compressions on a beating heart, but that will require extensive testing
  // to evaluate the hemodynamic stability.
1347
  if (!m_data.GetEvents().IsEventActive(eEvent::CardiacArrest))
Aaron Bray's avatar
Aaron Bray committed
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
  {
    Warning("CPR attempted on beating heart. Action ignored.");
    m_data.GetActions().GetPatientActions().RemoveChestCompression();
    return;
  }

  // Have a new call for a chest compression
  if (m_data.GetActions().GetPatientActions().HasChestCompressionForceScale())
  {
    m_CompressionRatio = m_data.GetActions().GetPatientActions().GetChestCompressionForceScale()->GetForceScale().GetValue();
    /// \error Warning: CPR compression ratio must be a positive value between 0 and 1 inclusive.
    if (m_CompressionRatio < 0.0)
      Warning("CPR compression ratio must be a positive value between 0 and 1 inclusive.");
    if (m_CompressionRatio > 1.0)
      Warning("CPR compression ratio must be a positive value between 0 and 1 inclusive.");

    BLIM(m_CompressionRatio, 0., 1.);
    // If no period was assigned by the user, then use the default - 0.4s
    if (m_data.GetActions().GetPatientActions().GetChestCompressionForceScale()->HasForcePeriod())
    {
      m_CompressionPeriod_s = m_data.GetActions().GetPatientActions().GetChestCompressionForceScale()->GetForcePeriod().GetValue(TimeUnit::s);
    }
    else
    {
      m_CompressionPeriod_s = 0.4;
    }

    m_data.GetActions().GetPatientActions().RemoveChestCompression();
  }

  CalculateAndSetCPRcompressionForce();
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// Calculates and sets the pressure on the heart pressure sources when a CPR compression is applied.
///
/// \details
/// Calculates and sets the pressure on the heart pressure sources when a CPR compression is applied.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::CalculateAndSetCPRcompressionForce()
{

  double compressionForce_N = 0.0;
  double compressionForceMax_N = 500.0;   // The maximum allowed compression force (corresponds to 1.0 when force scale is used)
  double compressionForceMin_N = 0.0;     // The minimum allowed compression force

  if (m_CompressionRatio > 0.0) //Force scale
  {
    // Bell curve shaping parameters
    double c = -10; // Defines the start and stop of the force bell curve given the period
    double a = 4 * c / (m_CompressionPeriod_s*m_CompressionPeriod_s);
    double b = -a*m_CompressionPeriod_s;

    compressionForce_N = pow(2, a*m_CompressionTime_s*m_CompressionTime_s + b*m_CompressionTime_s + c)*m_CompressionRatio*compressionForceMax_N;

    // 2 second max compression time is arbitrary. I just put it in to make sure it doesn't get stuck if
    // we accidentally make a really wide bell curve. Note that the bell curve parameters are currently hardcoded above.
    // If compression force has decayed to less than some amount or the time is above some amount, end the compression 
    if (m_CompressionTime_s > m_CompressionPeriod_s)
    {
      compressionForce_N = 0.0;
      m_CompressionTime_s = 0.0;
      m_CompressionRatio = 0.0;
      m_CompressionPeriod_s = 0.0;
    }
  }
  else //Explicit force
  {
    compressionForce_N = m_data.GetActions().GetPatientActions().GetChestCompressionForce()->GetForce().GetValue(ForceUnit::N);
  }

  m_CompressionTime_s += m_dT_s;

  if (compressionForce_N > compressionForceMax_N)
  {
    compressionForce_N = compressionForceMax_N;
    Warning("The compression force exceeded the maximum compression force. Compression force limited to 500N.");
  }

  if (compressionForce_N < compressionForceMin_N)
  {
    compressionForce_N = compressionForceMin_N;
    Warning("The compression force was less than the required minimum. Compression force limited to 0N.");
  }

  double leftHeartForceToPressureFactor = 0.1; // Tuning parameter to translate compression force in N to left heart pressure in mmHg
  double rightHeartForceToPressureFactor = 0.1; // Tuning parameter to translate compression force in N to right heart pressure in mmHg
  double nextLeftPressure_mmHg = leftHeartForceToPressureFactor*compressionForce_N;
  double nextRightPressure_mmHg = rightHeartForceToPressureFactor*compressionForce_N;

  m_pRightHeartToGnd->GetNextPressureSource().SetValue(nextRightPressure_mmHg, PressureUnit::mmHg);
  m_pLeftHeartToGnd->GetNextPressureSource().SetValue(nextLeftPressure_mmHg, PressureUnit::mmHg);

  // The action is removed when the force is set to 0.
  if (compressionForce_N == 0)
    m_data.GetActions().GetPatientActions().RemoveChestCompression();
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// The cardiac arrest action causes the sudden loss of heart function and breathing.
///
/// \details
/// Cardiac arrest is the sudden loss of effective blood circulation. When the cardiac arrest
/// action is active, the heart will not beat effectively and breathing will not occur.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::CardiacArrest()
{
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
  if (m_data.GetActions().GetPatientActions().HasCardiacArrest())
  {
    // Flip the cardiac arrest switch
    // This tells the CV system that a cardiac arrest has been initiated.
    // The cardiac arrest event will be triggered by CardiacCycleCalculations() at the end of the cardiac cycle.
    m_EnterCardiacArrest = true;
    //Force a new cardiac cycle to start when cardiac arrest is removed
    m_CurrentCardiacCycleTime_s = m_CardiacCyclePeriod_s - m_dT_s;
  }
  else
  {
    m_EnterCardiacArrest = false;
1469
    m_data.GetEvents().