Debian Codegraph @

packages/seacas/libraries/ioss/src/Ioss_DatabaseIO.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 "Ioss_BoundingBox.h"
8 #include "Ioss_CodeTypes.h"
9 #include "Ioss_ElementTopology.h"
10 #include "Ioss_Enumerate.h"
11 #include "Ioss_FileInfo.h"
12 #include "Ioss_ParallelUtils.h"
13 #include "Ioss_Sort.h"
14 #include <algorithm>
15 #include <cassert>
16 #include <cfloat>
17 #include <cmath>
18 #include <cstddef>
19 #include <fmt/ostream.h>
20 #include <iostream>
21 #include <map>
22 #include <set>
23 #include <stdint.h>
24 #include <string>
25 #include <tokenize.h>
26 #include <utility>
27 #include <vector>
28
29 #include "Ioss_Assembly.h"
30 #include "Ioss_Blob.h"
31 #include "Ioss_CommSet.h"
32 #include "Ioss_DBUsage.h"
33 #include "Ioss_DataSize.h"
34 #include "Ioss_DatabaseIO.h"
35 #include "Ioss_EdgeBlock.h"
36 #include "Ioss_EdgeSet.h"
37 #include "Ioss_ElementBlock.h"
38 #include "Ioss_ElementSet.h"
39 #include "Ioss_EntityType.h"
40 #include "Ioss_FaceBlock.h"
41 #include "Ioss_FaceSet.h"
42 #include "Ioss_Field.h"
43 #include "Ioss_GroupingEntity.h"
44 #include "Ioss_Map.h"
45 #include "Ioss_NodeBlock.h"
46 #include "Ioss_NodeSet.h"
47 #include "Ioss_Property.h"
48 #include "Ioss_PropertyManager.h"
49 #include "Ioss_Region.h"
50 #include "Ioss_SerializeIO.h"
51 #include "Ioss_SideBlock.h"
52 #include "Ioss_SideSet.h"
53 #include "Ioss_StructuredBlock.h"
54 #include "Ioss_SurfaceSplit.h"
55 #include "Ioss_Utils.h"
56 #include "Ioss_VariableType.h"
57
58 #if defined SEACAS_HAVE_DATAWARP
59 extern "C" {
60 #include <datawarp.h>
61 }
62 #endif
63
64 namespace {
65 auto initial_time = std::chrono::steady_clock::now();
66
67 void log_time(std::chrono::time_point<std::chrono::steady_clock> &start,
68 std::chrono::time_point<std::chrono::steady_clock> &finish, int current_state,
69 double state_time, bool is_input, bool single_proc_only,
70 const Ioss::ParallelUtils &util);
71
72 void log_field(const char *symbol, const Ioss::GroupingEntity *entity, const Ioss::Field &field,
73 bool single_proc_only, const Ioss::ParallelUtils &util);
74
75 #ifndef NDEBUG
76 bool internal_parallel_consistent(bool single_proc_only, const Ioss::GroupingEntity *ge,
77 const Ioss::Field &field, int in_out,
78 const Ioss::ParallelUtils &util)
79 {
80 if (single_proc_only) {
81 return true;
82 }
83
84 const std::string &field_name = field.get_name();
85 unsigned int hash_code = ge->hash() + Ioss::Utils::hash(field_name);
86 unsigned int max_hash = util.global_minmax(hash_code, Ioss::ParallelUtils::DO_MAX);
87 unsigned int min_hash = util.global_minmax(hash_code, Ioss::ParallelUtils::DO_MIN);
88 if (max_hash != min_hash) {
89 const std::string &ge_name = ge->name();
90 fmt::print(Ioss::WarnOut(),
91 "[{}] Parallel inconsistency detected for {} field '{}' on entity '{}'. (Hash: {} "
92 "{} {})\n",
93 in_out == 0 ? "writing" : "reading", util.parallel_rank(), field_name, ge_name,
94 hash_code, min_hash, max_hash);
95 return false;
96 }
97 return true;
98 }
99 #endif
100 double my_min(double x1, double x2) { return x1 < x2 ? x1 : x2; }
101
102 double my_max(double x1, double x2) { return x1 > x2 ? x1 : x2; }
103
104 template <typename INT>
105 void calc_bounding_box(size_t ndim, size_t node_count, std::vector<double> &coordinates,
106 std::vector<INT> &connectivity, double &xmin, double &ymin, double &zmin,
107 double &xmax, double &ymax, double &zmax)
108 {
109 std::vector<int> elem_block_nodes(node_count);
110 for (const auto &node : connectivity) {
111 elem_block_nodes[node - 1] = 1;
112 }
113
114 xmin = DBL_MAX;
115 ymin = DBL_MAX;
116 zmin = DBL_MAX;
117
118 xmax = -DBL_MAX;
119 ymax = -DBL_MAX;
120 zmax = -DBL_MAX;
121
122 for (size_t i = 0; i < node_count; i++) {
123 if (elem_block_nodes[i] == 1) {
124 xmin = my_min(xmin, coordinates[ndim * i + 0]);
125 xmax = my_max(xmax, coordinates[ndim * i + 0]);
126
127 if (ndim > 1) {
128 ymin = my_min(ymin, coordinates[ndim * i + 1]);
129 ymax = my_max(ymax, coordinates[ndim * i + 1]);
130 }
131
132 if (ndim > 2) {
133 zmin = my_min(zmin, coordinates[ndim * i + 2]);
134 zmax = my_max(zmax, coordinates[ndim * i + 2]);
135 }
136 }
137 }
138 if (ndim < 3) {
139 zmin = zmax = 0.0;
140 }
141 if (ndim < 2) {
142 ymin = ymax = 0.0;
143 }
144 }
145
146 void calc_bounding_box(size_t ndim, size_t node_count, std::vector<double> &coordinates,
147 double &xmin, double &ymin, double &zmin, double &xmax, double &ymax,
148 double &zmax)
149 {
150 xmin = DBL_MAX;
151 ymin = DBL_MAX;
152 zmin = DBL_MAX;
153
154 xmax = -DBL_MAX;
155 ymax = -DBL_MAX;
156 zmax = -DBL_MAX;
157
158 for (size_t i = 0; i < node_count; i++) {
159 xmin = my_min(xmin, coordinates[ndim * i + 0]);
160 xmax = my_max(xmax, coordinates[ndim * i + 0]);
161
162 if (ndim > 1) {
163 ymin = my_min(ymin, coordinates[ndim * i + 1]);
164 ymax = my_max(ymax, coordinates[ndim * i + 1]);
165 }
166
167 if (ndim > 2) {
168 zmin = my_min(zmin, coordinates[ndim * i + 2]);
169 zmax = my_max(zmax, coordinates[ndim * i + 2]);
170 }
171 }
172 if (ndim < 3) {
173 zmin = zmax = 0.0;
174 }
175 if (ndim < 2) {
176 ymin = ymax = 0.0;
177 }
178 }
179
180 template <typename T>
181 std::vector<size_t> get_entity_offsets(const std::string &field_name,
182 const std::vector<T *> &entity_container)
183 {
184 size_t num_blocks = entity_container.size();
185 std::vector<size_t> offsets(num_blocks + 1, 0);
186
187 for (auto [i, entity] : enumerate(entity_container)) {
188 if (entity->field_exists(field_name)) {
189 Ioss::Field field = entity->get_field(field_name);
190 offsets[i + 1] = entity->entity_count() * field.raw_storage()->component_count();
191 }
192 }
193
194 for (size_t i = 1; i <= num_blocks; ++i) {
195 offsets[i] += offsets[i - 1];
196 }
197
198 return offsets;
199 }
200
201 template <typename ENTITY>
202 int64_t zero_copy_not_enabled(const ENTITY *entity, const Ioss::Field &field,
203 const Ioss::DatabaseIO *db)
204 {
205 IOSS_ERROR(fmt::format(
206 "On {} {}, the field {} is specified as zero-copy enabled, but the database {} does "
207 "not support zero-copy for this field and/or entity type.\n",
208 entity->type_string(), entity->name(), field.get_name(), db->get_filename()));
209 }
210 } // namespace
211
212 namespace Ioss {
213 DatabaseIO::DatabaseIO(Region *region, std::string filename, DatabaseUsage db_usage,
214 Ioss_MPI_Comm communicator, const PropertyManager &props)
215 : properties(props), DBFilename(std::move(filename)), dbUsage(db_usage),
216 util_(db_usage == WRITE_HISTORY || db_usage == WRITE_HEARTBEAT
217 ? Ioss::ParallelUtils::comm_self()
218 : communicator),
219 region_(region), isInput(is_input_event(db_usage)),
220 singleProcOnly(db_usage == WRITE_HISTORY || db_usage == WRITE_HEARTBEAT ||
221 SerializeIO::isEnabled())
222 {
223 isParallel = util_.parallel_size() > 1;
224 myProcessor = util_.parallel_rank();
225
226 nodeMap.set_rank(myProcessor);
227 edgeMap.set_rank(myProcessor);
228 faceMap.set_rank(myProcessor);
229 elemMap.set_rank(myProcessor);
230
231 // Some operations modify DBFilename and there is a need to get
232 // back to the original filename...
233 originalDBFilename = DBFilename;
234
235 // Check environment variable IOSS_PROPERTIES. If it exists, parse
236 // the contents and add to the 'properties' map.
237 util_.add_environment_properties(properties);
238
239 Utils::check_set_bool_property(properties, "ENABLE_FIELD_RECOGNITION", enableFieldRecognition);
240 Utils::check_set_bool_property(properties, "IGNORE_REALN_FIELDS", m_ignoreRealnFields);
241
242 if (properties.exists("FIELD_SUFFIX_SEPARATOR")) {
243 std::string tmp = properties.get("FIELD_SUFFIX_SEPARATOR").get_string();
244 fieldSeparator = tmp[0];
245 fieldSeparatorSpecified = true;
246 }
247
248 // If `FIELD_SUFFIX_SEPARATOR` is empty and there are fields that
249 // end with an underscore, then strip the underscore. This will
250 // cause d_x, d_y, d_z to be a 3-component field 'd' and vx, vy,
251 // vz to be a 3-component field 'v'.
252 Utils::check_set_bool_property(properties, "FIELD_STRIP_TRAILING_UNDERSCORE",
253 fieldStripTrailing_);
254
255 // Determine how to handle duplicate incompatible fields (transient and attribute field with
256 // same name, ...)
257 if (properties.exists("DUPLICATE_FIELD_NAME_BEHAVIOR")) {
258 auto prop = properties.get("DUPLICATE_FIELD_NAME_BEHAVIOR").get_string();
259 if (prop == "IGNORE") {
260 duplicateFieldBehavior = DuplicateFieldBehavior::IGNORE_;
261 }
262 else if (prop == "WARNING") {
263 duplicateFieldBehavior = DuplicateFieldBehavior::WARNING_;
264 }
265 else if (prop == "ERROR") {
266 duplicateFieldBehavior = DuplicateFieldBehavior::ERROR_;
267 }
268 else {
269 IOSS_ERROR(fmt::format("Invalid value ({}) for property `DUPLICATE_FIELD_NAME_BEHAVIOR`.\n"
270 "\tValid values are `IGNORE`, `WARNING`, or `ERROR`\n",
271 prop));
272 }
273 }
274 else {
275 bool allow_duplicate = false;
276 Utils::check_set_bool_property(properties, "IGNORE_DUPLICATE_FIELD_NAMES", allow_duplicate);
277 if (allow_duplicate) {
278 duplicateFieldBehavior = DuplicateFieldBehavior::WARNING_;
279 }
280 else {
281 duplicateFieldBehavior = DuplicateFieldBehavior::ERROR_;
282 }
283 }
284
285 if (properties.exists("SURFACE_SPLIT_TYPE")) {
286 Ioss::SurfaceSplitType split_type = Ioss::SPLIT_INVALID;
287 auto type = properties.get("SURFACE_SPLIT_TYPE").get_type();
288 if (type == Ioss::Property::INTEGER) {
289 int split = properties.get("SURFACE_SPLIT_TYPE").get_int();
290 split_type = Ioss::int_to_surface_split(split);
291 }
292 else if (type == Ioss::Property::STRING) {
293 std::string split = properties.get("SURFACE_SPLIT_TYPE").get_string();
294 if (Ioss::Utils::str_equal(split, "TOPOLOGY")) {
295 split_type = Ioss::SPLIT_BY_TOPOLOGIES;
296 }
297 else if (Ioss::Utils::str_equal(split, "BLOCK")) {
298 split_type = Ioss::SPLIT_BY_ELEMENT_BLOCK;
299 }
300 else if (Ioss::Utils::str_equal(split, "NO_SPLIT")) {
301 split_type = Ioss::SPLIT_BY_DONT_SPLIT;
302 }
303 else {
304 split_type = Ioss::SPLIT_INVALID;
305 fmt::print(Ioss::WarnOut(),
306 "Invalid setting for SURFACE_SPLIT_TYPE Property ('{}'). Valid entries are "
307 "TOPOLOGY, BLOCK, NO_SPLIT. Ignoring.\n",
308 split);
309 }
310 }
311 if (split_type != Ioss::SPLIT_INVALID) {
312 set_surface_split_type(split_type);
313 }
314 }
315
316 if (properties.exists("INTEGER_SIZE_API")) {
317 int isize = properties.get("INTEGER_SIZE_API").get_int();
318 if (isize == 8) {
319 set_int_byte_size_api(Ioss::USE_INT64_API);
320 }
321 }
322
323 if (properties.exists("SERIALIZE_IO")) {
324 int isize = properties.get("SERIALIZE_IO").get_int();
325 Ioss::SerializeIO::setGroupFactor(isize);
326 if (isize > 0) {
327 singleProcOnly = true;
328 }
329 }
330
331 cycleCount = properties.get_optional("CYCLE_COUNT", cycleCount);
332 overlayCount = properties.get_optional("OVERLAY_COUNT", overlayCount);
333
334 Utils::check_set_bool_property(properties, "ENABLE_TRACING", m_enableTracing);
335 Utils::check_set_bool_property(properties, "TIME_STATE_INPUT_OUTPUT", m_timeStateInOut);
336 {
337 bool logging = false;
338 if (Utils::check_set_bool_property(properties, "LOGGING", logging)) {
339 set_logging(logging);
340 }
341 }
342 {
343 bool nan_detection = false;
344 if (Utils::check_set_bool_property(properties, "NAN_DETECTION", nan_detection)) {
345 set_nan_detection(nan_detection);
346 }
347 }
348
349 Utils::check_set_bool_property(properties, "LOWER_CASE_VARIABLE_NAMES", lowerCaseVariableNames);
350 Utils::check_set_bool_property(properties, "USE_GENERIC_CANONICAL_NAMES",
351 useGenericCanonicalName);
352 Utils::check_set_bool_property(properties, "IGNORE_DATABASE_NAMES", ignoreDatabaseNames);
353
354 {
355 bool consistent;
356 if (Utils::check_set_bool_property(properties, "PARALLEL_CONSISTENCY", consistent)) {
357 set_parallel_consistency(consistent);
358 }
359 }
360
361 check_set_dw();
362
363 if (!is_input()) {
364 // Create full path to the output file at this point if it doesn't
365 // exist...
366 if (isParallel) {
367 Ioss::FileInfo::create_path(DBFilename, util().communicator());
368 }
369 else {
370 Ioss::FileInfo::create_path(DBFilename);
371 }
372 }
373 }
374
375 DatabaseIO::~DatabaseIO() = default;
376
377 Ioss::DataSize DatabaseIO::int_byte_size_data_size() const { return dbIntSizeAPI; }
378
379 int DatabaseIO::int_byte_size_api() const
380 {
381 if (dbIntSizeAPI == USE_INT32_API) {
382 return 4;
383 }
384 return 8;
385 }
386
387 /** \brief Set the number of bytes used to represent an integer.
388 *
389 * \param[in] size The number of bytes. This is 4 for INT32 or 8 for INT64.
390 */
391 void DatabaseIO::set_int_byte_size_api(DataSize size) const
392 {
393 dbIntSizeAPI = size; // mutable
394 }
395
396 /** \brief Set the character used to separate a field suffix from the field basename
397 * when recognizing vector, tensor fields.
398 *
399 * \param[in] separator The separator character.
400 */
401 void DatabaseIO::set_field_separator(const char separator)
402 {
403 if (properties.exists("FIELD_SUFFIX_SEPARATOR")) {
404 properties.erase("FIELD_SUFFIX_SEPARATOR");
405 }
406 char tmp[2] = {separator, '\0'};
407 properties.add(Property("FIELD_SUFFIX_SEPARATOR", tmp));
408 fieldSeparator = separator;
409 fieldSeparatorSpecified = true;
410 }
411
412 std::string DatabaseIO::get_component_name(const Ioss::Field &field, Ioss::Field::InOut in_out,
413 int component) const
414 {
415 // If the user has explicitly set the suffix separator for this database,
416 // then use it for all fields.
417 // If it was not explicitly set, then use whatever the field has defined,
418 // of if field also has nothing explicitly set, use '_'
419 char suffix = fieldSeparatorSpecified ? get_field_separator() : 1;
420 return field.get_component_name(component, in_out, suffix);
421 }
422
423 /**
424 * Check whether user wants to use Cray DataWarp. It will be enabled if:
425 * the `DW_JOB_STRIPED` or `DW_JOB_PRIVATE` environment variable
426 * is set by the queuing system during runtime and the IOSS property
427 * `ENABLE_DATAWARP` set to `YES`.
428 *
429 * We currently only want output files to be directed to BB.
430 */
431 void DatabaseIO::check_set_dw() const
432 {
433 if (!is_input()) {
434 bool set_dw = false;
435 Utils::check_set_bool_property(properties, "ENABLE_DATAWARP", set_dw);
436 if (set_dw) {
437 std::string bb_path;
438 // Selected via `#DW jobdw type=scratch access_mode=striped`
439 util().get_environment("DW_JOB_STRIPED", bb_path, isParallel);
440
441 if (bb_path.empty()) { // See if using `private` mode...
442 // Selected via `#DW jobdw type=scratch access_mode=private`
443 util().get_environment("DW_JOB_PRIVATE", bb_path, isParallel);
444 }
445 if (!bb_path.empty()) {
446 usingDataWarp = true;
447 dwPath = bb_path;
448 if (myProcessor == 0) {
449 fmt::print(Ioss::OUTPUT(), "\nDataWarp Burst Buffer Enabled. Path = `{}`\n\n", dwPath);
450 }
451 }
452 else {
453 if (myProcessor == 0) {
454 fmt::print(Ioss::WarnOut(),
455 "DataWarp enabled via Ioss property `ENABLE_DATAWARP`, but\n"
456 " burst buffer path was not specified via `DW_JOB_STRIPED` or "
457 "`DW_JOB_PRIVATE`\n"
458 " environment variables (typically set by queuing system)\n"
459 " DataWarp will *NOT* be enabled, but job will still run.\n\n");
460 }
461 }
462 }
463 }
464 }
465
466 /**
467 * In this wrapper function we check if user intends to use Cray
468 * DataWarp(aka DW), which provides ability to use NVMe based flash
469 * storage available across all compute nodes accessible via high
470 * speed NIC.
471 */
472 void DatabaseIO::open_dw(const std::string &filename) const
473 {
474 set_pfs_name(filename); // Name on permanent-file-store
475 if (using_dw()) { // We are about to write to a output database in BB
476 Ioss::FileInfo path{filename};
477 Ioss::FileInfo bb_file{get_dw_path() + path.tailname()};
478 if (bb_file.exists() && !bb_file.is_writable()) {
479 // already existing file which has been closed If we can't
480 // write to the file on the BB, then it is a file which is
481 // being staged by datawarp system over to the permanent
482 // filesystem. Wait until staging has finished... stage wait
483 // returns 0 = success, -ENOENT or -errno
484 #if defined SEACAS_HAVE_DATAWARP
485 #if IOSS_DEBUG_OUTPUT
486 if (myProcessor == 0) {
487 fmt::print(Ioss::DebugOut(), "DW: dw_wait_file_stage({});\n", bb_file.filename());
488 }
489 #endif
490 int dwret = dw_wait_file_stage(bb_file.filename().c_str());
491 if (dwret < 0) {
492 IOSS_ERROR(fmt::format("ERROR: failed waiting for file stage `{}`: {}\n",
493 bb_file.filename(), std::strerror(-dwret)));
494 }
495 #else
496 // Used to debug DataWarp logic on systems without DataWarp...
497 fmt::print(Ioss::DebugOut(), "DW: (FAKE) dw_wait_file_stage({});\n", bb_file.filename());
498 #endif
499 }
500 set_dw_name(bb_file.filename());
501 }
502 else {
503 set_dw_name(filename);
504 }
505 }
506
507 /** \brief This function gets called inside closeDatabase_nl(), which checks if Cray Datawarp (DW)
508 * is in use, if so, we want to call a stageout before actual close of this file.
509 */
510 void DatabaseIO::close_dw() const
511 {
512 if (using_dw()) {
513 if (!using_parallel_io() || myProcessor == 0) {
514 #if defined SEACAS_HAVE_DATAWARP
515 int complete = 0, pending = 0, deferred = 0, failed = 0;
516 dw_query_file_stage(get_dw_name().c_str(), &complete, &pending, &deferred, &failed);
517 #if IOSS_DEBUG_OUTPUT
518 auto initial = std::chrono::steady_clock::now();
519 fmt::print(Ioss::DebugOut(), "Query: {}, {}, {}, {}\n", complete, pending, deferred,
520 failed);
521 #endif
522 if (pending > 0) {
523 int dwret = dw_wait_file_stage(get_dw_name().c_str());
524 if (dwret < 0) {
525 IOSS_ERROR(fmt::format("ERROR: failed waiting for file stage `{}`: {}\n", get_dw_name(),
526 std::strerror(-dwret)));
527 }
528 #if IOSS_DEBUG_OUTPUT
529 dw_query_file_stage(get_dw_name().c_str(), &complete, &pending, &deferred, &failed);
530 fmt::print(Ioss::DebugOut(), "Query: {}, {}, {}, {}\n", complete, pending, deferred,
531 failed);
532 #endif
533 }
534
535 #if IOSS_DEBUG_OUTPUT
536 fmt::print(Ioss::DebugOut(), "\nDW: BEGIN dw_stage_file_out({}, {}, DW_STAGE_IMMEDIATE);\n",
537 get_dw_name(), get_pfs_name());
538 #endif
539 int ret =
540 dw_stage_file_out(get_dw_name().c_str(), get_pfs_name().c_str(), DW_STAGE_IMMEDIATE);
541
542 #if IOSS_DEBUG_OUTPUT
543 auto time_now = std::chrono::steady_clock::now();
544 std::chrono::duration<double> diff = time_now - initial;
545 fmt::print(Ioss::DebugOut(), "\nDW: END dw_stage_file_out({})\n", diff.count());
546 #endif
547 if (ret < 0) {
548 IOSS_ERROR(fmt::format("ERROR: file staging of `{}` to `{}` failed at close: {}\n",
549 get_dw_name(), get_pfs_name(), std::strerror(-ret)));
550 }
551 #else
552 fmt::print(Ioss::DebugOut(),
553 "\nDW: (FAKE) dw_stage_file_out({}, {}, DW_STAGE_IMMEDIATE);\n", get_dw_name(),
554 get_pfs_name());
555 #endif
556 }
557 if (using_parallel_io()) {
558 util().barrier();
559 }
560 }
561 }
562
563 void DatabaseIO::openDatabase_nl() const { open_dw(get_filename()); }
564
565 void DatabaseIO::closeDatabase_nl() const { close_dw(); }
566
567 IfDatabaseExistsBehavior DatabaseIO::open_create_behavior() const
568 {
569 IfDatabaseExistsBehavior exists = DB_OVERWRITE;
570 if (properties.exists("APPEND_OUTPUT")) {
571 exists = static_cast<IfDatabaseExistsBehavior>(properties.get("APPEND_OUTPUT").get_int());
572 }
573 return exists;
574 }
575
576 const std::string &DatabaseIO::decoded_filename() const
577 {
578 if (decodedFilename.empty()) {
579 if (isParallel) {
580 decodedFilename = util().decode_filename(get_filename(), isParallel && !usingParallelIO);
581 }
582 else if (properties.exists("processor_count") && properties.exists("my_processor")) {
583 int proc_count = properties.get("processor_count").get_int();
584 int my_proc = properties.get("my_processor").get_int();
585 decodedFilename = Ioss::Utils::decode_filename(get_filename(), my_proc, proc_count);
586 }
587 else {
588 decodedFilename = get_filename();
589 }
590
591 open_dw(decodedFilename);
592 if (using_dw()) {
593 // Note that if using_dw(), then we need to set the decodedFilename to the BB name.
594 decodedFilename = get_dw_name();
595 }
596 }
597 return decodedFilename;
598 }
599
600 bool DatabaseIO::verify_field_data(const GroupingEntity *ge, const Field &field,
601 Ioss::Field::InOut in_out, void *data) const
602 {
603 bool nan_found = false;
604 if (field.is_type(Ioss::Field::BasicType::DOUBLE)) {
605
606 auto *rdata = static_cast<double *>(data);
607 size_t comp_count = field.get_component_count(in_out);
608 size_t num_to_get = field.raw_count();
609
610 // First, let's just see if there are ANY nans...
611 nan_found = std::find_if(rdata, rdata + comp_count * num_to_get, [](double v) {
612 return std::isnan(v);
613 }) != rdata + comp_count * num_to_get;
614
615 if (nan_found) {
616 // We know there is at least on nan. Now we will do a slower run through the data so can
617 // give user a more accurate idea of how many and where they exist...
618 std::string direction = in_out == Ioss::Field::InOut::OUTPUT ? "writing" : "reading";
619 std::vector<size_t> nans;
620 nans.reserve(num_to_get / 10);
621
622 for (size_t comp = 0; comp < comp_count; comp++) {
623 for (size_t i = 0; i < num_to_get; i++) {
624 size_t idx = comp_count * i + comp;
625 if (std::isnan(rdata[idx])) {
626 nans.push_back(i);
627 }
628 }
629 if (!nans.empty()) {
630 fmt::print(Ioss::WarnOut(), "Found {} NaN{} {} field '{}' on {} '{}' at {} {}.\n",
631 nans.size(), nans.size() > 1 ? "s" : "", direction,
632 get_component_name(field, in_out, comp + 1), ge->type_string(), ge->name(),
633 nans.size() > 1 ? "indices" : "index", Ioss::Utils::format_id_list(nans));
634 nans.clear();
635 }
636 }
637 }
638 }
639 return nan_found;
640 }
641
642 void DatabaseIO::verify_and_log(const GroupingEntity *ge, const Field &field, int in_out) const
643 {
644 if (ge != nullptr) {
645 assert(!is_parallel_consistent() ||
646 internal_parallel_consistent(singleProcOnly, ge, field, in_out, util_));
647 }
648 if (get_logging()) {
649 log_field(in_out == 1 ? ">" : "<", ge, field, singleProcOnly, util_);
650 }
651 }
652
653 bool DatabaseIO::begin_state(int state, double time)
654 {
655 IOSS_FUNC_ENTER(m_);
656 progress(__func__);
657 if (m_timeStateInOut) {
658 m_stateStart = std::chrono::steady_clock::now();
659 }
660 return begin_state_nl(state, time);
661 }
662 bool DatabaseIO::end_state(int state, double time)
663 {
664 IOSS_FUNC_ENTER(m_);
665 bool res = end_state_nl(state, time);
666 if (m_timeStateInOut) {
667 auto finish = std::chrono::steady_clock::now();
668 log_time(m_stateStart, finish, state, time, is_input(), singleProcOnly, util_);
669 }
670 progress(__func__);
671 return res;
672 }
673
674 // Default versions do nothing...
675 bool DatabaseIO::begin_state_nl(int /* state */, double /* time */) { return true; }
676
677 bool DatabaseIO::end_state_nl(int /* state */, double /* time */) { return true; }
678
679 void DatabaseIO::handle_groups()
680 {
681 // Set Grouping requests are specified as properties...
682 // See if the property exists and decode...
683 // There is a property for each "type":
684 // GROUP_SIDESET, GROUP_NODESET, GROUP_EDGESET, GROUP_FACESET,
685 // GROUP_ELEMSET.
686 // Within the property, the "value" consists of multiple groups separated by
687 // ":"
688 // Within the group, the names are "," separated:
689 //
690 // new_surf1,member1,member2,member3:new_surf2,mem1,mem2,mem3,mem4:new_surf3,....
691 //
692 // Currently does not check for duplicate entity membership in a set --
693 // union
694 // with duplicates
695 //
696 create_groups("GROUP_SIDESET", SIDESET, "side", (SideSet *)nullptr);
697 create_groups("GROUP_NODESET", NODESET, "node", (NodeSet *)nullptr);
698 create_groups("GROUP_EDGESET", EDGESET, "edge", (EdgeSet *)nullptr);
699 create_groups("GROUP_FACESET", FACESET, "face", (FaceSet *)nullptr);
700 create_groups("GROUP_ELEMSET", ELEMENTSET, "elem", (ElementSet *)nullptr);
701 }
702
703 template <typename T>
704 void DatabaseIO::create_groups(const std::string &property_name, EntityType type,
705 const std::string &type_name, const T *set_type)
706 {
707 if (!properties.exists(property_name)) {
708 return;
709 }
710
711 std::string prop = properties.get(property_name).get_string();
712 Ioss::NameList groups = tokenize(prop, ":");
713 for (auto &group : groups) {
714 Ioss::NameList group_spec = tokenize(group, ",");
715
716 // group_spec should contain the name of the new group as
717 // the first location and the members of the group as subsequent
718 // locations. OK to have a single member
719 if (group_spec.size() < 2) {
720 IOSS_ERROR(
721 fmt::format("ERROR: Invalid {} group specification '{}'\n"
722 " Correct syntax is 'new_group,member1,...,memberN' and there must "
723 " be at least 1 member of the group",
724 type_name, group));
725 }
726
727 create_group(type, type_name, group_spec, set_type);
728 }
729 }
730
731 template <typename T>
732 void DatabaseIO::create_group(EntityType /*type*/, const std::string &type_name,
733 const Ioss::NameList &group_spec, const T * /*set_type*/)
734 {
735 fmt::print(Ioss::WarnOut(),
736 "Grouping of {0} sets is not yet implemented.\n"
737 " Skipping the creation of {0} set '{1}'\n\n",
738 type_name, group_spec[0]);
739 }
740
741 template <>
742 void DatabaseIO::create_group(EntityType type, const std::string &/*type_name*/,
743 const Ioss::NameList &group_spec, const SideSet * /*set_type*/)
744 {
745 // Not generalized yet... This only works for T == SideSet
746 if (type != SIDESET) {
747 return;
748 }
749
750 int64_t entity_count = 0;
751 int64_t df_count = 0;
752
753 // Create the new set...
754 auto *new_set = new SideSet(this, group_spec[0]);
755
756 get_region()->add(new_set);
757
758 // Find the member SideSets...
759 for (const auto &spec : group_spec) {
760 SideSet *set = get_region()->get_sideset(spec);
761 if (set != nullptr) {
762 const SideBlockContainer &side_blocks = set->get_side_blocks();
763 for (const auto &sbold : side_blocks) {
764 size_t side_count = sbold->entity_count();
765 auto *sbnew = new SideBlock(this, sbold->name(), sbold->topology()->name(),
766 sbold->parent_element_topology()->name(), side_count);
767 int64_t id = sbold->get_property("id").get_int();
768 sbnew->property_add(Property("set_offset", entity_count));
769 sbnew->property_add(Property("set_df_offset", df_count));
770 sbnew->property_add(Property("id", id));
771 sbnew->property_add(Property("id", id));
772 sbnew->property_add(Property("guid", util().generate_guid(id)));
773
774 new_set->add(sbnew);
775
776 size_t old_df_count = sbold->get_property("distribution_factor_count").get_int();
777 if (old_df_count > 0) {
778 std::string storage = "Real[";
779 storage += std::to_string(sbnew->topology()->number_nodes());
780 storage += "]";
781 sbnew->field_add(
782 Field("distribution_factors", Field::REAL, storage, Field::MESH, side_count));
783 }
784 entity_count += side_count;
785 df_count += old_df_count;
786 }
787 }
788 else {
789 fmt::print(Ioss::WarnOut(),
790 "While creating the grouped surface '{}', the surface '{}' does not exist. "
791 "This surface will skipped and not added to the group.\n\n",
792 group_spec[0], spec);
793 }
794 }
795 }
796
797 // Utility function that may be used by derived classes. Determines
798 // whether all elements in the model have the same face topology.
799 // This can be used to speed-up certain algorithms since they don't
800 // have to check each face (or group of faces) individually.
801 void DatabaseIO::set_common_side_topology() const
802 {
803 auto *new_this = const_cast<DatabaseIO *>(this);
804
805 bool first = true;
806 const ElementBlockContainer &element_blocks = get_region()->get_element_blocks();
807 for (auto *block : element_blocks) {
808 size_t element_count = block->entity_count();
809
810 // Check face types.
811 if (element_count > 0) {
812 if (commonSideTopology != nullptr || first) {
813 first = false;
814 ElementTopology *side_type = block->topology()->boundary_type();
815 if (commonSideTopology == nullptr) { // First block
816 new_this->commonSideTopology = side_type;
817 }
818 if (commonSideTopology != side_type) { // Face topologies differ in mesh
819 new_this->commonSideTopology = nullptr;
820 return;
821 }
822 }
823 }
824 }
825 }
826
827 /** \brief Add multiple information records (informative strings) to the database.
828 *
829 * \param[in] info The strings to add.
830 */
831 void DatabaseIO::add_information_records(const Ioss::NameList &info)
832 {
833 informationRecords.reserve(informationRecords.size() + info.size());
834 informationRecords.insert(informationRecords.end(), info.begin(), info.end());
835 }
836
837 /** \brief Add an information record (an informative string) to the database.
838 *
839 * \param[in] info The string to add.
840 */
841 void DatabaseIO::add_information_record(const std::string &info)
842 {
843 informationRecords.push_back(info);
844 }
845
846 /** \brief Add a QA record, which consists of 4 strings, to the database
847 *
848 * The 4 function parameters correspond to the 4 QA record strings.
849 *
850 * \param[in] code A descriptive code name, such as the application that modified the database.
851 * \param[in] code_qa A descriptive string, such as the version of the application that modified
852 * the database.
853 * \param[in] date A relevant date, such as the date the database was modified.
854 * \param[in] time A relevant time, such as the time the database was modified.
855 */
856 void DatabaseIO::add_qa_record(const std::string &code, const std::string &code_qa,
857 const std::string &date, const std::string &time)
858 {
859 qaRecords.push_back(code);
860 qaRecords.push_back(code_qa);
861 qaRecords.push_back(date);
862 qaRecords.push_back(time);
863 }
864
865 void DatabaseIO::set_block_omissions(const Ioss::NameList &omissions,
866 const Ioss::NameList &inclusions)
867 {
868 if (!omissions.empty() && !inclusions.empty()) {
869 // Only one can be non-empty
870 IOSS_ERROR(
871 fmt::format("ERROR: Only one of element block omission or inclusion can be non-empty"
872 " [{}]\n",
873 get_filename()));
874 }
875
876 if (!assemblyOmissions.empty() && !inclusions.empty()) {
877 IOSS_ERROR(fmt::format(
878 "ERROR: Only one of element block inclusion or assembly omission can be non-empty"
879 " [{}]\n",
880 get_filename()));
881 }
882
883 if (!assemblyInclusions.empty() && !omissions.empty()) {
884 IOSS_ERROR(fmt::format(
885 "ERROR: Only one of element block omission or assembly inclusion can be non-empty"
886 " [{}]\n",
887 get_filename()));
888 }
889
890 if (!omissions.empty()) {
891 blockOmissions.assign(omissions.cbegin(), omissions.cend());
892 Ioss::sort(blockOmissions.begin(), blockOmissions.end());
893 }
894 if (!inclusions.empty()) {
895 blockInclusions.assign(inclusions.cbegin(), inclusions.cend());
896 Ioss::sort(blockInclusions.begin(), blockInclusions.end());
897 }
898 }
899
900 void DatabaseIO::set_assembly_omissions(const Ioss::NameList &omissions,
901 const Ioss::NameList &inclusions)
902 {
903 if (!omissions.empty() && !inclusions.empty()) {
904 // Only one can be non-empty
905 IOSS_ERROR(fmt::format("ERROR: Only one of assembly omission or inclusion can be non-empty"
906 " [{}]\n",
907 get_filename()));
908 }
909
910 if (!blockOmissions.empty() && !inclusions.empty()) {
911 IOSS_ERROR(fmt::format(
912 "ERROR: Only one of element block omission or assembly inclusion can be non-empty"
913 " [{}]\n",
914 get_filename()));
915 }
916
917 if (!blockInclusions.empty() && !omissions.empty()) {
918 IOSS_ERROR(fmt::format(
919 "ERROR: Only one of element block inclusion or assembly omission can be non-empty"
920 " [{}]\n",
921 get_filename()));
922 }
923
924 if (!omissions.empty()) {
925 assemblyOmissions.assign(omissions.cbegin(), omissions.cend());
926 Ioss::sort(assemblyOmissions.begin(), assemblyOmissions.end());
927 }
928 if (!inclusions.empty()) {
929 assemblyInclusions.assign(inclusions.cbegin(), inclusions.cend());
930 Ioss::sort(assemblyInclusions.begin(), assemblyInclusions.end());
931 }
932 }
933
934 // Check topology of all sides (face/edges) in model...
935 void DatabaseIO::check_side_topology() const
936 {
937 // The following code creates the sideTopology sets which contain
938 // a list of the side topologies in this model.
939 //
940 // If sideTopology.size() > 1 --> the model has sides with mixed
941 // topology (i.e., quads and tris).
942 //
943 // If sideTopology.size() == 1 --> the model has homogeneous sides
944 // and each side is of the topology type 'sideTopology[0]'
945 //
946 // This is used in other code speed up some tests.
947
948 // Spheres and Circle have no faces/edges, so handle them special...
949
950 if (sideTopology.empty()) {
951 // Set contains (parent_element, boundary_topology) pairs...
952 std::set<std::pair<const ElementTopology *, const ElementTopology *>> side_topo;
953
954 const ElementBlockContainer &element_blocks = get_region()->get_element_blocks();
955
956 bool all_sphere = true;
957 for (const auto &block : element_blocks) {
958 const ElementTopology *elem_type = block->topology();
959 const ElementTopology *side_type = elem_type->boundary_type();
960 if (side_type == nullptr) {
961 // heterogeneous sides. Iterate through... (or there is no
962 // defined `side` for this parent topology.
963 int size = elem_type->number_boundaries();
964 for (int i = 1; i <= size; i++) {
965 side_type = elem_type->boundary_type(i);
966 side_topo.insert(std::make_pair(elem_type, side_type));
967 all_sphere = false;
968 }
969 }
970 else {
971 // homogeneous sides.
972 side_topo.insert(std::make_pair(elem_type, side_type));
973 all_sphere = false;
974 }
975 }
976 if (all_sphere) {
977 // If we end up here, the model either contains all spheres,
978 // or there are no element blocks in the model...
979 const ElementTopology *ftopo = ElementTopology::factory("unknown");
980 if (element_blocks.empty()) {
981 side_topo.insert(std::make_pair(ftopo, ftopo));
982 }
983 else {
984 const ElementBlock *block = *element_blocks.cbegin();
985 side_topo.insert(std::make_pair(block->topology(), ftopo));
986 }
987 }
988 assert(!side_topo.empty());
989 assert(sideTopology.empty());
990 // Copy into the sideTopology container...
991 auto *new_this = const_cast<DatabaseIO *>(this);
992 std::copy(side_topo.cbegin(), side_topo.cend(), std::back_inserter(new_this->sideTopology));
993 }
994 assert(!sideTopology.empty());
995 }
996
997 void DatabaseIO::get_block_adjacencies_nl(const Ioss::ElementBlock *eb,
998 Ioss::NameList &block_adjacency) const
999 {
1000 if (!blockAdjacenciesCalculated) {
1001 compute_block_adjacencies();
1002 }
1003
1004 const Ioss::ElementBlockContainer &element_blocks = get_region()->get_element_blocks();
1005 assert(Ioss::Utils::check_block_order(element_blocks));
1006
1007 // Extract the computed block adjacency information for this
1008 // element block:
1009 int blk_position = 0;
1010 if (eb->property_exists("original_block_order")) {
1011 blk_position = eb->get_property("original_block_order").get_int();
1012 }
1013 else {
1014 for (const auto &leb : element_blocks) {
1015 if (leb == eb) {
1016 break;
1017 }
1018 blk_position++;
1019 }
1020 }
1021
1022 int lblk_position = -1;
1023 for (const auto &leb : element_blocks) {
1024 if (leb->property_exists("original_block_order")) {
1025 lblk_position = leb->get_property("original_block_order").get_int();
1026 }
1027 else {
1028 lblk_position++;
1029 }
1030
1031 if (blk_position != lblk_position &&
1032 static_cast<int>(blockAdjacency[blk_position][lblk_position]) == 1) {
1033 block_adjacency.push_back(leb->name());
1034 }
1035 }
1036 }
1037
1038 // common
1039 void DatabaseIO::compute_block_adjacencies() const
1040 {
1041 // Add a field to each element block specifying which other element
1042 // blocks the block is adjacent to (defined as sharing nodes).
1043 // This is only calculated on request...
1044
1045 blockAdjacenciesCalculated = true;
1046
1047 const Ioss::ElementBlockContainer &element_blocks = get_region()->get_element_blocks();
1048 assert(Ioss::Utils::check_block_order(element_blocks));
1049
1050 if (element_blocks.size() == 1) {
1051 blockAdjacency.resize(1);
1052 blockAdjacency[0].resize(1);
1053 blockAdjacency[0][0] = false;
1054 return;
1055 }
1056
1057 // Each processor first calculates the adjacencies on their own
1058 // processor...
1059
1060 std::vector<int64_t> node_used(nodeCount);
1061 std::vector<std::vector<int>> inv_con(nodeCount);
1062
1063 {
1064 Ioss::SerializeIO serializeIO_(this);
1065 int blk_position = -1;
1066 for (Ioss::ElementBlock *eb : element_blocks) {
1067 if (eb->property_exists("original_block_order")) {
1068 blk_position = eb->get_property("original_block_order").get_int();
1069 }
1070 else {
1071 blk_position++;
1072 }
1073 int64_t my_element_count = eb->entity_count();
1074 if (int_byte_size_api() == 8) {
1075 std::vector<int64_t> conn;
1076 eb->get_field_data("connectivity_raw", conn);
1077 for (const auto &node : conn) {
1078 assert(node > 0 && node - 1 < nodeCount);
1079 node_used[node - 1] = blk_position + 1;
1080 }
1081 }
1082 else {
1083 std::vector<int> conn;
1084 eb->get_field_data("connectivity_raw", conn);
1085 for (const auto &node : conn) {
1086 assert(node > 0 && node - 1 < nodeCount);
1087 node_used[node - 1] = blk_position + 1;
1088 }
1089 }
1090
1091 if (my_element_count > 0) {
1092 for (int64_t i = 0; i < nodeCount; i++) {
1093 if (node_used[i] == blk_position + 1) {
1094 inv_con[i].push_back(blk_position);
1095 }
1096 }
1097 }
1098 }
1099 }
1100
1101 #ifdef SEACAS_HAVE_MPI
1102 if (isParallel) {
1103 // Get contributions from other processors...
1104 // Get the communication map...
1105 Ioss::CommSet *css = get_region()->get_commset("commset_node");
1106 Ioss::Utils::check_non_null(css, "communication map", "commset_node", __func__);
1107 std::vector<std::pair<int, int>> proc_node;
1108 {
1109 std::vector<int> entity_processor;
1110 css->get_field_data("entity_processor", entity_processor);
1111 proc_node.reserve(entity_processor.size() / 2);
1112 for (size_t i = 0; i < entity_processor.size(); i += 2) {
1113 proc_node.emplace_back(entity_processor[i + 1], entity_processor[i]);
1114 }
1115 }
1116
1117 // Now sort by increasing processor number.
1118 Ioss::sort(proc_node.begin(), proc_node.end());
1119
1120 // Pack the data: global_node_id, bits for each block, ...
1121 // Use 'int' as basic type...
1122 size_t id_size = 1;
1123 size_t word_size = sizeof(int) * 8;
1124 size_t bits_size = (element_blocks.size() + word_size - 1) / word_size;
1125 std::vector<unsigned> send(proc_node.size() * (id_size + bits_size));
1126 std::vector<unsigned> recv(proc_node.size() * (id_size + bits_size));
1127
1128 std::vector<int> procs(util().parallel_size());
1129 size_t offset = 0;
1130 for (const auto &pn : proc_node) {
1131 int64_t glob_id = pn.second;
1132 int proc = pn.first;
1133 procs[proc]++;
1134 send[offset++] = glob_id;
1135 int64_t loc_id = nodeMap.global_to_local(glob_id, true) - 1;
1136 for (int jblk : inv_con[loc_id]) {
1137 size_t wrd_off = jblk / word_size;
1138 size_t bit = jblk % word_size;
1139 send[offset + wrd_off] |= (1 << bit);
1140 }
1141 offset += bits_size;
1142 }
1143
1144 // Count nonzero entries in 'procs' array -- count of
1145 // sends/receives
1146 size_t non_zero = util().parallel_size() - std::count(procs.begin(), procs.end(), 0);
1147
1148 // Post all receives...
1149 MPI_Request request_null = MPI_REQUEST_NULL;
1150 std::vector<MPI_Request> request(non_zero, request_null);
1151 std::vector<MPI_Status> status(non_zero);
1152
1153 int result = MPI_SUCCESS;
1154 size_t req_cnt = 0;
1155 offset = 0;
1156 for (int i = 0; result == MPI_SUCCESS && i < util().parallel_size(); i++) {
1157 if (procs[i] > 0) {
1158 const unsigned size = procs[i] * (id_size + bits_size);
1159 void *const recv_buf = &recv[offset];
1160 result = MPI_Irecv(recv_buf, size, MPI_INT, i, 10101, util().communicator(),
1161 &request[req_cnt]);
1162 req_cnt++;
1163 offset += size;
1164 }
1165 }
1166 assert(result != MPI_SUCCESS || non_zero == req_cnt);
1167
1168 if (result != MPI_SUCCESS) {
1169 IOSS_ERROR(fmt::format("ERROR: MPI_Irecv error on processor {} in {}",
1170 util().parallel_rank(), __func__));
1171 }
1172
1173 int local_error = (MPI_SUCCESS == result) ? 0 : 1;
1174 int global_error = util().global_minmax(local_error, Ioss::ParallelUtils::DO_MAX);
1175
1176 if (global_error != 0) {
1177 IOSS_ERROR(fmt::format("ERROR: MPI_Irecv error on some processor in {}", __func__));
1178 }
1179
1180 result = MPI_SUCCESS;
1181 req_cnt = 0;
1182 offset = 0;
1183 for (int i = 0; result == MPI_SUCCESS && i < util().parallel_size(); i++) {
1184 if (procs[i] > 0) {
1185 const unsigned size = procs[i] * (id_size + bits_size);
1186 void *const send_buf = &send[offset];
1187 result = MPI_Rsend(send_buf, size, MPI_INT, i, 10101, util().communicator());
1188 req_cnt++;
1189 offset += size;
1190 }
1191 }
1192 assert(result != MPI_SUCCESS || non_zero == req_cnt);
1193
1194 if (result != MPI_SUCCESS) {
1195 IOSS_ERROR(fmt::format("ERROR: MPI_Rsend error on processor {} in {}",
1196 util().parallel_rank(), __func__));
1197 }
1198
1199 local_error = (MPI_SUCCESS == result) ? 0 : 1;
1200 global_error = util().global_minmax(local_error, Ioss::ParallelUtils::DO_MAX);
1201
1202 if (global_error != 0) {
1203 IOSS_ERROR(fmt::format("ERROR: MPI_Rsend error on some processor in {}", __func__));
1204 }
1205
1206 result = MPI_Waitall(req_cnt, Data(request), Data(status));
1207
1208 if (result != MPI_SUCCESS) {
1209 IOSS_ERROR(fmt::format("ERROR: MPI_Waitall error on processor {} in {}",
1210 util().parallel_rank(), __func__));
1211 }
1212
1213 // Unpack the data and update the inv_con arrays for boundary
1214 // nodes...
1215 offset = 0;
1216 for (size_t i = 0; i < proc_node.size(); i++) {
1217 int64_t glob_id = recv[offset++];
1218 int64_t loc_id = nodeMap.global_to_local(glob_id, true) - 1;
1219 for (size_t iblk = 0; iblk < element_blocks.size(); iblk++) {
1220 size_t wrd_off = iblk / word_size;
1221 size_t bit = iblk % word_size;
1222 if (recv[offset + wrd_off] & (1 << bit)) {
1223 inv_con[loc_id].push_back(iblk); // May result in duplicates, but that is OK.
1224 }
1225 }
1226 offset += bits_size;
1227 }
1228 }
1229 #endif
1230
1231 // Convert from inv_con arrays to block adjacency...
1232 blockAdjacency.resize(element_blocks.size());
1233 for (auto &block : blockAdjacency) {
1234 block.resize(element_blocks.size());
1235 }
1236
1237 for (int64_t i = 0; i < nodeCount; i++) {
1238 for (size_t j = 0; j < inv_con[i].size(); j++) {
1239 int jblk = inv_con[i][j];
1240 for (size_t k = j + 1; k < inv_con[i].size(); k++) {
1241 int kblk = inv_con[i][k];
1242 blockAdjacency[jblk][kblk] = true;
1243 blockAdjacency[kblk][jblk] = true;
1244 }
1245 }
1246 }
1247
1248 #ifdef SEACAS_HAVE_MPI
1249 if (isParallel) {
1250 // Sync across all processors...
1251 size_t word_size = sizeof(int) * 8;
1252 size_t bits_size = (element_blocks.size() + word_size - 1) / word_size;
1253
1254 std::vector<unsigned> data(element_blocks.size() * bits_size);
1255 int64_t offset = 0;
1256 for (size_t jblk = 0; jblk < element_blocks.size(); jblk++) {
1257 for (size_t iblk = 0; iblk < element_blocks.size(); iblk++) {
1258 if (blockAdjacency[jblk][iblk] == 1) {
1259 size_t wrd_off = iblk / word_size;
1260 size_t bit = iblk % word_size;
1261 data[offset + wrd_off] |= (1 << bit);
1262 }
1263 }
1264 offset += bits_size;
1265 }
1266
1267 std::vector<unsigned> out_data(element_blocks.size() * bits_size);
1268 MPI_Allreduce((void *)Data(data), Data(out_data), static_cast<int>(data.size()), MPI_UNSIGNED,
1269 MPI_BOR, util().communicator());
1270
1271 offset = 0;
1272 for (size_t jblk = 0; jblk < element_blocks.size(); jblk++) {
1273 for (size_t iblk = 0; iblk < element_blocks.size(); iblk++) {
1274 if (blockAdjacency[jblk][iblk] == 0) {
1275 size_t wrd_off = iblk / word_size;
1276 size_t bit = iblk % word_size;
1277 if (out_data[offset + wrd_off] & (1 << bit)) {
1278 blockAdjacency[jblk][iblk] = 1;
1279 }
1280 }
1281 }
1282 offset += bits_size;
1283 }
1284 }
1285 #endif
1286
1287 // Make it symmetric... (TODO: this probably isn't needed...)
1288 for (size_t iblk = 0; iblk < element_blocks.size(); iblk++) {
1289 for (size_t jblk = iblk; jblk < element_blocks.size(); jblk++) {
1290 blockAdjacency[jblk][iblk] = blockAdjacency[iblk][jblk];
1291 }
1292 }
1293 }
1294
1295 AxisAlignedBoundingBox DatabaseIO::get_bounding_box(const Ioss::ElementBlock *eb) const
1296 {
1297 if (elementBlockBoundingBoxes.empty()) {
1298 // Calculate the bounding boxes for all element blocks...
1299 std::vector<double> coordinates;
1300 Ioss::NodeBlock *nb = get_region()->get_node_blocks()[0];
1301 nb->get_field_data("mesh_model_coordinates", coordinates);
1302 auto nnode = nb->entity_count();
1303 auto ndim = nb->get_property("component_degree").get_int();
1304
1305 const Ioss::ElementBlockContainer &element_blocks = get_region()->get_element_blocks();
1306 size_t nblock = element_blocks.size();
1307 std::vector<double> minmax;
1308 minmax.reserve(6 * nblock);
1309
1310 for (const auto &block : element_blocks) {
1311 double xmin, ymin, zmin, xmax, ymax, zmax;
1312 if (block->get_database()->int_byte_size_api() == 8) {
1313 std::vector<int64_t> connectivity;
1314 block->get_field_data("connectivity_raw", connectivity);
1315 calc_bounding_box(ndim, nnode, coordinates, connectivity, xmin, ymin, zmin, xmax, ymax,
1316 zmax);
1317 }
1318 else {
1319 std::vector<int> connectivity;
1320 block->get_field_data("connectivity_raw", connectivity);
1321 calc_bounding_box(ndim, nnode, coordinates, connectivity, xmin, ymin, zmin, xmax, ymax,
1322 zmax);
1323 }
1324
1325 minmax.push_back(xmin);
1326 minmax.push_back(ymin);
1327 minmax.push_back(zmin);
1328 minmax.push_back(-xmax);
1329 minmax.push_back(-ymax);
1330 minmax.push_back(-zmax);
1331 }
1332
1333 util().global_array_minmax(minmax, Ioss::ParallelUtils::DO_MIN);
1334
1335 for (auto [i, block] : enumerate(element_blocks)) {
1336 const std::string &name = block->name();
1337 AxisAlignedBoundingBox bbox(minmax[6 * i + 0], minmax[6 * i + 1], minmax[6 * i + 2],
1338 -minmax[6 * i + 3], -minmax[6 * i + 4], -minmax[6 * i + 5]);
1339 elementBlockBoundingBoxes[name] = bbox;
1340 }
1341 }
1342 return elementBlockBoundingBoxes[eb->name()];
1343 }
1344
1345 AxisAlignedBoundingBox DatabaseIO::get_bounding_box(const Ioss::NodeBlock *nb) const
1346 {
1347 std::vector<double> coordinates;
1348 nb->get_field_data("mesh_model_coordinates", coordinates);
1349 auto nnode = nb->entity_count();
1350 auto ndim = nb->get_property("component_degree").get_int();
1351
1352 double xmin, ymin, zmin, xmax, ymax, zmax;
1353 calc_bounding_box(ndim, nnode, coordinates, xmin, ymin, zmin, xmax, ymax, zmax);
1354
1355 std::vector<double> minmax;
1356 minmax.reserve(6);
1357 minmax.push_back(xmin);
1358 minmax.push_back(ymin);
1359 minmax.push_back(zmin);
1360 minmax.push_back(-xmax);
1361 minmax.push_back(-ymax);
1362 minmax.push_back(-zmax);
1363
1364 util().global_array_minmax(minmax, Ioss::ParallelUtils::DO_MIN);
1365
1366 AxisAlignedBoundingBox bbox(minmax[0], minmax[1], minmax[2], -minmax[3], -minmax[4],
1367 -minmax[5]);
1368 return bbox;
1369 }
1370
1371 AxisAlignedBoundingBox DatabaseIO::get_bounding_box(const Ioss::StructuredBlock *sb) const
1372 {
1373 auto ndim = sb->get_property("component_degree").get_int();
1374
1375 std::pair<double, double> xx;
1376 std::pair<double, double> yy;
1377 std::pair<double, double> zz;
1378
1379 std::vector<double> coordinates;
1380 sb->get_field_data("mesh_model_coordinates_x", coordinates);
1381 auto x = std::minmax_element(coordinates.cbegin(), coordinates.cend());
1382 xx = std::make_pair(*(x.first), *(x.second));
1383
1384 if (ndim > 1) {
1385 sb->get_field_data("mesh_model_coordinates_y", coordinates);
1386 auto y = std::minmax_element(coordinates.cbegin(), coordinates.cend());
1387 yy = std::make_pair(*(y.first), *(y.second));
1388 }
1389
1390 if (ndim > 2) {
1391 sb->get_field_data("mesh_model_coordinates_z", coordinates);
1392 auto z = std::minmax_element(coordinates.cbegin(), coordinates.cend());
1393 zz = std::make_pair(*(z.first), *(z.second));
1394 }
1395
1396 return {xx.first, yy.first, zz.first, xx.second, yy.second, zz.second};
1397 }
1398
1399 #ifndef DOXYGEN_SKIP_THIS
1400 template std::vector<size_t>
1401 DatabaseIO::get_entity_field_data_internal(const std::string &field_name,
1402 const std::vector<Ioss::ElementBlock *> &elem_blocks,
1403 void *data, size_t data_size) const;
1404 #endif
1405
1406 template <typename T>
1407 std::vector<size_t>
1408 DatabaseIO::get_entity_field_data_internal(const std::string &field_name,
1409 const std::vector<T *> &entity_container, void *data,
1410 size_t data_size) const
1411 {
1412 std::vector<size_t> offset = get_entity_offsets(field_name, entity_container);
1413
1414 for (const auto [i, entity] : enumerate(entity_container)) {
1415 if (entity->field_exists(field_name)) {
1416 auto num_to_get_for_block = offset[i + 1] - offset[i];
1417 Ioss::Field field = entity->get_field(field_name);
1418 size_t field_byte_size = field.get_basic_size();
1419 size_t block_data_size = num_to_get_for_block * field_byte_size;
1420
1421 if (block_data_size != field.get_size()) {
1422 IOSS_ERROR(fmt::format(
1423 "ERROR: Field '{}' data size {} on entity {} does not match computed size {}\n\n",
1424 field_name, field.get_size(), entity->name(), block_data_size));
1425 }
1426
1427 size_t expected_data_size = offset[i + 1] * field_byte_size;
1428
1429 if (data_size < expected_data_size) {
1430 IOSS_ERROR(fmt::format(
1431 "ERROR: Field '{}' data size {} on entity {} is less than expected size {}\n\n",
1432 field_name, data_size, entity->name(), expected_data_size));
1433 }
1434
1435 size_t block_data_offset = offset[i] * field_byte_size;
1436
1437 auto retval =
1438 get_field_internal(entity, field, (char *)data + block_data_offset, block_data_size);
1439
1440 size_t block_component_count = field.raw_storage()->component_count();
1441 if (num_to_get_for_block != retval * block_component_count) {
1442 IOSS_ERROR(fmt::format(
1443 "ERROR: Data length {} for field {} on block {} is not expected length {}\n\n",
1444 retval * block_component_count, field_name, entity->name(), num_to_get_for_block));
1445 }
1446
1447 if (retval >= 0) {
1448 field.transform((char *)data + block_data_offset);
1449 }
1450 }
1451 }
1452
1453 return offset;
1454 }
1455
1456 std::vector<size_t>
1457 DatabaseIO::get_entity_field_data(const std::string &field_name,
1458 const std::vector<Ioss::ElementBlock *> &elem_blocks,
1459 void *data, size_t data_size) const
1460 {
1461 return get_entity_field_data_internal(field_name, elem_blocks, data, data_size);
1462 }
1463
1464 int64_t DatabaseIO::get_zc_field_internal(const Ioss::Region *reg, const Ioss::Field &field,
1465 void **, size_t *) const
1466 {
1467 return zero_copy_not_enabled(reg, field, this);
1468 }
1469
1470 int64_t DatabaseIO::get_zc_field_internal(const Ioss::NodeBlock *nb, const Ioss::Field &field,
1471 void **, size_t *) const
1472 {
1473 return zero_copy_not_enabled(nb, field, this);
1474 }
1475
1476 int64_t DatabaseIO::get_zc_field_internal(const Ioss::EdgeBlock *nb, const Ioss::Field &field,
1477 void **, size_t *) const
1478 {
1479 return zero_copy_not_enabled(nb, field, this);
1480 }
1481
1482 int64_t DatabaseIO::get_zc_field_internal(const Ioss::FaceBlock *nb, const Ioss::Field &field,
1483 void **, size_t *) const
1484 {
1485 return zero_copy_not_enabled(nb, field, this);
1486 }
1487
1488 int64_t DatabaseIO::get_zc_field_internal(const Ioss::ElementBlock *eb, const Ioss::Field &field,
1489 void **, size_t *) const
1490 {
1491 return zero_copy_not_enabled(eb, field, this);
1492 }
1493
1494 int64_t DatabaseIO::get_zc_field_internal(const Ioss::SideBlock *fb, const Ioss::Field &field,
1495 void **, size_t *) const
1496 {
1497 return zero_copy_not_enabled(fb, field, this);
1498 }
1499
1500 int64_t DatabaseIO::get_zc_field_internal(const Ioss::NodeSet *ns, const Ioss::Field &field,
1501 void **, size_t *) const
1502 {
1503 return zero_copy_not_enabled(ns, field, this);
1504 }
1505
1506 int64_t DatabaseIO::get_zc_field_internal(const Ioss::EdgeSet *ns, const Ioss::Field &field,
1507 void **, size_t *) const
1508 {
1509 return zero_copy_not_enabled(ns, field, this);
1510 }
1511
1512 int64_t DatabaseIO::get_zc_field_internal(const Ioss::FaceSet *ns, const Ioss::Field &field,
1513 void **, size_t *) const
1514 {
1515 return zero_copy_not_enabled(ns, field, this);
1516 }
1517
1518 int64_t DatabaseIO::get_zc_field_internal(const Ioss::ElementSet *ns, const Ioss::Field &field,
1519 void **, size_t *) const
1520 {
1521 return zero_copy_not_enabled(ns, field, this);
1522 }
1523
1524 int64_t DatabaseIO::get_zc_field_internal(const Ioss::SideSet *fs, const Ioss::Field &field,
1525 void **, size_t *) const
1526 {
1527 return zero_copy_not_enabled(fs, field, this);
1528 }
1529
1530 int64_t DatabaseIO::get_zc_field_internal(const Ioss::CommSet *cs, const Ioss::Field &field,
1531 void **, size_t *) const
1532 {
1533 return zero_copy_not_enabled(cs, field, this);
1534 }
1535
1536 int64_t DatabaseIO::get_zc_field_internal(const Ioss::Assembly *as, const Ioss::Field &field,
1537 void **, size_t *) const
1538 {
1539 return zero_copy_not_enabled(as, field, this);
1540 }
1541
1542 int64_t DatabaseIO::get_zc_field_internal(const Ioss::Blob *bl, const Ioss::Field &field, void **,
1543 size_t *) const
1544 {
1545 return zero_copy_not_enabled(bl, field, this);
1546 }
1547
1548 int64_t DatabaseIO::get_zc_field_internal(const Ioss::StructuredBlock *sb,
1549 const Ioss::Field &field, void **, size_t *) const
1550 {
1551 return zero_copy_not_enabled(sb, field, this);
1552 }
1553
1554 void DatabaseIO::release_memory_nl()
1555 {
1556 nodeMap.release_memory();
1557 edgeMap.release_memory();
1558 faceMap.release_memory();
1559 elemMap.release_memory();
1560 }
1561
1562 void DatabaseIO::reset_database_nl()
1563 {
1564 release_memory_nl();
1565 dbState = STATE_INVALID;
1566 nodeCount = 0;
1567 elementCount = 0;
1568 sideTopology.clear();
1569 blockAdjacency.clear();
1570 blockAdjacenciesCalculated = false;
1571 elementBlockBoundingBoxes.clear();
1572 }
1573 } // namespace Ioss
1574
1575 namespace {
1576 void log_time(std::chrono::time_point<std::chrono::steady_clock> &start,
1577 std::chrono::time_point<std::chrono::steady_clock> &finish, int current_state,
1578 double state_time, bool is_input, bool single_proc_only,
1579 const Ioss::ParallelUtils &util)
1580 {
1581 std::vector<double> all_times;
1582 double duration = std::chrono::duration<double, std::milli>(finish - start).count();
1583 if (single_proc_only) {
1584 all_times.push_back(duration);
1585 }
1586 else {
1587 util.gather(duration, all_times);
1588 }
1589
1590 if (util.parallel_rank() == 0 || single_proc_only) {
1591 std::ostringstream strm;
1592 fmt::print(strm, "\nIOSS: Time to {} state {}, time {} is ", (is_input ? "read " : "write"),
1593 current_state, state_time);
1594
1595 double total = 0.0;
1596 for (const auto &p_time : all_times) {
1597 total += p_time;
1598 }
1599
1600 // Now append each processors time onto the stream...
1601 if (util.parallel_size() == 1) {
1602 fmt::print(strm, "{} (ms)\n", total);
1603 }
1604 else if (util.parallel_size() > 4) {
1605 Ioss::sort(all_times.begin(), all_times.end());
1606 fmt::print(strm, " Min: {}\tMax: {}\tMed: {}", all_times.front(), all_times.back(),
1607 all_times[all_times.size() / 2]);
1608 }
1609 else {
1610 char sep = (util.parallel_size() > 1) ? ':' : ' ';
1611 for (auto &p_time : all_times) {
1612 fmt::print(strm, "{:8}{}", p_time, sep);
1613 }
1614 }
1615 if (util.parallel_size() > 1) {
1616 fmt::print(strm, "\tTot: {} (ms)\n", total);
1617 }
1618 fmt::print(Ioss::DebugOut(), "{}", strm.str());
1619 }
1620 }
1621
1622 void log_field(const char *symbol, const Ioss::GroupingEntity *entity, const Ioss::Field &field,
1623 bool single_proc_only, const Ioss::ParallelUtils &util)
1624 {
1625 if (entity != nullptr) {
1626 std::vector<int64_t> all_sizes;
1627 if (single_proc_only) {
1628 all_sizes.push_back(field.get_size());
1629 }
1630 else {
1631 util.gather(static_cast<int64_t>(field.get_size()), all_sizes);
1632 }
1633
1634 if (util.parallel_rank() == 0 || single_proc_only) {
1635 const std::string &name = entity->name();
1636 std::ostringstream strm;
1637 auto now = std::chrono::steady_clock::now();
1638 std::chrono::duration<double> diff = now - initial_time;
1639 fmt::print(strm, "{} [{:.5f}]\t", symbol, diff.count());
1640
1641 int64_t total = 0;
1642 for (const auto &p_size : all_sizes) {
1643 total += p_size;
1644 }
1645 // Now append each processors size onto the stream...
1646 if (util.parallel_size() > 4) {
1647 auto min_max = std::minmax_element(all_sizes.cbegin(), all_sizes.cend());
1648 fmt::print(strm, " m: {:8d} M: {:8d} A: {:8d}", *min_max.first, *min_max.second,
1649 total / all_sizes.size());
1650 }
1651 else {
1652 for (const auto &p_size : all_sizes) {
1653 fmt::print(strm, "{:8d}:", p_size);
1654 }
1655 }
1656 if (util.parallel_size() > 1) {
1657 fmt::print(strm, " T:{:8d}", total);
1658 }
1659 fmt::print(strm, "\t{}/{}\n", name, field.get_name());
1660 fmt::print(Ioss::DebugOut(), "{}", strm.str());
1661 }
1662 }
1663 else {
1664 if (!single_proc_only) {
1665 util.barrier();
1666 }
1667 if (util.parallel_rank() == 0 || single_proc_only) {
1668 auto time_now = std::chrono::steady_clock::now();
1669 std::chrono::duration<double> diff = time_now - initial_time;
1670 fmt::print(Ioss::DebugOut(), "{} [{:.5f}]\n", symbol, diff.count());
1671 }
1672 }
1673 }
1674 } // namespace