Cardiovascular.cpp 104 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
33
#include "substance/SESubstance.h"
#include "substance/SESubstanceTransport.h"
Aaron Bray's avatar
Aaron Bray committed
34
#include "circuit/fluid/SEFluidCircuit.h"
35
#include "circuit/fluid/SEFluidCircuitCalculator.h"
Aaron Bray's avatar
Aaron Bray committed
36
37
38
39
40
41
42
43
44
45
46
47
#include "compartment/fluid/SELiquidCompartmentGraph.h"
#include "compartment/substances/SELiquidSubstanceQuantity.h"
#include "properties/SEScalar0To1.h"
#include "properties/SEScalarPressure.h"
#include "properties/SEScalarFlowResistance.h"
#include "properties/SEScalarFrequency.h"
#include "properties/SEScalarVolume.h"
#include "properties/SEScalarVolumePerTime.h"
#include "properties/SEScalarFlowCompliance.h"
#include "properties/SEScalarMass.h"
#include "properties/SEScalarMassPerVolume.h"
#include "properties/SEScalarFlowElastance.h"
48
#include "properties/SEScalar0To1.h"
Aaron Bray's avatar
Aaron Bray committed
49
50
51
52
53
54
55
56
57
58
#include "properties/SEScalarForce.h"
#include "properties/SEScalarElectricPotential.h"
#include "properties/SEScalarTime.h"
#include "properties/SEScalarPressurePerVolume.h"
#include "properties/SEScalarPower.h"
#include "properties/SEScalarTemperature.h"
#include "properties/SEScalarAmountPerVolume.h"
#include "properties/SEScalarVolumePerTimeArea.h"
#include "properties/SEScalarArea.h"
#include "properties/SEScalarPressureTimePerVolumeArea.h"
59
#include "properties/SERunningAverage.h"
60
#include "utils/DataTrack.h"
Aaron Bray's avatar
Aaron Bray committed
61

62
Cardiovascular::Cardiovascular(PulseController& data) : SECardiovascularSystem(data.GetLogger()), m_data(data)
Aaron Bray's avatar
Aaron Bray committed
63
64
{
  m_TuningFile = "";
65
66
  m_transporter = new SELiquidTransporter(VolumePerTimeUnit::mL_Per_s, VolumeUnit::mL, MassUnit::ug, MassPerVolumeUnit::ug_Per_mL, data.GetLogger());
  m_circuitCalculator = new SEFluidCircuitCalculator(FlowComplianceUnit::mL_Per_mmHg, VolumePerTimeUnit::mL_Per_s, FlowInertanceUnit::mmHg_s2_Per_mL, PressureUnit::mmHg, VolumeUnit::mL, FlowResistanceUnit::mmHg_s_Per_mL, data.GetLogger());
67
68
69
70
71
72
73
74
  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
75
  Clear();
Aaron Bray's avatar
Aaron Bray committed
76
77
78
79
80
}

Cardiovascular::~Cardiovascular()
{
  Clear();
81
82
83
84
85
86
87
88
89
90
  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
91
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_patient = nullptr;

  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
163
164
165
166
167
  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();
Aaron Bray's avatar
Aaron Bray committed
168
169
170
171
172
173
174
175
}

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

178
  m_HeartRhythm = eHeartRhythm::NormalSinus;
Aaron Bray's avatar
Aaron Bray committed
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

  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;
  m_LeftHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetLeftHeartElastanceMaximum(FlowElastanceUnit::mmHg_Per_mL);
  m_LeftHeartElastanceMin_mmHg_Per_mL = m_data.GetConfiguration().GetLeftHeartElastanceMinimum(FlowElastanceUnit::mmHg_Per_mL);
  m_LeftHeartElastanceModifier = 1.0; //Utilized for reducing the maximum elastance to represent left ventricular systolic dysfunction
  m_RightHeartElastance_mmHg_Per_mL = 0.0;
  m_RightHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetRightHeartElastanceMaximum(FlowElastanceUnit::mmHg_Per_mL);
  m_RightHeartElastanceMin_mmHg_Per_mL = m_data.GetConfiguration().GetRightHeartElastanceMinimum(FlowElastanceUnit::mmHg_Per_mL);
  
  // 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
  GetBloodVolume().Set(m_patient->GetBloodVolumeBaseline());
  m_CardiacCycleAortaPressureHigh_mmHg = m_patient->GetSystolicArterialPressureBaseline(PressureUnit::mmHg);
  m_CardiacCycleAortaPressureLow_mmHg = m_patient->GetDiastolicArterialPressureBaseline(PressureUnit::mmHg);
  GetMeanArterialPressure().SetValue((2. / 3.*m_CardiacCycleAortaPressureLow_mmHg) + (1. / 3.*m_CardiacCycleAortaPressureHigh_mmHg), PressureUnit::mmHg);
207
  m_CardiacCycleArterialPressure_mmHg->Sample(GetMeanArterialPressure().GetValue(PressureUnit::mmHg));
Aaron Bray's avatar
Aaron Bray committed
208
209
210
211
212
213
214
215
  m_CardiacCyclePulmonaryArteryPressureHigh_mmHg = 26;
  m_CardiacCyclePulmonaryArteryPressureLow_mmHg = 9;
  GetPulmonaryMeanArterialPressure().SetValue(15, PressureUnit::mmHg);
  GetHeartRate().Set(m_patient->GetHeartRateBaseline());
  RecordAndResetCardiacCycle();  
  
  // Set system data based on physiology norms
  GetMeanCentralVenousPressure().SetValue(5.0, PressureUnit::mmHg);
216
  m_CardiacCycleArterialCO2PartialPressure_mmHg->Sample(60.0);
Aaron Bray's avatar
Aaron Bray committed
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
  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);
  GetPulmonaryVascularResistance().SetValue(0.14, FlowResistanceUnit::mmHg_min_Per_mL);
  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);
  GetSystemicVascularResistance().SetValue(systemicVascularResistance_mmHg_s_Per_mL, FlowResistanceUnit::mmHg_s_Per_mL);
  // 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);
  GetSystemicVascularResistance().SetValue(systemicVascularResistance_mmHg_s_Per_mL, FlowResistanceUnit::mmHg_s_Per_mL);
  m_LeftHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetLeftHeartElastanceMaximum(FlowElastanceUnit::mmHg_Per_mL);
  m_RightHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetRightHeartElastanceMaximum(FlowElastanceUnit::mmHg_Per_mL);
}

//--------------------------------------------------------------------------------------------------
/// \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_patient = &m_data.GetPatient();
  m_minIndividialSystemicResistance__mmHg_s_Per_mL = 0.1;

  //Circuits
  m_CirculatoryCircuit = &m_data.GetCircuits().GetActiveCardiovascularCircuit();
  m_CirculatoryGraph = &m_data.GetCompartments().GetActiveCardiovascularGraph();
264
  //Compartments
Aaron Bray's avatar
Aaron Bray committed
265
  m_Aorta = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::Aorta);
Aaron Bray's avatar
Aaron Bray committed
266
  m_AortaCO2 = m_Aorta->GetSubstanceQuantity(m_data.GetSubstances().GetCO2());
Aaron Bray's avatar
Aaron Bray committed
267
  m_Brain = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::Brain);
268
  m_Groundcmpt = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::Ground);
Aaron Bray's avatar
Aaron Bray committed
269
270
271
272
273
274
275
276
277
278
  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);
279
  m_AbdominalCavity = m_data.GetCompartments().GetLiquidCompartment(pulse::VascularCompartment::AbdominalCavity);
Aaron Bray's avatar
Aaron Bray committed
280
  //Nodes
Aaron Bray's avatar
Aaron Bray committed
281
282
  m_MainPulmonaryArteries = m_CirculatoryCircuit->GetNode(pulse::CardiovascularNode::MainPulmonaryArteries);
  m_LeftHeart2 = m_CirculatoryCircuit->GetNode(pulse::CardiovascularNode::LeftHeart2);
283
  m_Ground = m_CirculatoryCircuit->GetNode(pulse::CardiovascularNode::Ground);
Aaron Bray's avatar
Aaron Bray committed
284
  //Paths
Aaron Bray's avatar
Aaron Bray committed
285
286
287
288
289
  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);

290
  m_InternalHemorrhageToAorta = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta3ToAorta1);
Aaron Bray's avatar
Aaron Bray committed
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
  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);

310
311
312
  m_pGndToAbdominalCavity = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::GroundToAbdominalCavity1);
  m_pAbdominalCavityToGnd = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::AbdominalCavity1ToGround);

Aaron Bray's avatar
Aaron Bray committed
313
314
315
316
317
318
319
  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
320
321

  /// \todo We are assuming that the complex renal system is connected. Make it agnostic.
Aaron Bray's avatar
Aaron Bray committed
322
323
  m_leftRenalArteryPath = m_CirculatoryCircuit->GetPath(pulse::RenalPath::LeftRenalArteryToAfferentArteriole);
  m_rightRenalArteryPath = m_CirculatoryCircuit->GetPath(pulse::RenalPath::RightRenalArteryToAfferentArteriole);
Aaron Bray's avatar
Aaron Bray committed
324
325
326
327

  m_systemicResistancePaths.clear();
  m_systemicCompliancePaths.clear();
  std::vector<SEFluidCircuitNode*> venousNodes;
Aaron Bray's avatar
Aaron Bray committed
328
  SEFluidCircuitNode* aorta = m_CirculatoryCircuit->GetNode(pulse::CardiovascularNode::Aorta1);
Aaron Bray's avatar
Aaron Bray committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
  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
352
  SEFluidCircuitPath* p = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::PortalVeinToLiver1);
Aaron Bray's avatar
Aaron Bray committed
353
354
  if (!Contains(m_systemicResistancePaths, (*p)))
    m_systemicResistancePaths.push_back(p);
Aaron Bray's avatar
Aaron Bray committed
355
356
357
358
  m_AortaCompliance = m_CirculatoryCircuit->GetPath(pulse::CardiovascularPath::Aorta1ToGround);
  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
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
}

//--------------------------------------------------------------------------------------------------
/// \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()
{
  m_patient->GetHeartRateBaseline().Set(GetHeartRate());
  m_patient->GetDiastolicArterialPressureBaseline().Set(GetDiastolicArterialPressure());
  m_patient->GetSystolicArterialPressureBaseline().Set(GetSystolicArterialPressure());
  m_patient->GetMeanArterialPressureBaseline().Set(GetMeanArterialPressure());

  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();
  }

  m_LeftHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetLeftHeartElastanceMaximum(FlowElastanceUnit::mmHg_Per_mL);
  m_RightHeartElastanceMax_mmHg_Per_mL = m_data.GetConfiguration().GetRightHeartElastanceMaximum(FlowElastanceUnit::mmHg_Per_mL);
}

//--------------------------------------------------------------------------------------------------
/// \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.
430
    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
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
    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())
    {
    path->GetResistanceBaseline().SetValue(path->GetResistanceBaseline(FlowResistanceUnit::mmHg_s_Per_mL)*viscousModifier, FlowResistanceUnit::mmHg_s_Per_mL);
    }   
  }
}

//--------------------------------------------------------------------------------------------------
/// \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 
494
/// are set in the Pulse engine so that life-threatening tamponade will occur 
Aaron Bray's avatar
Aaron Bray committed
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
///  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;
  }

561
  //Aorta1ToAfferentArteriole paths are equivalent to the renal artery in Pulse. Resistance increases on these paths to represent renal arterial stenosis
Aaron Bray's avatar
Aaron Bray committed
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
  double currentLeftResistance_mmHg_s_Per_mL = m_leftRenalArteryPath->GetResistanceBaseline(FlowResistanceUnit::mmHg_s_Per_mL);
  double currentRightResistance_mmHg_s_Per_mL = m_rightRenalArteryPath->GetResistanceBaseline(FlowResistanceUnit::mmHg_s_Per_mL);

  //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.
  double openResistance_mmHg_s_Per_mL = m_data.GetConfiguration().GetCardiovascularOpenResistance(FlowResistanceUnit::mmHg_s_Per_mL);

  double newLeftResistance_mmHg_s_Per_mL = GeneralMath::ResistanceFunction(baseResistance_mmHg_s_Per_mL, openResistance_mmHg_s_Per_mL, currentLeftResistance_mmHg_s_Per_mL, LeftOcclusionFraction);
  double newRightResistance_mmHg_s_Per_mL = GeneralMath::ResistanceFunction(baseResistance_mmHg_s_Per_mL, openResistance_mmHg_s_Per_mL, currentRightResistance_mmHg_s_Per_mL, RightOcclusionFraction);

  m_leftRenalArteryPath->GetResistanceBaseline().SetValue(newLeftResistance_mmHg_s_Per_mL, FlowResistanceUnit::mmHg_s_Per_mL);
  m_rightRenalArteryPath->GetResistanceBaseline().SetValue(newRightResistance_mmHg_s_Per_mL, FlowResistanceUnit::mmHg_s_Per_mL);
}

//--------------------------------------------------------------------------------------------------
/// \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();
592
  UpdateHeartRhythm();
Aaron Bray's avatar
Aaron Bray committed
593
594
595
596
597
598
599
600
601
}

//--------------------------------------------------------------------------------------------------
/// \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 
602
603
/// is solved using %Pulse @ref CircuitMethodology. Advective substance transport
/// is computed using the %Pulse @ref SubstanceTransportMethodology.
Aaron Bray's avatar
Aaron Bray committed
604
605
606
607
608
/// Finally, vitals sign data is computed and system data is populated in the 
/// CalculateVitalSigns method.
//--------------------------------------------------------------------------------------------------
void Cardiovascular::Process()
{
609
610
  m_circuitCalculator->Process(*m_CirculatoryCircuit, m_dT_s);
  m_transporter->Transport(*m_CirculatoryGraph, m_dT_s);
Aaron Bray's avatar
Aaron Bray committed
611
612
613
614
615
616
617
618
619
620
621
622
  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()
{
623
  m_circuitCalculator->PostProcess(*m_CirculatoryCircuit);
Aaron Bray's avatar
Aaron Bray committed
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
}

//--------------------------------------------------------------------------------------------------
/// \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;
700
701
702
703
704
705
706
707
  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
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

  /// \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
    if (GetBloodVolume().GetValue(VolumeUnit::mL) <= (m_data.GetConfiguration().GetMinimumBloodVolumeFraction()*m_patient->GetBloodVolumeBaseline(VolumeUnit::mL)))
    {
736
      m_patient->SetEvent(ePatient_Event::HypovolemicShock, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
737
738
739
740
741
742
743
744
745

      /// \event Patient: blood loss below 50%, irreversible state enacted 
      // @cite Gutierrez2004HemorrhagicShock
      double hypovolemicShock = 0.5*m_patient->GetBloodVolumeBaseline(VolumeUnit::mL);
      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.
746
        m_patient->SetEvent(ePatient_Event::IrreversibleState, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
747
748
749
750
      }
    }
    else
    {
751
      m_patient->SetEvent(ePatient_Event::HypovolemicShock, false, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
752
753
754
755
756
757
758
759
760
    }

    //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
761
      m_patient->SetEvent(ePatient_Event::CardiogenicShock, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
762
763
764
    }
    else
    {
765
      m_patient->SetEvent(ePatient_Event::CardiogenicShock, false, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
766
767
768
769
770
    }

    //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)
771
      m_patient->SetEvent(ePatient_Event::Tachycardia, false, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
772
    if (GetHeartRate().GetValue(FrequencyUnit::Per_min) > 100)
773
      m_patient->SetEvent(ePatient_Event::Tachycardia, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
774
775
    /// \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)
776
      m_patient->SetEvent(ePatient_Event::Bradycardia, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
777
    if (GetHeartRate().GetValue(FrequencyUnit::Per_min) > 65)
778
      m_patient->SetEvent(ePatient_Event::Bradycardia, false, m_data.GetSimulationTime());
779
    if (GetHeartRate().GetValue(FrequencyUnit::Per_min) == 0 || m_data.GetActions().GetPatientActions().HasCardiacArrest())
Aaron Bray's avatar
Aaron Bray committed
780
    {
781
      m_patient->SetEvent(ePatient_Event::Asystole, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
782
    }
783
    else
Aaron Bray's avatar
Aaron Bray committed
784
    {
785
      m_patient->SetEvent(ePatient_Event::Asystole, false, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
786
787
788
789
    }
  }

  // Irreversible state if asystole persists.
790
  if (GetHeartRhythm() == eHeartRhythm::Asystole)
Aaron Bray's avatar
Aaron Bray committed
791
792
  {
    /// \event Patient: Irreversible State: heart has been in asystole for over 45 min:
793
    if (m_patient->GetEventDuration(ePatient_Event::Asystole, TimeUnit::s) > 2700.0) // \cite: Zijlmans2002EpilepticSeizuresAsystole
Aaron Bray's avatar
Aaron Bray committed
794
    {
795
      m_ss << "Asystole has occurred for " << m_patient->GetEventDuration(ePatient_Event::Asystole, TimeUnit::s) << " seconds, patient is in irreversible state.";
Aaron Bray's avatar
Aaron Bray committed
796
797
      Warning(m_ss);
      /// \irreversible Heart has been in asystole for over 45 min
798
      m_patient->SetEvent(ePatient_Event::IrreversibleState, true, m_data.GetSimulationTime());
Aaron Bray's avatar
Aaron Bray committed
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
    }
  }

  // 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);
  GetCardiacIndex().SetValue(GetCardiacOutput().GetValue(VolumePerTimeUnit::mL_Per_min) / m_patient->GetSkinSurfaceArea(AreaUnit::m2), VolumePerTimeAreaUnit::mL_Per_min_m2);

  // Running means
  // Mean Arterial Pressure
840
  GetMeanArterialPressure().SetValue(m_CardiacCycleArterialPressure_mmHg->Value(), PressureUnit::mmHg);
841
  m_CardiacCycleArterialPressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
842
  // Mean Aterial CO2 Partial Pressure
843
  GetMeanArterialCarbonDioxidePartialPressure().SetValue(m_CardiacCycleArterialCO2PartialPressure_mmHg->Value(), PressureUnit::mmHg);
Aaron Bray's avatar
Aaron Bray committed
844
  // Mean Aterial CO2 Partial Pressure Delta
845
846
  GetMeanArterialCarbonDioxidePartialPressureDelta().SetValue(m_CardiacCycleArterialCO2PartialPressure_mmHg->Value() - m_LastCardiacCycleMeanArterialCO2PartialPressure_mmHg, PressureUnit::mmHg);
  m_LastCardiacCycleMeanArterialCO2PartialPressure_mmHg = m_CardiacCycleArterialCO2PartialPressure_mmHg->Value();
847
  m_CardiacCycleArterialCO2PartialPressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
848
  // Pulmonary Capillary Wedge Pressure
849
  GetPulmonaryCapillariesWedgePressure().SetValue(m_CardiacCyclePulmonaryCapillariesWedgePressure_mmHg->Value(), PressureUnit::mmHg);
850
  m_CardiacCyclePulmonaryCapillariesWedgePressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
851
  // Pulmonary Capillary Mean Flow
852
  GetPulmonaryMeanCapillaryFlow().SetValue(m_CardiacCyclePulmonaryCapillariesFlow_mL_Per_s->Value(), VolumePerTimeUnit::mL_Per_s);
853
  m_CardiacCyclePulmonaryCapillariesFlow_mL_Per_s->Clear();
Aaron Bray's avatar
Aaron Bray committed
854
  // Pulmonary Shunt Mean Flow
855
  GetPulmonaryMeanShuntFlow().SetValue(m_CardiacCyclePulmonaryShuntFlow_mL_Per_s->Value(), VolumePerTimeUnit::mL_Per_s);
856
  m_CardiacCyclePulmonaryShuntFlow_mL_Per_s->Clear();
Aaron Bray's avatar
Aaron Bray committed
857
  // Mean Pulmonary Artery Pressure
858
  GetPulmonaryMeanArterialPressure().SetValue(m_CardiacCyclePulmonaryArteryPressure_mmHg->Value(), PressureUnit::mmHg);
859
  m_CardiacCyclePulmonaryArteryPressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
860
  // Mean Central Venous Pressure
861
  GetMeanCentralVenousPressure().SetValue(m_CardiacCycleCentralVenousPressure_mmHg->Value(), PressureUnit::mmHg);
862
  m_CardiacCycleCentralVenousPressure_mmHg->Clear();
Aaron Bray's avatar
Aaron Bray committed
863
  // Mean Skin Flow
864
  GetMeanSkinFlow().SetValue(m_CardiacCycleSkinFlow_mL_Per_s->Value(), VolumePerTimeUnit::mL_Per_s);
865
  m_CardiacCycleSkinFlow_mL_Per_s->Clear();
Aaron Bray's avatar
Aaron Bray committed
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

  // Computed systemic Vascular Resistance
  double cardiacOutput_mL_Per_min = GetCardiacOutput().GetValue(VolumePerTimeUnit::mL_Per_s);
  double systemicVascularResistance_mmHg_s_Per_mL = 0.0;
  if (cardiacOutput_mL_Per_min > ZERO_APPROX)
    systemicVascularResistance_mmHg_s_Per_mL = (GetMeanArterialPressure().GetValue(PressureUnit::mmHg) - GetMeanCentralVenousPressure().GetValue(PressureUnit::mmHg)) / cardiacOutput_mL_Per_min;
  GetSystemicVascularResistance().SetValue(systemicVascularResistance_mmHg_s_Per_mL, FlowResistanceUnit::mmHg_s_Per_mL);

  // Computed pulmonary Vascular Resistances
  if (cardiacOutput_mL_Per_min == 0.0)
  {
    GetPulmonaryVascularResistance().SetValue(0.0, FlowResistanceUnit::mmHg_min_Per_mL);
    GetPulmonaryVascularResistanceIndex().SetValue(0.0, PressureTimePerVolumeAreaUnit::mmHg_min_Per_mL_m2);
  }
  else
  {
    GetPulmonaryVascularResistance().SetValue((m_MainPulmonaryArteries->GetNextPressure(PressureUnit::mmHg) - m_LeftHeart2->GetNextPressure(PressureUnit::mmHg)) / cardiacOutput_mL_Per_min, FlowResistanceUnit::mmHg_min_Per_mL);
    GetPulmonaryVascularResistanceIndex().SetValue(GetPulmonaryVascularResistance(FlowResistanceUnit::mmHg_min_Per_mL) / m_patient->GetSkinSurfaceArea(AreaUnit::m2), PressureTimePerVolumeAreaUnit::mmHg_min_Per_mL_m2);
  }  
  
  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);

  m_pBrainResistanceDownstream->GetNextResistance().SetValue(dsMult * m_pBrainResistanceDownstream->GetResistanceBaseline().GetValue(FlowResistanceUnit::mmHg_s_Per_mL), FlowResistanceUnit::mmHg_s_Per_mL);
  m_pBrainResistanceUpstream->GetNextResistance().SetValue(usMult * m_pBrainResistanceUpstream->GetResistanceBaseline().GetValue(FlowResistanceUnit::mmHg_s_Per_mL), FlowResistanceUnit::mmHg_s_Per_mL);
}

//--------------------------------------------------------------------------------------------------
/// \brief
/// The hemorrhage function simulates bleeding from a specified compartment
///
/// \details
949
/// The user may specify multiple bleeds across the anatomical compartments. The Model creates a 
950
951
952
/// 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
953
954
955
956
//--------------------------------------------------------------------------------------------------
void Cardiovascular::Hemorrhage()
{
  /// \todo Enforce limits and remove fatal errors.
957

958
959
960
  //Set all hemorrhage flows to zero, so:
  // - We can increment for overlapping compartments
  // - We know to remove ones that are turned off
961
  for (unsigned int hIter = 0; hIter < m_HemorrhagePaths.size(); hIter++)
962
  {
963
    m_HemorrhagePaths.at(hIter)->GetNextFlowSource().SetValue(0.0, VolumePerTimeUnit::mL_Per_s);
964
965
  }
  
Aaron Bray's avatar
Aaron Bray committed
966
  SEHemorrhage* h;
967
  double TotalLossRate_mL_Per_s = 0.0;
968
  double internal_rate_mL_Per_s = 0.0;
969
  std::vector<SEHemorrhage*> invalid_hemorrhages;
Aaron Bray's avatar
Aaron Bray committed
970
971
972
973
  const std::map <std::string, SEHemorrhage*> & hems = m_data.GetActions().GetPatientActions().GetHemorrhages();
  for (auto hem : hems)
  {
    h = hem.second;
974
    double rate_mL_Per_s = h->GetRate().GetValue(VolumePerTimeUnit::mL_Per_s);
975
976
977
978
    // Allow shorthand naming
    if(h->GetCompartment().find("Vasculature") == std::string::npos)
      h->SetCompartment(h->GetCompartment() + "Vasculature");
    SELiquidCompartment* compartment = m_data.GetCompartments().GetCardiovascularGraph().GetCompartment(h->GetCompartment());
979

980
    /// \error Error: Bleeding rate cannot exceed cardiac output
981
    if (rate_mL_Per_s > GetCardiacOutput().GetValue(VolumePerTimeUnit::mL_Per_s))
Aaron Bray's avatar
Aaron Bray committed
982
983
984
    {      
      m_ss << "Cannot have bleeding rate greater than cardiac output. \n\tCurrent cardiac output is: " << GetCardiacOutput()
        << "\n\tAnd specified bleeding rate is: " << h->GetRate();
985
986
987
      Error(m_ss);
      invalid_hemorrhages.push_back(h);
      continue;
Aaron Bray's avatar
Aaron Bray committed
988
    }
989
    /// \error Error: Bleeding rate cannot be less than zero
990
    if (rate_mL_Per_s < 0)
Aaron Bray's avatar
Aaron Bray committed
991
992
    {
      m_ss << "Cannot specify bleeding less than 0";
993
994
995
      Error(m_ss);
      invalid_hemorrhages.push_back(h);
      continue;
Aaron Bray's avatar
Aaron Bray committed
996
    }
997
    /// \error Error: Bleeding must be from a vascular compartment
998
999
    if (!compartment)
    {
1000
      m_ss << "Cannot hemorrhage from compartment "+h->GetComment()+", must be a valid vascular compartment";
For faster browsing, not all history is shown. View entire blame