forked from Cantera/cantera
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSolutionArray.cpp
More file actions
2119 lines (1987 loc) · 72.4 KB
/
SolutionArray.cpp
File metadata and controls
2119 lines (1987 loc) · 72.4 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
/**
* @file SolutionArray.cpp
* Definition file for class SolutionArray.
*/
// This file is part of Cantera. See License.txt in the top-level directory or
// at https://cantera.org/license.txt for license and copyright information.
#include "cantera/base/SolutionArray.h"
#include "cantera/base/Solution.h"
#include "cantera/base/Storage.h"
#include "cantera/base/stringUtils.h"
#include "cantera/thermo/ThermoPhase.h"
#include "cantera/thermo/SurfPhase.h"
#include "cantera/base/utilities.h"
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <sstream>
namespace ba = boost::algorithm;
const std::map<std::string, std::string> aliasMap = {
{"T", "temperature"},
{"P", "pressure"},
{"D", "density"},
{"Y", "mass-fractions"},
{"X", "mole-fractions"},
{"C", "coverages"},
{"U", "specific-internal-energy"},
{"V", "specific-volume"},
{"H", "specific-enthalpy"},
{"S", "specific-entropy"},
{"Q", "vapor-fraction"},
};
namespace Cantera
{
SolutionArray::SolutionArray(const shared_ptr<Solution>& sol,
int size, const AnyMap& meta)
: m_sol(sol)
, m_size(size)
, m_dataSize(size)
, m_meta(meta)
{
if (!m_sol || !m_sol->thermo()) {
throw CanteraError("SolutionArray::SolutionArray",
"Unable to create SolutionArray from invalid Solution object.");
}
m_stride = m_sol->thermo()->stateSize();
m_sol->thermo()->addSpeciesLock();
m_data = make_shared<vector<double>>(m_dataSize * m_stride, 0.);
m_extra = make_shared<map<string, AnyValue>>();
m_order = make_shared<map<int, string>>();
for (size_t i = 0; i < m_dataSize; ++i) {
m_active.push_back(static_cast<int>(i));
}
reset();
m_apiShape.resize(1);
m_apiShape[0] = static_cast<long>(m_dataSize);
}
SolutionArray::SolutionArray(const SolutionArray& other,
const vector<int>& selected)
: m_sol(other.m_sol)
, m_size(selected.size())
, m_dataSize(other.m_data->size())
, m_stride(other.m_stride)
, m_data(other.m_data)
, m_extra(other.m_extra)
, m_order(other.m_order)
, m_shared(true)
, m_active(selected)
{
m_sol->thermo()->addSpeciesLock();
for (auto loc : m_active) {
if (loc < 0 || loc >= (int)m_dataSize) {
IndexError("SolutionArray::SolutionArray", "indices", loc, m_dataSize);
}
}
set<int> unique(selected.begin(), selected.end());
if (unique.size() < selected.size()) {
throw CanteraError("SolutionArray::SolutionArray", "Indices must be unique.");
}
}
SolutionArray::~SolutionArray()
{
m_sol->thermo()->removeSpeciesLock();
}
namespace { // restrict scope of helper functions to local translation unit
template<class T>
void resetSingle(AnyValue& extra, const vector<int>& slice);
template<class T>
AnyValue getSingle(const AnyValue& extra, const vector<int>& slice);
template<class T>
void setSingle(AnyValue& extra, const AnyValue& data, const vector<int>& slice);
template<class T>
void resizeSingle(AnyValue& extra, size_t size, const AnyValue& value);
template<class T>
void resetMulti(AnyValue& extra, const vector<int>& slice);
template<class T>
AnyValue getMulti(const AnyValue& extra, const vector<int>& slice);
template<class T>
void setMulti(AnyValue& extra, const AnyValue& data, const vector<int>& slice);
template<class T>
void resizeMulti(AnyValue& extra, size_t size, const AnyValue& value);
template<class T>
void setAuxiliarySingle(size_t loc, AnyValue& extra, const AnyValue& value);
template<class T>
void setAuxiliaryMulti(size_t loc, AnyValue& extra, const AnyValue& data);
template<class T>
void setScalar(AnyValue& extra, const AnyValue& data, const vector<int>& slice);
} // end unnamed namespace
void SolutionArray::reset()
{
size_t nState = m_sol->thermo()->stateSize();
vector<double> state(nState);
m_sol->thermo()->saveState(state); // thermo contains current state
for (size_t k = 0; k < m_size; ++k) {
std::copy(state.begin(), state.end(), m_data->data() + m_active[k] * m_stride);
}
for (auto& [key, extra] : *m_extra) {
if (extra.is<void>()) {
// cannot reset placeholder (uninitialized component)
} else if (extra.isVector<double>()) {
resetSingle<double>(extra, m_active);
} else if (extra.isVector<long int>()) {
resetSingle<long int>(extra, m_active);
} else if (extra.isVector<string>()) {
resetSingle<string>(extra, m_active);
} else if (extra.isVector<vector<double>>()) {
resetMulti<double>(extra, m_active);
} else if (extra.isVector<vector<long int>>()) {
resetMulti<long int>(extra, m_active);
} else if (extra.isVector<vector<string>>()) {
resetMulti<string>(extra, m_active);
} else {
throw NotImplementedError("SolutionArray::reset",
"Unable to reset component '{}' with type '{}'.",
key, extra.type_str());
}
}
}
void SolutionArray::resize(int size)
{
if (apiNdim() > 1) {
throw CanteraError("SolutionArray::resize",
"Resize is ambiguous for multi-dimensional arrays; use setApiShape "
"instead.");
}
if (m_data.use_count() > 1) {
throw CanteraError("SolutionArray::resize",
"Unable to resize as data are shared by multiple objects.");
}
_resize(static_cast<size_t>(size));
m_apiShape[0] = static_cast<long>(size);
}
void SolutionArray::setApiShape(const vector<long int>& shape)
{
size_t size = 1;
for (auto dim : shape) {
size *= dim;
}
if (m_shared && size != m_size) {
throw CanteraError("SolutionArray::setApiShape",
"Unable to set shape of shared data as sizes are inconsistent:\n"
"active size is {} but shape implies {}.", m_size, size);
}
if (!m_shared && size != m_dataSize) {
if (m_data.use_count() > 1) {
throw CanteraError("SolutionArray::setApiShape",
"Unable to set shape as data are shared by multiple objects.");
}
_resize(size);
}
m_apiShape = shape;
}
void SolutionArray::_resize(size_t size)
{
m_size = size;
m_dataSize = size;
m_data->resize(m_dataSize * m_stride, 0.);
for (auto& [key, data] : *m_extra) {
_resizeExtra(key);
}
m_active.clear();
for (size_t i = 0; i < m_dataSize; ++i) {
m_active.push_back(static_cast<int>(i));
}
}
namespace { // restrict scope of helper functions to local translation unit
vector<string> doubleColumn(string name, const vector<double>& comp,
int rows, int width)
{
// extract data for processing
vector<double> data;
vector<string> raw;
string notation = fmt::format("{{:{}.{}g}}", width, (width - 1) / 2);
int csize = static_cast<int>(comp.size());
int dots = csize + 1;
if (csize <= rows) {
for (const auto& val : comp) {
data.push_back(val);
raw.push_back(boost::trim_copy(fmt::format(notation, val)));
}
} else {
dots = (rows + 1) / 2;
for (int row = 0; row < dots; row++) {
data.push_back(comp[row]);
raw.push_back(boost::trim_copy(fmt::format(notation, comp[row])));
}
for (int row = csize - rows / 2; row < csize; row++) {
data.push_back(comp[row]);
raw.push_back(boost::trim_copy(fmt::format(notation, comp[row])));
}
}
// determine notation; all entries use identical formatting
bool isFloat = false;
bool isScientific = false;
size_t head = 0;
size_t tail = 0;
size_t exp = 0;
for (const auto& repr : raw) {
string name = repr;
if (name[0] == '-') {
// leading negative sign is not considered
name = name.substr(1);
}
if (name.find('e') != string::npos) {
// scientific notation
if (!isScientific) {
head = 1;
tail = name.find('e') - name.find('.');
exp = 4; // size of exponent
} else {
tail = std::max(tail, name.find('e') - name.find('.'));
}
isFloat = true;
isScientific = true;
} else if (name.find('.') != string::npos) {
// floating point notation
isFloat = true;
if (!isScientific) {
head = std::max(head, name.find('.'));
tail = std::max(tail, name.size() - name.find('.'));
}
} else {
head = std::max(head, name.size());
}
}
size_t maxLen = std::max((size_t)4, head + tail + exp + isFloat + 1);
size_t over = std::max(0, (int)name.size() - (int)maxLen);
if (isScientific) {
// at least one entry has scientific notation
notation = fmt::format(" {{:>{}.{}e}}", over + maxLen, tail);
} else if (isFloat) {
// at least one entry is a floating point
notation = fmt::format(" {{:>{}.{}f}}", over + maxLen, tail);
} else {
// all entries are integers
notation = fmt::format(" {{:>{}.0f}}", over + maxLen);
}
maxLen = fmt::format(notation, 0.).size();
// assemble output
string section = fmt::format("{{:>{}}}", maxLen);
vector<string> col = {fmt::format(section, name)};
int count = 0;
for (const auto& val : data) {
col.push_back(fmt::format(notation, val));
count++;
if (count == dots) {
col.push_back(fmt::format(section, "..."));
}
}
return col;
}
vector<string> integerColumn(string name, const vector<long int>& comp,
int rows, int width)
{
// extract data for processing
vector<long int> data;
string notation = fmt::format("{{:{}}}", width);
size_t maxLen = 2; // minimum column width is 2
int csize = static_cast<int>(comp.size());
int dots = csize + 1;
if (csize <= rows) {
for (const auto& val : comp) {
data.push_back(val);
string formatted = boost::trim_copy(fmt::format(notation, val));
if (formatted[0] == '-') {
formatted = formatted.substr(1);
}
maxLen = std::max(maxLen, formatted.size());
}
} else {
dots = (rows + 1) / 2;
for (int row = 0; row < dots; row++) {
data.push_back(comp[row]);
string formatted = boost::trim_copy(fmt::format(notation, comp[row]));
if (formatted[0] == '-') {
formatted = formatted.substr(1);
}
maxLen = std::max(maxLen, formatted.size());
}
for (int row = csize - rows / 2; row < csize; row++) {
data.push_back(comp[row]);
string formatted = boost::trim_copy(fmt::format(notation, comp[row]));
if (formatted[0] == '-') {
formatted = formatted.substr(1);
}
maxLen = std::max(maxLen, formatted.size());
}
}
if (name == "") {
// index column
notation = fmt::format("{{:<{}}}", maxLen);
} else {
// regular column
maxLen = std::max(maxLen, name.size());
notation = fmt::format(" {{:>{}}}", maxLen + 1);
}
// assemble output
vector<string> col = {fmt::format(notation, name)};
int count = 0;
for (const auto& val : data) {
col.push_back(fmt::format(notation, val));
count++;
if (count == dots) {
col.push_back(fmt::format(notation, ".."));
}
}
return col;
}
vector<string> stringColumn(string name, const vector<string>& comp,
int rows, int width)
{
// extract data for processing
vector<string> data;
string notation = fmt::format("{{:{}}}", width);
size_t maxLen = 3; // minimum column width is 3
int csize = static_cast<int>(comp.size());
int dots = csize + 1;
if (csize <= rows) {
for (const auto& val : comp) {
data.push_back(val);
maxLen = std::max(maxLen,
boost::trim_copy(fmt::format(notation, val)).size());
}
} else {
dots = (rows + 1) / 2;
for (int row = 0; row < dots; row++) {
data.push_back(comp[row]);
maxLen = std::max(maxLen,
boost::trim_copy(fmt::format(notation, comp[row])).size());
}
for (int row = csize - rows / 2; row < csize; row++) {
data.push_back(comp[row]);
maxLen = std::max(maxLen,
boost::trim_copy(fmt::format(notation, comp[row])).size());
}
}
// assemble output
notation = fmt::format(" {{:>{}}}", maxLen);
vector<string> col = {fmt::format(notation, name)};
int count = 0;
for (const auto& val : data) {
col.push_back(fmt::format(notation, val));
count++;
if (count == dots) {
col.push_back(fmt::format(notation, "..."));
}
}
return col;
}
vector<string> formatColumn(string name, const AnyValue& comp, int rows, int width)
{
if (comp.isVector<double>()) {
return doubleColumn(name, comp.asVector<double>(), rows, width);
}
if (comp.isVector<long int>()) {
return integerColumn(name, comp.asVector<long int>(), rows, width);
}
if (comp.isVector<string>()) {
return stringColumn(name, comp.asVector<string>(), rows, width);
}
// create alternative representation
string repr;
int size;
if (comp.isVector<vector<double>>()) {
repr = "[ <double> ]";
size = len(comp.asVector<vector<double>>());
} else if (comp.isVector<vector<long int>>()) {
repr = "[ <long int> ]";
size = len(comp.asVector<vector<long int>>());
} else if (comp.isVector<vector<string>>()) {
repr = "[ <string> ]";
size = len(comp.asVector<vector<string>>());
} else {
throw CanteraError(
"formatColumn", "Encountered invalid data for component '{}'.", name);
}
size_t maxLen = std::max(repr.size(), name.size());
// assemble output
string notation = fmt::format(" {{:>{}}}", maxLen);
repr = fmt::format(notation, repr);
vector<string> col = {fmt::format(notation, name)};
if (size <= rows) {
for (int row = 0; row < size; row++) {
col.push_back(repr);
}
} else {
int dots = (rows + 1) / 2;
for (int row = 0; row < dots; row++) {
col.push_back(repr);
}
col.push_back(fmt::format(notation, "..."));
for (int row = size - rows / 2; row < size; row++) {
col.push_back(repr);
}
}
return col;
}
} // end unnamed namespace
string SolutionArray::info(const vector<string>& keys, int rows, int width)
{
fmt::memory_buffer b;
int col_width = 12; // targeted maximum column width
vector<string> components;
if (keys.size()) {
components = keys;
} else {
components = componentNames();
}
try {
// build columns
vector<long int> index;
for (const auto ix : m_active) {
index.push_back(ix);
}
vector<vector<string>> cols = {integerColumn("", index, rows, col_width)};
vector<vector<string>> tail; // trailing columns in reverse order
size_t size = cols.back().size();
// assemble columns fitting within a maximum width; if this width is exceeded,
// a "..." separator is inserted close to the center. Accordingly, the matrix
// needs to be assembled from two halves.
int front = 0;
int back = len(components) - 1;
int fLen = len(cols.back()[0]);
int bLen = 0;
int sep = 5; // separator width
bool done = false;
while (!done && front <= back) {
string key;
while (bLen + sep <= fLen && front <= back) {
// add trailing columns
key = components[back];
auto col = formatColumn(key, getComponent(key), rows, col_width);
if (len(col[0]) + fLen + bLen + sep > width) {
done = true;
break;
}
tail.push_back(col);
bLen += len(tail.back()[0]);
back--;
}
if (done || front > back) {
break;
}
while (fLen <= bLen + sep && front <= back) {
// add leading columns
key = components[front];
auto col = formatColumn(key, getComponent(key), rows, col_width);
if (len(col[0]) + fLen + bLen + sep > width) {
done = true;
break;
}
cols.push_back(col);
fLen += len(cols.back()[0]);
front++;
}
}
if (cols.size() + tail.size() < components.size() + 1) {
// add separator
cols.push_back(vector<string>(size + 1, " ..."));
}
// copy trailing columns
cols.insert(cols.end(), tail.rbegin(), tail.rend());
// assemble formatted output
for (size_t row = 0; row < size; row++) {
for (const auto& col : cols) {
fmt_append(b, col[row]);
}
fmt_append(b, "\n");
}
// add size information
fmt_append(b, "\n[{} rows x {} components; state='{}']",
m_size, components.size(), m_sol->thermo()->nativeMode());
} catch (CanteraError& err) {
return to_string(b) + err.what();
}
return to_string(b);
}
shared_ptr<ThermoPhase> SolutionArray::thermo()
{
return m_sol->thermo();
}
vector<string> SolutionArray::componentNames() const
{
vector<string> components;
// leading auxiliary components
int pos = 0;
while (m_order->count(pos)) {
components.push_back(m_order->at(pos));
pos++;
}
// state information
auto phase = m_sol->thermo();
for (auto code : phase->nativeMode()) {
string name = string(1, code);
if (name == "X" || name == "Y") {
for (auto& spc : phase->speciesNames()) {
components.push_back(spc);
}
} else {
components.push_back(name);
}
}
// trailing auxiliary components
pos = -1;
while (m_order->count(pos)) {
components.push_back(m_order->at(pos));
pos--;
}
return components;
}
void SolutionArray::addExtra(const string& name, bool back)
{
if (m_extra->count(name)) {
throw CanteraError("SolutionArray::addExtra",
"Component '{}' already exists.", name);
}
(*m_extra)[name] = AnyValue();
if (back) {
if (m_order->size()) {
// add name at end of back components
m_order->emplace(m_order->begin()->first - 1, name);
} else {
// first name after state components
m_order->emplace(-1, name);
}
} else {
if (m_order->size()) {
// insert name at end of front components
m_order->emplace(m_order->rbegin()->first + 1, name);
} else {
// name in leading position
m_order->emplace(0, name);
}
}
}
vector<string> SolutionArray::listExtra(bool all) const
{
vector<string> names;
int pos = 0;
while (m_order->count(pos)) {
const auto& name = m_order->at(pos);
if (all || !m_extra->at(name).is<void>()) {
names.push_back(name);
}
pos++;
}
// trailing auxiliary components
pos = -1;
while (m_order->count(pos)) {
const auto& name = m_order->at(pos);
if (all || !m_extra->at(name).is<void>()) {
names.push_back(name);
}
pos--;
}
return names;
}
bool SolutionArray::hasComponent(const string& name) const
{
if (m_extra->count(name)) {
// auxiliary data
return true;
}
if (m_sol->thermo()->speciesIndex(name) != npos) {
// species
return true;
}
if (name == "X" || name == "Y") {
// reserved names
return false;
}
// native state
return (m_sol->thermo()->nativeState().count(name));
}
AnyValue SolutionArray::getComponent(const string& name) const
{
if (!hasComponent(name)) {
throw CanteraError("SolutionArray::getComponent",
"Unknown component '{}'.", name);
}
AnyValue out;
if (m_extra->count(name)) {
// extra component
const auto& extra = m_extra->at(name);
if (extra.is<void>()) {
return AnyValue();
}
if (m_size == m_dataSize) {
return extra; // slicing not necessary
}
if (extra.isVector<long int>()) {
return getSingle<long int>(extra, m_active);
}
if (extra.isVector<double>()) {
return getSingle<double>(extra, m_active);
}
if (extra.isVector<string>()) {
return getSingle<string>(extra, m_active);
}
if (extra.isVector<vector<double>>()) {
return getMulti<double>(extra, m_active);
}
if (extra.isVector<vector<long int>>()) {
return getMulti<long int>(extra, m_active);
}
if (extra.isVector<vector<string>>()) {
return getMulti<string>(extra, m_active);
}
throw NotImplementedError("SolutionArray::getComponent",
"Unable to get sliced data for component '{}' with type '{}'.",
name, extra.type_str());
}
// component is part of state information
vector<double> data(m_size);
size_t ix = m_sol->thermo()->speciesIndex(name);
if (ix == npos) {
// state other than species
ix = m_sol->thermo()->nativeState()[name];
} else {
// species information
ix += m_stride - m_sol->thermo()->nSpecies();
}
for (size_t k = 0; k < m_size; ++k) {
data[k] = (*m_data)[m_active[k] * m_stride + ix];
}
out = data;
return out;
}
bool isSimpleVector(const AnyValue& any) {
return any.isVector<double>() || any.isVector<long int>() ||
any.isVector<string>() || any.isVector<bool>() ||
any.isVector<vector<double>>() || any.isVector<vector<long int>>() ||
any.isVector<vector<string>>() || any.isVector<vector<bool>>();
}
void SolutionArray::setComponent(const string& name, const AnyValue& data)
{
if (!hasComponent(name)) {
throw CanteraError("SolutionArray::setComponent",
"Unknown component '{}'.", name);
}
if (m_extra->count(name)) {
_setExtra(name, data);
return;
}
size_t size = data.vectorSize();
if (size == npos) {
throw CanteraError("SolutionArray::setComponent",
"Invalid type of component '{}': expected simple array type, "
"but received '{}'.", name, data.type_str());
}
if (size != m_size) {
throw CanteraError("SolutionArray::setComponent",
"Invalid size of component '{}': expected size {} but received {}.",
name, m_size, size);
}
auto& vec = data.asVector<double>();
size_t ix = m_sol->thermo()->speciesIndex(name);
if (ix == npos) {
ix = m_sol->thermo()->nativeState()[name];
} else {
ix += m_stride - m_sol->thermo()->nSpecies();
}
for (size_t k = 0; k < m_size; ++k) {
(*m_data)[m_active[k] * m_stride + ix] = vec[k];
}
}
void SolutionArray::setLoc(int loc, bool restore)
{
size_t loc_ = static_cast<size_t>(loc);
if (m_size == 0) {
throw CanteraError("SolutionArray::setLoc",
"Unable to set location in empty SolutionArray.");
} else if (loc < 0) {
if (m_loc == npos) {
throw CanteraError("SolutionArray::setLoc",
"Both current and buffered indices are invalid.");
}
return;
} else if (static_cast<size_t>(m_active[loc_]) == m_loc) {
return;
} else if (loc_ >= m_size) {
throw IndexError("SolutionArray::setLoc", "indices", loc_, m_size - 1);
}
m_loc = static_cast<size_t>(m_active[loc_]);
if (restore) {
size_t nState = m_sol->thermo()->stateSize();
m_sol->thermo()->restoreState(nState, m_data->data() + m_loc * m_stride);
}
}
void SolutionArray::updateState(int loc)
{
setLoc(loc, false);
size_t nState = m_sol->thermo()->stateSize();
m_sol->thermo()->saveState(nState, m_data->data() + m_loc * m_stride);
}
vector<double> SolutionArray::getState(int loc)
{
setLoc(loc);
size_t nState = m_sol->thermo()->stateSize();
vector<double> out(nState);
m_sol->thermo()->saveState(out); // thermo contains current state
return out;
}
void SolutionArray::setState(int loc, const vector<double>& state)
{
size_t nState = m_sol->thermo()->stateSize();
if (state.size() != nState) {
throw CanteraError("SolutionArray::setState",
"Expected array to have length {}, but received an array of length {}.",
nState, state.size());
}
setLoc(loc, false);
m_sol->thermo()->restoreState(state);
m_sol->thermo()->saveState(nState, m_data->data() + m_loc * m_stride);
}
void SolutionArray::normalize() {
auto phase = m_sol->thermo();
auto nativeState = phase->nativeState();
if (nativeState.size() < 3) {
return;
}
size_t nState = phase->stateSize();
vector<double> out(nState);
if (nativeState.count("Y")) {
size_t offset = nativeState["Y"];
for (int loc = 0; loc < static_cast<int>(m_size); loc++) {
setLoc(loc, true); // set location and restore state
phase->setMassFractions(m_data->data() + m_loc * m_stride + offset);
m_sol->thermo()->saveState(out);
setState(loc, out);
}
} else if (nativeState.count("X")) {
size_t offset = nativeState["X"];
for (int loc = 0; loc < static_cast<int>(m_size); loc++) {
setLoc(loc, true); // set location and restore state
phase->setMoleFractions(m_data->data() + m_loc * m_stride + offset);
m_sol->thermo()->saveState(out);
setState(loc, out);
}
} else {
throw NotImplementedError("SolutionArray::normalize",
"Not implemented for mode '{}'.", phase->nativeMode());
}
}
AnyMap SolutionArray::getAuxiliary(int loc)
{
setLoc(loc);
AnyMap out;
for (const auto& [key, extra] : *m_extra) {
if (extra.is<void>()) {
out[key] = extra;
} else if (extra.isVector<long int>()) {
out[key] = extra.asVector<long int>()[m_loc];
} else if (extra.isVector<double>()) {
out[key] = extra.asVector<double>()[m_loc];
} else if (extra.isVector<string>()) {
out[key] = extra.asVector<string>()[m_loc];
} else if (extra.isVector<vector<long int>>()) {
out[key] = extra.asVector<vector<long int>>()[m_loc];
} else if (extra.isVector<vector<double>>()) {
out[key] = extra.asVector<vector<double>>()[m_loc];
} else if (extra.isVector<vector<string>>()) {
out[key] = extra.asVector<vector<string>>()[m_loc];
} else {
throw NotImplementedError("SolutionArray::getAuxiliary",
"Unable to retrieve data for component '{}' with type '{}'.",
key, extra.type_str());
}
}
return out;
}
void SolutionArray::setAuxiliary(int loc, const AnyMap& data)
{
setLoc(loc, false);
for (const auto& [name, value] : data) {
if (!m_extra->count(name)) {
throw CanteraError("SolutionArray::setAuxiliary",
"Unknown auxiliary component '{}'.", name);
}
auto& extra = m_extra->at(name);
if (extra.is<void>()) {
if (m_dataSize > 1) {
throw CanteraError("SolutionArray::setAuxiliary",
"Unable to set location for type '{}': "
"component is not initialized.", name);
}
_initExtra(name, value);
_resizeExtra(name);
}
try {
if (extra.isVector<long int>()) {
setAuxiliarySingle<long int>(m_loc, extra, value);
} else if (extra.isVector<double>()) {
setAuxiliarySingle<double>(m_loc, extra, value);
} else if (extra.isVector<string>()) {
setAuxiliarySingle<string>(m_loc, extra, value);
} else if (extra.isVector<vector<long int>>()) {
setAuxiliaryMulti<long int>(m_loc, extra, value);
} else if (extra.isVector<vector<double>>()) {
setAuxiliaryMulti<double>(m_loc, extra, value);
} else if (extra.isVector<vector<string>>()) {
setAuxiliaryMulti<string>(m_loc, extra, value);
} else {
throw CanteraError("SolutionArray::setAuxiliary",
"Unable to set entry for type '{}'.", extra.type_str());
}
} catch (CanteraError& err) {
// make failed type conversions traceable
throw CanteraError("SolutionArray::setAuxiliary",
"Encountered incompatible value for component '{}':\n{}",
name, err.getMessage());
}
}
}
AnyMap preamble(const string& desc)
{
AnyMap data;
if (desc.size()) {
data["description"] = desc;
}
data["generator"] = "Cantera SolutionArray";
data["cantera-version"] = CANTERA_VERSION;
// escape commit to ensure commits are read correctly from YAML
// example: prevent '3491027e7' from being converted to an integer
data["git-commit"] = "'" + gitCommit() + "'";
// Add a timestamp indicating the current time
time_t aclock;
::time(&aclock); // Get time in seconds
struct tm* newtime = localtime(&aclock); // Convert time to struct tm form
data["date"] = stripnonprint(asctime(newtime));
// Force metadata fields to the top of the file
if (data.hasKey("description")) {
data["description"].setLoc(-6, 0);
}
data["generator"].setLoc(-5, 0);
data["cantera-version"].setLoc(-4, 0);
data["git-commit"].setLoc(-3, 0);
data["date"].setLoc(-2, 0);
return data;
}
AnyMap& openField(AnyMap& root, const string& name)
{
if (!name.size()) {
return root;
}
// locate field based on 'name'
vector<string> tokens;
tokenizePath(name, tokens);
AnyMap* ptr = &root; // use raw pointer to avoid copying
string path = "";
for (auto& field : tokens) {
path += "/" + field;
AnyMap& sub = *ptr;
if (sub.hasKey(field) && !sub[field].is<AnyMap>()) {
throw CanteraError("openField",
"Encountered invalid existing field '{}'.", path);
} else if (!sub.hasKey(field)) {
sub[field] = AnyMap();
}
ptr = &sub[field].as<AnyMap>();
}
return *ptr;
}
void SolutionArray::writeHeader(const string& fname, const string& name,
const string& desc, bool overwrite)
{
Storage file(fname, true);
if (file.checkGroup(name, true)) {
if (!overwrite) {
throw CanteraError("SolutionArray::writeHeader",
"Group name '{}' exists; use 'overwrite' argument to overwrite.", name);
}
file.deleteGroup(name);
file.checkGroup(name, true);
}
file.writeAttributes(name, preamble(desc));
}
void SolutionArray::writeHeader(AnyMap& root, const string& name,
const string& desc, bool overwrite)
{
AnyMap& data = openField(root, name);
if (!data.empty() && !overwrite) {
throw CanteraError("SolutionArray::writeHeader",
"Field name '{}' exists; use 'overwrite' argument to overwrite.", name);
}
data.update(preamble(desc));
}
void SolutionArray::writeEntry(const string& fname, bool overwrite, const string& basis)
{
if (apiNdim() != 1) {
throw CanteraError("SolutionArray::writeEntry",
"Tabular output of CSV data only works for 1D SolutionArray objects.");
}
set<string> speciesNames;
for (const auto& species : m_sol->thermo()->speciesNames()) {
speciesNames.insert(species);
}
bool mole;
if (basis == "") {
const auto& nativeState = m_sol->thermo()->nativeState();
mole = nativeState.find("X") != nativeState.end();
} else if (basis == "X" || basis == "mole") {
mole = true;
} else if (basis == "Y" || basis == "mass") {
mole = false;
} else {