-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBiogearsThread.cpp
More file actions
2026 lines (1788 loc) · 69.6 KB
/
BiogearsThread.cpp
File metadata and controls
2026 lines (1788 loc) · 69.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "BiogearsThread.h"
using namespace biogears;
namespace AMM {
class EventHandler : public SEEventHandler {
public:
// State flags
bool paralyzed = false;
bool paralyzedSent = false;
bool irreversible = false;
bool irreversibleSent = false;
bool tachypnea = false;
bool tachypneaSent = false;
bool tachycardia = false;
bool tachycardiaSent = false;
bool startOfExhale = false;
bool startOfInhale = false;
bool pneumothoraxLClosed = false;
bool pneumothoraxLClosedSent = false;
bool pneumothoraxRClosed = false;
bool pneumothoraxRClosedSent = false;
bool pneumothoraxLOpen = false;
bool pneumothoraxLOpenSent = false;
bool pneumothoraxROpen = false;
bool pneumothoraxROpenSent = false;
bool hemorrhage = false;
bool hemorrhageSent = false;
bool acuteStress = false;
bool acuteStressSent = false;
bool asthmaAttack = false;
bool asthmaAttackSent = false;
bool brainInjury = false;
bool brainInjurySent = false;
EventHandler(Logger* logger)
: SEEventHandler()
{
}
/**
* @brief log anesthesia events that are active in the BioGears physiology engine
*
* @param type is an enum event generated by BioGears
* @param active check if we are logigng
* @param time BioGears engine time, can be used for future logging
*/
virtual void HandleAnesthesiaMachineEvent(CDM::enumAnesthesiaMachineEvent::value type, bool active,
const SEScalarTime* time = nullptr) { }
virtual void HandlePatientEvent(CDM::enumPatientEvent::value type, bool active, const SEScalarTime* time = nullptr)
{
if (active) {
switch (type) {
case CDM::enumPatientEvent::IrreversibleState:
LOG_INFO << " Patient has entered irreversible state.";
irreversible = true;
break;
case CDM::enumPatientEvent::Tachypnea:
LOG_INFO << " Patient has entered state: Tachypnea.";
tachypnea = true;
break;
case CDM::enumPatientEvent::Tachycardia:
LOG_INFO << " Patient has entered state: Tachycardia.";
tachycardia = true;
break;
case CDM::enumPatientEvent::StartOfCardiacCycle:
break;
case CDM::enumPatientEvent::StartOfExhale:
startOfExhale = true;
startOfInhale = false;
break;
case CDM::enumPatientEvent::StartOfInhale:
startOfInhale = true;
startOfExhale = false;
break;
default:
LOG_INFO << " Patient has entered state : " << type;
break;
}
} else {
switch (type) {
case CDM::enumPatientEvent::StartOfCardiacCycle:
break;
case CDM::enumPatientEvent::StartOfExhale:
startOfExhale = false;
break;
case CDM::enumPatientEvent::StartOfInhale:
startOfInhale = false;
break;
default:
LOG_INFO << " Patient has exited state : " << type;
break;
}
}
}
};
std::vector<std::string> BiogearsThread::highFrequencyNodes;
std::map<std::string, double (BiogearsThread::*)()> BiogearsThread::nodePathTable;
/**
* @brief Construct a new Biogears Thread:: Biogears Thread object
*
* @param logFile biogears log file
*/
BiogearsThread::BiogearsThread(const std::string& logFile)
{
try {
m_pe = std::make_unique<BioGearsEngine>("biogears.log");
bg = dynamic_cast<BioGears*>(m_pe.get());
} catch (std::exception& e) {
LOG_ERROR << "Error starting engine: " << e.what();
}
PopulateNodePathTable();
running = false;
}
/**
* @brief Destroy the Biogears Thread:: Biogears Thread object
*
*/
BiogearsThread::~BiogearsThread()
{
running = false;
m_pe = nullptr;
bg = nullptr;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
/**
* @brief set up the map that associates string to biogears data
*
*/
void BiogearsThread::PopulateNodePathTable()
{
highFrequencyNodes.clear();
nodePathTable.clear();
// Legacy values
nodePathTable["ECG"] = &BiogearsThread::GetECGWaveform;
nodePathTable["HR"] = &BiogearsThread::GetHeartRate;
nodePathTable["PATIENT_TIME"] = &BiogearsThread::GetPatientTime;
nodePathTable["SIM_TIME"] = &BiogearsThread::GetSimulationTime;
nodePathTable["LOGGING_STATUS"] = &BiogearsThread::GetLoggingStatus;
nodePathTable["Patient_Age"] = &BiogearsThread::GetPatientAge;
nodePathTable["Patient_Weight"] = &BiogearsThread::GetPatientWeight;
nodePathTable["Patient_Gender"] = &BiogearsThread::GetPatientGender;
nodePathTable["Patient_Height"] = &BiogearsThread::GetPatientHeight;
nodePathTable["Patient_BodyFatFraction"] = &BiogearsThread::GetPatient_BodyFatFraction;
nodePathTable["GCS_Value"] = &BiogearsThread::GetGCSValue;
nodePathTable["IntracranialPressure"] = &BiogearsThread::GetIntracranialPressure;
nodePathTable["CerebralPerfusionPressure"] = &BiogearsThread::GetCerebralPerfusionPressure;
nodePathTable["CerebralBloodFlow"] = &BiogearsThread::GetCerebralBloodFlow;
// Cardiovascular System
nodePathTable["Cardiovascular_HeartRate"] = &BiogearsThread::GetHeartRate;
nodePathTable["Cardiovascular_BloodVolume"] = &BiogearsThread::GetBloodVolume;
nodePathTable["Cardiovascular_BloodLossPercentage"] = &BiogearsThread::GetBloodLossPercentage;
nodePathTable["Cardiovascular_Arterial_Pressure"] = &BiogearsThread::GetArterialPressure;
nodePathTable["Cardiovascular_Arterial_Mean_Pressure"] = &BiogearsThread::GetMeanArterialPressure;
nodePathTable["Cardiovascular_Arterial_Systolic_Pressure"] = &BiogearsThread::GetArterialSystolicPressure;
nodePathTable["Cardiovascular_Arterial_Diastolic_Pressure"] = &BiogearsThread::GetArterialDiastolicPressure;
nodePathTable["Cardiovascular_CentralVenous_Mean_Pressure"] = &BiogearsThread::GetMeanCentralVenousPressure;
nodePathTable["Cardiovascular_CardiacOutput"] = &BiogearsThread::GetCardiacOutput;
// Respiratory System
nodePathTable["Respiratory_Respiration_Rate_RAW"] = &BiogearsThread::GetRawRespirationRate;
nodePathTable["Respiratory_Respiration_Rate_MOD"] = &BiogearsThread::GetRespirationRate;
nodePathTable["Respiratory_Respiration_Rate"] = &BiogearsThread::GetRawRespirationRate;
nodePathTable["Respiratory_Inspiratory_Flow"] = &BiogearsThread::GetInspiratoryFlow;
nodePathTable["Respiratory_TotalPressure"] = &BiogearsThread::GetRespiratoryTotalPressure;
nodePathTable["Respiration_EndTidalCarbonDioxide"] = &BiogearsThread::GetEndTidalCarbonDioxidePressure;
nodePathTable["Respiration_EndTidalCarbonDioxideFraction"] = &BiogearsThread::GetEndTidalCarbonDioxideFraction;
nodePathTable["Respiratory_Tidal_Volume"] = &BiogearsThread::GetTidalVolume;
nodePathTable["Respiratory_LungTotal_Volume"] = &BiogearsThread::GetTotalLungVolume;
nodePathTable["Respiratory_LeftPleuralCavity_Volume"] = &BiogearsThread::GetLeftPleuralCavityVolume;
nodePathTable["Respiratory_LeftLung_Volume"] = &BiogearsThread::GetLeftLungVolume;
nodePathTable["Respiratory_LeftAlveoli_BaseCompliance"] = &BiogearsThread::GetLeftAlveoliBaselineCompliance;
nodePathTable["Respiratory_RightPleuralCavity_Volume"] = &BiogearsThread::GetRightPleuralCavityVolume;
nodePathTable["Respiratory_RightLung_Volume"] = &BiogearsThread::GetRightLungVolume;
nodePathTable["Respiratory_LeftLung_Tidal_Volume"] = &BiogearsThread::GetLeftLungTidalVolume;
nodePathTable["Respiratory_RightLung_Tidal_Volume"] = &BiogearsThread::GetRightLungTidalVolume;
nodePathTable["Respiratory_PulmonaryResistance"] = &BiogearsThread::GetPulmonaryResistance;
nodePathTable["Respiratory_RightAlveoli_BaseCompliance"] = &BiogearsThread::GetRightAlveoliBaselineCompliance;
nodePathTable["Respiratory_CarbonDioxide_Exhaled"] = &BiogearsThread::GetExhaledCO2;
// Energy system
nodePathTable["Energy_Core_Temperature"] = &BiogearsThread::GetCoreTemperature;
// Nervous
nodePathTable["Nervous_GetPainVisualAnalogueScale"] = &BiogearsThread::GetPainVisualAnalogueScale;
// Blood chemistry system
nodePathTable["BloodChemistry_WhiteBloodCell_Count"] = &BiogearsThread::GetWhiteBloodCellCount;
nodePathTable["BloodChemistry_RedBloodCell_Count"] = &BiogearsThread::GetRedBloodCellCount;
nodePathTable["BloodChemistry_BloodUreaNitrogen_Concentration"] = &BiogearsThread::GetBUN;
nodePathTable["BloodChemistry_Oxygen_Saturation"] = &BiogearsThread::GetOxygenSaturation;
nodePathTable["BloodChemistry_CarbonMonoxide_Saturation"] = &BiogearsThread::GetCarbonMonoxideSaturation;
nodePathTable["BloodChemistry_Hemaocrit"] = &BiogearsThread::GetHematocrit;
nodePathTable["BloodChemistry_BloodPH_RAW"] = &BiogearsThread::GetRawBloodPH;
nodePathTable["BloodChemistry_BloodPH_MOD"] = &BiogearsThread::GetModBloodPH;
nodePathTable["BloodChemistry_BloodPH"] = &BiogearsThread::GetModBloodPH;
nodePathTable["BloodChemistry_Arterial_CarbonDioxide_Pressure"] = &BiogearsThread::GetArterialCarbonDioxidePressure;
nodePathTable["BloodChemistry_Arterial_Oxygen_Pressure"] = &BiogearsThread::GetArterialOxygenPressure;
nodePathTable["BloodChemistry_VenousOxygenPressure"] = &BiogearsThread::GetVenousOxygenPressure;
nodePathTable["BloodChemistry_VenousCarbonDioxidePressure"] = &BiogearsThread::GetVenousCarbonDioxidePressure;
// Substances
nodePathTable["Substance_Sodium"] = &BiogearsThread::GetSodium;
nodePathTable["Substance_Sodium_Concentration"] = &BiogearsThread::GetSodiumConcentration;
nodePathTable["Substance_Bicarbonate"] = &BiogearsThread::GetBicarbonate;
nodePathTable["Substance_Bicarbonate_Concentration"] = &BiogearsThread::GetBicarbonateConcentration;
nodePathTable["Substance_BaseExcess"] = &BiogearsThread::GetBaseExcess;
nodePathTable["Substance_BaseExcess_RAW"] = &BiogearsThread::GetBaseExcessRaw;
nodePathTable["Substance_Bicarbonate_RAW"] = &BiogearsThread::GetBicarbonateRaw;
nodePathTable["Substance_Glucose_Concentration"] = &BiogearsThread::GetGlucoseConcentration;
nodePathTable["Substance_Creatinine_Concentration"] = &BiogearsThread::GetCreatinineConcentration;
nodePathTable["Substance_Hemoglobin_Concentration"] = &BiogearsThread::GetHemoglobinConcentration;
nodePathTable["Substance_Oxyhemoglobin_Concentration"] = &BiogearsThread::GetOxyhemoglobinConcentration;
nodePathTable["Substance_Carbaminohemoglobin_Concentration"] = &BiogearsThread::GetCarbaminohemoglobinConcentration;
nodePathTable["Substance_OxyCarbaminohemoglobin_Concentration"] = &BiogearsThread::GetOxyCarbaminohemoglobinConcentration;
nodePathTable["Substance_Carboxyhemoglobin_Concentration"] = &BiogearsThread::GetCarboxyhemoglobinConcentration;
nodePathTable["Anion_Gap"] = &BiogearsThread::GetAnionGap;
nodePathTable["Substance_Ionized_Calcium"] = &BiogearsThread::GetIonizedCalcium;
nodePathTable["Substance_Calcium_Concentration"] = &BiogearsThread::GetCalciumConcentration;
nodePathTable["Substance_Albumin_Concentration"] = &BiogearsThread::GetAlbuminConcentration;
nodePathTable["Substance_Lactate_Concentration"] = &BiogearsThread::GetLactateConcentration;
nodePathTable["Substance_Lactate_Concentration_mmol"] = &BiogearsThread::GetLactateConcentrationMMOL;
nodePathTable["MetabolicPanel_Bilirubin"] = &BiogearsThread::GetTotalBilirubin;
nodePathTable["MetabolicPanel_Protein"] = &BiogearsThread::GetTotalProtein;
nodePathTable["MetabolicPanel_CarbonDioxide"] = &BiogearsThread::GetCO2;
nodePathTable["MetabolicPanel_Potassium"] = &BiogearsThread::GetPotassium;
nodePathTable["MetabolicPanel_Chloride"] = &BiogearsThread::GetChloride;
nodePathTable["CompleteBloodCount_Platelet"] = &BiogearsThread::GetPlateletCount;
nodePathTable["Renal_UrineProductionRate"] = &BiogearsThread::GetUrineProductionRate;
nodePathTable["Urinalysis_SpecificGravity"] = &BiogearsThread::GetUrineSpecificGravity;
nodePathTable["Renal_UrineOsmolality"] = &BiogearsThread::GetUrineOsmolality;
nodePathTable["Renal_UrineOsmolarity"] = &BiogearsThread::GetUrineOsmolarity;
nodePathTable["Renal_BladderGlucose"] = &BiogearsThread::GetBladderGlucose;
nodePathTable["ShuntFraction"] = &BiogearsThread::GetShuntFraction;
// Label which nodes are high-frequency
highFrequencyNodes = { "ECG",
"Cardiovascular_HeartRate",
"Respiratory_TotalPressure",
"Respiratory_Inspiratory_Flow",
"Cardiovascular_Arterial_Pressure",
"Respiratory_CarbonDioxide_Exhaled",
"Respiratory_LungTotal_Volume",
"Respiratory_Respiration_Rate" };
}
/**
* @brief return 1 or 0 if logging is enabled or disabled
*
* @return double value changes based upon logging status
*/
double BiogearsThread::GetLoggingStatus()
{
if (logging_enabled) {
return double(1);
} else {
return double(0);
}
}
std::map<std::string, double (BiogearsThread::*)()>* BiogearsThread::GetNodePathTable()
{
return &nodePathTable;
}
void BiogearsThread::Shutdown()
{
}
void BiogearsThread::StartSimulation()
{
if (!running) {
running = true;
}
}
void BiogearsThread::StopSimulation()
{
if (running) {
running = false;
}
}
/**
* @brief loads a specific patient file into biogears also gets all the substance objects, initializes data tracks if logging is enabled
* and event handeler
*
* @param patientFile a string (biogears compliant) patient file
* @return true if engine is able to initialize with patient file and all objects/data is created successfully
* @return false if engine doesn't load
*/
bool BiogearsThread::LoadPatient(const std::string& patientFile)
{
if (m_pe == nullptr) {
LOG_ERROR << "Unable to load state, Biogears has not been initialized.";
return false;
}
LOG_INFO << "Loading patient file " << patientFile;
m_mutex.lock();
try {
if (!m_pe->InitializeEngine(patientFile)) {
LOG_ERROR << "Error loading patient";
m_mutex.unlock();
return false;
}
} catch (std::exception& e) {
LOG_ERROR << "Exception loading patient: " << e.what();
m_mutex.unlock();
return false;
}
m_mutex.unlock();
// preload substances
if (InitializeBioGearsSubstances()) {
LOG_DEBUG << "Preloading substances";
}
// logging
if (BioGearsLogging()) {
LOG_DEBUG << "Set up logging";
}
try {
LOG_DEBUG << "Attaching event handler";
myEventHandler = new EventHandler(m_pe->GetLogger());
m_pe->SetEventHandler(myEventHandler);
} catch (std::exception& e) {
LOG_ERROR << "Error attaching event handler: " << e.what();
}
return true;
}
/**
* @brief load a biogears state and check for active actions, also set all substance objects, datarequests (if logging)
* and create an event handeler
*
* @param stateFile string for the name of the biogears compliant state file
* @param sec simulation time
* @return true if biogears an all objects/data are initialized properly
* @return false if not
*/
bool BiogearsThread::LoadState(const std::string& stateFile, double sec)
{
if (m_pe == nullptr) {
LOG_ERROR << "Unable to load state, Biogears has not been initialized.";
return false;
}
LOG_INFO << "We have created our patient action object";
auto* startTime = new biogears::SEScalarTime();
startTime->SetValue(sec, biogears::TimeUnit::s);
LOG_INFO << "Loading state file " << stateFile << " at position " << sec << " seconds";
m_mutex.lock();
try {
if (!m_pe->LoadState(stateFile, startTime)) {
LOG_ERROR << "Error loading state";
m_mutex.unlock();
return false;
}
} catch (std::exception& e) {
LOG_ERROR << "Exception loading state: " << e.what();
m_mutex.unlock();
return false;
}
m_mutex.unlock();
auto& patientactions = bg->GetActions().GetPatientActions();
// check for actions and send appropriate render mods
LOG_INFO << "Iterating over action data";
m_mutex.lock();
// get state data
///\todo: add other actions to this and determine how to handle mild/moderate/severe cases separately
// PNEUMOTHORAX
pneumothoraxLClosed = patientactions.HasLeftClosedTensionPneumothorax();
pneumothoraxLOpen = patientactions.HasLeftOpenTensionPneumothorax();
pneumothoraxRClosed = patientactions.HasRightClosedTensionPneumothorax();
pneumothoraxROpen = patientactions.HasRightOpenTensionPneumothorax();
hemorrhage = patientactions.HasHemorrhage();
acuteStress = patientactions.HasAcuteStress();
asthmaAttack = patientactions.HasAsthmaAttack();
brainInjury = patientactions.HasBrainInjury();
m_mutex.unlock();
// preload substances
if (InitializeBioGearsSubstances()) {
LOG_DEBUG << "Preloading substances";
}
// logging
if (BioGearsLogging()) {
LOG_DEBUG << "Set up logging";
}
try {
LOG_DEBUG << "Attaching event handler";
myEventHandler = new EventHandler(m_pe->GetLogger());
m_pe->SetEventHandler(myEventHandler);
} catch (std::exception& e) {
LOG_ERROR << "Error attaching event handler: " << e.what();
}
return true;
}
/**
* @brief save a biogears state of the patient
*
* @param stateFile name of the state file
* @return true if successful
* @return false if biogears is a nullptr (not initialized)
*/
bool BiogearsThread::SaveState(const std::string& stateFile)
{
if (m_pe == nullptr) {
LOG_ERROR << "Unable to save state, Biogears has not been initialized.";
return false;
}
m_mutex.lock();
m_pe->SaveStateToFile(stateFile);
// m_pe->SaveState(stateFile);
m_mutex.unlock();
return true;
}
// bool BiogearsThread::Execute(std::function<std::unique_ptr<biogears::PhysiologyEngine>(
// std::unique_ptr<biogears::PhysiologyEngine>&&)>
// func)
// {
// m_pe = func(std::move(m_pe));
// return true;
// }
void BiogearsThread::SetLastFrame(int lF)
{
lastFrame = lF;
}
void BiogearsThread::SetLogging(bool log)
{
logging_enabled = log;
}
bool BiogearsThread::ExecuteXMLCommand(const std::string& cmd)
{
char* tmpname = strdup("/tmp/tmp_amm_xml_XXXXXX");
std::ofstream out(tmpname);
if (out.is_open()) {
out << cmd;
out.close();
if (!LoadScenarioFile(tmpname)) {
LOG_ERROR << "Unable to load scenario file from temp.";
return false;
} else {
return true;
}
} else {
LOG_ERROR << "Unable to open file.";
}
return true;
}
bool file_exists(const char* fileName)
{
std::ifstream infile(fileName);
return infile.good();
}
/**
* @brief Load a scenario from an XML file, apply conditions and iterate through the actions
* his bypasses the standard BioGears ExecuteScenario method to avoid resetting the BioGears
*
* @param scenarioFile is a string name of a biogears-compliant scenario
* @return true if successful
* @return false if not
*/
bool BiogearsThread::LoadScenarioFile(const std::string& scenarioFile)
{
if (m_pe == nullptr) {
LOG_ERROR << "Unable to load scenario, Biogears has not been initialized.";
return false;
}
if (!file_exists(scenarioFile.c_str())) {
LOG_WARNING << "Scenario/action file does not exist: " << scenarioFile;
return false;
}
biogears::SEScenario sce(m_pe->GetSubstanceManager());
sce.Load(scenarioFile);
if (scenarioLoading) {
if (sce.HasEngineStateFile()) {
if (!m_pe->LoadState(sce.GetEngineStateFile())) {
LOG_ERROR << "Unable to load state file.";
return false;
}
} else if (sce.HasInitialParameters()) {
SEScenarioInitialParameters& sip = sce.GetInitialParameters();
if (sip.HasPatientFile()) {
std::vector<const SECondition*> conditions;
for (SECondition* c : sip.GetConditions())
conditions.push_back(c); // Copy to const
if (!m_pe->InitializeEngine(sip.GetPatientFile(), &conditions, &sip.GetConfiguration())) {
LOG_ERROR << "Unable to load patient file.";
return false;
}
} else if (sip.HasPatient()) {
std::vector<const SECondition*> conditions;
for (SECondition* c : sip.GetConditions())
conditions.push_back(c); // Copy to const
if (!m_pe->InitializeEngine(sip.GetPatient(), &conditions, &sip.GetConfiguration())) {
LOG_ERROR << "Unable to load conditions.";
return false;
}
}
}
// preload substances
if (InitializeBioGearsSubstances()) {
LOG_DEBUG << "Preloading substances";
}
// logging
if (BioGearsLogging()) {
LOG_DEBUG << "Set up logging";
}
try {
LOG_DEBUG << "Attaching event handler";
myEventHandler = new EventHandler(m_pe->GetLogger());
m_pe->SetEventHandler(myEventHandler);
} catch (std::exception& e) {
LOG_ERROR << "Error attaching event handler: " << e.what();
}
scenarioLoading = false;
}
LOG_INFO << "Executing actions";
SEAdvanceTime* adv;
// Now run the scenario actions
for (SEAction* a : sce.GetActions()) {
adv = dynamic_cast<SEAdvanceTime*>(a);
if (adv != nullptr) {
m_mutex.lock();
try {
auto begin = std::chrono::high_resolution_clock::now();
LOG_INFO << "Simulating " << adv->GetTime(TimeUnit::s) << " seconds...";
m_pe->AdvanceModelTime(adv->GetTime(TimeUnit::s), TimeUnit::s);
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
LOG_INFO << "Done simulating time advancement. Simulated " << adv->GetTime(TimeUnit::s) << "s in "
<< elapsed.count() * 1e-9 << "s.";
} catch (std::exception& e) {
LOG_ERROR << "Error advancing time: " << e.what();
}
m_mutex.unlock();
} else {
m_mutex.lock();
try {
if (!m_pe->ProcessAction(*a)) {
LOG_ERROR << "Unable to process action.";
}
} catch (std::exception& e) {
LOG_ERROR << "Error processing action: " << e.what();
}
m_mutex.unlock();
}
}
LOG_INFO << "Done loading scenario and executing actions.";
return true;
}
/**
* @brief advance BioGears by 1 time step, check events
*
*/
void BiogearsThread::AdvanceTimeTick()
{
if (m_pe == nullptr) {
LOG_ERROR << "Unable to advance time, Biogears has not been initialized.";
return;
}
if (!running) {
LOG_ERROR << "Cannot advance time, simulation is not running.";
return;
}
if (myEventHandler != nullptr) {
if (myEventHandler->irreversible && !irreversible) {
irreversible = true;
}
tachypnea = myEventHandler->tachypnea;
tachycardia = myEventHandler->tachycardia;
startOfInhale = myEventHandler->startOfInhale;
startOfExhale = myEventHandler->startOfExhale;
}
m_mutex.lock();
try {
m_pe->AdvanceModelTime();
if (logging_enabled) {
if ((lastFrame % loggingFrequency) == 0) {
m_pe->GetEngineTrack()->TrackData(m_pe->GetSimulationTime(biogears::TimeUnit::s));
}
}
} catch (std::exception& e) {
LOG_ERROR << "Error advancing time: " << e.what();
}
m_mutex.unlock();
}
/**
* @brief set biogears substances and compartments used in the thread
*
* @return true if successful
* @return false if the physioogy engine isnt running
*/
bool BiogearsThread::InitializeBioGearsSubstances()
{
if (m_pe == nullptr) {
LOG_ERROR << "Physiology engine is not running";
return false;
}
m_mutex.lock();
sodium = m_pe->GetSubstanceManager().GetSubstance("Sodium");
glucose = m_pe->GetSubstanceManager().GetSubstance("Glucose");
creatinine = m_pe->GetSubstanceManager().GetSubstance("Creatinine");
calcium = m_pe->GetSubstanceManager().GetSubstance("Calcium");
bicarbonate = m_pe->GetSubstanceManager().GetSubstance("Bicarbonate");
albumin = m_pe->GetSubstanceManager().GetSubstance("Albumin");
CO2 = m_pe->GetSubstanceManager().GetSubstance("CarbonDioxide");
N2 = m_pe->GetSubstanceManager().GetSubstance("Nitrogen");
O2 = m_pe->GetSubstanceManager().GetSubstance("Oxygen");
CO = m_pe->GetSubstanceManager().GetSubstance("CarbonMonoxide");
Hb = m_pe->GetSubstanceManager().GetSubstance("Hemoglobin");
HbO2 = m_pe->GetSubstanceManager().GetSubstance("Oxyhemoglobin");
HbCO2 = m_pe->GetSubstanceManager().GetSubstance("Carbaminohemoglobin");
HbCO = m_pe->GetSubstanceManager().GetSubstance("Carboxyhemoglobin");
HbO2CO2 = m_pe->GetSubstanceManager().GetSubstance("OxyCarbaminohemoglobin");
potassium = m_pe->GetSubstanceManager().GetSubstance("Potassium");
chloride = m_pe->GetSubstanceManager().GetSubstance("Chloride");
lactate = m_pe->GetSubstanceManager().GetSubstance("Lactate");
// preload compartments
carina = m_pe->GetCompartments().GetGasCompartment(BGE::PulmonaryCompartment::Trachea);
leftLung = m_pe->GetCompartments().GetGasCompartment(BGE::PulmonaryCompartment::LeftLung);
rightLung = m_pe->GetCompartments().GetGasCompartment(BGE::PulmonaryCompartment::RightLung);
bladder = m_pe->GetCompartments().GetLiquidCompartment(BGE::UrineCompartment::Bladder);
startingBloodVolume = m_pe->GetCardiovascularSystem()->GetBloodVolume(biogears::VolumeUnit::mL);
currentBloodVolume = startingBloodVolume;
m_mutex.unlock();
return true;
}
/**
* @brief set up csv file for logging, uses a generic collection of data requests
*
* @return true if successful
* @return false if logging is not enabled
*/
bool BiogearsThread::BioGearsLogging()
{
if (!logging_enabled) {
return false;
}
std::string logFilename = Utility::getTimestampedFilename("./logs/AMM_Output_", ".csv");
LOG_INFO << "Initializing log file: " << logFilename;
std::fstream fs;
fs.open(logFilename, std::ios::out);
fs.close();
m_pe->GetEngineTrack()->GetDataRequestManager().Clear();
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"HeartRate", biogears::FrequencyUnit::Per_min);
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"MeanArterialPressure", biogears::PressureUnit::mmHg);
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"SystolicArterialPressure", biogears::PressureUnit::mmHg);
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"DiastolicArterialPressure", biogears::PressureUnit::mmHg);
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"RespirationRate", biogears::FrequencyUnit::Per_min);
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"TidalVolume", biogears::VolumeUnit::mL);
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"TotalLungVolume", biogears::VolumeUnit::mL);
m_pe->GetEngineTrack()->GetDataRequestManager().CreateGasCompartmentDataRequest().Set(
BGE::PulmonaryCompartment::LeftLung, "Volume");
m_pe->GetEngineTrack()->GetDataRequestManager().CreateGasCompartmentDataRequest().Set(
BGE::PulmonaryCompartment::RightLung, "Volume");
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"OxygenSaturation");
m_pe->GetEngineTrack()->GetDataRequestManager().CreateGasCompartmentDataRequest().Set(
BGE::PulmonaryCompartment::Trachea, "InFlow");
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"BloodVolume", biogears::VolumeUnit::mL);
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"ArterialBloodPH");
m_pe->GetEngineTrack()->GetDataRequestManager().CreateSubstanceDataRequest().Set(
*lactate, "BloodConcentration", biogears::MassPerVolumeUnit::ug_Per_mL);
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"UrineProductionRate", biogears::VolumePerTimeUnit::mL_Per_min);
m_pe->GetEngineTrack()->GetDataRequestManager().CreateGasCompartmentDataRequest().Set(
BGE::PulmonaryCompartment::Trachea, *O2, "PartialPressure");
m_pe->GetEngineTrack()->GetDataRequestManager().CreateGasCompartmentDataRequest().Set(
BGE::PulmonaryCompartment::Trachea, *CO2, "PartialPressure");
m_pe->GetEngineTrack()->GetDataRequestManager().CreateGasCompartmentDataRequest().Set(
BGE::PulmonaryCompartment::Trachea, "Pressure", biogears::PressureUnit::cmH2O);
m_pe->GetEngineTrack()->GetDataRequestManager().CreatePhysiologyDataRequest().Set(
"BaseExcess", biogears::AmountPerVolumeUnit::mmol_Per_L);
m_pe->GetEngineTrack()->GetDataRequestManager().SetResultsFilename(logFilename);
return true;
}
/**
* @brief can manage shutsdown
*
* @return double
*/
double BiogearsThread::GetShutdownMessage()
{
return -1;
}
/**
* @brief return the simulation time (not biogears)
*
* @return double
*/
double BiogearsThread::GetSimulationTime()
{
return (double)lastFrame / (double)50;
}
/**
* @brief return the biogears simulation time (not returning)
*
* @todo why is this not returning the patient time
* @return double
*/
double BiogearsThread::GetPatientTime()
{
return 0.0;
// return m_pe->GetSimulationTime(biogears::TimeUnit::s);
}
/**
* @brief find a specific value from the nodepath table
*
* @param nodePath string of the value you want
* @return double return a double of the string name
*/
double BiogearsThread::GetNodePath(const std::string& nodePath)
{
std::map<std::string, double (BiogearsThread::*)()>::iterator entry;
entry = nodePathTable.find(nodePath);
if (entry != nodePathTable.end()) {
return (this->*(entry->second))();
}
LOG_ERROR << "Unable to access nodepath " << nodePath;
return 0;
}
double BiogearsThread::GetBloodVolume()
{
currentBloodVolume = m_pe->GetCardiovascularSystem()->GetBloodVolume(biogears::VolumeUnit::mL);
return currentBloodVolume;
}
double BiogearsThread::GetBloodLossPercentage()
{
double loss = (startingBloodVolume - currentBloodVolume) / startingBloodVolume;
return loss;
}
double BiogearsThread::GetHeartRate()
{
return m_pe->GetCardiovascularSystem()->GetHeartRate(biogears::FrequencyUnit::Per_min);
}
// SYS (ART) - Arterial Systolic Pressure - mmHg
double BiogearsThread::GetArterialSystolicPressure()
{
return m_pe->GetCardiovascularSystem()->GetSystolicArterialPressure(
biogears::PressureUnit::mmHg);
}
// DIA (ART) - Arterial Diastolic Pressure - mmHg
double BiogearsThread::GetArterialDiastolicPressure()
{
return m_pe->GetCardiovascularSystem()->GetDiastolicArterialPressure(
biogears::PressureUnit::mmHg);
}
// MAP (ART) - Mean Arterial Pressure - mmHg
double BiogearsThread::GetMeanArterialPressure()
{
return m_pe->GetCardiovascularSystem()->GetMeanArterialPressure(biogears::PressureUnit::mmHg);
}
// AP - Arterial Pressure - mmHg
double BiogearsThread::GetArterialPressure()
{
return m_pe->GetCardiovascularSystem()->GetArterialPressure(biogears::PressureUnit::mmHg);
}
// CVP - Central Venous Pressure - mmHg
double BiogearsThread::GetMeanCentralVenousPressure()
{
return m_pe->GetCardiovascularSystem()->GetMeanCentralVenousPressure(
biogears::PressureUnit::mmHg);
}
// MCO2 - End Tidal Carbon Dioxide Fraction - unitless % roughly scaled to mmHg
double BiogearsThread::GetEndTidalCarbonDioxideFraction()
{
return (m_pe->GetRespiratorySystem()->GetEndTidalCarbonDioxideFraction() * 762);
}
// EtCO2 - End-Tidal Carbon Dioxide - mmHg
double BiogearsThread::GetEndTidalCarbonDioxidePressure()
{
return m_pe->GetRespiratorySystem()->GetEndTidalCarbonDioxidePressure(biogears::PressureUnit::mmHg);
}
// SPO2 - Oxygen Saturation - unitless %
double BiogearsThread::GetOxygenSaturation()
{
return m_pe->GetBloodChemistrySystem()->GetOxygenSaturation() * 100;
}
double BiogearsThread::GetCarbonMonoxideSaturation()
{
return m_pe->GetBloodChemistrySystem()->GetCarbonMonoxideSaturation() * 100;
}
double BiogearsThread::GetInspiratoryFlow()
{
return m_pe->GetRespiratorySystem()->GetInspiratoryFlow(biogears::VolumePerTimeUnit::L_Per_min);
}
double BiogearsThread::GetRespiratoryTotalPressure()
{
return carina->GetSubstanceQuantity(*CO2)->GetPartialPressure(biogears::PressureUnit::cmH2O);
}
double BiogearsThread::GetPulmonaryResistance()
{
return m_pe->GetRespiratorySystem()->GetPulmonaryResistance(biogears::FlowResistanceUnit::cmH2O_s_Per_L);
}
double BiogearsThread::GetRawRespirationRate()
{
rawRespirationRate = m_pe->GetRespiratorySystem()->GetRespirationRate(biogears::FrequencyUnit::Per_min);
return rawRespirationRate;
}
// BR - Respiration Rate - per minute
double BiogearsThread::GetRespirationRate()
{
double rr;
double loss = GetBloodLossPercentage();
if (m_pe->GetAnesthesiaMachine()->HasConnection() && m_pe->GetAnesthesiaMachine()->GetConnection() != CDM::enumAnesthesiaMachineConnection::Off) {
rr = rawRespirationRate;
} else if (loss > 0.0) {
rr = rawRespirationRate * (1 + 3 * std::max(0.0, loss - 0.2));
} else {
rr = rawRespirationRate;
}
return rr;
}
// T2 - Core Temperature - degrees C
double BiogearsThread::GetCoreTemperature()
{
return m_pe->GetEnergySystem()->GetCoreTemperature(biogears::TemperatureUnit::C);
}
// ECG Waveform in mV
double BiogearsThread::GetECGWaveform()
{
double ecgLead3_mV = m_pe->GetElectroCardioGram()->GetLead3ElectricPotential(
biogears::ElectricPotentialUnit::mV);
return ecgLead3_mV;
}
double BiogearsThread::GetOxyhemoglobinConcentration()
{
return HbO2->GetBloodConcentration(biogears::MassPerVolumeUnit::g_Per_dL);
}
double BiogearsThread::GetCarbaminohemoglobinConcentration()
{
return HbCO2->GetBloodConcentration(biogears::MassPerVolumeUnit::g_Per_dL);
}
double BiogearsThread::GetOxyCarbaminohemoglobinConcentration()
{
return HbO2CO2->GetBloodConcentration(biogears::MassPerVolumeUnit::g_Per_dL);
}
double BiogearsThread::GetCarboxyhemoglobinConcentration()
{
return HbCO->GetBloodConcentration(biogears::MassPerVolumeUnit::g_Per_dL);
}
double BiogearsThread::GetAnionGap()
{
return GetSodium() - (GetChloride() + GetBicarbonate());
}
// Na+ - Sodium Concentration - mg/dL
double BiogearsThread::GetSodiumConcentration()
{
return sodium->GetBloodConcentration(biogears::MassPerVolumeUnit::mg_Per_dL);
}
// Na+ - Sodium - mmol/L
double BiogearsThread::GetSodium()
{
return GetSodiumConcentration() * 0.43;
}
// Glucose - Glucose Concentration - mg/dL
double BiogearsThread::GetGlucoseConcentration()
{
return glucose->GetBloodConcentration(biogears::MassPerVolumeUnit::mg_Per_dL);
}
// BUN - BloodUreaNitrogenConcentration - mg/dL
double BiogearsThread::GetBUN()
{
return m_pe->GetBloodChemistrySystem()->GetBloodUreaNitrogenConcentration(
biogears::MassPerVolumeUnit::mg_Per_dL);
}
// Creatinine - Creatinine Concentration - mg/dL
double BiogearsThread::GetCreatinineConcentration()
{
return creatinine->GetBloodConcentration(biogears::MassPerVolumeUnit::mg_Per_dL);
}
double BiogearsThread::GetCalciumConcentration()
{
return calcium->GetBloodConcentration(biogears::MassPerVolumeUnit::mg_Per_dL);
}
double BiogearsThread::GetIonizedCalcium()
{
double c1 = calcium->GetBloodConcentration(biogears::MassPerVolumeUnit::mg_Per_dL);
return 0.45 * 0.2495 * c1;
}
double BiogearsThread::GetAlbuminConcentration()
{
return albumin->GetBloodConcentration(biogears::MassPerVolumeUnit::g_Per_dL);
}
double BiogearsThread::GetLactateConcentration()
{
lactateConcentration = lactate->GetBloodConcentration(biogears::MassPerVolumeUnit::g_Per_dL);