Debian Codegraph @

packages/seacas/libraries/ioss/src/exodus/Ioex_BaseDatabaseIO.C

raw
1 // Copyright(C) 1999-2024 National Technology & Engineering Solutions
2 // of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
3 // NTESS, the U.S. Government retains certain rights in this software.
4 //
5 // See packages/seacas/LICENSE for details
6
7 #include <algorithm>
8 #include <cassert>
9 #include <cctype>
10 #include <cstdlib>
11 #include <cstring>
12 #include <ctime>
13 #include <exodusII.h>
14 #include <exodusII_int.h>
15 #include <fmt/core.h>
16 #include <fmt/ostream.h>
17 #include <map>
18 #include <sstream>
19 #include <string>
20 #include <tokenize.h>
21 #include <vector>
22
23 #include "Ioex_Utils.h"
24 #include "Ioss_Assembly.h"
25 #include "Ioss_BasisVariableType.h"
26 #include "Ioss_Blob.h"
27 #include "Ioss_CodeTypes.h"
28 #include "Ioss_ComposedVariableType.h"
29 #include "Ioss_CompositeVariableType.h"
30 #include "Ioss_DBUsage.h"
31 #include "Ioss_DatabaseIO.h"
32 #include "Ioss_EdgeBlock.h"
33 #include "Ioss_EdgeSet.h"
34 #include "Ioss_ElementBlock.h"
35 #include "Ioss_ElementSet.h"
36 #include "Ioss_EntityBlock.h"
37 #include "Ioss_EntityType.h"
38 #include "Ioss_Enumerate.h"
39 #include "Ioss_FaceBlock.h"
40 #include "Ioss_FaceSet.h"
41 #include "Ioss_Field.h"
42 #include "Ioss_FileInfo.h"
43 #include "Ioss_GroupingEntity.h"
44 #include "Ioss_IOFactory.h"
45 #include "Ioss_Map.h"
46 #include "Ioss_MeshType.h"
47 #include "Ioss_NamedSuffixVariableType.h"
48 #include "Ioss_NodeBlock.h"
49 #include "Ioss_NodeSet.h"
50 #include "Ioss_ParallelUtils.h"
51 #include "Ioss_Property.h"
52 #include "Ioss_PropertyManager.h"
53 #include "Ioss_QuadratureVariableType.h"
54 #include "Ioss_Region.h"
55 #include "Ioss_SerializeIO.h"
56 #include "Ioss_SideBlock.h"
57 #include "Ioss_SideSet.h"
58 #include "Ioss_SmartAssert.h"
59 #include "Ioss_State.h"
60 #include "Ioss_Utils.h"
61
62 #include "exodus/Ioex_BaseDatabaseIO.h"
63 #include "exodus/Ioex_Internals.h"
64
65 // Transitioning from treating global variables as Ioss::Field::TRANSIENT
66 // to Ioss::Field::REDUCTION. To get the old behavior, define the value
67 // below to '1'.
68 #define GLOBALS_ARE_TRANSIENT 0
69
70 // ========================================================================
71 // Static internal helper functions
72 // ========================================================================
73 namespace {
74 bool sixty_four_bit_message_output = false;
75
76 std::vector<ex_entity_type> exodus_types({EX_GLOBAL, EX_BLOB, EX_ASSEMBLY, EX_NODE_BLOCK,
77 EX_EDGE_BLOCK, EX_FACE_BLOCK, EX_ELEM_BLOCK,
78 EX_NODE_SET, EX_EDGE_SET, EX_FACE_SET, EX_ELEM_SET,
79 EX_SIDE_SET});
80
81 const size_t max_line_length = MAX_LINE_LENGTH;
82
83 void check_variable_consistency(const ex_var_params &exo_params, int my_processor,
84 const std::string &filename, const Ioss::ParallelUtils &util);
85
86 void check_attribute_index_order(Ioss::GroupingEntity *block);
87
88 template <typename T>
89 void write_attribute_names(int exoid, ex_entity_type type, const std::vector<T *> &entities);
90
91 void query_groups(int exoid, Ioss::NameList &names, bool return_full_names);
92
93 class AssemblyTreeFilter
94 {
95 public:
96 AssemblyTreeFilter() = delete;
97 AssemblyTreeFilter(const AssemblyTreeFilter &) = delete;
98
99 AssemblyTreeFilter(Ioss::Region *region, const Ioss::EntityType filterType,
100 const std::vector<ex_assembly> &assemblies)
101 : m_region(region), m_type(filterType), m_assemblies(assemblies),
102 m_visitedAssemblies(assemblies.size(), false)
103 {
104 }
105
106 void update_list_from_assembly_tree(size_t assemblyIndex, Ioss::NameList &list)
107 {
108 // Walk the tree without cyclic dependency
109 if (assemblyIndex < m_assemblies.size()) {
110 if (!m_visitedAssemblies[assemblyIndex]) {
111 m_visitedAssemblies[assemblyIndex] = true;
112
113 const auto &assembly = m_assemblies[assemblyIndex];
114 const Ioss::EntityType assemblyType = Ioex::map_exodus_type(assembly.type);
115 if (m_type == assemblyType) {
116 for (int j = 0; j < assembly.entity_count; j++) {
117 Ioss::GroupingEntity *ge = m_region->get_entity(assembly.entity_list[j], m_type);
118 if (nullptr != ge) {
119 list.push_back(ge->name());
120 }
121 }
122 }
123
124 if (Ioss::ASSEMBLY == assemblyType) {
125 for (int i = 0; i < assembly.entity_count; i++) {
126 // Find the sub assembly with the same id
127 int64_t subAssemblyId = assembly.entity_list[i];
128 bool found = false;
129 for (size_t j = 0; j < m_assemblies.size(); j++) {
130 if (m_assemblies[j].id == subAssemblyId) {
131 found = true;
132 update_list_from_assembly_tree(j, list);
133 break;
134 }
135 }
136
137 if (!found) {
138 IOSS_ERROR(
139 fmt::format("ERROR: Could not find sub-assembly with id: {} and name: {}",
140 assembly.id, assembly.name));
141 }
142 }
143 }
144 }
145 }
146 }
147
148 void update_assembly_filter_list(Ioss::NameList &assemblyFilterList)
149 {
150 for (size_t i = 0; i < m_assemblies.size(); ++i) {
151 if (m_visitedAssemblies[i]) {
152 assemblyFilterList.emplace_back(m_assemblies[i].name);
153 }
154 }
155
156 std::sort(assemblyFilterList.begin(), assemblyFilterList.end(), std::less<>());
157 auto endIter = std::unique(assemblyFilterList.begin(), assemblyFilterList.end());
158 assemblyFilterList.resize(endIter - assemblyFilterList.begin());
159 }
160
161 private:
162 Ioss::Region *m_region = nullptr;
163 Ioss::EntityType m_type = Ioss::INVALID_TYPE;
164 const std::vector<ex_assembly> &m_assemblies;
165 mutable std::vector<bool> m_visitedAssemblies;
166 };
167
168 std::vector<ex_assembly> get_exodus_assemblies(int exoid)
169 {
170 std::vector<ex_assembly> assemblies;
171 int nassem = ex_inquire_int(exoid, EX_INQ_ASSEMBLY);
172 if (nassem > 0) {
173 assemblies.resize(nassem);
174
175 int max_name_length = ex_inquire_int(exoid, EX_INQ_DB_MAX_USED_NAME_LENGTH);
176 for (auto &assembly : assemblies) {
177 assembly.name = new char[max_name_length + 1];
178 }
179
180 int ierr = ex_get_assemblies(exoid, Data(assemblies));
181 if (ierr < 0) {
182 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
183 }
184
185 // Now allocate space for member list and get assemblies again...
186 for (auto &assembly : assemblies) {
187 assembly.entity_list = new int64_t[assembly.entity_count];
188 }
189
190 ierr = ex_get_assemblies(exoid, Data(assemblies));
191 if (ierr < 0) {
192 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
193 }
194 }
195 return assemblies;
196 }
197
198 void cleanup_exodus_assembly_vector(std::vector<ex_assembly> &assemblies)
199 {
200 for (const auto &assembly : assemblies) {
201 delete[] assembly.entity_list;
202 delete[] assembly.name;
203 }
204 }
205
206 } // namespace
207
208 namespace Ioex {
209 BaseDatabaseIO::BaseDatabaseIO(Ioss::Region *region, const std::string &filename,
210 Ioss::DatabaseUsage db_usage, Ioss_MPI_Comm communicator,
211 const Ioss::PropertyManager &props)
212 : Ioss::DatabaseIO(region, filename, db_usage, communicator, props)
213 {
214 m_groupCount[EX_GLOBAL] = 1; // To make some common code work more cleanly.
215 m_groupCount[EX_NODE_BLOCK] = 1; // To make some common code work more cleanly.
216
217 // A history file is only written on processor 0...
218 if (db_usage == Ioss::WRITE_HISTORY) {
219 isParallel = false;
220 }
221
222 timeLastFlush = time(nullptr);
223
224 dbState = Ioss::STATE_UNKNOWN;
225
226 // Set exodusII warning level.
227 if (util().get_environment("EX_DEBUG", isParallel)) {
228 fmt::print(
229 Ioss::DebugOut(),
230 "IOEX: Setting EX_VERBOSE|EX_DEBUG because EX_DEBUG environment variable is set.\n");
231 ex_opts(EX_VERBOSE | EX_DEBUG);
232 }
233 // This is also done down in the exodus library, but helps logic to do it here...
234 if (util().get_environment("EXODUS_VERBOSE", isParallel)) {
235 fmt::print(Ioss::DebugOut(), "IOEX: Exodus error reporting set to VERBOSE because "
236 "EXODUS_VERBOSE environment variable is set.\n");
237 ex_opts(EX_VERBOSE);
238 }
239
240 if (!is_input()) {
241 if (util().get_environment("EX_MODE", exodusMode, isParallel)) {
242 fmt::print(
243 Ioss::OUTPUT(),
244 "IOEX: Exodus create mode set to {} from value of EX_MODE environment variable.\n",
245 exodusMode);
246 }
247
248 if (util().get_environment("EX_MINIMIZE_OPEN_FILES", isParallel)) {
249 fmt::print(Ioss::OUTPUT(),
250 "IOEX: Minimizing open files because EX_MINIMIZE_OPEN_FILES environment "
251 "variable is set.\n");
252 minimizeOpenFiles = true;
253 }
254 else {
255 Ioss::Utils::check_set_bool_property(properties, "MINIMIZE_OPEN_FILES", minimizeOpenFiles);
256 }
257
258 {
259 bool file_per_state = false;
260 Ioss::Utils::check_set_bool_property(properties, "FILE_PER_STATE", file_per_state);
261 if (file_per_state) {
262 set_file_per_state(true);
263 }
264 }
265 }
266
267 // See if there are any properties that need to (or can) be
268 // handled prior to opening/creating database...
269 if (properties.exists("FILE_TYPE")) {
270 std::string type = properties.get("FILE_TYPE").get_string();
271 type = Ioss::Utils::lowercase(type);
272 if (type == "netcdf3" || type == "netcdf-3") {
273 exodusMode = EX_CLOBBER; // Reset back to default...
274 }
275 if (type == "netcdf4" || type == "netcdf-4" || type == "hdf5") {
276 #if NC_HAS_HDF5
277 exodusMode |= EX_NETCDF4;
278 #else
279 fmt::print(Ioss::OUTPUT(), "IOEX: HDF5/netcdf-4 is not supported in this build. FILE_TYPE "
280 "setting will be ignored.\n");
281 #endif
282 }
283 else if (type == "netcdf5" || type == "netcdf-5" || type == "cdf5") {
284 #if NC_HAS_CDF5
285 exodusMode |= EX_64BIT_DATA;
286 #else
287 fmt::print(Ioss::OUTPUT(), "IOEX: CDF5/netcdf-5 is not supported in this build. FILE_TYPE "
288 "setting will be ignored.\n");
289 #endif
290 }
291 }
292
293 if (properties.exists("ENABLE_FILE_GROUPS")) {
294 #if NC_HAS_HDF5
295 exodusMode |= EX_NETCDF4;
296 exodusMode |= EX_NOCLASSIC;
297 #else
298 fmt::print(Ioss::OUTPUT(), "IOEX: HDF5/netcdf-4 is not supported in this build. "
299 "ENABLE_FILE_GROUPS setting will be ignored.\n");
300 #endif
301 }
302
303 bool compress = ((properties.exists("COMPRESSION_LEVEL") &&
304 properties.get("COMPRESSION_LEVEL").get_int() > 0) ||
305 (properties.exists("COMPRESSION_SHUFFLE") &&
306 properties.get("COMPRESSION_SHUFFLE").get_int() > 0));
307
308 if (compress) {
309 #if NC_HAS_HDF5
310 if (!(exodusMode & EX_NETCDF4)) {
311 fmt::print(Ioss::OUTPUT(), "IOEX: Compression requires netcdf-4/HDF5-based file. Setting "
312 "file type to netcdf-4.\n");
313 exodusMode |= EX_NETCDF4;
314 }
315 #else
316 fmt::print(Ioss::OUTPUT(), "IOEX: HDF5/netcdf-4 is not supported in this build. Compression "
317 "setting will be ignored.\n");
318 #endif
319 }
320
321 if (properties.exists("MAXIMUM_NAME_LENGTH")) {
322 maximumNameLength = properties.get("MAXIMUM_NAME_LENGTH").get_int();
323 }
324
325 if (properties.exists("REAL_SIZE_DB")) {
326 int rsize = properties.get("REAL_SIZE_DB").get_int();
327 if (rsize == 4) {
328 dbRealWordSize = 4; // Only used for file create...
329 }
330 }
331
332 if (properties.exists("INTEGER_SIZE_DB")) {
333 int isize = properties.get("INTEGER_SIZE_DB").get_int();
334 if (isize == 8) {
335 exodusMode |= EX_ALL_INT64_DB;
336 }
337 }
338
339 if (properties.exists("INTEGER_SIZE_API")) {
340 int isize = properties.get("INTEGER_SIZE_API").get_int();
341 if (isize == 8) {
342 set_int_byte_size_api(Ioss::USE_INT64_API);
343 }
344 }
345
346 if (!is_input()) {
347 if (properties.exists("FLUSH_INTERVAL")) {
348 int interval = properties.get("FLUSH_INTERVAL").get_int();
349 flushInterval = interval;
350 }
351 }
352
353 // Don't open output files until they are actually going to be
354 // written to. This is needed for proper support of the topology
355 // files and auto restart so we don't overwrite a file with data we
356 // need to save...
357 }
358
359 void BaseDatabaseIO::set_int_byte_size_api(Ioss::DataSize size) const
360 {
361 if (m_exodusFilePtr > 0) {
362 int old_status = ex_int64_status(get_file_pointer());
363 if (size == 8) {
364 ex_set_int64_status(get_file_pointer(), EX_ALL_INT64_API | old_status);
365 }
366 else {
367 // Need to clear EX_ALL_INT64_API if set...
368 if ((old_status & EX_ALL_INT64_API) != 0) {
369 old_status &= ~EX_ALL_INT64_API;
370 assert(!(old_status & EX_ALL_INT64_API));
371 ex_set_int64_status(m_exodusFilePtr, old_status);
372 }
373 }
374 }
375 else {
376 if (size == 8) {
377 exodusMode |= EX_ALL_INT64_API;
378 }
379 else {
380 exodusMode &= ~EX_ALL_INT64_API;
381 }
382 }
383 dbIntSizeAPI = size; // mutable
384 }
385
386 // Returns byte size of integers stored on the database...
387 int BaseDatabaseIO::int_byte_size_db() const
388 {
389 int status = ex_int64_status(get_file_pointer());
390 if (status & EX_MAPS_INT64_DB || status & EX_IDS_INT64_DB || status & EX_BULK_INT64_DB) {
391 return 8;
392 }
393 else {
394 return 4;
395 }
396 }
397
398 // common
399 BaseDatabaseIO::~BaseDatabaseIO()
400 {
401 try {
402 free_file_pointer();
403 }
404 catch (...) {
405 }
406 }
407
408 // common
409 unsigned BaseDatabaseIO::entity_field_support() const
410 {
411 return Ioss::NODEBLOCK | Ioss::EDGEBLOCK | Ioss::FACEBLOCK | Ioss::ELEMENTBLOCK |
412 Ioss::NODESET | Ioss::EDGESET | Ioss::FACESET | Ioss::ELEMENTSET | Ioss::SIDESET |
413 Ioss::SIDEBLOCK | Ioss::REGION | Ioss::SUPERELEMENT;
414 }
415
416 // common
417 int BaseDatabaseIO::get_file_pointer() const
418 {
419 // Returns the file_pointer used to access the file on disk.
420 // Checks that the file is open and if not, opens it first.
421 if (m_exodusFilePtr < 0) {
422 bool write_message = true;
423 bool abort_if_error = true;
424 if (is_input()) {
425 open_input_file(write_message, nullptr, nullptr, abort_if_error);
426 }
427 else {
428 bool overwrite = true;
429 handle_output_file(write_message, nullptr, nullptr, overwrite, abort_if_error);
430 }
431 }
432 assert(m_exodusFilePtr >= 0);
433 fileExists = true;
434 return m_exodusFilePtr;
435 }
436
437 int BaseDatabaseIO::free_file_pointer() const
438 {
439 if (m_exodusFilePtr != -1) {
440 bool do_timer = false;
441 if (isParallel) {
442 Ioss::Utils::check_set_bool_property(properties, "IOSS_TIME_FILE_OPEN_CLOSE", do_timer);
443 }
444 double t_begin = (do_timer ? Ioss::Utils::timer() : 0);
445
446 ex_close(m_exodusFilePtr);
447 close_dw();
448 if (do_timer && isParallel) {
449 double t_end = Ioss::Utils::timer();
450 double duration = util().global_minmax(t_end - t_begin, Ioss::ParallelUtils::DO_MAX);
451 if (myProcessor == 0) {
452 fmt::print(Ioss::DebugOut(), "File Close Time = {} ({})\n", duration, get_filename());
453 }
454 }
455 }
456 m_exodusFilePtr = -1;
457
458 return m_exodusFilePtr;
459 }
460
461 bool BaseDatabaseIO::ok_nl(bool write_message, std::string *error_message, int *bad_count) const
462 {
463 // For input, we try to open the existing file.
464
465 // For output, we do not want to overwrite or clobber the output
466 // file if it already exists since the app might be reading the restart
467 // data from this file and then later clobbering it and then writing
468 // restart data to the same file. So, for output, we first check
469 // whether the file exists and if it it and is writable, assume
470 // that we can later create a new or append to existing file.
471
472 // Returns the number of processors on which this file is *NOT* ok in 'bad_count' if not null.
473 // Will return 'true' only if file ok on all processors.
474
475 if (fileExists) {
476 // File has already been opened at least once...
477 return dbState != Ioss::STATE_INVALID;
478 }
479
480 bool abort_if_error = false;
481 bool is_ok;
482 if (is_input()) {
483 is_ok = open_input_file(write_message, error_message, bad_count, abort_if_error);
484 }
485 else {
486 // See if file exists... Don't overwrite (yet) it it exists.
487 bool overwrite = false;
488 is_ok =
489 handle_output_file(write_message, error_message, bad_count, overwrite, abort_if_error);
490 // Close all open files...
491 if (m_exodusFilePtr >= 0) {
492 ex_close(m_exodusFilePtr);
493 m_exodusFilePtr = -1;
494 }
495 }
496 return is_ok;
497 }
498
499 void BaseDatabaseIO::finalize_file_open() const
500 {
501 assert(m_exodusFilePtr >= 0);
502 // Check byte-size of integers stored on the database...
503 if ((ex_int64_status(m_exodusFilePtr) & EX_ALL_INT64_DB) != 0) {
504 if (myProcessor == 0 && !sixty_four_bit_message_output) {
505 fmt::print(Ioss::DebugOut(),
506 "IOSS: Input database contains 8-byte integers. Setting Ioss to use "
507 "8-byte integers.\n");
508 sixty_four_bit_message_output = true;
509 }
510 ex_set_int64_status(m_exodusFilePtr, EX_ALL_INT64_API);
511 set_int_byte_size_api(Ioss::USE_INT64_API);
512 }
513
514 // Check for maximum name length used on the input file.
515 int max_name_length = ex_inquire_int(m_exodusFilePtr, EX_INQ_DB_MAX_USED_NAME_LENGTH);
516 if (max_name_length > maximumNameLength) {
517 maximumNameLength = max_name_length;
518 }
519
520 ex_set_max_name_length(m_exodusFilePtr, maximumNameLength);
521
522 open_root_group_nl();
523 open_child_group_nl(0);
524 }
525
526 bool BaseDatabaseIO::supports_internal_change_set_nl() { return supports_group(); }
527
528 bool BaseDatabaseIO::supports_group() const
529 {
530 Ioss::SerializeIO serializeIO_(this);
531 int exoid = get_file_pointer();
532
533 int64_t format = ex_inquire_int(exoid, EX_INQ_FILE_FORMAT);
534
535 if (format < 0) {
536 IOSS_ERROR(
537 fmt::format("ERROR: Could not query file format for file '{}'.\n", get_filename()));
538 }
539
540 return (NC_FORMAT_NETCDF4 == format);
541 }
542
543 bool BaseDatabaseIO::open_root_group_nl() const
544 {
545 // Get existing file pointer...
546 bool success = false;
547
548 Ioss::SerializeIO serializeIO_(this);
549 int exoid = get_file_pointer();
550
551 int group_name_length = ex_inquire_int(exoid, EX_INQ_GROUP_NAME_LEN);
552 std::vector<char> group_name(group_name_length + 1, '\0');
553
554 // Get name of this group...
555 int idum;
556 float rdum;
557 int ierr = ex_inquire(exoid, EX_INQ_GROUP_NAME, &idum, &rdum, group_name.data());
558 if (ierr < 0) {
559 IOSS_ERROR(fmt::format("ERROR: Could not open root group of group named '{}' in file '{}'.\n",
560 m_groupName, get_filename()));
561 }
562
563 m_groupName = std::string(group_name.data());
564 m_exodusFilePtr = ex_inquire_int(exoid, EX_INQ_GROUP_ROOT);
565
566 if (m_exodusFilePtr < 0) {
567 IOSS_ERROR(fmt::format("ERROR: Could not open group named '{}' in file '{}'.\n", m_groupName,
568 get_filename()));
569 }
570 success = true;
571 return success;
572 }
573
574 bool BaseDatabaseIO::open_internal_change_set_nl(const std::string &set_name)
575 {
576 if (set_name == m_groupName) {
577 return true;
578 }
579
580 // Check name for '/' which is not allowed since it is the
581 // separator character in a full group path
582 if (set_name.find('/') != std::string::npos) {
583 IOSS_ERROR(fmt::format(
584 "ERROR: Invalid group name '{}' contains a '/' which is not allowed.\n", set_name));
585 }
586
587 if (!open_root_group_nl())
588 return false;
589
590 return open_group_nl(set_name);
591 }
592
593 bool BaseDatabaseIO::open_group_nl(const std::string &group_name) const
594 {
595 // Get existing file pointer...
596 bool success = false;
597
598 Ioss::SerializeIO serializeIO_(this);
599 int exoid = get_file_pointer();
600
601 m_groupName = group_name;
602 ex_get_group_id(exoid, m_groupName.c_str(), &m_exodusFilePtr);
603
604 if (m_exodusFilePtr < 0) {
605 IOSS_ERROR(fmt::format("ERROR: Could not open group named '{}' in file '{}'.\n", m_groupName,
606 get_filename()));
607 }
608 success = true;
609 return success;
610 }
611
612 bool BaseDatabaseIO::create_internal_change_set_nl(const std::string &set_name)
613 {
614 if (!open_root_group_nl())
615 return false;
616
617 return create_subgroup_nl(set_name);
618 }
619
620 bool BaseDatabaseIO::create_subgroup_nl(const std::string &group_name)
621 {
622 bool success = false;
623 if (!is_input()) {
624 // Get existing file pointer...
625 Ioss::SerializeIO serializeIO_(this);
626 int exoid = get_file_pointer();
627
628 // Check name for '/' which is not allowed since it is the
629 // separator character in a full group path
630 if (group_name.find('/') != std::string::npos) {
631 IOSS_ERROR(fmt::format(
632 "ERROR: Invalid group name '{}' contains a '/' which is not allowed.\n", m_groupName));
633 }
634
635 m_groupName = group_name;
636 exoid = ex_create_group(exoid, m_groupName.c_str());
637 if (exoid < 0) {
638 IOSS_ERROR(fmt::format("ERROR: Could not create group named '{}' in file '{}'.\n",
639 m_groupName, get_filename()));
640 }
641 m_exodusFilePtr = exoid;
642 success = true;
643 }
644 // QA and Info records are written at "root" level by first "group/database"
645 properties.add(Ioss::Property("OMIT_QA_RECORDS", "YES"));
646 properties.add(Ioss::Property("OMIT_INFO_RECORDS", "YES"));
647 return success;
648 }
649
650 // common
651 void BaseDatabaseIO::put_qa()
652 {
653 struct qa_element
654 {
655 char *qa_record[1][4];
656 };
657
658 size_t num_qa_records = qaRecords.size() / 4;
659
660 if (using_parallel_io() && myProcessor != 0) {
661 // This call only sets the `num_qa_records` metadata on the other ranks...
662 ex_put_qa(get_file_pointer(), num_qa_records + 1, nullptr);
663 }
664 else {
665 std::vector<qa_element> qa(num_qa_records + 1);
666 for (size_t i = 0; i < num_qa_records + 1; i++) {
667 for (int j = 0; j < 4; j++) {
668 qa[i].qa_record[0][j] = new char[MAX_STR_LENGTH + 1];
669 }
670 }
671
672 {
673 int j = 0;
674 for (size_t i = 0; i < num_qa_records; i++) {
675 Ioss::Utils::copy_string(qa[i].qa_record[0][0], qaRecords[j++], MAX_STR_LENGTH + 1);
676 Ioss::Utils::copy_string(qa[i].qa_record[0][1], qaRecords[j++], MAX_STR_LENGTH + 1);
677 Ioss::Utils::copy_string(qa[i].qa_record[0][2], qaRecords[j++], MAX_STR_LENGTH + 1);
678 Ioss::Utils::copy_string(qa[i].qa_record[0][3], qaRecords[j++], MAX_STR_LENGTH + 1);
679 }
680 }
681
682 Ioss::Utils::time_and_date(qa[num_qa_records].qa_record[0][3],
683 qa[num_qa_records].qa_record[0][2], MAX_STR_LENGTH);
684
685 std::string codename = "unknown";
686 std::string version = "unknown";
687
688 if (get_region()->property_exists("code_name")) {
689 codename = get_region()->get_property("code_name").get_string();
690 }
691 if (get_region()->property_exists("code_version")) {
692 version = get_region()->get_property("code_version").get_string();
693 }
694
695 Ioss::Utils::copy_string(qa[num_qa_records].qa_record[0][0], codename, MAX_STR_LENGTH + 1);
696 Ioss::Utils::copy_string(qa[num_qa_records].qa_record[0][1], version, MAX_STR_LENGTH + 1);
697
698 int ierr = 0;
699 ierr = ex_put_qa(get_file_pointer(), num_qa_records + 1, qa[0].qa_record);
700 if (ierr < 0) {
701 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
702 }
703
704 for (size_t i = 0; i < num_qa_records + 1; i++) {
705 for (int j = 0; j < 4; j++) {
706 delete[] qa[i].qa_record[0][j];
707 }
708 }
709 }
710 }
711
712 // common
713 void BaseDatabaseIO::put_info()
714 {
715 int total_lines = 0;
716 char **info = nullptr;
717
718 if (!using_parallel_io() || myProcessor == 0) {
719 // dump info records, include the product_registry
720 // See if the input file was specified as a property on the database...
721 Ioss::NameList input_lines;
722 if (get_region()->property_exists("input_file_name")) {
723 std::string filename = get_region()->get_property("input_file_name").get_string();
724 // Determine size of input file so can embed it in info records...
725 Ioss::Utils::input_file(filename, &input_lines, max_line_length);
726 }
727
728 // Get configuration information for IOSS library.
729 // Split into strings and remove empty lines...
730 std::string config = Ioss::IOFactory::show_configuration();
731 std::replace(std::begin(config), std::end(config), '\t', ' ');
732 auto lines = Ioss::tokenize(config, "\n");
733 lines.erase(std::remove_if(lines.begin(), lines.end(),
734 [](const std::string &line) { return line.empty(); }),
735 lines.end());
736
737 // See if the client added any "information_records"
738 size_t info_rec_size = informationRecords.size();
739 size_t in_lines = input_lines.size();
740 size_t qa_lines = 1; // Platform info
741 size_t config_lines = lines.size();
742
743 total_lines = in_lines + qa_lines + info_rec_size + config_lines;
744
745 // 'total_lines' pointers to char buffers
746 info = Ioex::get_name_array(total_lines, max_line_length);
747
748 int i = 0;
749 Ioss::Utils::copy_string(info[i++], Ioss::Utils::platform_information(), max_line_length + 1);
750
751 // Copy input file lines into 'info' array...
752 for (size_t j = 0; j < input_lines.size(); j++, i++) {
753 Ioss::Utils::copy_string(info[i], input_lines[j], max_line_length + 1);
754 }
755
756 // Copy "information_records" property data ...
757 for (size_t j = 0; j < informationRecords.size(); j++, i++) {
758 Ioss::Utils::copy_string(info[i], informationRecords[j], max_line_length + 1);
759 }
760
761 for (size_t j = 0; j < lines.size(); j++, i++) {
762 Ioss::Utils::copy_string(info[i], lines[j], max_line_length + 1);
763 }
764 }
765
766 if (using_parallel_io()) {
767 util().broadcast(total_lines);
768 }
769
770 int ierr = 0;
771 if (!using_parallel_io() || myProcessor == 0) {
772 ierr = ex_put_info(get_file_pointer(), total_lines, info);
773 Ioex::delete_name_array(info, total_lines);
774 }
775 else {
776 // This call only sets the `total_lines` metadata on the other ranks...
777 ierr = ex_put_info(get_file_pointer(), total_lines, nullptr);
778 }
779 if (ierr < 0) {
780 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
781 }
782 }
783
784 // common
785 int BaseDatabaseIO::get_current_state() const
786 {
787 int step = get_region()->get_current_state();
788
789 if (step <= 0) {
790 IOSS_ERROR(
791 fmt::format("ERROR: No currently active state. The calling code must call "
792 "Ioss::Region::begin_state(int step)\n"
793 " to set the database timestep from which to read the transient data.\n"
794 " [{}]\n",
795 get_filename()));
796 }
797 return step;
798 }
799
800 void BaseDatabaseIO::update_block_omissions_from_assemblies()
801 {
802 Ioss::SerializeIO serializeIO_(this);
803
804 // Query number of assemblies...
805 auto assemblies = get_exodus_assemblies(get_file_pointer());
806 if (!assemblies.empty()) {
807 Ioss::NameList exclusions;
808 Ioss::NameList inclusions;
809
810 AssemblyTreeFilter inclusionFilter(get_region(), Ioss::ELEMENTBLOCK, assemblies);
811 AssemblyTreeFilter exclusionFilter(get_region(), Ioss::ELEMENTBLOCK, assemblies);
812
813 for (size_t i = 0; i < assemblies.size(); ++i) {
814 const auto &assembly = assemblies[i];
815
816 bool omitAssembly =
817 std::binary_search(assemblyOmissions.begin(), assemblyOmissions.end(), assembly.name);
818 bool includeAssembly =
819 std::binary_search(assemblyInclusions.begin(), assemblyInclusions.end(), assembly.name);
820
821 if (omitAssembly) {
822 exclusionFilter.update_list_from_assembly_tree(i, exclusions);
823 }
824
825 if (includeAssembly) {
826 inclusionFilter.update_list_from_assembly_tree(i, inclusions);
827 }
828 }
829
830 exclusionFilter.update_assembly_filter_list(assemblyOmissions);
831 inclusionFilter.update_assembly_filter_list(assemblyInclusions);
832
833 cleanup_exodus_assembly_vector(assemblies);
834
835 Ioss::Utils::insert_sort_and_unique(exclusions, blockOmissions);
836 Ioss::Utils::insert_sort_and_unique(inclusions, blockInclusions);
837 }
838 }
839
840 void BaseDatabaseIO::get_assemblies()
841 {
842 Ioss::SerializeIO serializeIO_(this);
843
844 auto assemblies = get_exodus_assemblies(get_file_pointer());
845 if (!assemblies.empty()) {
846 for (const auto &assembly : assemblies) {
847 auto *assem = new Ioss::Assembly(get_region()->get_database(), assembly.name);
848 assem->property_add(Ioss::Property("id", assembly.id));
849 get_region()->add(assem);
850 }
851
852 // Now iterate again and populate member lists...
853 for (const auto &assembly : assemblies) {
854 Ioss::Assembly *assem = get_region()->get_assembly(assembly.name);
855 assert(assem != nullptr);
856 auto type = Ioex::map_exodus_type(assembly.type);
857 size_t num_added_entities = 0;
858
859 for (int j = 0; j < assembly.entity_count; j++) {
860 auto *ge = get_region()->get_entity(assembly.entity_list[j], type);
861 if (ge == nullptr) {
862 fmt::print(Ioss::WarnOut(),
863 "Error: Failed to find entity of type {} with id {} for assembly {}.\n",
864 Ioss::Utils::entity_type_to_string(type), assembly.entity_list[j],
865 assem->name());
866 continue;
867 }
868
869 if (!Ioss::Utils::block_is_omitted(ge)) {
870 assem->add(ge);
871 num_added_entities++;
872 }
873 }
874 SMART_ASSERT(assem->member_count() == num_added_entities)
875 (assem->member_count())(num_added_entities);
876
877 add_mesh_reduction_fields(assembly.id, assem);
878 // Check for additional variables.
879 int attribute_count = assem->get_property("attribute_count").get_int();
880 add_attribute_fields(assem, attribute_count, "Assembly");
881 add_reduction_results_fields(assem);
882 }
883
884 // If there are any reduction results fields ("REDUCTION"), then need to
885 // allocate space for the values to be stored on each timestep...
886 if (!m_reductionVariables[EX_ASSEMBLY].empty()) {
887 size_t size = m_reductionVariables[EX_ASSEMBLY].size();
888 for (const auto &assembly : assemblies) {
889 m_reductionValues[EX_ASSEMBLY][assembly.id].resize(size);
890 }
891 }
892 cleanup_exodus_assembly_vector(assemblies);
893
894 assert(assemblyOmissions.empty() || assemblyInclusions.empty()); // Only one can be non-empty
895
896 // Handle all assembly omissions or inclusions...
897 if (!assemblyOmissions.empty()) {
898 for (const auto &name : assemblyOmissions) {
899 auto assembly = get_region()->get_assembly(name);
900 if (assembly != nullptr) {
901 assembly->property_add(Ioss::Property(std::string("omitted"), 1));
902 }
903 }
904 }
905
906 if (!assemblyInclusions.empty()) {
907 const auto &ioss_assemblies = get_region()->get_assemblies();
908 for (auto &assembly : ioss_assemblies) {
909 assembly->property_add(Ioss::Property(std::string("omitted"), 1));
910 }
911
912 // Now, erase the property on any assemblies in the inclusion list...
913 for (const auto &name : assemblyInclusions) {
914 auto assembly = get_region()->get_assembly(name);
915 if (assembly != nullptr) {
916 assembly->property_erase("omitted");
917 }
918 }
919 }
920 }
921 }
922
923 void BaseDatabaseIO::get_blobs()
924 {
925 Ioss::SerializeIO serializeIO_(this);
926 // Query number of blobs...
927 int nblob = ex_inquire_int(get_file_pointer(), EX_INQ_BLOB);
928
929 if (nblob > 0) {
930 std::vector<ex_blob> blobs(nblob);
931 int max_name_length = ex_inquire_int(get_file_pointer(), EX_INQ_DB_MAX_USED_NAME_LENGTH);
932 for (auto &bl : blobs) {
933 bl.name = new char[max_name_length + 1];
934 }
935
936 int ierr = ex_get_blobs(get_file_pointer(), Data(blobs));
937 if (ierr < 0) {
938 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
939 }
940
941 for (const auto &bl : blobs) {
942 #ifdef SEACAS_HAVE_MPI
943 // Each blob is spread across all processors (should support a minimum size...)
944 // Determine size of blob on each rank and offset from beginning of blob.
945 size_t per_proc = bl.num_entry / parallel_size();
946 size_t extra = bl.num_entry % parallel_size();
947 size_t count = per_proc + (myProcessor < (int)extra ? 1 : 0);
948
949 size_t offset = 0;
950 if (myProcessor < (int)extra) {
951 offset = (per_proc + 1) * myProcessor;
952 }
953 else {
954 offset = (per_proc + 1) * extra + per_proc * (myProcessor - extra);
955 }
956 Ioss::Blob *blob = new Ioss::Blob(get_region()->get_database(), bl.name, count);
957 blob->property_add(Ioss::Property("_processor_offset", (int64_t)offset));
958 blob->property_add(Ioss::Property("global_size", (int64_t)bl.num_entry));
959 #else
960 auto *blob = new Ioss::Blob(get_region()->get_database(), bl.name, bl.num_entry);
961 #endif
962 blob->property_add(Ioss::Property("id", bl.id));
963 get_region()->add(blob);
964 }
965
966 // Now iterate again and populate member lists...
967 int iblk = 0;
968 for (const auto &bl : blobs) {
969 Ioss::Blob *blob = get_region()->get_blob(bl.name);
970 assert(blob != nullptr);
971
972 add_mesh_reduction_fields(bl.id, blob);
973 // Check for additional variables.
974 int attribute_count = blob->get_property("attribute_count").get_int();
975 add_attribute_fields(blob, attribute_count, "Blob");
976 add_reduction_results_fields(blob);
977 add_results_fields(blob, iblk++);
978 }
979
980 // If there are any reduction results fields ("REDUCTION"), then need to
981 // allocate space for the values to be stored on each timestep...
982 if (!m_reductionVariables[EX_BLOB].empty()) {
983 size_t size = m_reductionVariables[EX_BLOB].size();
984 for (const auto &blob : blobs) {
985 m_reductionValues[EX_BLOB][blob.id].resize(size);
986 }
987 }
988
989 for (const auto &bl : blobs) {
990 delete[] bl.name;
991 }
992 }
993 }
994
995 // common
996 void BaseDatabaseIO::get_nodeblocks()
997 {
998 // For exodusII, there is only a single node block which contains
999 // all of the nodes.
1000 // The default id assigned is '1' and the name is 'nodeblock_1'
1001
1002 std::string block_name = "nodeblock_1";
1003 auto block = new Ioss::NodeBlock(this, block_name, nodeCount, spatialDimension);
1004 block->property_add(Ioss::Property("id", 1));
1005 block->property_add(Ioss::Property("guid", util().generate_guid(1)));
1006 // Check for results variables.
1007
1008 int num_attr = 0;
1009 {
1010 Ioss::SerializeIO serializeIO_(this);
1011 int ierr = ex_get_attr_param(get_file_pointer(), EX_NODE_BLOCK, 1, &num_attr);
1012 if (ierr < 0) {
1013 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1014 }
1015 }
1016
1017 add_attribute_fields(block, num_attr, "");
1018 // Not supported on nodeblocks at this time
1019 // add_reduction_results_fields(block);
1020 add_results_fields(block);
1021
1022 // If there are any reduction results fields ("REDUCTION"), then need to
1023 // allocate space for the values to be stored on each timestep...
1024 if (!m_reductionVariables[EX_NODE_BLOCK].empty()) {
1025 size_t size = m_reductionVariables[EX_NODE_BLOCK].size();
1026 m_reductionValues[EX_NODE_BLOCK][1].resize(size);
1027 }
1028
1029 bool added = get_region()->add(block);
1030 if (!added) {
1031 delete block;
1032 }
1033 }
1034
1035 // common
1036 // common
1037 size_t BaseDatabaseIO::handle_block_ids(const Ioss::EntityBlock *eb, ex_entity_type map_type,
1038 Ioss::Map &entity_map, void *ids, size_t num_to_get,
1039 size_t offset) const
1040 {
1041 /*!
1042 * NOTE: "element" is generic for "element", "face", or "edge"
1043 *
1044 * There are two modes we need to support in this routine:
1045 * 1. Initial definition of element map (local->global) and
1046 * elemMap.reverse (global->local).
1047 * 2. Redefinition of element map via 'reordering' of the original
1048 * map when the elements on this processor are the same, but their
1049 * order is changed.
1050 *
1051 * So, there will be two maps the 'elemMap.map' map is a 'direct lookup'
1052 * map which maps current local position to global id and the
1053 * 'elemMap.reverse' is an associative lookup which maps the
1054 * global id to 'original local'. There is also a
1055 * 'elemMap.reorder' which is direct lookup and maps current local
1056 * position to original local.
1057
1058 * The ids coming in are the global ids; their position is the
1059 * local id -1 (That is, data[0] contains the global id of local
1060 * element 1 in this element block). The 'model-local' id is
1061 * given by eb_offset + 1 + position:
1062 *
1063 * int local_position = elemMap.reverse[ElementMap[i+1]]
1064 * (the elemMap.map and elemMap.reverse are 1-based)
1065 *
1066 * But, this assumes 1..numel elements are being output at the same
1067 * time; we are actually outputting a blocks worth of elements at a
1068 * time, so we need to consider the block offsets.
1069 * So... local-in-block position 'i' is index 'eb_offset+i' in
1070 * 'elemMap.map' and the 'local_position' within the element
1071 * blocks data arrays is 'local_position-eb_offset'. With this, the
1072 * position within the data array of this element block is:
1073 *
1074 * int eb_position =
1075 * elemMap.reverse[elemMap.map[eb_offset+i+1]]-eb_offset-1
1076 *
1077 * To determine which map to update on a call to this function, we
1078 * use the following heuristics:
1079 * -- If the database state is 'Ioss::STATE_MODEL:', then update the
1080 * 'elemMap.reverse'.
1081 * -- If the database state is not Ioss::STATE_MODEL, then leave
1082 * the 'elemMap.reverse' alone since it corresponds to the
1083 * information already written to the database. [May want to add
1084 * a Ioss::STATE_REDEFINE_MODEL]
1085 * -- Always update elemMap.map to match the passed in 'ids'
1086 * array.
1087 *
1088 * NOTE: the maps are built an element block at a time...
1089 * NOTE: The mapping is done on TRANSIENT fields only; MODEL fields
1090 * should be in the original order...
1091 */
1092
1093 // Overwrite this portion of the 'elemMap.map', but keep other
1094 // parts as they were. We are adding elements starting at position
1095 // 'eb_offset+offset' and ending at
1096 // 'eb_offset+offset+num_to_get'. If the entire block is being
1097 // processed, this reduces to the range 'eb_offset..eb_offset+my_element_count'
1098
1099 bool in_define = (dbState == Ioss::STATE_MODEL) || (dbState == Ioss::STATE_DEFINE_MODEL);
1100 int64_t eb_offset = eb->get_offset();
1101 if (int_byte_size_api() == 4) {
1102 entity_map.set_map(static_cast<int *>(ids), num_to_get, eb_offset, in_define);
1103 }
1104 else {
1105 entity_map.set_map(static_cast<int64_t *>(ids), num_to_get, eb_offset, in_define);
1106 }
1107
1108 // Now, if the state is Ioss::STATE_MODEL, output this portion of
1109 // the entity number map...
1110 if (in_define) {
1111 if (ex_put_partial_id_map(get_file_pointer(), map_type, offset + 1, num_to_get, ids) < 0) {
1112 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1113 }
1114 }
1115 return num_to_get;
1116 }
1117
1118 // common
1119 void BaseDatabaseIO::compute_block_membership_nl(Ioss::SideBlock *efblock,
1120 Ioss::NameList &block_membership) const
1121 {
1122 const Ioss::ElementBlockContainer &element_blocks = get_region()->get_element_blocks();
1123 assert(Ioss::Utils::check_block_order(element_blocks));
1124
1125 Ioss::Int64Vector block_ids(element_blocks.size());
1126 if (block_ids.size() == 1) {
1127 block_ids[0] = 1;
1128 }
1129 else {
1130 Ioss::Int64Vector element_side;
1131 if (int_byte_size_api() == 4) {
1132 Ioss::IntVector es32;
1133 efblock->get_field_data("element_side", es32);
1134 element_side.resize(es32.size());
1135 std::copy(es32.begin(), es32.end(), element_side.begin());
1136 }
1137 else {
1138 efblock->get_field_data("element_side", element_side);
1139 }
1140
1141 size_t number_sides = element_side.size() / 2;
1142 Ioss::ElementBlock *block = nullptr;
1143 for (size_t iel = 0; iel < number_sides; iel++) {
1144 int64_t elem_id = element_side[2 * iel]; // Vector contains both element and side.
1145 elem_id = elemMap.global_to_local(elem_id);
1146 if (block == nullptr || !block->contains(elem_id)) {
1147 block = get_region()->get_element_block(elem_id);
1148 assert(block != nullptr);
1149 size_t block_order = block->get_property("original_block_order").get_int();
1150 assert(block_order < block_ids.size());
1151 block_ids[block_order] = 1;
1152 }
1153 }
1154 }
1155
1156 // Synchronize among all processors....
1157 if (isParallel) {
1158 util().global_array_minmax(block_ids, Ioss::ParallelUtils::DO_MAX);
1159 }
1160
1161 for (const auto &block : element_blocks) {
1162 size_t block_order = block->get_property("original_block_order").get_int();
1163 assert(block_order < block_ids.size());
1164 if (block_ids[block_order] == 1) {
1165 if (!Ioss::Utils::block_is_omitted(block)) {
1166 block_membership.push_back(block->name());
1167 }
1168 }
1169 }
1170 }
1171
1172 // common
1173 int64_t BaseDatabaseIO::get_field_internal(const Ioss::Region * /* region */,
1174 const Ioss::Field &field, void *data,
1175 size_t data_size) const
1176 {
1177 // For now, assume that all TRANSIENT fields on a region
1178 // are REDUCTION fields (1 value). We need to gather these
1179 // and output them all at one time. The storage location is a
1180 // 'globalVariables' array
1181 {
1182 size_t num_to_get = field.verify(data_size);
1183 Ioss::SerializeIO serializeIO_(this);
1184
1185 Ioss::Field::RoleType role = field.get_role();
1186
1187 if (role == Ioss::Field::TRANSIENT || role == Ioss::Field::REDUCTION) {
1188 get_reduction_field(field, get_region(), data);
1189 }
1190 else {
1191 IOSS_ERROR("ERROR: Can not handle non-TRANSIENT or non-REDUCTION fields on regions");
1192 }
1193 return num_to_get;
1194 }
1195 }
1196
1197 // common
1198 int64_t BaseDatabaseIO::put_field_internal(const Ioss::Region * /* region */,
1199 const Ioss::Field &field, void *data,
1200 size_t data_size) const
1201 {
1202 // For now, assume that all TRANSIENT fields on a region
1203 // are REDUCTION fields (1 value). We need to gather these
1204 // and output them all at one time. The storage location is a
1205 // 'globalVariables' array
1206 {
1207 Ioss::SerializeIO serializeIO_(this);
1208
1209 Ioss::Field::RoleType role = field.get_role();
1210 size_t num_to_get = field.verify(data_size);
1211
1212 if ((role == Ioss::Field::TRANSIENT || role == Ioss::Field::REDUCTION) && num_to_get == 1) {
1213 store_reduction_field(field, get_region(), data);
1214 }
1215 else if (num_to_get != 1) {
1216 // There should have been a warning/error message printed to the
1217 // log file earlier for this, so we won't print anything else
1218 // here since it would be printed for each and every timestep....
1219 ;
1220 }
1221 else {
1222 IOSS_ERROR(fmt::format(
1223 "ERROR: The variable named '{}' is of the wrong type. A region variable must be of type"
1224 " TRANSIENT or REDUCTION.\n"
1225 "This is probably an internal error; please notify [email protected]",
1226 field.get_name()));
1227 }
1228 return num_to_get;
1229 }
1230 }
1231
1232 namespace {
1233 // common
1234 template <typename T>
1235 void generate_block_truth_table(const VariableNameMap &variables, Ioss::IntVector &truth_table,
1236 std::vector<T *> &blocks, char field_suffix_separator)
1237 {
1238 size_t block_count = blocks.size();
1239 size_t var_count = variables.size();
1240
1241 if (var_count == 0 || block_count == 0) {
1242 return;
1243 }
1244
1245 truth_table.resize(block_count * var_count);
1246
1247 // Fill in the truth table. It is conceptually a two-dimensional array of
1248 // the form 'array[num_blocks][num_element_var]'. In C++,
1249 // the values for the first block are first, followed by
1250 // next block, ...
1251 size_t offset = 0;
1252 for (const auto &block : blocks) {
1253 // Get names of all transient and reduction fields...
1254 Ioss::NameList results_fields = block->field_describe(Ioss::Field::TRANSIENT);
1255 block->field_describe(Ioss::Field::REDUCTION, &results_fields);
1256
1257 for (const auto &fn : results_fields) {
1258 Ioss::Field field = block->get_field(fn);
1259 Ioss::Field::BasicType ioss_type = field.get_type();
1260
1261 int re_im = 1;
1262 if (ioss_type == Ioss::Field::COMPLEX) {
1263 re_im = 2;
1264 }
1265 for (int complex_comp = 0; complex_comp < re_im; complex_comp++) {
1266 for (int i = 1; i <= field.get_component_count(Ioss::Field::InOut::INPUT); i++) {
1267 std::string var_string =
1268 field.get_component_name(i, Ioss::Field::InOut::INPUT, field_suffix_separator);
1269 // Find position of 'var_string' in 'variables'
1270 auto VN = variables.find(var_string);
1271 if (VN != variables.end()) {
1272 // Index '(*VN).second' is 1-based...
1273 truth_table[offset + (*VN).second - 1] = 1;
1274 }
1275 }
1276 }
1277 }
1278 offset += var_count;
1279 }
1280 assert(offset == var_count * block_count);
1281 }
1282 } // namespace
1283 // common
1284 void BaseDatabaseIO::store_reduction_field(const Ioss::Field &field,
1285 const Ioss::GroupingEntity *ge, void *variables) const
1286 {
1287 Ioss::Field::BasicType ioss_type = field.get_type();
1288 assert(ioss_type == Ioss::Field::REAL || ioss_type == Ioss::Field::INTEGER ||
1289 ioss_type == Ioss::Field::INT64 || ioss_type == Ioss::Field::COMPLEX);
1290 auto *rvar = static_cast<double *>(variables);
1291 auto *ivar = static_cast<int *>(variables);
1292 auto *ivar64 = static_cast<int64_t *>(variables);
1293
1294 auto id = ge->get_optional_property("id", 0);
1295
1296 auto type = Ioex::map_exodus_type(ge->type());
1297
1298 // Note that if the field's basic type is COMPLEX, then each component of
1299 // the VariableType is a complex variable consisting of a real and
1300 // imaginary part. Since exodus cannot handle complex variables,
1301 // we have to output a (real and imaginary) X (number of
1302 // components) fields. For example, if V is a 3d vector of complex
1303 // data, the data in the 'variables' array are v_x, v.im_x, v_y,
1304 // v.im_y, v_z, v.im_z which need to be output in six separate
1305 // exodus fields. These fields were already defined in
1306 // "write_results_metadata".
1307
1308 // get number of components, cycle through each component
1309 // and add suffix to base 'field_name'. Look up index
1310 // of this name in 'm_variables[EX_GLOBAL]' map
1311 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
1312 int var_index = 0;
1313
1314 int re_im = 1;
1315 if (field.get_type() == Ioss::Field::COMPLEX) {
1316 re_im = 2;
1317 }
1318 for (int complex_comp = 0; complex_comp < re_im; complex_comp++) {
1319 for (int i = 0; i < comp_count; i++) {
1320 std::string var_name = get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
1321
1322 #if GLOBALS_ARE_TRANSIENT
1323 if (type == EX_GLOBAL) {
1324 SMART_ASSERT(m_variables[type].find(var_name) != m_variables[type].end())(type)(var_name);
1325 var_index = m_variables[type].find(var_name)->second;
1326 }
1327 else {
1328 SMART_ASSERT(m_reductionVariables[type].find(var_name) !=
1329 m_reductionVariables[type].end())
1330 (type)(var_name);
1331 var_index = m_reductionVariables[type].find(var_name)->second;
1332 }
1333 #else
1334 SMART_ASSERT(m_reductionVariables[type].find(var_name) != m_reductionVariables[type].end())
1335 (type)(var_name);
1336 var_index = m_reductionVariables[type].find(var_name)->second;
1337 #endif
1338
1339 SMART_ASSERT(static_cast<int>(m_reductionValues[type][id].size()) >= var_index)
1340 (id)(m_reductionValues[type][id].size())(var_index);
1341
1342 // Transfer from 'variables' array.
1343 if (ioss_type == Ioss::Field::REAL || ioss_type == Ioss::Field::COMPLEX) {
1344 m_reductionValues[type][id][var_index - 1] = rvar[i];
1345 }
1346 else if (ioss_type == Ioss::Field::INTEGER) {
1347 m_reductionValues[type][id][var_index - 1] = ivar[i];
1348 }
1349 else if (ioss_type == Ioss::Field::INT64) {
1350 m_reductionValues[type][id][var_index - 1] = ivar64[i]; // FIX 64 UNSAFE
1351 }
1352 }
1353 }
1354 }
1355
1356 // common
1357 void BaseDatabaseIO::get_reduction_field(const Ioss::Field &field, const Ioss::GroupingEntity *ge,
1358 void *variables) const
1359 {
1360 auto id = ge->get_optional_property("id", 0);
1361 auto type = Ioex::map_exodus_type(ge->type());
1362
1363 Ioss::Field::BasicType ioss_type = field.get_type();
1364 assert(ioss_type == Ioss::Field::REAL || ioss_type == Ioss::Field::INTEGER ||
1365 ioss_type == Ioss::Field::INT64);
1366 auto *rvar = static_cast<double *>(variables);
1367 auto *ivar = static_cast<int *>(variables);
1368 auto *i64var = static_cast<int64_t *>(variables);
1369
1370 // get number of components, cycle through each component
1371 // and add suffix to base 'field_name'. Look up index
1372 // of this name in 'm_variables[type]' map
1373
1374 int comp_count = field.get_component_count(Ioss::Field::InOut::INPUT);
1375 for (int i = 0; i < comp_count; i++) {
1376 int var_index = 0;
1377 std::string var_name = get_component_name(field, Ioss::Field::InOut::INPUT, i + 1);
1378
1379 #if GLOBALS_ARE_TRANSIENT
1380 if (type == EX_GLOBAL) {
1381 assert(m_variables[type].find(var_name) != m_variables[type].end());
1382 var_index = m_variables[type].find(var_name)->second;
1383 }
1384 else {
1385 assert(m_reductionVariables[type].find(var_name) != m_reductionVariables[type].end());
1386 var_index = m_reductionVariables[type].find(var_name)->second;
1387 }
1388
1389 assert(static_cast<int>(m_reductionValues[type][id].size()) >= var_index);
1390 #else
1391 SMART_ASSERT(m_reductionVariables[type].find(var_name) != m_reductionVariables[type].end())
1392 (type)(var_name);
1393 var_index = m_reductionVariables[type].find(var_name)->second;
1394 SMART_ASSERT(static_cast<int>(m_reductionValues[type][id].size()) >= var_index);
1395 #endif
1396 // Transfer to 'variables' array.
1397 if (ioss_type == Ioss::Field::REAL) {
1398 rvar[i] = m_reductionValues[type][id][var_index - 1];
1399 }
1400 else if (ioss_type == Ioss::Field::INT64) {
1401 i64var[i] = static_cast<int64_t>(m_reductionValues[type][id][var_index - 1]);
1402 }
1403 else if (ioss_type == Ioss::Field::INTEGER) {
1404 ivar[i] = static_cast<int>(m_reductionValues[type][id][var_index - 1]);
1405 }
1406 }
1407 }
1408
1409 // common
1410 void BaseDatabaseIO::write_reduction_fields() const
1411 {
1412 int step = get_current_state();
1413 step = get_database_step(step);
1414 for (const auto &type : exodus_types) {
1415 const auto &id_values = m_reductionValues[type];
1416 for (const auto &values : id_values) {
1417 int64_t id = values.first;
1418 auto &vals = values.second;
1419 size_t count = vals.size();
1420 if (count > 0) {
1421 int ierr = ex_put_reduction_vars(get_file_pointer(), step, type, id, count, Data(vals));
1422 if (ierr < 0) {
1423 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1424 }
1425 }
1426 }
1427 }
1428 }
1429
1430 // common
1431 void BaseDatabaseIO::read_reduction_fields() const
1432 {
1433 int step = get_current_state();
1434
1435 for (const auto &type : exodus_types) {
1436 const auto &id_values = m_reductionValues[type];
1437 for (const auto &values : id_values) {
1438 int64_t id = values.first;
1439 auto &vals = values.second;
1440 size_t count = vals.size();
1441 if (count > 0) {
1442 int ierr = ex_get_reduction_vars(get_file_pointer(), step, type, id, count,
1443 (double *)Data(vals));
1444 if (ierr < 0) {
1445 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1446 }
1447 }
1448 }
1449 }
1450 }
1451
1452 // common
1453 bool BaseDatabaseIO::begin_nl(Ioss::State state)
1454 {
1455 dbState = state;
1456 return true;
1457 }
1458
1459 // common
1460 bool BaseDatabaseIO::end_nl(Ioss::State state)
1461 {
1462 // Transitioning out of state 'state'
1463 assert(state == dbState);
1464 switch (state) {
1465 case Ioss::STATE_DEFINE_MODEL:
1466 if (!is_input()) {
1467 write_meta_data(open_create_behavior());
1468 }
1469 break;
1470 case Ioss::STATE_DEFINE_TRANSIENT:
1471 if (!is_input()) {
1472 write_results_metadata(true, open_create_behavior());
1473 }
1474 break;
1475 default: // ignore everything else...
1476 break;
1477 }
1478
1479 {
1480 Ioss::SerializeIO serializeIO_(this);
1481
1482 if (!is_input()) {
1483 ex_update(get_file_pointer());
1484 if (minimizeOpenFiles) {
1485 free_file_pointer();
1486 }
1487 }
1488 dbState = Ioss::STATE_UNKNOWN;
1489 }
1490
1491 return true;
1492 }
1493
1494 void BaseDatabaseIO::open_state_file(int state)
1495 {
1496 // Close current file...
1497 free_file_pointer();
1498
1499 // Update filename to append state count...
1500 decodedFilename.clear();
1501
1502 Ioss::FileInfo db(originalDBFilename);
1503 std::string new_filename;
1504 if (!db.pathname().empty()) {
1505 new_filename += db.pathname() + "/";
1506 }
1507
1508 if (get_cycle_count() >= 1) {
1509 static const std::string suffix{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
1510 int index = (state - 1) % get_cycle_count();
1511 new_filename += db.basename() + "-state-" + suffix[index] + "." + db.extension();
1512 }
1513 else {
1514 new_filename += db.basename() + "-state-" + std::to_string(state) + "." + db.extension();
1515 }
1516
1517 DBFilename = new_filename;
1518 fileExists = false;
1519
1520 ex_var_params exo_params{};
1521 #if GLOBALS_ARE_TRANSIENT
1522 exo_params.num_glob = m_variables[EX_GLOBAL].size();
1523 #else
1524 exo_params.num_glob = m_reductionVariables[EX_GLOBAL].size();
1525 #endif
1526 exo_params.num_node = m_variables[EX_NODE_BLOCK].size();
1527 exo_params.num_edge = m_variables[EX_EDGE_BLOCK].size();
1528 exo_params.num_face = m_variables[EX_FACE_BLOCK].size();
1529 exo_params.num_elem = m_variables[EX_ELEM_BLOCK].size();
1530 exo_params.num_nset = m_variables[EX_NODE_SET].size();
1531 exo_params.num_eset = m_variables[EX_EDGE_SET].size();
1532 exo_params.num_fset = m_variables[EX_FACE_SET].size();
1533 exo_params.num_sset = m_variables[EX_SIDE_SET].size();
1534 exo_params.num_elset = m_variables[EX_ELEM_SET].size();
1535
1536 char the_title[max_line_length + 1];
1537
1538 // Title...
1539 if (get_region()->property_exists("title")) {
1540 std::string title_str = get_region()->get_property("title").get_string();
1541 Ioss::Utils::copy_string(the_title, title_str);
1542 }
1543 else {
1544 Ioss::Utils::copy_string(the_title, "IOSS Default Output Title");
1545 }
1546
1547 Ioex::Mesh mesh(spatialDimension, the_title, util(), !usingParallelIO);
1548 mesh.populate(get_region());
1549
1550 // Write the metadata to the exodus file...
1551 Ioex::Internals data(get_file_pointer(), maximumNameLength, util());
1552 int ierr = data.initialize_state_file(mesh, exo_params, originalDBFilename);
1553
1554 if (ierr < 0) {
1555 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1556 }
1557 }
1558
1559 bool BaseDatabaseIO::begin_state_nl(int state, double time)
1560 {
1561 Ioss::SerializeIO serializeIO_(this);
1562
1563 time /= timeScaleFactor;
1564
1565 if (!is_input()) {
1566 if (get_file_per_state()) {
1567 // Close current file; create new file and output transient metadata...
1568 open_state_file(state);
1569 write_results_metadata(false, open_create_behavior());
1570 }
1571 int ierr = ex_put_time(get_file_pointer(), get_database_step(state), &time);
1572 if (ierr < 0) {
1573 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1574 }
1575
1576 // Zero global variable array...
1577 for (const auto &type : exodus_types) {
1578 auto &id_values = m_reductionValues[type];
1579 for (auto &values : id_values) {
1580 auto &vals = values.second;
1581 std::fill(vals.begin(), vals.end(), 0.0);
1582 }
1583 }
1584 }
1585 else {
1586 // Store reduction variables
1587 read_reduction_fields();
1588 }
1589 return true;
1590 }
1591
1592 // common
1593 bool BaseDatabaseIO::end_state_nl(int state, double time)
1594 {
1595 Ioss::SerializeIO serializeIO_(this);
1596
1597 if (!is_input()) {
1598 write_reduction_fields();
1599 time /= timeScaleFactor;
1600 finalize_write(state, time);
1601 if (minimizeOpenFiles) {
1602 free_file_pointer();
1603 }
1604 }
1605 return true;
1606 }
1607
1608 // common
1609 void BaseDatabaseIO::add_region_fields()
1610 {
1611 #if GLOBALS_ARE_TRANSIENT
1612 int field_count = add_results_fields(get_region());
1613 #else
1614 int field_count = add_reduction_results_fields(get_region());
1615 #endif
1616 m_reductionValues[EX_GLOBAL][0].resize(field_count);
1617 add_mesh_reduction_fields(0, get_region());
1618 }
1619
1620 namespace {
1621 // Memory allocated in `ex_get_attributes`, this makes deletion cleaner...
1622 class EX_attribute : public ex_attribute
1623 {
1624 public:
1625 EX_attribute() { values = nullptr; }
1626 ~EX_attribute() { free(values); }
1627 };
1628 } // namespace
1629
1630 void BaseDatabaseIO::add_mesh_reduction_fields(int64_t id, Ioss::GroupingEntity *entity)
1631 {
1632 // Get "global attributes"
1633 // These are single key-value per grouping entity
1634 // Stored as Ioss::Property with origin of ATTRIBUTE
1635 Ioss::SerializeIO serializeIO_(this);
1636 auto type = Ioex::map_exodus_type(entity->type());
1637 int att_count = ex_get_attribute_count(get_file_pointer(), type, id);
1638
1639 if (att_count > 0) {
1640 std::vector<EX_attribute> attr(att_count);
1641 ex_get_attribute_param(get_file_pointer(), type, id, Data(attr));
1642 ex_get_attributes(get_file_pointer(), att_count, Data(attr));
1643
1644 // Create a property on `entity` for each `attribute`
1645 for (const auto &att : attr) {
1646 if (att.value_count == 0) {
1647 // Just an attribute name. Give it an empty value...
1648 entity->property_add(Ioss::Property(att.name, "", Ioss::Property::ATTRIBUTE));
1649 continue;
1650 }
1651 assert(att.values != nullptr);
1652
1653 switch (att.type) {
1654 case EX_INTEGER: {
1655 const auto *idata = static_cast<int *>(att.values);
1656 if (att.value_count == 1) {
1657 entity->property_add(Ioss::Property(att.name, *idata, Ioss::Property::ATTRIBUTE));
1658 }
1659 else {
1660 std::vector<int> tmp(att.value_count);
1661 std::copy(idata, idata + att.value_count, tmp.begin());
1662 entity->property_add(Ioss::Property(att.name, tmp, Ioss::Property::ATTRIBUTE));
1663 }
1664 } break;
1665 case EX_DOUBLE: {
1666 const auto *ddata = static_cast<double *>(att.values);
1667 if (att.value_count == 1) {
1668 entity->property_add(Ioss::Property(att.name, *ddata, Ioss::Property::ATTRIBUTE));
1669 }
1670 else {
1671 std::vector<double> tmp(att.value_count);
1672 std::copy(ddata, ddata + att.value_count, tmp.begin());
1673 entity->property_add(Ioss::Property(att.name, tmp, Ioss::Property::ATTRIBUTE));
1674 }
1675 } break;
1676 case EX_CHAR: {
1677 const auto *cdata = static_cast<char *>(att.values);
1678 entity->property_add(Ioss::Property(att.name, cdata, Ioss::Property::ATTRIBUTE));
1679 } break;
1680 }
1681 }
1682 }
1683 }
1684
1685 // common
1686 int64_t BaseDatabaseIO::add_results_fields(Ioss::GroupingEntity *entity, int64_t position)
1687 {
1688 ex_entity_type type = Ioex::map_exodus_type(entity->type());
1689 return internal_add_results_fields(type, entity, position, m_groupCount[type],
1690 m_truthTable[type], m_variables[type]);
1691 }
1692
1693 // common
1694 int64_t BaseDatabaseIO::internal_add_results_fields(ex_entity_type type,
1695 Ioss::GroupingEntity *entity,
1696 int64_t position, int64_t block_count,
1697 Ioss::IntVector &truth_table,
1698 Ioex::VariableNameMap &variables)
1699 {
1700 int nvar = 0;
1701 {
1702 Ioss::SerializeIO serializeIO_(this);
1703
1704 int ierr = ex_get_variable_param(get_file_pointer(), type, &nvar);
1705 if (ierr < 0) {
1706 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1707 }
1708 }
1709
1710 if (nvar > 0) {
1711
1712 if (truth_table.empty()) {
1713 truth_table.resize(block_count * nvar);
1714
1715 // Read and store the truth table (Should be there since we only
1716 // get to this routine if there are variables...)
1717
1718 if (type == EX_NODE_BLOCK || type == EX_GLOBAL || type == EX_ASSEMBLY) {
1719 // These types don't have a truth table in the exodus api...
1720 // They do in Ioss just for some consistency...
1721 std::fill(truth_table.begin(), truth_table.end(), 1);
1722 }
1723 else {
1724 Ioss::SerializeIO serializeIO_(this);
1725 int ierr =
1726 ex_get_truth_table(get_file_pointer(), type, block_count, nvar, Data(truth_table));
1727 if (ierr < 0) {
1728 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1729 }
1730 }
1731
1732 // If parallel, then synchronize the truth table among all
1733 // processors... Need to know that block_X has variable_Y
1734 // even if block_X is empty on a specific processor... The
1735 // truth table contains 0 if the variable doesn't exist and 1
1736 // if it does, so we just take the maximum at each location...
1737 // This is a collective call... Make sure not in Serialize
1738 if (isParallel) {
1739 util().global_array_minmax(truth_table, Ioss::ParallelUtils::DO_MAX);
1740 }
1741 }
1742
1743 // Get the variable names and add as fields. Need to decode these
1744 // into vector/tensor/... eventually, for now store all as
1745 // scalars.
1746
1747 // Read the names...
1748 // (Currently, names are read for every block. We could save them...)
1749 Ioss::NameList names;
1750 {
1751 Ioss::SerializeIO serializeIO_(this);
1752 names = Ioex::get_variable_names(nvar, maximumNameLength, get_file_pointer(), type);
1753 }
1754
1755 // Add to VariableNameMap so can determine exodusII index given a
1756 // Sierra field name. exodusII index is just 'i+1'
1757 for (int i = 0; i < nvar; i++) {
1758 std::string var = names[i];
1759 if (lowerCaseVariableNames) {
1760 Ioss::Utils::fixup_name(var);
1761 }
1762 variables.insert(VNMValuePair(var, i + 1));
1763 }
1764
1765 int offset = position * nvar;
1766 int *local_truth = nullptr;
1767 if (!truth_table.empty()) {
1768 local_truth = &truth_table[offset];
1769 }
1770
1771 // If the file contains field metadata, define fields via that mechanism...
1772 auto fields = get_fields_via_field_metadata(entity, type, names);
1773
1774 // Now, either get all fields via suffix matching, or if the file did not
1775 // specify all fields in the field metadata, get the rest...
1776 Ioss::Utils::get_fields(entity->entity_count(), names, Ioss::Field::TRANSIENT, this,
1777 local_truth, fields);
1778
1779 for (auto &field : fields) {
1780 if (lowerCaseVariableNames) {
1781 Ioss::Utils::fixup_name(field.get_name());
1782 }
1783 entity->field_add(field);
1784 }
1785
1786 for (auto [i, name] : Ioss::enumerate(names)) {
1787 // Verify that all names were used for a field...
1788 SMART_ASSERT(name.empty() || (local_truth && local_truth[i] == 0))(i)(name);
1789 }
1790 }
1791 return nvar;
1792 }
1793
1794 std::vector<Ioss::Field>
1795 Ioex::BaseDatabaseIO::get_fields_via_field_metadata(Ioss::GroupingEntity *entity,
1796 ex_entity_type type, Ioss::NameList &names)
1797 {
1798 std::vector<Ioss::Field> fields;
1799 if (!entity->get_database()->get_field_recognition()) {
1800 return fields;
1801 }
1802 // See if this entity is using enhanced field attributes...
1803 auto id = entity->get_optional_property("id", 0);
1804 int enhanced_fld_cnt;
1805 {
1806 Ioss::SerializeIO serializeIO_(this);
1807 enhanced_fld_cnt = ex_get_field_metadata_count(get_file_pointer(), type, id);
1808 }
1809
1810 if (enhanced_fld_cnt > 0) {
1811 std::vector<ex_field> exo_fields(enhanced_fld_cnt);
1812 for (auto &field : exo_fields) {
1813 field.entity_type = type;
1814 field.entity_id = id;
1815 }
1816
1817 {
1818 Ioss::SerializeIO serializeIO_(this);
1819 int ierr = ex_get_field_metadata(get_file_pointer(), Data(exo_fields));
1820 if (ierr < 0) {
1821 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1822 }
1823 }
1824
1825 for (const auto &exo_field : exo_fields) {
1826 std::string ios_field_type{};
1827
1828 auto type_names = Ioss::tokenize(exo_field.type_name, ",", true);
1829 if (exo_field.type[0] == EX_FIELD_TYPE_SEQUENCE) {
1830 ios_field_type = fmt::format("Real[{}]", exo_field.cardinality[0]);
1831 }
1832 else if (exo_field.type[0] == EX_FIELD_TYPE_USER_DEFINED) {
1833 auto suffices = Ioss::tokenize(exo_field.suffices, ",");
1834 Ioss::VariableType::create_named_suffix_type(exo_field.name, suffices);
1835 ios_field_type = exo_field.name;
1836 }
1837 else if (exo_field.type[0] == EX_BASIS || exo_field.type[0] == EX_QUADRATURE) {
1838 ios_field_type = Ioss::Utils::lowercase(type_names[0]);
1839 }
1840 else {
1841 ios_field_type = Ioex::map_ioss_field_type(exo_field.type[0]);
1842 }
1843
1844 int num_copies = 1;
1845 std::string secondary_field_type{};
1846
1847 if (exo_field.nesting == 2) {
1848 // For IOSS, the nesting is basically N copies of the field
1849 // at nesting level 1, so we just need to verify that the
1850 // field type is `EX_FIELD_TYPE_SEQUENCE`, `EX_BASIS`, or
1851 // `EX_QUADRATURE` and then get the cardinality...
1852 if (exo_field.type[1] == EX_FIELD_TYPE_SEQUENCE) {
1853 num_copies = exo_field.cardinality[1];
1854 }
1855 else if (exo_field.type[1] == EX_BASIS || exo_field.type[1] == EX_QUADRATURE) {
1856 secondary_field_type = Ioss::Utils::lowercase(type_names[1]);
1857 }
1858 else {
1859 fmt::print("ERROR: Unrecognized field type for nested field.\n");
1860 }
1861 }
1862 if (secondary_field_type.empty()) {
1863 fields.emplace_back(exo_field.name, Ioss::Field::REAL, ios_field_type, num_copies,
1864 Ioss::Field::TRANSIENT, entity->entity_count());
1865 }
1866 else {
1867 fields.emplace_back(exo_field.name, Ioss::Field::REAL, ios_field_type,
1868 secondary_field_type, Ioss::Field::TRANSIENT, entity->entity_count());
1869 }
1870
1871 auto &field = fields.back();
1872 if (exo_field.nesting == 1) {
1873 field.set_suffix_separator(exo_field.component_separator[0]);
1874 }
1875 else {
1876 field.set_suffix_separator(exo_field.component_separator[0],
1877 exo_field.component_separator[1]);
1878 }
1879
1880 if (lowerCaseVariableNames) {
1881 field.set_suffices_uppercase(false);
1882 }
1883
1884 // Now remove the used field+component names from `names` to verify that we found all
1885 // fields on this entity... (Also set suffices_uppercase...)
1886 for (int i = 0; i < field.get_component_count(Ioss::Field::InOut::INPUT); i++) {
1887 auto comp_name = field.get_component_name(i + 1, Ioss::Field::InOut::INPUT);
1888 // Find `comp_name` in `names`...
1889 for (size_t j = 0; j < names.size(); j++) {
1890 if (Ioss::Utils::str_equal(comp_name, names[j])) {
1891 if (!lowerCaseVariableNames &&
1892 field.get_component_count(Ioss::Field::InOut::INPUT) > 1 && i == 0) {
1893 // Find the last-most alphabetic character...
1894 auto len = names[j].length();
1895 for (size_t k = 0; k < len; k++) {
1896 if (isalpha(names[j][len - k - 1])) {
1897 field.set_suffices_uppercase(isupper(names[j][len - k - 1]));
1898 break;
1899 }
1900 }
1901 }
1902 names[j] = "";
1903 break;
1904 }
1905 }
1906 }
1907
1908 #if IOSS_DEBUG_OUTPUT
1909 if (myProcessor == 0) {
1910 fmt::print(Ioss::DebugOut(), "Enhanced Field: Adding to {} {}:\n\t{}\n",
1911 entity->type_string(), entity->name(), field);
1912 }
1913 #endif
1914 }
1915 }
1916 return fields;
1917 }
1918
1919 // common
1920 int64_t BaseDatabaseIO::add_reduction_results_fields(Ioss::GroupingEntity *entity)
1921 {
1922 ex_entity_type type = Ioex::map_exodus_type(entity->type());
1923 int nvar = 0;
1924 {
1925 Ioss::SerializeIO serializeIO_(this);
1926
1927 int ierr = ex_get_reduction_variable_param(get_file_pointer(), type, &nvar);
1928 if (ierr < 0) {
1929 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
1930 }
1931 }
1932
1933 if (nvar > 0) {
1934 // Get the variable names and add as fields. Need to decode these
1935 // into vector/tensor/... eventually, for now store all as
1936 // scalars.
1937 Ioss::NameList names;
1938 {
1939 Ioss::SerializeIO serializeIO_(this);
1940 names =
1941 Ioex::get_reduction_variable_names(nvar, maximumNameLength, get_file_pointer(), type);
1942 }
1943
1944 // Add to VariableNameMap so can determine exodusII index given a
1945 // Sierra field name. exodusII index is just 'i+1'
1946 auto &variables = m_reductionVariables[type];
1947 for (int i = 0; i < nvar; i++) {
1948 if (lowerCaseVariableNames) {
1949 Ioss::Utils::fixup_name(names[i]);
1950 }
1951 variables.insert(VNMValuePair(std::string(names[i]), i + 1));
1952 }
1953
1954 int *local_truth = nullptr;
1955
1956 std::vector<Ioss::Field> fields;
1957 int64_t count = 1;
1958 Ioss::Utils::get_fields(count, names, Ioss::Field::REDUCTION, this, local_truth, fields);
1959
1960 for (const auto &field : fields) {
1961 entity->field_add(field);
1962 }
1963
1964 for (int i = 0; i < nvar; i++) {
1965 // Verify that all names were used for a field...
1966 assert(names[i].empty() || (local_truth && local_truth[i] == 0));
1967 }
1968 }
1969 return nvar;
1970 }
1971
1972 // common
1973 void BaseDatabaseIO::write_results_metadata(bool gather_data,
1974 Ioss::IfDatabaseExistsBehavior behavior)
1975 {
1976 if (gather_data) {
1977 int glob_index = 0;
1978 #if GLOBALS_ARE_TRANSIENT
1979 glob_index = gather_names(m_variables[EX_GLOBAL], get_region(), glob_index, true);
1980 #else
1981 glob_index = gather_names(m_reductionVariables[EX_GLOBAL], get_region(), glob_index, true);
1982 #endif
1983 m_reductionValues[EX_GLOBAL][0].resize(glob_index);
1984
1985 const Ioss::NodeBlockContainer &node_blocks = get_region()->get_node_blocks();
1986 assert(node_blocks.size() <= 1);
1987 internal_gather_results_metadata(EX_NODE_BLOCK, node_blocks);
1988
1989 const Ioss::EdgeBlockContainer &edge_blocks = get_region()->get_edge_blocks();
1990 internal_gather_results_metadata(EX_EDGE_BLOCK, edge_blocks);
1991
1992 const Ioss::FaceBlockContainer &face_blocks = get_region()->get_face_blocks();
1993 internal_gather_results_metadata(EX_FACE_BLOCK, face_blocks);
1994
1995 const Ioss::ElementBlockContainer &element_blocks = get_region()->get_element_blocks();
1996 internal_gather_results_metadata(EX_ELEM_BLOCK, element_blocks);
1997
1998 const Ioss::NodeSetContainer &nodesets = get_region()->get_nodesets();
1999 internal_gather_results_metadata(EX_NODE_SET, nodesets);
2000
2001 const Ioss::EdgeSetContainer &edgesets = get_region()->get_edgesets();
2002 internal_gather_results_metadata(EX_EDGE_SET, edgesets);
2003
2004 const Ioss::FaceSetContainer &facesets = get_region()->get_facesets();
2005 internal_gather_results_metadata(EX_FACE_SET, facesets);
2006
2007 const Ioss::ElementSetContainer &elementsets = get_region()->get_elementsets();
2008 internal_gather_results_metadata(EX_ELEM_SET, elementsets);
2009
2010 const auto &blobs = get_region()->get_blobs();
2011 internal_gather_results_metadata(EX_BLOB, blobs);
2012
2013 const auto &assemblies = get_region()->get_assemblies();
2014 internal_gather_results_metadata(EX_ASSEMBLY, assemblies);
2015
2016 {
2017 int index = 0;
2018 const Ioss::SideSetContainer &sidesets = get_region()->get_sidesets();
2019 for (const auto &sideset : sidesets) {
2020 const Ioss::SideBlockContainer &side_blocks = sideset->get_side_blocks();
2021 for (const auto &block : side_blocks) {
2022 glob_index = gather_names(m_reductionVariables[EX_SIDE_SET], block, glob_index, true);
2023 index = gather_names(m_variables[EX_SIDE_SET], block, index, false);
2024 }
2025 }
2026 generate_sideset_truth_table();
2027 }
2028 }
2029
2030 if (behavior != Ioss::DB_APPEND && behavior != Ioss::DB_MODIFY) {
2031 ex_var_params exo_params{};
2032 #if GLOBALS_ARE_TRANSIENT
2033 exo_params.num_glob = m_variables[EX_GLOBAL].size();
2034 #else
2035 exo_params.num_glob = m_reductionVariables[EX_GLOBAL].size();
2036 #endif
2037 exo_params.num_node = m_variables[EX_NODE_BLOCK].size();
2038 exo_params.num_edge = m_variables[EX_EDGE_BLOCK].size();
2039 exo_params.num_face = m_variables[EX_FACE_BLOCK].size();
2040 exo_params.num_elem = m_variables[EX_ELEM_BLOCK].size();
2041 exo_params.num_nset = m_variables[EX_NODE_SET].size();
2042 exo_params.num_eset = m_variables[EX_EDGE_SET].size();
2043 exo_params.num_fset = m_variables[EX_FACE_SET].size();
2044 exo_params.num_sset = m_variables[EX_SIDE_SET].size();
2045 exo_params.num_elset = m_variables[EX_ELEM_SET].size();
2046
2047 exo_params.edge_var_tab = Data(m_truthTable[EX_EDGE_BLOCK]);
2048 exo_params.face_var_tab = Data(m_truthTable[EX_FACE_BLOCK]);
2049 exo_params.elem_var_tab = Data(m_truthTable[EX_ELEM_BLOCK]);
2050 exo_params.nset_var_tab = Data(m_truthTable[EX_NODE_SET]);
2051 exo_params.eset_var_tab = Data(m_truthTable[EX_EDGE_SET]);
2052 exo_params.fset_var_tab = Data(m_truthTable[EX_FACE_SET]);
2053 exo_params.sset_var_tab = Data(m_truthTable[EX_SIDE_SET]);
2054 exo_params.elset_var_tab = Data(m_truthTable[EX_ELEM_SET]);
2055
2056 if (isParallel) {
2057 // Check consistency among all processors. They should all
2058 // have the same number of each variable type...
2059 // The called function will throw an exception if the counts differ.
2060 check_variable_consistency(exo_params, myProcessor, get_filename(), util());
2061 }
2062
2063 {
2064 Ioss::SerializeIO serializeIO_(this);
2065
2066 int ierr = ex_put_all_var_param_ext(get_file_pointer(), &exo_params);
2067 if (ierr < 0) {
2068 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
2069 }
2070
2071 // Blob and Assembly not supported in ex_put_all_var_param_ext...
2072 if (!m_variables[EX_BLOB].empty()) {
2073 ierr = ex_put_variable_param(get_file_pointer(), EX_BLOB, m_variables[EX_BLOB].size());
2074 if (ierr < 0) {
2075 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
2076 }
2077 }
2078 if (!m_variables[EX_ASSEMBLY].empty()) {
2079 ierr = ex_put_variable_param(get_file_pointer(), EX_ASSEMBLY,
2080 m_variables[EX_ASSEMBLY].size());
2081 if (ierr < 0) {
2082 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
2083 }
2084 }
2085
2086 for (const auto &type : exodus_types) {
2087 output_results_names(type, m_variables[type], false);
2088 output_results_names(type, m_reductionVariables[type], true);
2089 }
2090 }
2091
2092 // Output field metadata
2093 bool do_metadata = false;
2094 Ioss::Utils::check_set_bool_property(properties, "OUTPUT_FIELD_METADATA", do_metadata);
2095 if (do_metadata) {
2096 output_field_metadata();
2097 }
2098 }
2099 }
2100
2101 namespace {
2102 void internal_output_field_metadata(int exoid, ex_entity_type type,
2103 Ioss::GroupingEntity *entity)
2104 {
2105 // Get all transient fields on this entity...
2106 char default_separator = entity->get_database()->get_field_separator();
2107 auto results_fields = entity->field_describe(Ioss::Field::TRANSIENT);
2108
2109 std::vector<ex_field> exo_fields(results_fields.size());
2110 for (const auto &[i, field_name] : Ioss::enumerate(results_fields)) {
2111 exo_fields[i].type[0] = EX_SCALAR;
2112
2113 const auto &field = entity->get_fieldref(field_name);
2114
2115 Ioss::Utils::copy_string(exo_fields[i].name, field_name);
2116 exo_fields[i].entity_type = type;
2117 exo_fields[i].entity_id = entity->get_optional_property("id", 0);
2118
2119 auto *storage = field.transformed_storage();
2120 auto storage_type = storage->type();
2121
2122 if (storage_type == Ioss::VariableType::Type::COMPOSED) {
2123 exo_fields[i].nesting = 2;
2124
2125 const auto *composed = dynamic_cast<const Ioss::ComposedVariableType *>(storage);
2126 assert(composed != nullptr);
2127 exo_fields[i].type[0] = Ioex::map_ioss_field_type(composed->get_base_type());
2128 exo_fields[i].cardinality[0] = composed->get_base_type()->component_count();
2129 char separator0 = field.get_suffix_separator();
2130 exo_fields[i].component_separator[0] = separator0 == 1 ? default_separator : separator0;
2131
2132 if (exo_fields[i].type[0] == EX_FIELD_TYPE_USER_DEFINED) {
2133 assert(composed->get_base_type()->type() == Ioss::VariableType::Type::NAMED_SUFFIX);
2134 auto nsvt =
2135 dynamic_cast<const Ioss::NamedSuffixVariableType *>(composed->get_base_type());
2136 assert(nsvt != nullptr);
2137 std::string suffices{};
2138 for (int ii = 0; ii < nsvt->component_count(); ii++) {
2139 if (ii > 0) {
2140 suffices += ",";
2141 }
2142 suffices += nsvt->label(ii + 1, 0);
2143 }
2144 Ioss::Utils::copy_string(exo_fields[i].suffices, suffices.c_str(), EX_MAX_NAME + 1);
2145 }
2146
2147 exo_fields[i].type[1] = Ioex::map_ioss_field_type(composed->get_secondary_type());
2148 exo_fields[i].cardinality[1] = composed->get_secondary_type()->component_count();
2149 char separator1 = field.get_suffix_separator(1);
2150 exo_fields[i].component_separator[1] = separator1 == 1 ? default_separator : separator1;
2151 if (exo_fields[i].type[1] == EX_BASIS || exo_fields[i].type[1] == EX_QUADRATURE) {
2152 exo_fields[i].type_name[0] = ',';
2153 Ioss::Utils::copy_string(&exo_fields[i].type_name[1],
2154 composed->get_secondary_type()->name(), EX_MAX_NAME);
2155 }
2156 }
2157 else if (storage_type == Ioss::VariableType::Type::COMPOSITE) {
2158 exo_fields[i].nesting = 2;
2159
2160 const auto *composite = dynamic_cast<const Ioss::CompositeVariableType *>(storage);
2161 assert(composite != nullptr);
2162 exo_fields[i].type[0] = Ioex::map_ioss_field_type(composite->get_base_type());
2163 exo_fields[i].cardinality[0] = composite->get_base_type()->component_count();
2164 char separator0 = field.get_suffix_separator();
2165 exo_fields[i].component_separator[0] = separator0 == 1 ? default_separator : separator0;
2166
2167 exo_fields[i].type[1] = EX_FIELD_TYPE_SEQUENCE;
2168 exo_fields[i].cardinality[1] = composite->get_num_copies();
2169 char separator1 = field.get_suffix_separator(1);
2170 exo_fields[i].component_separator[1] = separator1 == 1 ? default_separator : separator1;
2171 }
2172 else {
2173 exo_fields[i].nesting = 1;
2174 exo_fields[i].type[0] = Ioex::map_ioss_field_type(storage);
2175 if (exo_fields[i].type[0] == EX_FIELD_TYPE_SEQUENCE) {
2176 exo_fields[i].cardinality[0] = storage->component_count();
2177 }
2178 if (exo_fields[i].type[0] == EX_BASIS) {
2179 assert(storage->type() == Ioss::VariableType::Type::BASIS);
2180 const auto *basis = dynamic_cast<const Ioss::BasisVariableType *>(storage);
2181 assert(basis != nullptr);
2182 exo_fields[i].cardinality[0] = storage->component_count();
2183 Ioss::Utils::copy_string(exo_fields[i].type_name, basis->name());
2184 }
2185 if (exo_fields[i].type[0] == EX_QUADRATURE) {
2186 assert(storage->type() == Ioss::VariableType::Type::QUADRATURE);
2187 const auto *quad = dynamic_cast<const Ioss::QuadratureVariableType *>(storage);
2188 assert(quad != nullptr);
2189 exo_fields[i].cardinality[0] = storage->component_count();
2190 Ioss::Utils::copy_string(exo_fields[i].type_name, quad->name());
2191 }
2192 if (exo_fields[i].type[0] == EX_FIELD_TYPE_USER_DEFINED) {
2193 assert(storage->type() == Ioss::VariableType::Type::NAMED_SUFFIX);
2194 auto nsvt = dynamic_cast<const Ioss::NamedSuffixVariableType *>(storage);
2195 assert(nsvt != nullptr);
2196 exo_fields[i].cardinality[0] = nsvt->component_count();
2197 std::string suffices{};
2198 for (int ii = 0; ii < nsvt->component_count(); ii++) {
2199 if (ii > 0) {
2200 suffices += ",";
2201 }
2202 suffices += nsvt->label(ii + 1, 0);
2203 }
2204 Ioss::Utils::copy_string(exo_fields[i].suffices, suffices.c_str(), EX_MAX_NAME + 1);
2205 }
2206 char separator = field.get_suffix_separator();
2207 exo_fields[i].component_separator[0] = separator == 1 ? default_separator : separator;
2208 }
2209 }
2210
2211 ex_put_multi_field_metadata(exoid, Data(exo_fields), exo_fields.size());
2212 for (const auto &exo_field : exo_fields) {
2213 if (exo_field.type[0] != EX_SCALAR) {
2214 if (exo_field.type[0] == EX_FIELD_TYPE_USER_DEFINED) {
2215 ex_put_field_suffices(exoid, exo_field, exo_field.suffices);
2216 }
2217 }
2218 }
2219 }
2220
2221 void output_basis(int exoid, const Ioss::VariableType *var)
2222 {
2223 const auto *basis = dynamic_cast<const Ioss::BasisVariableType *>(var);
2224 assert(basis != nullptr);
2225 ex_basis exo_basis{};
2226 exo_basis.cardinality = basis->component_count();
2227 ex_initialize_basis_struct(&exo_basis, 1, 1);
2228 Ioss::Utils::copy_string(exo_basis.name, basis->name(), EX_MAX_NAME);
2229 for (int i = 0; i < basis->component_count(); i++) {
2230 const auto &component = basis->get_basis_component(i + 1);
2231 exo_basis.subc_dim[i] = component.subc_dim;
2232 exo_basis.subc_ordinal[i] = component.subc_ordinal;
2233 exo_basis.subc_dof_ordinal[i] = component.subc_dof_ordinal;
2234 exo_basis.subc_num_dof[i] = component.subc_num_dof;
2235 exo_basis.xi[i] = component.xi;
2236 exo_basis.eta[i] = component.eta;
2237 exo_basis.zeta[i] = component.zeta;
2238 }
2239 ex_put_basis(exoid, exo_basis);
2240 ex_initialize_basis_struct(&exo_basis, 1, -1);
2241 }
2242
2243 void output_quad(int exoid, const Ioss::VariableType *var)
2244 {
2245 const auto *quadrature = dynamic_cast<const Ioss::QuadratureVariableType *>(var);
2246 assert(quadrature != nullptr);
2247 ex_quadrature exo_quadrature{};
2248 exo_quadrature.cardinality = quadrature->component_count();
2249 ex_initialize_quadrature_struct(&exo_quadrature, 1, 1);
2250 Ioss::Utils::copy_string(exo_quadrature.name, quadrature->name(), EX_MAX_NAME);
2251 const auto &quad = quadrature->get_quadrature();
2252 for (const auto &[i, component] : Ioss::enumerate(quad)) {
2253 exo_quadrature.xi[i] = component.xi;
2254 exo_quadrature.eta[i] = component.eta;
2255 exo_quadrature.zeta[i] = component.zeta;
2256 exo_quadrature.weight[i] = component.weight;
2257 }
2258 ex_put_quadrature(exoid, exo_quadrature);
2259 ex_initialize_quadrature_struct(&exo_quadrature, 1, -1);
2260 }
2261
2262 void output_type_metadata(int exoid)
2263 {
2264 // Iterate the list and output the `quadrature` and `basis` types...
2265 auto basis_list = Ioss::VariableType::external_types(Ioss::VariableType::Type::BASIS);
2266 for (auto &var : basis_list) {
2267 output_basis(exoid, var);
2268 }
2269
2270 auto quad_list = Ioss::VariableType::external_types(Ioss::VariableType::Type::QUADRATURE);
2271 for (auto &var : quad_list) {
2272 output_quad(exoid, var);
2273 }
2274 }
2275
2276 template <typename T>
2277 void internal_output_field_metadata(int exoid, ex_entity_type type, std::vector<T *> entities)
2278 {
2279 for (const auto &entity : entities) {
2280 internal_output_field_metadata(exoid, type, entity);
2281 }
2282 }
2283 } // namespace
2284
2285 void BaseDatabaseIO::output_field_metadata()
2286 {
2287 Ioss::SerializeIO serializeIO_(this);
2288 // Output the 'basis' and 'quadrature' type metadata...
2289 exi_persist_redef(get_file_pointer(), __func__);
2290 output_type_metadata(get_file_pointer());
2291
2292 const Ioss::NodeBlockContainer &node_blocks = get_region()->get_node_blocks();
2293 assert(node_blocks.size() <= 1);
2294 internal_output_field_metadata(get_file_pointer(), EX_NODE_BLOCK, node_blocks);
2295
2296 const Ioss::EdgeBlockContainer &edge_blocks = get_region()->get_edge_blocks();
2297 internal_output_field_metadata(get_file_pointer(), EX_EDGE_BLOCK, edge_blocks);
2298
2299 const Ioss::FaceBlockContainer &face_blocks = get_region()->get_face_blocks();
2300 internal_output_field_metadata(get_file_pointer(), EX_FACE_BLOCK, face_blocks);
2301
2302 const Ioss::ElementBlockContainer &element_blocks = get_region()->get_element_blocks();
2303 internal_output_field_metadata(get_file_pointer(), EX_ELEM_BLOCK, element_blocks);
2304
2305 const Ioss::NodeSetContainer &nodesets = get_region()->get_nodesets();
2306 internal_output_field_metadata(get_file_pointer(), EX_NODE_SET, nodesets);
2307
2308 const Ioss::EdgeSetContainer &edgesets = get_region()->get_edgesets();
2309 internal_output_field_metadata(get_file_pointer(), EX_EDGE_SET, edgesets);
2310
2311 const Ioss::FaceSetContainer &facesets = get_region()->get_facesets();
2312 internal_output_field_metadata(get_file_pointer(), EX_FACE_SET, facesets);
2313
2314 const Ioss::ElementSetContainer &elementsets = get_region()->get_elementsets();
2315 internal_output_field_metadata(get_file_pointer(), EX_ELEM_SET, elementsets);
2316
2317 const auto &blobs = get_region()->get_blobs();
2318 internal_output_field_metadata(get_file_pointer(), EX_BLOB, blobs);
2319
2320 const auto &assemblies = get_region()->get_assemblies();
2321 internal_output_field_metadata(get_file_pointer(), EX_ASSEMBLY, assemblies);
2322
2323 const Ioss::SideSetContainer &sidesets = get_region()->get_sidesets();
2324 internal_output_field_metadata(get_file_pointer(), EX_SIDE_SET, sidesets);
2325 exi_persist_leavedef(get_file_pointer(), __func__);
2326 }
2327
2328 // common
2329 template <typename T>
2330 void BaseDatabaseIO::internal_gather_results_metadata(ex_entity_type type,
2331 std::vector<T *> entities)
2332 {
2333 int index = 0;
2334 int red_index = 0;
2335 for (const auto &entity : entities) {
2336 red_index = gather_names(m_reductionVariables[type], entity, red_index, true);
2337 index = gather_names(m_variables[type], entity, index, false);
2338 }
2339
2340 #if GLOBALS_ARE_TRANSIENT
2341 size_t value_size =
2342 type == EX_GLOBAL ? m_variables[type].size() : m_reductionVariables[type].size();
2343 #else
2344 size_t value_size = m_reductionVariables[type].size();
2345 #endif
2346 for (const auto &entity : entities) {
2347 auto id = entity->get_optional_property("id", 0);
2348 m_reductionValues[type][id].resize(value_size);
2349 }
2350
2351 generate_block_truth_table(m_variables[type], m_truthTable[type], entities,
2352 get_field_separator());
2353 }
2354
2355 // common
2356 int BaseDatabaseIO::gather_names(VariableNameMap &variables, const Ioss::GroupingEntity *ge,
2357 int index, bool reduction)
2358 {
2359 int new_index = index;
2360
2361 auto type = Ioex::map_exodus_type(ge->type());
2362 bool nblock = (type == EX_NODE_BLOCK);
2363
2364 // Get names of all transient and reduction fields...
2365 Ioss::NameList results_fields;
2366 if (reduction) {
2367 ge->field_describe(Ioss::Field::REDUCTION, &results_fields);
2368 }
2369
2370 if (!reduction || type == EX_GLOBAL) {
2371 ge->field_describe(Ioss::Field::TRANSIENT, &results_fields);
2372 }
2373
2374 // Some applications will set the index on the field to get a specific
2375 // ordering of the fields. For exodus, we typically use that to get the
2376 // same output ordering as the input ordering. The output from `field_describe`
2377 // comes back sorted on field names. Lets check whether any of the fields
2378 // have an index set and if so, then sort the fields based on the index...
2379 std::vector<Ioss::Field> fields;
2380 fields.reserve(results_fields.size());
2381 for (const auto &name : results_fields) {
2382 fields.push_back(ge->get_field(name));
2383 }
2384 std::stable_sort(fields.begin(), fields.end(), [](const Ioss::Field &a, const Ioss::Field &b) {
2385 return a.get_index() < b.get_index();
2386 });
2387
2388 // NOTE: For exodusII, the convention is that the displacement
2389 // fields are the first 'ndim' fields in the file.
2390 // Try to find a likely displacement field
2391 std::string disp_name;
2392 bool has_disp = false;
2393 if (!reduction && nblock && new_index == 0) {
2394 has_disp = find_displacement_field(results_fields, ge, spatialDimension, &disp_name);
2395 if (has_disp) {
2396 new_index += spatialDimension;
2397 }
2398 }
2399
2400 int save_index = 0;
2401 for (const auto &field : fields) {
2402 if (has_disp && field.get_name() == disp_name && new_index != 0) {
2403 save_index = new_index;
2404 new_index = 0;
2405 }
2406
2407 int re_im = 1;
2408 if (field.get_type() == Ioss::Field::COMPLEX) {
2409 re_im = 2;
2410 }
2411 for (int complex_comp = 0; complex_comp < re_im; complex_comp++) {
2412 for (int i = 1; i <= field.get_component_count(Ioss::Field::InOut::OUTPUT); i++) {
2413 std::string var_string = get_component_name(field, Ioss::Field::InOut::OUTPUT, i);
2414
2415 if (variables.find(var_string) == variables.end()) {
2416 variables.insert(VNMValuePair(var_string, ++new_index));
2417 }
2418 }
2419 }
2420 if (has_disp && field.get_name() == disp_name) {
2421 new_index = save_index;
2422 }
2423 }
2424 return new_index;
2425 }
2426
2427 // common
2428 void BaseDatabaseIO::generate_sideset_truth_table()
2429 {
2430 size_t var_count = m_variables[EX_SIDE_SET].size();
2431
2432 if (var_count == 0 || m_groupCount[EX_SIDE_SET] == 0) {
2433 return;
2434 }
2435
2436 // Member variable. Will be deleted in destructor...
2437 m_truthTable[EX_SIDE_SET].resize(m_groupCount[EX_SIDE_SET] * var_count);
2438
2439 // Fill in the truth table. It is conceptually a two-dimensional array of
2440 // the form 'array[num_blocks][num_var]'. In C++,
2441 // the values for the first block are first, followed by
2442 // next block, ...
2443 size_t offset = 0;
2444
2445 const Ioss::SideSetContainer &sidesets = get_region()->get_sidesets();
2446 for (const auto &sideset : sidesets) {
2447
2448 const Ioss::SideBlockContainer &side_blocks = sideset->get_side_blocks();
2449 for (const auto &block : side_blocks) {
2450 // See if this sideblock has a corresponding entry in the sideset list.
2451 if (block->property_exists("invalid")) {
2452 continue;
2453 }
2454
2455 // Get names of all transient and reduction fields...
2456 Ioss::NameList results_fields = block->field_describe(Ioss::Field::TRANSIENT);
2457 block->field_describe(Ioss::Field::REDUCTION, &results_fields);
2458
2459 for (const auto &fn : results_fields) {
2460 Ioss::Field field = block->get_field(fn);
2461 Ioss::Field::BasicType ioss_type = field.get_type();
2462
2463 int re_im = 1;
2464 if (ioss_type == Ioss::Field::COMPLEX) {
2465 re_im = 2;
2466 }
2467 for (int complex_comp = 0; complex_comp < re_im; complex_comp++) {
2468 for (int i = 1; i <= field.get_component_count(Ioss::Field::InOut::OUTPUT); i++) {
2469 std::string var_string = get_component_name(field, Ioss::Field::InOut::OUTPUT, i);
2470 // Find position of 'var_string' in 'm_variables[]'
2471 auto VN = m_variables[EX_SIDE_SET].find(var_string);
2472 if (VN != m_variables[EX_SIDE_SET].end()) {
2473 // Index '(*VN).second' is 1-based...
2474 m_truthTable[EX_SIDE_SET][offset + (*VN).second - 1] = 1;
2475 }
2476 }
2477 }
2478 }
2479 }
2480 offset += var_count;
2481 }
2482 assert(offset == var_count * m_groupCount[EX_SIDE_SET]);
2483 }
2484
2485 // common
2486 void BaseDatabaseIO::output_results_names(ex_entity_type type, VariableNameMap &variables,
2487 bool reduction) const
2488 {
2489 bool lowercase_names =
2490 (properties.exists("VARIABLE_NAME_CASE") &&
2491 Ioss::Utils::lowercase(properties.get("VARIABLE_NAME_CASE").get_string()) == "lower");
2492 bool uppercase_names =
2493 (properties.exists("VARIABLE_NAME_CASE") &&
2494 Ioss::Utils::lowercase(properties.get("VARIABLE_NAME_CASE").get_string()) == "upper");
2495
2496 size_t var_count = variables.size();
2497
2498 if (var_count > 0) {
2499 size_t name_length = 0;
2500 // Push into a char** array...
2501 std::vector<char *> var_names(var_count);
2502 Ioss::NameList variable_names(var_count);
2503 for (const auto &variable : variables) {
2504 size_t index = variable.second;
2505 assert(index > 0 && index <= var_count);
2506 variable_names[index - 1] = variable.first;
2507 if (uppercase_names) {
2508 variable_names[index - 1] = Ioss::Utils::uppercase(variable_names[index - 1]);
2509 }
2510 else if (lowercase_names) {
2511 variable_names[index - 1] = Ioss::Utils::lowercase(variable_names[index - 1]);
2512 }
2513 var_names[index - 1] = const_cast<char *>(variable_names[index - 1].c_str());
2514 size_t name_len = variable_names[index - 1].length();
2515 name_length = name_len > name_length ? name_len : name_length;
2516 }
2517
2518 // Should handle this automatically, but by the time we get to defining transient fields, we
2519 // have already created the output database and populated the set/block names. At this point,
2520 // it is too late to change the size of the names stored on the output database... (I think...
2521 // try changing DIM_STR_NAME value and see if works...)
2522 if (name_length > static_cast<size_t>(maximumNameLength)) {
2523 if (myProcessor == 0) {
2524 fmt::print(Ioss::WarnOut(),
2525 "There are variables names whose name length ({0}) exceeds the current "
2526 "maximum name length ({1})\n set for this database ({2}).\n"
2527 " You should either reduce the length of the variable name, or "
2528 "set the 'MAXIMUM_NAME_LENGTH' property\n"
2529 " to at least {0}.\n Contact [email protected] for more "
2530 "information.\n\n",
2531 name_length, maximumNameLength, get_filename());
2532 }
2533 }
2534 int ierr = 0;
2535 if (reduction) {
2536 ierr =
2537 ex_put_reduction_variable_names(get_file_pointer(), type, var_count, Data(var_names));
2538 }
2539 else {
2540 ierr = ex_put_variable_names(get_file_pointer(), type, var_count, Data(var_names));
2541 }
2542 if (ierr < 0) {
2543 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
2544 }
2545 }
2546 }
2547
2548 // common
2549 // Handle special output time requests -- primarily restart (cycle, overwrite)
2550 // Given the global region step, return the step on the database...
2551 int BaseDatabaseIO::get_database_step(int global_step) const
2552 {
2553 if (get_file_per_state()) {
2554 return 1;
2555 }
2556
2557 assert(overlayCount >= 0 && cycleCount >= 0);
2558 if (overlayCount == 0 && cycleCount == 0) {
2559 return global_step;
2560 }
2561
2562 int local_step = global_step - 1;
2563 local_step /= (overlayCount + 1);
2564 if (cycleCount > 0) {
2565 local_step %= cycleCount;
2566 }
2567 return local_step + 1;
2568 }
2569
2570 // common
2571 void BaseDatabaseIO::flush_database_nl() const
2572 {
2573 if (!is_input()) {
2574 if (isParallel || myProcessor == 0) {
2575 ex_update(get_file_pointer());
2576 }
2577 }
2578 }
2579
2580 void BaseDatabaseIO::finalize_write(int state, double sim_time)
2581 {
2582 // Attempt to ensure that all data written up to this point has
2583 // actually made it out to disk. We also write a special attribute
2584 // to the file to indicate that the current timestep should be
2585 // complete on the disk.
2586 // The attribute is a GLOBAL attribute named "last_written_time"
2587 // which is a double value which can be compared to the values in
2588 // the time array to make sure they match. If they don't, then
2589 // hopefully the "last_written_time" is smaller than the time
2590 // array value and indicates that the last step is corrupt.
2591
2592 // Update the attribute.
2593 Ioex::update_last_time_attribute(get_file_pointer(), sim_time);
2594
2595 // Flush the files buffer to disk...
2596 // If:
2597 // flushInterval == -1 (default) -- flush if there is more
2598 // than 10 seconds since the last flush to avoid
2599 // the flush eating up cpu time for small fast jobs...
2600 //
2601 // flushInterval == 0 -- do not flush until file is closed.
2602 //
2603 // flushInterval == 1 -- flush every step
2604 //
2605 // flushInterval > 1 -- flush if step % flushInterval == 0
2606
2607 bool do_flush = true;
2608 if (flushInterval == 1) {
2609 do_flush = true;
2610 }
2611 else if (flushInterval == 0) {
2612 do_flush = false;
2613 }
2614 else if (flushInterval < 0) {
2615 time_t cur_time = time(nullptr);
2616 if (cur_time - timeLastFlush >= 10) {
2617 timeLastFlush = cur_time;
2618 do_flush = true;
2619 }
2620 else {
2621 do_flush = false;
2622 }
2623 #ifdef SEACAS_HAVE_MPI
2624 if (isParallel) {
2625 int iflush = do_flush ? 1 : 0;
2626 util().broadcast(iflush);
2627 do_flush = iflush == 1;
2628 }
2629 #endif
2630 }
2631 else if (flushInterval > 1) {
2632 if (state % flushInterval == 0) {
2633 do_flush = true;
2634 }
2635 }
2636
2637 if (do_flush) {
2638 flush_database_nl();
2639 }
2640 }
2641
2642 // common
2643 void Ioex::BaseDatabaseIO::add_attribute_fields(Ioss::GroupingEntity *block, int attribute_count,
2644 const std::string &type)
2645 {
2646 /// \todo REFACTOR Some of the attribute knowledge should be at
2647 /// the Ioss::ElementTopology level instead of here. That would
2648 /// make it easier for an application to register a new element
2649 /// type and its attributes.
2650
2651 // Attribute "Conventions" to be used if there are no attribute names on the database:
2652 // from Table 1 in ExodusII manual
2653 //
2654 // Circle 1 Radius [Volume]
2655 // Sphere 1 Radius [Volume]
2656 // Truss 1 Area
2657 // 2D Beam 3 Area, I, J
2658 // 3D Beam 7 Area, I1, I2, J, V1, V2, V3 (V will be a 3D vector named "reference_axis")
2659 // Shell 1 Thickness
2660 //
2661 // Additional conventions not defined in ExodusII manual:
2662 // * If a "beam" has 1 attribute, call it "area"
2663 // * Treat "bar" and "rod" as aliases for "truss"
2664 // * Treat "trishell" as alias for "shell"
2665 // * All "shell" or "trishell" elements -- If #attributes == #node/element, the
2666 // attribute is "nodal_thickness"
2667 //
2668 // If there are attribute names on the database, use those names.
2669 // Always create a variable "attribute" which contains a single
2670 // field for all attributes...
2671
2672 assert(block != nullptr);
2673 if (attribute_count > 0) {
2674 // Some older applications do not want to used named
2675 // attributes; in this case, just create a field for each
2676 // attribute named "attribute_1", "attribute_2", ..., "attribute_#"
2677 // This is controlled by the database property
2678 // "IGNORE_ATTRIBUTE_NAMES"
2679 bool attributes_named = true; // Possibly reset below; note that even if ignoring
2680 // attribute names, they are still 'named'
2681
2682 size_t my_element_count = block->entity_count();
2683 Ioss::NameList names;
2684 names.reserve(attribute_count);
2685 if (properties.exists("IGNORE_ATTRIBUTE_NAMES")) {
2686 for (int i = 0; i < attribute_count; i++) {
2687 names.emplace_back(fmt::format("attribute_{}", i + 1));
2688 }
2689 }
2690 else {
2691 // Use attribute names if they exist.
2692
2693 // Get the attribute names. May not exist or may be blank...
2694 char **cnames = Ioex::get_name_array(attribute_count, maximumNameLength);
2695 int64_t id = block->get_property("id").get_int();
2696
2697 {
2698 Ioss::SerializeIO serializeIO_(this);
2699 if (block->entity_count() != 0) {
2700 ex_entity_type entity_type = Ioex::map_exodus_type(block->type());
2701 int ierr = ex_get_attr_names(get_file_pointer(), entity_type, id, &cnames[0]);
2702 if (ierr < 0) {
2703 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
2704 }
2705 }
2706 }
2707
2708 // Sync names across processors...
2709 if (isParallel) {
2710 std::vector<char> cname(attribute_count * (maximumNameLength + 1));
2711 if (block->entity_count() != 0) {
2712 for (int i = 0; i < attribute_count; i++) {
2713 std::memcpy(&cname[i * (maximumNameLength + 1)], cnames[i], maximumNameLength + 1);
2714 }
2715 }
2716 util().attribute_reduction(attribute_count * (maximumNameLength + 1), Data(cname));
2717 for (int i = 0; i < attribute_count; i++) {
2718 std::memcpy(cnames[i], &cname[i * (maximumNameLength + 1)], maximumNameLength + 1);
2719 }
2720 }
2721
2722 // Convert to lowercase.
2723 attributes_named = true;
2724 for (int i = 0; i < attribute_count; i++) {
2725 if (cnames[i][0] == '\0' || (!(std::isalnum(cnames[i][0]) || cnames[i][0] == '_'))) {
2726 attributes_named = false;
2727 }
2728 }
2729 if (attributes_named) {
2730 for (int i = 0; i < attribute_count; i++) {
2731 fix_bad_name(cnames[i]);
2732 Ioss::Utils::fixup_name(cnames[i]);
2733 names.emplace_back(cnames[i]);
2734 }
2735 }
2736 // Release memory...
2737 Ioex::delete_name_array(cnames, attribute_count);
2738 }
2739
2740 if (attributes_named) {
2741 std::vector<Ioss::Field> attributes;
2742 Ioss::Utils::get_fields(my_element_count, names, Ioss::Field::ATTRIBUTE, this, nullptr,
2743 attributes);
2744 int offset = 1;
2745 for (const auto &field : attributes) {
2746 if (block->field_exists(field.get_name())) {
2747 IOSS_ERROR(fmt::format(
2748 "ERROR: In block '{}', attribute '{}' is defined multiple times which is "
2749 "not allowed.\n",
2750 block->name(), field.get_name()));
2751 }
2752 block->field_add(field);
2753 const Ioss::Field &tmp_field = block->get_fieldref(field.get_name());
2754 tmp_field.set_index(offset);
2755 offset += field.get_component_count(Ioss::Field::InOut::INPUT);
2756 }
2757 }
2758 else {
2759 // Attributes are not named....
2760 // Try to assign some meaningful names based on conventions...
2761 int unknown_attributes = 0;
2762
2763 if (type_match(type, "shell") || type_match(type, "trishell")) {
2764 if (attribute_count == block->get_property("topology_node_count").get_int()) {
2765
2766 std::string att_name = "nodal_thickness";
2767
2768 std::string storage = fmt::format("Real[{}]", attribute_count);
2769 block->field_add(Ioss::Field(std::move(att_name), Ioss::Field::REAL, storage,
2770 Ioss::Field::ATTRIBUTE, my_element_count, 1));
2771 }
2772 else {
2773 std::string att_name = "thickness";
2774 block->field_add(Ioss::Field(std::move(att_name), Ioss::Field::REAL, IOSS_SCALAR(),
2775 Ioss::Field::ATTRIBUTE, my_element_count, 1));
2776 unknown_attributes = attribute_count - 1;
2777 }
2778 }
2779
2780 // NOTE: This must appear before the "sphere" check since
2781 // sphere is substring of "sphere-mass"
2782 // Want an exact match here, not substring match...
2783 else if (Ioss::Utils::str_equal(type, "sphere-mass")) {
2784 if (attribute_count != 10) {
2785 if (myProcessor == 0) {
2786 fmt::print(Ioss::WarnOut(),
2787 "For element block '{}' of type '{}' there were {} attributes instead of "
2788 "the expected 10 attributes "
2789 "known to the IO Subsystem. "
2790 " The attributes can be accessed as the field named 'attribute'",
2791 block->name(), type, attribute_count);
2792 }
2793 }
2794 else {
2795 // First attribute is concentrated mass...
2796 size_t offset = 1;
2797 block->field_add(Ioss::Field("mass", Ioss::Field::REAL, IOSS_SCALAR(),
2798 Ioss::Field::ATTRIBUTE, my_element_count, offset));
2799 offset += 1;
2800
2801 // Next six attributes are moment of inertia -- symmetric tensor
2802 block->field_add(Ioss::Field("inertia", Ioss::Field::REAL, IOSS_SYM_TENSOR(),
2803 Ioss::Field::ATTRIBUTE, my_element_count, offset));
2804 offset += 6;
2805
2806 // Next three attributes are offset from node to CG
2807 block->field_add(Ioss::Field("offset", Ioss::Field::REAL, IOSS_VECTOR_3D(),
2808 Ioss::Field::ATTRIBUTE, my_element_count, offset));
2809 }
2810 }
2811
2812 else if (type_match(type, "circle") || type_match(type, "sphere")) {
2813 std::string att_name = "radius";
2814 size_t offset = 1;
2815 block->field_add(Ioss::Field(att_name, Ioss::Field::REAL, IOSS_SCALAR(),
2816 Ioss::Field::ATTRIBUTE, my_element_count, offset++));
2817 if (attribute_count > 1) {
2818 // Default second attribute (from sphgen3d) is "volume"
2819 // which is the volume of the cube which would surround a
2820 // sphere of the given radius.
2821 att_name = "volume";
2822 block->field_add(Ioss::Field(std::move(att_name), Ioss::Field::REAL, IOSS_SCALAR(),
2823 Ioss::Field::ATTRIBUTE, my_element_count, offset++));
2824 }
2825 unknown_attributes = attribute_count - 2;
2826 }
2827
2828 else if (type_match(type, "truss") || type_match(type, "bar") || type_match(type, "beam") ||
2829 type_match(type, "rod")) {
2830 // Technically, truss, bar, rod should all only have 1 attribute; however,
2831 // there are some mesh generation codes that treat all of these types the
2832 // same and put "beam-type" attributes on bars...
2833 int index = 1;
2834 std::string att_name = "area";
2835 block->field_add(Ioss::Field(std::move(att_name), Ioss::Field::REAL, IOSS_SCALAR(),
2836 Ioss::Field::ATTRIBUTE, my_element_count, index++));
2837
2838 if (spatialDimension == 2 && attribute_count >= 3) {
2839 block->field_add(Ioss::Field("i", Ioss::Field::REAL, IOSS_SCALAR(),
2840 Ioss::Field::ATTRIBUTE, my_element_count, index++));
2841 block->field_add(Ioss::Field("j", Ioss::Field::REAL, IOSS_SCALAR(),
2842 Ioss::Field::ATTRIBUTE, my_element_count, index++));
2843 }
2844 else if (spatialDimension == 3 && attribute_count >= 7) {
2845 block->field_add(Ioss::Field("i1", Ioss::Field::REAL, IOSS_SCALAR(),
2846 Ioss::Field::ATTRIBUTE, my_element_count, index++));
2847 block->field_add(Ioss::Field("i2", Ioss::Field::REAL, IOSS_SCALAR(),
2848 Ioss::Field::ATTRIBUTE, my_element_count, index++));
2849 block->field_add(Ioss::Field("j", Ioss::Field::REAL, IOSS_SCALAR(),
2850 Ioss::Field::ATTRIBUTE, my_element_count, index++));
2851 block->field_add(Ioss::Field("reference_axis", Ioss::Field::REAL, IOSS_VECTOR_3D(),
2852 Ioss::Field::ATTRIBUTE, my_element_count, index));
2853 index += 3;
2854 if (attribute_count >= 10) {
2855 // Next three attributes would (hopefully) be offset vector...
2856 // This is typically from a NASGEN model.
2857 block->field_add(Ioss::Field("offset", Ioss::Field::REAL, IOSS_VECTOR_3D(),
2858 Ioss::Field::ATTRIBUTE, my_element_count, index));
2859 index += 3;
2860 }
2861 }
2862 unknown_attributes = attribute_count - (index - 1);
2863 }
2864
2865 else {
2866 unknown_attributes = attribute_count;
2867 }
2868
2869 if (unknown_attributes > 0) {
2870 std::string att_name = "extra_attribute_";
2871 att_name += std::to_string(unknown_attributes);
2872 std::string storage = fmt::format("Real[{}]", unknown_attributes);
2873 size_t index = attribute_count - unknown_attributes + 1;
2874 block->field_add(Ioss::Field(std::move(att_name), Ioss::Field::REAL, storage,
2875 Ioss::Field::ATTRIBUTE, my_element_count, index));
2876 }
2877 }
2878
2879 // Always create a field called "attribute" containing data
2880 // for all attributes on the mesh
2881 std::string att_name = "attribute"; // Default
2882 std::string storage = fmt::format("Real[{}]", attribute_count);
2883
2884 block->field_add(Ioss::Field(std::move(att_name), Ioss::Field::REAL, storage,
2885 Ioss::Field::ATTRIBUTE, my_element_count, 1));
2886 }
2887 }
2888
2889 void BaseDatabaseIO::common_write_metadata(Ioss::IfDatabaseExistsBehavior behavior)
2890 {
2891 Ioss::Region *region = get_region();
2892
2893 // Verify that exodus supports the mesh_type...
2894 if (region->mesh_type() != Ioss::MeshType::UNSTRUCTURED) {
2895 IOSS_ERROR(fmt::format("ERROR: The mesh type is '{}' which Exodus does not support.\n"
2896 " Only 'Unstructured' is supported at this time.\n",
2897 region->mesh_type_string()));
2898 }
2899
2900 const Ioss::NodeBlockContainer &node_blocks = region->get_node_blocks();
2901 assert(node_blocks.size() <= 1);
2902 if (!node_blocks.empty()) {
2903 Ioex::get_id(node_blocks[0], &ids_);
2904 nodeCount = node_blocks[0]->entity_count();
2905 spatialDimension = node_blocks[0]->get_property("component_degree").get_int();
2906 }
2907 else {
2908 spatialDimension = 1;
2909 }
2910
2911 // Assemblies --
2912 {
2913 const auto &assemblies = region->get_assemblies();
2914 if (behavior != Ioss::DB_MODIFY) {
2915 // Set ids of all entities that have "id" property...
2916 for (const auto &assem : assemblies) {
2917 Ioex::set_id(assem, &ids_);
2918 }
2919
2920 for (const auto &assem : assemblies) {
2921 Ioex::get_id(assem, &ids_);
2922 }
2923 }
2924 m_groupCount[EX_ASSEMBLY] = assemblies.size();
2925 }
2926
2927 // Blobs --
2928 {
2929 const auto &blobs = region->get_blobs();
2930 // Set ids of all entities that have "id" property...
2931 if (behavior != Ioss::DB_MODIFY) {
2932 for (const auto &blob : blobs) {
2933 Ioex::set_id(blob, &ids_);
2934 }
2935
2936 for (const auto &blob : blobs) {
2937 Ioex::get_id(blob, &ids_);
2938 }
2939 }
2940 m_groupCount[EX_BLOB] = blobs.size();
2941 }
2942
2943 // Edge Blocks --
2944 {
2945 const Ioss::EdgeBlockContainer &edge_blocks = region->get_edge_blocks();
2946 assert(Ioss::Utils::check_block_order(edge_blocks));
2947 // Set ids of all entities that have "id" property...
2948 if (behavior != Ioss::DB_MODIFY) {
2949 for (const auto &edge_block : edge_blocks) {
2950 Ioex::set_id(edge_block, &ids_);
2951 }
2952
2953 edgeCount = 0;
2954 for (const auto &edge_block : edge_blocks) {
2955 edgeCount += edge_block->entity_count();
2956 // Set ids of all entities that do not have "id" property...
2957 Ioex::get_id(edge_block, &ids_);
2958 }
2959 }
2960 m_groupCount[EX_EDGE_BLOCK] = edge_blocks.size();
2961 }
2962
2963 // Face Blocks --
2964 {
2965 const Ioss::FaceBlockContainer &face_blocks = region->get_face_blocks();
2966 assert(Ioss::Utils::check_block_order(face_blocks));
2967 // Set ids of all entities that have "id" property...
2968 if (behavior != Ioss::DB_MODIFY) {
2969 for (const auto &face_block : face_blocks) {
2970 Ioex::set_id(face_block, &ids_);
2971 }
2972
2973 faceCount = 0;
2974 for (auto &face_block : face_blocks) {
2975 faceCount += face_block->entity_count();
2976 // Set ids of all entities that do not have "id" property...
2977 Ioex::get_id(face_block, &ids_);
2978 }
2979 }
2980 m_groupCount[EX_FACE_BLOCK] = face_blocks.size();
2981 }
2982
2983 // Element Blocks --
2984 {
2985 const Ioss::ElementBlockContainer &element_blocks = region->get_element_blocks();
2986 assert(Ioss::Utils::check_block_order(element_blocks));
2987 if (behavior != Ioss::DB_MODIFY) {
2988 // Set ids of all entities that have "id" property...
2989 for (const auto &element_block : element_blocks) {
2990 Ioex::set_id(element_block, &ids_);
2991 }
2992 }
2993 elementCount = 0;
2994 Ioss::Int64Vector element_counts;
2995 element_counts.reserve(element_blocks.size());
2996 for (const auto &element_block : element_blocks) {
2997 elementCount += element_block->entity_count();
2998 element_counts.push_back(element_block->entity_count());
2999 // Set ids of all entities that do not have "id" property...
3000 if (behavior != Ioss::DB_MODIFY) {
3001 Ioex::get_id(element_block, &ids_);
3002 }
3003 }
3004 m_groupCount[EX_ELEM_BLOCK] = element_blocks.size();
3005
3006 if (isParallel) {
3007 // Set "global_entity_count" property on all blocks.
3008 // Used to skip output on "globally" empty blocks.
3009 Ioss::Int64Vector global_counts(element_counts.size());
3010 util().global_count(element_counts, global_counts);
3011 size_t idx = 0;
3012 for (const auto &element_block : element_blocks) {
3013 element_block->property_add(Ioss::Property("global_entity_count", global_counts[idx++]));
3014 }
3015 }
3016 }
3017
3018 // NodeSets ...
3019 {
3020 const Ioss::NodeSetContainer &nodesets = region->get_nodesets();
3021 if (behavior != Ioss::DB_MODIFY) {
3022 for (const auto &set : nodesets) {
3023 Ioex::set_id(set, &ids_);
3024 }
3025
3026 for (const auto &set : nodesets) {
3027 Ioex::get_id(set, &ids_);
3028 }
3029 }
3030 m_groupCount[EX_NODE_SET] = nodesets.size();
3031 }
3032
3033 // EdgeSets ...
3034 {
3035 const Ioss::EdgeSetContainer &edgesets = region->get_edgesets();
3036 if (behavior != Ioss::DB_MODIFY) {
3037 for (const auto &set : edgesets) {
3038 Ioex::set_id(set, &ids_);
3039 }
3040
3041 for (const auto &set : edgesets) {
3042 Ioex::get_id(set, &ids_);
3043 }
3044 }
3045 m_groupCount[EX_EDGE_SET] = edgesets.size();
3046 }
3047
3048 // FaceSets ...
3049 {
3050 const Ioss::FaceSetContainer &facesets = region->get_facesets();
3051 if (behavior != Ioss::DB_MODIFY) {
3052 for (const auto &set : facesets) {
3053 Ioex::set_id(set, &ids_);
3054 }
3055
3056 for (const auto &set : facesets) {
3057 Ioex::get_id(set, &ids_);
3058 }
3059 }
3060 m_groupCount[EX_FACE_SET] = facesets.size();
3061 }
3062
3063 // ElementSets ...
3064 {
3065 const Ioss::ElementSetContainer &elementsets = region->get_elementsets();
3066 if (behavior != Ioss::DB_MODIFY) {
3067 for (const auto &set : elementsets) {
3068 Ioex::set_id(set, &ids_);
3069 }
3070
3071 for (const auto &set : elementsets) {
3072 Ioex::get_id(set, &ids_);
3073 }
3074 }
3075 m_groupCount[EX_ELEM_SET] = elementsets.size();
3076 }
3077
3078 // SideSets ...
3079 {
3080 const Ioss::SideSetContainer &ssets = region->get_sidesets();
3081 if (behavior != Ioss::DB_MODIFY) {
3082 for (const auto &set : ssets) {
3083 Ioex::set_id(set, &ids_);
3084 }
3085 }
3086 // Get entity counts for all face sets... Create SideSets.
3087 for (const auto &set : ssets) {
3088 if (behavior != Ioss::DB_MODIFY) {
3089 Ioex::get_id(set, &ids_);
3090 }
3091 int64_t id = set->get_property("id").get_int();
3092 int64_t entity_count = 0;
3093 int64_t df_count = 0;
3094
3095 const Ioss::SideBlockContainer &side_blocks = set->get_side_blocks();
3096 for (const auto &block : side_blocks) {
3097 // Add "*_offset" properties to specify at what offset
3098 // the data for this block appears in the containing set.
3099 auto *new_block = const_cast<Ioss::SideBlock *>(block);
3100 new_block->property_add(Ioss::Property("set_offset", entity_count));
3101 new_block->property_add(Ioss::Property("set_df_offset", df_count));
3102
3103 // If combining sideblocks into sidesets on output, then
3104 // the id of the sideblock must be the same as the sideset
3105 // id.
3106 new_block->property_update("id", id);
3107 new_block->property_update("guid", util().generate_guid(id));
3108
3109 entity_count += block->entity_count();
3110 df_count += block->get_property("distribution_factor_count").get_int();
3111 }
3112 auto *new_entity = const_cast<Ioss::SideSet *>(set);
3113 new_entity->property_add(Ioss::Property("entity_count", entity_count));
3114 new_entity->property_add(Ioss::Property("distribution_factor_count", df_count));
3115 }
3116 m_groupCount[EX_SIDE_SET] = ssets.size();
3117 }
3118 }
3119
3120 void BaseDatabaseIO::output_other_metadata()
3121 {
3122 // Write attribute names (if any)...
3123 write_attribute_names(get_file_pointer(), EX_NODE_SET, get_region()->get_nodesets());
3124 write_attribute_names(get_file_pointer(), EX_EDGE_SET, get_region()->get_edgesets());
3125 write_attribute_names(get_file_pointer(), EX_FACE_SET, get_region()->get_facesets());
3126 write_attribute_names(get_file_pointer(), EX_ELEM_SET, get_region()->get_elementsets());
3127 write_attribute_names(get_file_pointer(), EX_NODE_BLOCK, get_region()->get_node_blocks());
3128 write_attribute_names(get_file_pointer(), EX_EDGE_BLOCK, get_region()->get_edge_blocks());
3129 write_attribute_names(get_file_pointer(), EX_FACE_BLOCK, get_region()->get_face_blocks());
3130 write_attribute_names(get_file_pointer(), EX_ELEM_BLOCK, get_region()->get_element_blocks());
3131 write_attribute_names(get_file_pointer(), EX_ASSEMBLY, get_region()->get_assemblies());
3132 write_attribute_names(get_file_pointer(), EX_BLOB, get_region()->get_blobs());
3133
3134 // Write "reduction" attributes...
3135 std::vector<Ioss::Region *> regions;
3136 regions.push_back(get_region());
3137 Ioex::write_reduction_attributes(get_file_pointer(), regions);
3138 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_nodesets());
3139 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_nodesets());
3140 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_edgesets());
3141 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_facesets());
3142 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_elementsets());
3143 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_node_blocks());
3144 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_edge_blocks());
3145 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_face_blocks());
3146 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_element_blocks());
3147 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_assemblies());
3148 Ioex::write_reduction_attributes(get_file_pointer(), get_region()->get_blobs());
3149
3150 // Write coordinate names...
3151 if (!get_region()->get_node_blocks().empty()) {
3152 char const *labels[3];
3153 labels[0] = "x";
3154 labels[1] = "y";
3155 labels[2] = "z";
3156 int ierr = ex_put_coord_names(get_file_pointer(), (char **)labels);
3157 if (ierr < 0) {
3158 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
3159 }
3160 }
3161
3162 // Determine number of node, element maps (client-specified)
3163 // Set the index/order of the maps for later output.
3164 // Note that some fields have more than a single component and each component maps to a
3165 // different map
3166 size_t node_map_cnt = 0;
3167 if (get_region()->get_property("node_block_count").get_int() > 0) {
3168 auto *node_block = get_region()->get_node_blocks()[0];
3169 auto node_map_fields = node_block->field_describe(Ioss::Field::MAP);
3170 for (const auto &field_name : node_map_fields) {
3171 const auto &field = node_block->get_fieldref(field_name);
3172 if (field.get_index() == 0) {
3173 field.set_index(node_map_cnt + 1);
3174 }
3175 node_map_cnt += field.get_component_count(Ioss::Field::InOut::OUTPUT);
3176 }
3177 }
3178
3179 Ioss::NameList elem_map_fields;
3180 const auto &blocks = get_region()->get_element_blocks();
3181 for (const auto &block : blocks) {
3182 block->field_describe(Ioss::Field::MAP, &elem_map_fields);
3183 }
3184
3185 Ioss::Utils::uniquify(elem_map_fields);
3186
3187 // Now need to set the map index on any element map fields...
3188 // Note that not all blocks will potentially have all maps...
3189 size_t elem_map_cnt = 0;
3190 for (const auto &field_name : elem_map_fields) {
3191 int comp_count = 0;
3192 for (const auto &block : blocks) {
3193 if (block->field_exists(field_name)) {
3194 auto &field = block->get_fieldref(field_name);
3195 if (field.get_index() == 0) {
3196 field.set_index(elem_map_cnt + 1);
3197 }
3198 // Assumes all maps of a type have same component count
3199 comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
3200 }
3201 }
3202 elem_map_cnt += comp_count;
3203 }
3204
3205 int ierr = ex_put_map_param(get_file_pointer(), node_map_cnt, elem_map_cnt);
3206 if (ierr < 0) {
3207 Ioex::exodus_error(get_file_pointer(), __LINE__, __func__, __FILE__);
3208 }
3209
3210 if (node_map_cnt > 0) {
3211 char **names = Ioex::get_name_array(node_map_cnt, maximumNameLength);
3212 auto *node_block =
3213 get_region()->get_node_blocks()[0]; // If there are node_maps, then there is a node_block
3214 auto node_map_fields = node_block->field_describe(Ioss::Field::MAP);
3215 for (const auto &field_name : node_map_fields) {
3216 const auto &field = node_block->get_fieldref(field_name);
3217 int component_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
3218 if (component_count == 1) {
3219 Ioss::Utils::copy_string(names[field.get_index() - 1], field_name, maximumNameLength + 1);
3220 }
3221 else {
3222 for (int i = 0; i < component_count; i++) {
3223 auto name = fmt::format("{}:{}", field_name, i + 1);
3224 Ioss::Utils::copy_string(names[field.get_index() + i - 1], name, maximumNameLength + 1);
3225 }
3226 }
3227 }
3228 ex_put_names(get_file_pointer(), EX_NODE_MAP, names);
3229 Ioex::delete_name_array(names, node_map_cnt);
3230 }
3231
3232 if (elem_map_cnt > 0) {
3233 char **names = Ioex::get_name_array(elem_map_cnt, maximumNameLength);
3234 for (const auto &field_name : elem_map_fields) {
3235 // Now, we need to find an element block that has this field...
3236 for (const auto &block : blocks) {
3237 if (block->field_exists(field_name)) {
3238 const auto &field = block->get_fieldref(field_name);
3239 int component_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
3240 if (component_count == 1) {
3241 Ioss::Utils::copy_string(names[field.get_index() - 1], field_name,
3242 maximumNameLength + 1);
3243 }
3244 else {
3245 for (int i = 0; i < component_count; i++) {
3246 auto name = fmt::format("{}:{}", field_name, i + 1);
3247 if (field_name == "skin") {
3248 name = i == 0 ? "skin:parent_element_id" : "skin:parent_element_side_number";
3249 }
3250 else if (field_name == "chain") {
3251 name = i == 0 ? "chain:root_element_id" : "chain:depth_from_root";
3252 }
3253 Ioss::Utils::copy_string(names[field.get_index() + i - 1], name,
3254 maximumNameLength + 1);
3255 }
3256 }
3257 break;
3258 }
3259 }
3260 }
3261 ex_put_names(get_file_pointer(), EX_ELEM_MAP, names);
3262 Ioex::delete_name_array(names, elem_map_cnt);
3263 }
3264
3265 // Write coordinate frame data...
3266 write_coordinate_frames(get_file_pointer(), get_region()->get_coordinate_frames());
3267 }
3268
3269 Ioss::NameList BaseDatabaseIO::internal_change_set_describe_nl(bool return_full_names)
3270 {
3271 Ioss::NameList names = groups_describe(return_full_names);
3272
3273 // Downshift by 1 since the first is the root group "/"
3274 int numNames = static_cast<int>(names.size());
3275 for (int i = 0; i < numNames - 1; i++) {
3276 names[i] = names[i + 1];
3277 }
3278
3279 if (numNames > 0) {
3280 names.resize(numNames - 1);
3281 }
3282
3283 return names;
3284 }
3285
3286 Ioss::NameList BaseDatabaseIO::groups_describe(bool return_full_names) const
3287 {
3288 Ioss::SerializeIO serializeIO_(this);
3289
3290 Ioss::NameList names;
3291 int group_root = ex_inquire_int(get_file_pointer(), EX_INQ_GROUP_ROOT);
3292 query_groups(group_root, names, return_full_names);
3293
3294 return names;
3295 }
3296
3297 void BaseDatabaseIO::release_memory_nl()
3298 {
3299 Ioss::DatabaseIO::release_memory_nl();
3300
3301 ids_.clear();
3302 m_groupCount.clear();
3303
3304 nodeCmapIds.clear();
3305 nodeCmapNodeCnts.clear();
3306 elemCmapIds.clear();
3307 elemCmapElemCnts.clear();
3308
3309 m_truthTable.clear();
3310 m_variables.clear();
3311 m_reductionVariables.clear();
3312
3313 m_reductionValues.clear();
3314
3315 nodeConnectivityStatus.clear();
3316
3317 activeNodeSetNodesIndex.clear();
3318 }
3319
3320 int BaseDatabaseIO::num_internal_change_set_nl()
3321 {
3322 // Save and reset state
3323 int currentExodusFilePtr = m_exodusFilePtr;
3324 std::string currentGroupName = m_groupName;
3325
3326 if (!open_root_group_nl()) {
3327 IOSS_ERROR(fmt::format("ERROR: Could not open root group.\n", m_groupName));
3328 }
3329
3330 int numChildGroup = num_child_group();
3331
3332 m_exodusFilePtr = currentExodusFilePtr;
3333 m_groupName = currentGroupName;
3334
3335 return numChildGroup;
3336 }
3337
3338 int BaseDatabaseIO::num_child_group() const
3339 {
3340 Ioss::SerializeIO serializeIO_(this);
3341 int exoid = get_file_pointer();
3342 exoid = ex_inquire_int(exoid, EX_INQ_GROUP_ROOT);
3343 int num_children = ex_inquire_int(exoid, EX_INQ_NUM_CHILD_GROUPS);
3344 return num_children;
3345 }
3346
3347 bool BaseDatabaseIO::open_internal_change_set_nl(int index)
3348 {
3349 if (!open_root_group_nl()) {
3350 IOSS_ERROR(fmt::format("ERROR: Could not open root group.\n", m_groupName));
3351 }
3352
3353 return open_child_group_nl(index);
3354 }
3355
3356 bool BaseDatabaseIO::open_child_group_nl(int index) const
3357 {
3358 if (index < 0)
3359 return false;
3360 Ioss::SerializeIO serializeIO_(this);
3361 int exoid = get_file_pointer();
3362 int num_children = ex_inquire_int(exoid, EX_INQ_NUM_CHILD_GROUPS);
3363 if (num_children == 0)
3364 return true;
3365
3366 if (index >= num_children)
3367 return false;
3368
3369 std::vector<int> children(num_children);
3370
3371 int ierr = ex_get_group_ids(exoid, nullptr, Data(children));
3372 if (ierr < 0) {
3373 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
3374 }
3375
3376 exoid = children[index];
3377
3378 int group_name_length = ex_inquire_int(exoid, EX_INQ_GROUP_NAME_LEN);
3379 std::vector<char> group_name(group_name_length + 1, '\0');
3380
3381 // Get name of this group...
3382 int idum;
3383 float rdum;
3384 ierr = ex_inquire(exoid, EX_INQ_GROUP_NAME, &idum, &rdum, group_name.data());
3385 if (ierr < 0) {
3386 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
3387 }
3388
3389 m_exodusFilePtr = exoid;
3390 m_groupName = std::string(group_name.data());
3391
3392 return true;
3393 }
3394
3395 } // namespace Ioex
3396
3397 namespace {
3398 template <typename T>
3399 void write_attribute_names(int exoid, ex_entity_type type, const std::vector<T *> &entities)
3400 {
3401 // For the entity, determine the attribute fields and the correct
3402 // order. Write the names of these fields. However, be aware that
3403 // the field "attribute" always exists to contain all attributes
3404 // and its name should not be used even if it is the only
3405 // attribute field.
3406 for (const auto &ge : entities) {
3407 int attribute_count = ge->get_property("attribute_count").get_int();
3408 if (attribute_count > 0) {
3409
3410 check_attribute_index_order(ge);
3411
3412 std::vector<char *> names(attribute_count);
3413 Ioss::NameList names_str(attribute_count);
3414
3415 // Get the attribute fields...
3416 Ioss::NameList results_fields = ge->field_describe(Ioss::Field::ATTRIBUTE);
3417
3418 for (const auto &field_name : results_fields) {
3419 const Ioss::Field &field = ge->get_fieldref(field_name);
3420 assert(field.get_index() != 0);
3421
3422 if (field_name == "attribute") {
3423 field.set_index(1);
3424 continue;
3425 }
3426
3427 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
3428 int field_offset = field.get_index();
3429 for (int i = 0; i < comp_count; i++) {
3430 names_str[field_offset - 1 + i] =
3431 ge->get_database()->get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
3432 names[field_offset - 1 + i] =
3433 const_cast<char *>(names_str[field_offset - 1 + i].c_str());
3434 }
3435 }
3436 size_t ge_id = ge->get_property("id").get_int();
3437 int ierr = ex_put_attr_names(exoid, type, ge_id, Data(names));
3438 if (ierr < 0) {
3439 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
3440 }
3441 }
3442 }
3443 }
3444
3445 // common
3446 void check_attribute_index_order(Ioss::GroupingEntity *block)
3447 {
3448 int attribute_count = block->get_property("attribute_count").get_int();
3449 if (attribute_count == 0) {
3450 return;
3451 }
3452 int component_sum = 0;
3453
3454 std::vector<int> attributes(attribute_count + 1);
3455
3456 // Get the attribute fields...
3457 Ioss::NameList results_fields = block->field_describe(Ioss::Field::ATTRIBUTE);
3458
3459 bool all_attributes_indexed = true;
3460 bool some_attributes_indexed = false;
3461
3462 for (const auto &field_name : results_fields) {
3463 const Ioss::Field &field = block->get_fieldref(field_name);
3464
3465 if (field_name == "attribute") {
3466 field.set_index(1);
3467 if (results_fields.size() == 1) {
3468 return;
3469 }
3470 continue;
3471 }
3472
3473 int field_offset = field.get_index();
3474 if (field_offset == 0) {
3475 all_attributes_indexed = false;
3476 }
3477 else {
3478 some_attributes_indexed = true;
3479 }
3480
3481 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
3482 component_sum += comp_count;
3483
3484 if (field_offset == 0) {
3485 continue;
3486 }
3487
3488 if (field_offset + comp_count - 1 > attribute_count) {
3489 IOSS_ERROR(fmt::format(
3490 "INTERNAL ERROR: For block '{}', attribute '{}', the indexing is incorrect.\n"
3491 "Something is wrong in the Ioex::BaseDatabaseIO class, function {}. Please report.\n",
3492 block->name(), field_name, __func__));
3493 }
3494
3495 for (int i = field_offset; i < field_offset + comp_count; i++) {
3496 if (attributes[i] != 0) {
3497 IOSS_ERROR(fmt::format(
3498 "INTERNAL ERROR: For block '{}', attribute '{}', indexes into the same location as a "
3499 "previous attribute.\n"
3500 "Something is wrong in the Ioex::BaseDatabaseIO class, function {}. Please report.\n",
3501 block->name(), field_name, __func__));
3502 }
3503 attributes[i] = 1;
3504 }
3505 }
3506
3507 if (component_sum > attribute_count) {
3508 IOSS_ERROR(fmt::format(
3509 "INTERNAL ERROR: Block '{}' is supposed to have {} attributes, but {} attributes "
3510 "were counted.\n"
3511 "Something is wrong in the Ioex::BaseDatabaseIO class, function {}. Please report.\n",
3512 block->name(), attribute_count, component_sum, __func__));
3513 }
3514
3515 // Take care of the easy cases first...
3516 if (all_attributes_indexed) {
3517 // Check that all attributes are defined. This should have
3518 // caught above in the duplicate index check.
3519 for (int i = 1; i <= attribute_count; i++) {
3520 if (attributes[i] == 0) {
3521 IOSS_ERROR(fmt::format(
3522 "INTERNAL ERROR: Block '{}' has an incomplete set of attributes.\n"
3523 "Something is wrong in the Ioex::BaseDatabaseIO class, function {}. Please report.\n",
3524 block->name(), __func__));
3525 }
3526 }
3527 return;
3528 }
3529
3530 if (!some_attributes_indexed) {
3531 // Index was not set for any of the attributes; set them all...
3532 size_t offset = 1;
3533 for (const auto &field_name : results_fields) {
3534 const Ioss::Field &field = block->get_fieldref(field_name);
3535
3536 if (field_name == "attribute") {
3537 field.set_index(1);
3538 continue;
3539 }
3540
3541 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
3542
3543 assert(field.get_index() == 0);
3544 field.set_index(offset);
3545 offset += comp_count;
3546 }
3547 assert((int)offset == attribute_count + 1);
3548 return;
3549 }
3550
3551 // At this point, we have a partially indexed set of attributes. Some have an index and some
3552 // don't
3553 // The easy case is if the missing indices are at the end of the list...
3554 assert(!all_attributes_indexed && some_attributes_indexed);
3555 int last_defined = 0;
3556 for (int i = 1; i < attribute_count + 1; i++) {
3557 if (attributes[i] != 0) {
3558 last_defined = i;
3559 }
3560 }
3561 int first_undefined = attribute_count;
3562 for (int i = attribute_count; i > 0; i--) {
3563 if (attributes[i] == 0) {
3564 first_undefined = i;
3565 }
3566 }
3567 if (last_defined < first_undefined) {
3568 for (const auto &field_name : results_fields) {
3569 const Ioss::Field &field = block->get_fieldref(field_name);
3570
3571 if (field_name == "attribute") {
3572 field.set_index(1);
3573 continue;
3574 }
3575
3576 if (field.get_index() == 0) {
3577 field.set_index(first_undefined);
3578 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
3579 first_undefined += comp_count;
3580 }
3581 }
3582 assert(first_undefined == attribute_count + 1);
3583 return;
3584 }
3585
3586 // Take the easy way out... Just reindex all attributes.
3587 size_t offset = 1;
3588 for (const auto &field_name : results_fields) {
3589 const Ioss::Field &field = block->get_fieldref(field_name);
3590
3591 if (field_name == "attribute") {
3592 field.set_index(1);
3593 continue;
3594 }
3595
3596 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
3597
3598 assert(field.get_index() == 0);
3599 field.set_index(offset);
3600 offset += comp_count;
3601 }
3602 assert((int)offset == attribute_count + 1);
3603 }
3604
3605 void check_variable_consistency(IOSS_MAYBE_UNUSED const ex_var_params &exo_params,
3606 IOSS_MAYBE_UNUSED int my_processor,
3607 IOSS_MAYBE_UNUSED const std::string &filename,
3608 IOSS_MAYBE_UNUSED const Ioss::ParallelUtils &util)
3609 {
3610 IOSS_PAR_UNUSED(exo_params);
3611 IOSS_PAR_UNUSED(my_processor);
3612 IOSS_PAR_UNUSED(filename);
3613 IOSS_PAR_UNUSED(util);
3614 #ifdef SEACAS_HAVE_MPI
3615 const int num_types = 10;
3616 std::vector<int> var_counts(num_types);
3617 var_counts[0] = exo_params.num_glob;
3618 var_counts[1] = exo_params.num_node;
3619 var_counts[2] = exo_params.num_edge;
3620 var_counts[3] = exo_params.num_face;
3621 var_counts[4] = exo_params.num_elem;
3622 var_counts[5] = exo_params.num_nset;
3623 var_counts[6] = exo_params.num_eset;
3624 var_counts[7] = exo_params.num_fset;
3625 var_counts[8] = exo_params.num_sset;
3626 var_counts[9] = exo_params.num_elset;
3627
3628 Ioss::IntVector all_counts;
3629 util.gather(var_counts, all_counts);
3630
3631 bool any_diff = false;
3632 std::ostringstream errmsg;
3633 if (my_processor == 0) {
3634 bool diff[num_types];
3635 // See if any differ...
3636 for (int iv = 0; iv < 10; iv++) {
3637 diff[iv] = false;
3638 std::string type;
3639 switch (iv) {
3640 case 0: type = "global"; break;
3641 case 1: type = "nodal"; break;
3642 case 2: type = "edge"; break;
3643 case 3: type = "face"; break;
3644 case 4: type = "element"; break;
3645 case 5: type = "nodeset"; break;
3646 case 6: type = "edgeset"; break;
3647 case 7: type = "faceset"; break;
3648 case 8: type = "sideset"; break;
3649 case 9: type = "elementset"; break;
3650 }
3651
3652 for (int ip = 1; ip < util.parallel_size(); ip++) {
3653 if (var_counts[iv] != all_counts[ip * num_types + iv]) {
3654 any_diff = true;
3655 if (!diff[iv]) {
3656 Ioss::FileInfo db(filename);
3657 diff[iv] = true;
3658 fmt::print(errmsg,
3659 "\nERROR: Number of {} variables is not consistent on all processors.\n"
3660 " Database: '{}'\n"
3661 "\tProcessor 0 count = {}\n",
3662 type, db.tailname(), var_counts[iv]);
3663 }
3664 fmt::print(errmsg, "\tProcessor {} count = {}\n", ip, all_counts[ip * num_types + iv]);
3665 }
3666 }
3667 }
3668 }
3669 else {
3670 // Give the other processors something to say...
3671 fmt::print(errmsg, "ERROR: Variable type counts are inconsistent. See processor 0 output for "
3672 "more details.\n");
3673 }
3674 int idiff = any_diff ? 1 : 0;
3675 util.broadcast(idiff);
3676 any_diff = idiff == 1;
3677
3678 if (any_diff) {
3679 std::runtime_error x(errmsg.str());
3680 throw x;
3681 }
3682 #endif
3683 }
3684
3685 void query_groups(int exoid, Ioss::NameList &names, bool return_full_names)
3686 {
3687 int idum;
3688 float rdum;
3689
3690 int group_name_length = ex_inquire_int(exoid, EX_INQ_GROUP_NAME_LEN);
3691 std::vector<char> group_name(group_name_length + 1, '\0');
3692
3693 // Get name of this group...
3694 int ierr = ex_inquire(exoid, EX_INQ_GROUP_NAME, &idum, &rdum, group_name.data());
3695 if (ierr < 0) {
3696 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
3697 }
3698
3699 if (return_full_names) {
3700 std::fill(group_name.begin(), group_name.end(), '\0');
3701 ierr = ex_inquire(exoid, EX_INQ_FULL_GROUP_NAME, &idum, &rdum, group_name.data());
3702 if (ierr < 0) {
3703 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
3704 }
3705 names.push_back(std::string(group_name.data()));
3706 }
3707 else {
3708 names.push_back(std::string(group_name.data()));
3709 }
3710
3711 int num_children = ex_inquire_int(exoid, EX_INQ_NUM_CHILD_GROUPS);
3712 std::vector<int> children(num_children);
3713 ierr = ex_get_group_ids(exoid, nullptr, Data(children));
3714 if (ierr < 0) {
3715 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
3716 }
3717
3718 for (int i = 0; i < num_children; i++) {
3719 query_groups(children[i], names, return_full_names);
3720 }
3721 }
3722 } // namespace