Debian Codegraph @

packages/seacas/libraries/ioss/src/exodus/Ioex_Utils.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_ElementTopology.h"
8 #include "Ioss_Region.h"
9 #include "Ioss_SmartAssert.h"
10 #include "Ioss_Utils.h"
11 #include "Ioss_VariableType.h"
12 #include "exodus/Ioex_Utils.h"
13 #include <cstring>
14 #include <fmt/core.h>
15 #include <fmt/format.h>
16 #include <fmt/ostream.h>
17 #include <iosfwd>
18 #include <netcdf.h>
19 #include <strings.h>
20 #include <tokenize.h>
21
22 #include "Ioss_BasisVariableType.h"
23 #include "Ioss_CoordinateFrame.h"
24 #include "Ioss_DatabaseIO.h"
25 #include "Ioss_ElementBlock.h"
26 #include "Ioss_Field.h"
27 #include "Ioss_GroupingEntity.h"
28 #include "Ioss_NamedSuffixVariableType.h"
29 #include "Ioss_ParallelUtils.h"
30 #include "Ioss_Property.h"
31 #include "Ioss_QuadratureVariableType.h"
32 #include "exodusII.h"
33 #include "exodusII_int.h"
34
35 namespace {
36 size_t match(const std::string &name1, const std::string &name2)
37 {
38 size_t l1 = name1.size();
39 size_t l2 = name2.size();
40 size_t len = std::min(l1, l2);
41 for (size_t i = 0; i < len; i++) {
42 if (name1[i] != name2[i]) {
43 while (i > 0 && (isdigit(name1[i - 1]) != 0) && (isdigit(name2[i - 1]) != 0)) {
44 i--;
45 // Back up to first non-digit so to handle "evar0000, evar0001, ..., evar 1123"
46 }
47 return i;
48 }
49 }
50 return len;
51 }
52
53 template <typename INT>
54 void internal_write_coordinate_frames(int exoid, const Ioss::CoordinateFrameContainer &frames,
55 INT /*dummy*/)
56 {
57 // Query number of coordinate frames...
58 int nframes = static_cast<int>(frames.size());
59 if (nframes > 0) {
60 std::vector<char> tags(nframes);
61 std::vector<double> coordinates(nframes * 9);
62 std::vector<INT> ids(nframes);
63
64 for (size_t i = 0; i < frames.size(); i++) {
65 ids[i] = frames[i].id();
66 tags[i] = frames[i].tag();
67 const double *coord = frames[i].coordinates();
68 for (size_t j = 0; j < 9; j++) {
69 coordinates[9 * i + j] = coord[j];
70 }
71 }
72 int ierr = ex_put_coordinate_frames(exoid, nframes, Data(ids), Data(coordinates), Data(tags));
73 if (ierr < 0) {
74 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
75 }
76 }
77 }
78
79 template <typename INT>
80 void internal_add_coordinate_frames(int exoid, Ioss::Region *region, INT /*dummy*/)
81 {
82 // Query number of coordinate frames...
83 int nframes = 0;
84 int ierr = ex_get_coordinate_frames(exoid, &nframes, nullptr, nullptr, nullptr);
85 if (ierr < 0) {
86 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
87 }
88
89 if (nframes > 0) {
90 std::vector<char> tags(nframes);
91 std::vector<double> coord(nframes * 9);
92 std::vector<INT> ids(nframes);
93 ierr = ex_get_coordinate_frames(exoid, &nframes, Data(ids), Data(coord), Data(tags));
94 if (ierr < 0) {
95 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
96 }
97
98 for (int i = 0; i < nframes; i++) {
99 Ioss::CoordinateFrame cf(ids[i], tags[i], &coord[9 * i]);
100 region->add(cf);
101 }
102 }
103 }
104 } // namespace
105
106 namespace Ioex {
107 void update_last_time_attribute(int exodusFilePtr, double value)
108 {
109 double tmp = 0.0;
110 int rootid = static_cast<unsigned>(exodusFilePtr) & EX_FILE_ID_MASK;
111 int status = nc_get_att_double(rootid, NC_GLOBAL, "last_written_time", &tmp);
112
113 if (status == NC_NOERR && value > tmp) {
114 status = nc_put_att_double(rootid, NC_GLOBAL, "last_written_time", NC_DOUBLE, 1, &value);
115 if (status != NC_NOERR) {
116 ex_opts(EX_VERBOSE);
117 auto errmsg = fmt::format(
118 "Error: failed to define 'last_written_time' attribute to file id {}", exodusFilePtr);
119 ex_err_fn(exodusFilePtr, __func__, errmsg.c_str(), status);
120 }
121 }
122 }
123
124 std::string map_ioss_field_type(ex_field_type type)
125 {
126 if (type == EX_VECTOR_2D)
127 return "vector_2d";
128 if (type == EX_VECTOR_3D)
129 return "vector_3d";
130 if (type == EX_SCALAR)
131 return "scalar";
132 if (type == EX_VECTOR_1D)
133 return "vector_1d";
134 if (type == EX_QUATERNION_2D)
135 return "quaternion_2d";
136 if (type == EX_QUATERNION_3D)
137 return "quaternion_3d";
138 if (type == EX_FULL_TENSOR_36)
139 return "full_tensor_36";
140 if (type == EX_FULL_TENSOR_32)
141 return "full_tensor_32";
142 if (type == EX_FULL_TENSOR_22)
143 return "full_tensor_22";
144 if (type == EX_FULL_TENSOR_16)
145 return "full_tensor_16";
146 if (type == EX_FULL_TENSOR_12)
147 return "full_tensor_12";
148 if (type == EX_SYM_TENSOR_33)
149 return "sym_tensor_33";
150 if (type == EX_SYM_TENSOR_31)
151 return "sym_tensor_31";
152 if (type == EX_SYM_TENSOR_21)
153 return "sym_tensor_21";
154 if (type == EX_SYM_TENSOR_13)
155 return "sym_tensor_13";
156 if (type == EX_SYM_TENSOR_11)
157 return "sym_tensor_11";
158 if (type == EX_SYM_TENSOR_10)
159 return "sym_tensor_10";
160 if (type == EX_ASYM_TENSOR_03)
161 return "asym_tensor_03";
162 if (type == EX_ASYM_TENSOR_02)
163 return "asym_tensor_02";
164 if (type == EX_ASYM_TENSOR_01)
165 return "asym_tensor_01";
166 if (type == EX_MATRIX_2X2)
167 return "matrix_22";
168 if (type == EX_MATRIX_3X3)
169 return "matrix_33";
170 if (type == EX_FIELD_TYPE_SEQUENCE)
171 return "Real";
172 if (type == EX_BASIS)
173 return "Basis";
174 if (type == EX_QUADRATURE)
175 return "Quadrature";
176 return "invalid";
177 }
178
179 ex_field_type map_ioss_field_type(const Ioss::VariableType *type)
180 {
181 if (type->name() == "vector_2d")
182 return EX_VECTOR_2D;
183 if (type->name() == "vector_3d")
184 return EX_VECTOR_3D;
185 if (type->name() == "scalar")
186 return EX_SCALAR;
187 if (type->name() == "vector_1d")
188 return EX_VECTOR_1D;
189 if (type->name() == "quaternion_2d")
190 return EX_QUATERNION_2D;
191 if (type->name() == "quaternion_3d")
192 return EX_QUATERNION_3D;
193 if (type->name() == "full_tensor_36")
194 return EX_FULL_TENSOR_36;
195 if (type->name() == "full_tensor_32")
196 return EX_FULL_TENSOR_32;
197 if (type->name() == "full_tensor_22")
198 return EX_FULL_TENSOR_22;
199 if (type->name() == "full_tensor_16")
200 return EX_FULL_TENSOR_16;
201 if (type->name() == "full_tensor_12")
202 return EX_FULL_TENSOR_12;
203 if (type->name() == "sym_tensor_33")
204 return EX_SYM_TENSOR_33;
205 if (type->name() == "sym_tensor_31")
206 return EX_SYM_TENSOR_31;
207 if (type->name() == "sym_tensor_21")
208 return EX_SYM_TENSOR_21;
209 if (type->name() == "sym_tensor_13")
210 return EX_SYM_TENSOR_13;
211 if (type->name() == "sym_tensor_11")
212 return EX_SYM_TENSOR_11;
213 if (type->name() == "sym_tensor_10")
214 return EX_SYM_TENSOR_10;
215 if (type->name() == "asym_tensor_03")
216 return EX_ASYM_TENSOR_03;
217 if (type->name() == "asym_tensor_02")
218 return EX_ASYM_TENSOR_02;
219 if (type->name() == "asym_tensor_01")
220 return EX_ASYM_TENSOR_01;
221 if (type->name() == "matrix_22")
222 return EX_MATRIX_2X2;
223 if (type->name() == "matrix_33")
224 return EX_MATRIX_3X3;
225
226 if (Ioss::Utils::substr_equal("Real", type->name()))
227 return EX_FIELD_TYPE_SEQUENCE;
228
229 // This may be a basis, quadratur, or user type...
230 auto nsvt = dynamic_cast<const Ioss::NamedSuffixVariableType *>(type);
231 if (nsvt != nullptr) {
232 return EX_FIELD_TYPE_USER_DEFINED;
233 }
234 auto bvt = dynamic_cast<const Ioss::BasisVariableType *>(type);
235 if (bvt != nullptr) {
236 return EX_BASIS;
237 }
238 auto qvt = dynamic_cast<const Ioss::QuadratureVariableType *>(type);
239 if (qvt != nullptr) {
240 return EX_QUADRATURE;
241 }
242
243 return EX_FIELD_TYPE_INVALID;
244 }
245
246 Ioss::EntityType map_exodus_type(ex_entity_type type)
247 {
248 switch (type) {
249 case EX_ASSEMBLY: return Ioss::ASSEMBLY;
250 case EX_BLOB: return Ioss::BLOB;
251 case EX_EDGE_BLOCK: return Ioss::EDGEBLOCK;
252 case EX_EDGE_SET: return Ioss::EDGESET;
253 case EX_ELEM_BLOCK: return Ioss::ELEMENTBLOCK;
254 case EX_ELEM_SET: return Ioss::ELEMENTSET;
255 case EX_FACE_BLOCK: return Ioss::FACEBLOCK;
256 case EX_FACE_SET: return Ioss::FACESET;
257 case EX_NODAL: return Ioss::NODEBLOCK;
258 case EX_NODE_SET: return Ioss::NODESET;
259 case EX_SIDE_SET: return Ioss::SIDESET;
260 case EX_GLOBAL: return Ioss::REGION;
261 default: return Ioss::INVALID_TYPE;
262 }
263 }
264
265 int read_exodus_basis(int exoid)
266 {
267 auto bas_cnt = ex_get_basis_count(exoid);
268 if (bas_cnt == 0) {
269 return 0;
270 }
271 std::vector<ex_basis> exo_basis(bas_cnt);
272 auto *pbasis = Data(exo_basis);
273 ex_get_basis(exoid, &pbasis, &bas_cnt);
274
275 for (const auto &ebasis : exo_basis) {
276 Ioss::Basis basis;
277 for (int i = 0; i < ebasis.cardinality; i++) {
278 Ioss::BasisComponent bc{
279 ebasis.subc_dim[i], ebasis.subc_ordinal[i], ebasis.subc_dof_ordinal[i],
280 ebasis.subc_num_dof[i], ebasis.xi[i], ebasis.eta[i],
281 ebasis.zeta[i]};
282 basis.basies.push_back(bc);
283 }
284 Ioss::VariableType::create_basis_type(ebasis.name, basis);
285 }
286
287 // deallocate any memory allocated in the 'ex_basis' structs.
288 ex_initialize_basis_struct(Data(exo_basis), exo_basis.size(), -1);
289
290 return bas_cnt;
291 }
292
293 int read_exodus_quadrature(int exoid)
294 {
295 auto quad_cnt = ex_get_quadrature_count(exoid);
296 if (quad_cnt == 0) {
297 return quad_cnt;
298 }
299
300 std::vector<ex_quadrature> exo_quadrature(quad_cnt);
301 auto *pquad = Data(exo_quadrature);
302 ex_get_quadrature(exoid, &pquad, &quad_cnt);
303
304 for (const auto &equadrature : exo_quadrature) {
305 std::vector<Ioss::QuadraturePoint> quadrature;
306 quadrature.reserve(equadrature.cardinality);
307 for (int i = 0; i < equadrature.cardinality; i++) {
308 Ioss::QuadraturePoint q{equadrature.xi[i], equadrature.eta[i], equadrature.zeta[i],
309 equadrature.weight[i]};
310 quadrature.push_back(q);
311 }
312 Ioss::VariableType::create_quadrature_type(equadrature.name, quadrature);
313 }
314
315 // deallocate any memory allocated in the 'ex_quadrature' structs.
316 ex_initialize_quadrature_struct(Data(exo_quadrature), exo_quadrature.size(), -1);
317
318 return quad_cnt;
319 }
320
321 ex_entity_type map_exodus_type(Ioss::EntityType type)
322 {
323 switch (type) {
324 case Ioss::REGION: return EX_GLOBAL;
325 case Ioss::ASSEMBLY: return EX_ASSEMBLY;
326 case Ioss::BLOB: return EX_BLOB;
327 case Ioss::EDGEBLOCK: return EX_EDGE_BLOCK;
328 case Ioss::EDGESET: return EX_EDGE_SET;
329 case Ioss::ELEMENTBLOCK: return EX_ELEM_BLOCK;
330 case Ioss::ELEMENTSET: return EX_ELEM_SET;
331 case Ioss::FACEBLOCK: return EX_FACE_BLOCK;
332 case Ioss::FACESET: return EX_FACE_SET;
333 case Ioss::NODEBLOCK: return EX_NODAL;
334 case Ioss::NODESET: return EX_NODE_SET;
335 case Ioss::SIDESET: return EX_SIDE_SET;
336 case Ioss::SIDEBLOCK: return EX_SIDE_SET;
337 case Ioss::COMMSET: return static_cast<ex_entity_type>(0);
338 default: return EX_INVALID;
339 }
340 }
341
342 char **get_name_array(size_t count, int size)
343 {
344 auto *names = new char *[count];
345 for (size_t i = 0; i < count; i++) {
346 names[i] = new char[size + 1];
347 std::memset(names[i], '\0', size + 1);
348 }
349 return names;
350 }
351
352 void delete_name_array(char **names, int count)
353 {
354 for (int i = 0; i < count; i++) {
355 delete[] names[i];
356 }
357 delete[] names;
358 }
359
360 Ioss::NameList get_variable_names(int nvar, int maximumNameLength, int exoid, ex_entity_type type)
361 {
362 char **names = get_name_array(nvar, maximumNameLength);
363 int ierr = ex_get_variable_names(exoid, type, nvar, names);
364 if (ierr < 0) {
365 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
366 }
367
368 Ioss::NameList name_str;
369 name_str.reserve(nvar);
370 for (int i = 0; i < nvar; i++) {
371 name_str.emplace_back(names[i]);
372 }
373 delete_name_array(names, nvar);
374 return name_str;
375 }
376
377 Ioss::NameList get_reduction_variable_names(int nvar, int maximumNameLength, int exoid,
378 ex_entity_type type)
379 {
380 char **names = get_name_array(nvar, maximumNameLength);
381 int ierr = ex_get_reduction_variable_names(exoid, type, nvar, names);
382 if (ierr < 0) {
383 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
384 }
385
386 Ioss::NameList name_str;
387 name_str.reserve(nvar);
388 for (int i = 0; i < nvar; i++) {
389 name_str.emplace_back(names[i]);
390 }
391 delete_name_array(names, nvar);
392 return name_str;
393 }
394
395 bool read_last_time_attribute(int exodusFilePtr, double *value)
396 {
397 // Check whether the "last_written_time" attribute exists. If it does,
398 // return the value of the attribute in 'value' and return 'true'.
399 // If not, don't change 'value' and return 'false'.
400 bool found = false;
401
402 int rootid = static_cast<unsigned>(exodusFilePtr) & EX_FILE_ID_MASK;
403 nc_type att_type = NC_NAT;
404 size_t att_len = 0;
405 int status = nc_inq_att(rootid, NC_GLOBAL, "last_written_time", &att_type, &att_len);
406 if (status == NC_NOERR && att_type == NC_DOUBLE) {
407 // Attribute exists on this database, read it...
408 double tmp = 0.0;
409 status = nc_get_att_double(rootid, NC_GLOBAL, "last_written_time", &tmp);
410 if (status == NC_NOERR) {
411 *value = tmp;
412 found = true;
413 }
414 else {
415 ex_opts(EX_VERBOSE);
416 auto errmsg = fmt::format(
417 "Error: failed to read last_written_time attribute from file id {}", exodusFilePtr);
418 ex_err_fn(exodusFilePtr, __func__, errmsg.c_str(), status);
419 found = false;
420 }
421 }
422 return found;
423 }
424
425 bool check_processor_info(const std::string &filename, int exodusFilePtr, int processor_count,
426 int processor_id)
427 {
428 // A restart file may contain an attribute which contains
429 // information about the processor count and current processor id
430 // when the file was written. This code checks whether that
431 // information matches the current processor count and id. If it
432 // exists, but doesn't match, a warning message is printed.
433 // Eventually, this will be used to determine whether certain
434 // decomposition-related data in the file is valid or has been
435 // invalidated by a join/re-spread to a different number of
436 // processors.
437 bool matches = true;
438
439 nc_type att_type = NC_NAT;
440 size_t att_len = 0;
441 int status = nc_inq_att(exodusFilePtr, NC_GLOBAL, "processor_info", &att_type, &att_len);
442 if (status == NC_NOERR && att_type == NC_INT) {
443 // Attribute exists on this database, read it and check that the information
444 // matches the current processor count and processor id.
445 int proc_info[2];
446 status = nc_get_att_int(exodusFilePtr, NC_GLOBAL, "processor_info", proc_info);
447 if (status == NC_NOERR) {
448 if (proc_info[0] != processor_count && proc_info[0] > 1) {
449 fmt::print(Ioss::WarnOut(),
450 "Processor decomposition count in file ({}) does not match current "
451 "processor count ({}) in file named '{}'.\n",
452 proc_info[0], processor_count, filename);
453 matches = false;
454 }
455 if (proc_info[1] != processor_id) {
456 fmt::print(
457 Ioss::WarnOut(),
458 "The file '{}' was originally written on processor {}, but is now being read on "
459 "processor {}.\n"
460 "This may cause problems if there is any processor-dependent data on the file.\n",
461 filename, proc_info[1], processor_id);
462 matches = false;
463 }
464 }
465 else {
466 ex_opts(EX_VERBOSE);
467 auto errmsg =
468 fmt::format("Error: failed to read processor info attribute from file {}", filename);
469 ex_err_fn(exodusFilePtr, __func__, errmsg.c_str(), status);
470 return (EX_FATAL) != 0;
471 }
472 }
473 return matches;
474 }
475
476 bool type_match(const std::string &type, const char *substring)
477 {
478 // Returns true if 'substring' is a sub-string of 'type'.
479 // The comparisons are case-insensitive
480 // 'substring' is required to be in all lowercase.
481 const char *s = substring;
482 const char *t = type.c_str();
483
484 SMART_ASSERT(s != nullptr);
485 while (*s != '\0' && *t != '\0') {
486 if (*s++ != tolower(*t++)) {
487 return false;
488 }
489 }
490 return true;
491 }
492
493 void decode_surface_name(Ioex::SideSetMap &fs_map, Ioex::SideSetSet &fs_set,
494 const std::string &name)
495 {
496 auto tokens = Ioss::tokenize(name, "_");
497 if (tokens.size() >= 4) {
498 // Name of form: "name_eltopo_sidetopo_id" or
499 // "name_block_id_sidetopo_id" "name" is typically "surface".
500 // The sideset containing this should then be called "name_id"
501
502 // Check whether the second-last token is a side topology and
503 // the third-last token is an element topology.
504 const Ioss::ElementTopology *side_topo =
505 Ioss::ElementTopology::factory(tokens[tokens.size() - 2], true);
506 if (side_topo != nullptr) {
507 const Ioss::ElementTopology *element_topo =
508 Ioss::ElementTopology::factory(tokens[tokens.size() - 3], true);
509 if (element_topo != nullptr || tokens[tokens.size() - 4] == "block") {
510 // The remainder of the tokens will be used to create
511 // a side set name and then this sideset will be
512 // a side block in that set.
513 std::string fs_name;
514 size_t last_token = tokens.size() - 3;
515 if (element_topo == nullptr) {
516 last_token--;
517 }
518 for (size_t tok = 0; tok < last_token; tok++) {
519 fs_name += tokens[tok];
520 }
521 fs_name += "_";
522 fs_name += tokens[tokens.size() - 1]; // Add on the id.
523
524 fs_set.insert(fs_name);
525 fs_map.insert(Ioex::SideSetMap::value_type(name, fs_name));
526 }
527 }
528 }
529 }
530
531 bool set_id(const Ioss::GroupingEntity *entity, Ioex::EntityIdSet *idset)
532 {
533 // See description of 'get_id' function. This function just primes
534 // the idset with existing ids so that when we start generating ids,
535 // we don't overwrite an existing one.
536
537 // Avoid a few string constructors/destructors
538 static std::string id_prop("id");
539
540 bool succeed = false;
541 if (entity->property_exists(id_prop)) {
542 int64_t id = entity->get_property(id_prop).get_int();
543
544 // See whether it already exists...
545 auto type = map_exodus_type(entity->type());
546 succeed = idset->insert(std::make_pair(static_cast<int>(type), id)).second;
547 if (!succeed) {
548 // Need to remove the property so it doesn't cause problems
549 // later...
550 auto *new_entity = const_cast<Ioss::GroupingEntity *>(entity);
551 new_entity->property_erase(id_prop);
552 SMART_ASSERT(!entity->property_exists(id_prop))(id_prop);
553 }
554 }
555 return succeed;
556 }
557
558 // Potentially extract the id from a name possibly of the form name_id.
559 // If not of this form, return 0;
560 int64_t extract_id(const std::string &name_id)
561 {
562 auto tokens = Ioss::tokenize(name_id, "_");
563
564 if (tokens.size() == 1) {
565 return 0;
566 }
567
568 // Check whether last token is an integer...
569 std::string str_id = tokens.back();
570 std::size_t found = str_id.find_first_not_of("0123456789");
571 if (found == std::string::npos) {
572 // All digits...
573 return std::stoll(str_id);
574 }
575
576 return 0;
577 }
578
579 int64_t get_id(const Ioss::GroupingEntity *entity, Ioex::EntityIdSet *idset)
580 {
581 // Sierra uses names to refer to grouping entities; however,
582 // exodusII requires integer ids. When reading an exodusII file,
583 // the DatabaseIO creates a name by concatenating the entity
584 // type (e.g., 'block') and the id separated by an underscore. For
585 // example, an exodusII element block with an id of 100 would be
586 // encoded into "block_100"
587
588 // This routine tries to determine the id of the entity using 3
589 // approaches:
590 //
591 // 1. If the entity contains a property named 'id', this is used.
592 // The DatabaseIO actually stores the id in the "id" property;
593 // however, other grouping entity creators are not required to do
594 // this so the property is not guaranteed to exist.
595 //
596 // 2.If property does not exist, it tries to decode the entity name
597 // based on the above encoding. Again, it is not required that the
598 // name follow this convention so success is not guaranteed.
599 //
600 // 3. If all other schemes fail, the routine picks an id for the entity
601 // and returns it. It also stores this id in the "id" property so an
602 // entity will always return the same id for multiple calls.
603 // Note that this violates the 'const'ness of the entity so we use
604 // a const-cast.
605
606 // Avoid a few string constructors/destructors
607 static std::string prop_name("name");
608 static std::string id_prop("id");
609
610 int64_t id = 1;
611
612 if (entity->property_exists(id_prop)) {
613 id = entity->get_property(id_prop).get_int();
614 return id;
615 }
616
617 // Try to decode an id from the name.
618 std::string name_string = entity->get_property(prop_name).get_string();
619 std::string type_name = entity->short_type_string();
620 if (strncasecmp(type_name.c_str(), name_string.c_str(), type_name.size()) == 0) {
621 id = extract_id(name_string);
622 if (id <= 0) {
623 id = 1;
624 }
625 }
626
627 // At this point, we either have an id equal to '1' or we have an id
628 // extracted from the entities name. Increment it until it is
629 // unique...
630 ex_entity_type type = map_exodus_type(entity->type());
631 while (idset->find(std::make_pair(int(type), id)) != idset->end()) {
632 ++id;
633 }
634
635 // 'id' is a unique id for this entity type...
636 idset->insert(std::make_pair(static_cast<int>(type), id));
637 auto *new_entity = const_cast<Ioss::GroupingEntity *>(entity);
638 new_entity->property_add(Ioss::Property(id_prop, id));
639 new_entity->property_update("guid", entity->get_database()->util().generate_guid(id));
640 return id;
641 }
642
643 bool find_displacement_field(Ioss::NameList &fields, const Ioss::GroupingEntity *block, int ndim,
644 std::string *disp_name)
645 {
646 // This is a kluge to work with many of the SEACAS codes. The
647 // convention used (in Blot and others) is that the first 'ndim'
648 // nodal variables are assumed to be displacements *if* the first
649 // character of the names is 'D' and the last characters match the
650 // coordinate labels (typically 'X', 'Y', and 'Z'). This routine
651 // looks for the field that has the longest match with the string
652 // "displacement" and is of the correct storage type (VECTOR_2D or
653 // VECTOR_3D). If found, it returns the name.
654 //
655
656 static const std::string displace = "displacement";
657
658 size_t max_span = 0;
659 for (const auto &name : fields) {
660 std::string lc_name(name);
661
662 Ioss::Utils::fixup_name(lc_name);
663 size_t span = match(lc_name, displace);
664 if (span > max_span) {
665 const Ioss::VariableType *var_type = block->get_field(name).transformed_storage();
666 int comp_count = var_type->component_count();
667 if (comp_count == ndim) {
668 max_span = span;
669 *disp_name = name;
670 }
671 }
672 }
673 return max_span > 0;
674 }
675
676 void fix_bad_name(char *name)
677 {
678 SMART_ASSERT(name != nullptr);
679
680 size_t len = std::strlen(name);
681 for (size_t i = 0; i < len; i++) {
682 if (name[i] < 32 || name[i] > 126) {
683 // Zero out entire name if a bad character found anywhere in the name.
684 for (size_t j = 0; j < len; j++) {
685 name[j] = '\0';
686 }
687 return;
688 }
689 }
690 }
691
692 std::string get_entity_name(int exoid, ex_entity_type type, int64_t id,
693 const std::string &basename, int length, bool &db_has_name)
694 {
695 std::vector<char> buffer(length + 1);
696 buffer[0] = '\0';
697 int error = ex_get_name(exoid, type, id, Data(buffer));
698 if (error < 0) {
699 exodus_error(exoid, __LINE__, __func__, __FILE__);
700 }
701 if (buffer[0] != '\0') {
702 Ioss::Utils::fixup_name(Data(buffer));
703 // Filter out names of the form "basename_id" if the name
704 // id doesn't match the id in the name...
705 size_t base_size = basename.size();
706 if (std::strncmp(basename.c_str(), Data(buffer), base_size) == 0) {
707 int64_t name_id = extract_id(Data(buffer));
708
709 // See if name is truly of form "basename_name_id" (e.g. "surface_{id}")
710 std::string tmp_name = Ioss::Utils::encode_entity_name(basename, name_id);
711 if (tmp_name == Data(buffer)) {
712 if (name_id > 0) {
713 db_has_name = false;
714 if (name_id != id) {
715 std::string new_name = Ioss::Utils::encode_entity_name(basename, id);
716 fmt::print(Ioss::WarnOut(),
717 "The entity named '{}' has the id {} which does not match the "
718 "embedded id {}.\n"
719 " This can cause issues later; the entity will be renamed to '{}' "
720 "(IOSS)\n\n",
721 Data(buffer), id, name_id, new_name);
722 return new_name;
723 }
724 return tmp_name;
725 }
726 }
727 }
728 db_has_name = true;
729 return {Data(buffer)};
730 }
731 db_has_name = false;
732 return Ioss::Utils::encode_entity_name(basename, id);
733 }
734
735 void exodus_error(int exoid, int lineno, const char *function, const char *filename)
736 {
737 std::string empty{};
738 exodus_error(exoid, lineno, function, filename, empty);
739 }
740
741 void exodus_error(int exoid, int lineno, const char *function, const char *filename,
742 const std::string &extra)
743 {
744 std::ostringstream errmsg;
745 // Create errmsg here so that the exerrval doesn't get cleared by
746 // the ex_close call.
747 int status;
748 ex_get_err(nullptr, nullptr, &status);
749 fmt::print(errmsg, "Exodus error ({}) {} at line {} of file '{}' in function '{}'.", status,
750 ex_strerror(status), lineno, filename, function);
751
752 if (!extra.empty()) {
753 fmt::print(errmsg, " {}", extra);
754 }
755 fmt::print(errmsg, " Please report to [email protected] if you need help.");
756
757 ex_err_fn(exoid, nullptr, nullptr, EX_PRTLASTMSG);
758 IOSS_ERROR(errmsg);
759 }
760
761 int add_map_fields(int exoid, Ioss::ElementBlock *block, int64_t my_element_count,
762 size_t name_length)
763 {
764 // Check for optional element maps...
765 int map_count = ex_inquire_int(exoid, EX_INQ_ELEM_MAP);
766 if (map_count <= 0) {
767 return map_count;
768 }
769
770 // Get the names of the maps...
771 char **names = get_name_array(map_count, name_length);
772 int ierr = ex_get_names(exoid, EX_ELEM_MAP, names);
773 if (ierr < 0) {
774 Ioex::exodus_error(exoid, __LINE__, __func__, __FILE__);
775 }
776
777 // Convert to lowercase.
778 for (int i = 0; i < map_count; i++) {
779 Ioss::Utils::fixup_name(names[i]);
780 }
781
782 for (int i = 0; i < map_count; i++) {
783 // If the name does *not* contain a `:`, then assume that this is a scalar map and add to the
784 // block.
785 std::string name{names[i]};
786 if (name.find(':') == std::string::npos) {
787 auto field = Ioss::Field(name, block->field_int_type(), IOSS_SCALAR(), Ioss::Field::MAP,
788 my_element_count)
789 .set_index(i + 1);
790 block->field_add(std::move(field));
791 continue;
792 }
793
794 // Name does contain a `:` which is a loose convention for naming of maps in IOSS.
795 // If multiple maps start with the same substring before the `:`, then they are considered
796 // components of the same Ioss::Field::MAP field.
797 // Count the number of names that begin with the same substring...
798 auto base = name.substr(0, name.find(':'));
799
800 // Now see if the following name(s) contain the same substring...
801 int ii = i;
802 while (++ii < map_count) {
803 std::string next{names[ii]};
804 std::string next_base = next.substr(0, next.find(':'));
805 if (base != next_base) {
806 break;
807 }
808 }
809
810 int comp_count = ii - i;
811
812 std::string storage = fmt::format("Real[{}]", comp_count);
813 auto field =
814 Ioss::Field(base, block->field_int_type(), storage, Ioss::Field::MAP, my_element_count)
815 .set_index(i + 1);
816 block->field_add(std::move(field));
817
818 i = ii - 1;
819 }
820
821 delete_name_array(names, map_count);
822 return map_count;
823 }
824
825 void write_coordinate_frames(int exoid, const Ioss::CoordinateFrameContainer &frames)
826 {
827 if ((ex_int64_status(exoid) & EX_BULK_INT64_API) != 0) {
828 internal_write_coordinate_frames(exoid, frames, static_cast<int64_t>(0));
829 }
830 else {
831 internal_write_coordinate_frames(exoid, frames, 0);
832 }
833 }
834
835 void add_coordinate_frames(int exoid, Ioss::Region *region)
836 {
837 if ((ex_int64_status(exoid) & EX_BULK_INT64_API) != 0) {
838 internal_add_coordinate_frames(exoid, region, static_cast<int64_t>(0));
839 }
840 else {
841 internal_add_coordinate_frames(exoid, region, 0);
842 }
843 }
844
845 bool filter_node_list(Ioss::Int64Vector &nodes,
846 const std::vector<unsigned char> &node_connectivity_status)
847 {
848 // Iterate through 'nodes' and determine which of the nodes are
849 // not connected to any non-omitted blocks. The index of these
850 // nodes is then put in the 'nodes' list.
851 // Assumes that there is at least one omitted element block. The
852 // 'nodes' list on entry contains 1-based local node ids, not global.
853 // On return, the nodes list contains indices. To filter a nodeset list:
854 // for (size_t i = 0; i < nodes.size(); i++) {
855 // active_values[i] = some_nset_values[nodes[i]];
856 // }
857
858 size_t orig_size = nodes.size();
859 size_t active = 0;
860 for (size_t i = 0; i < orig_size; i++) {
861 if (node_connectivity_status[nodes[i] - 1] >= 2) {
862 // Node is connected to at least 1 active element...
863 nodes[active++] = i;
864 }
865 }
866 nodes.resize(active);
867 nodes.shrink_to_fit(); // shrink to fit
868 return (active != orig_size);
869 }
870
871 void filter_element_list(Ioss::Region *region, Ioss::Int64Vector &elements,
872 Ioss::Int64Vector &sides, bool remove_omitted_elements)
873 {
874 // Iterate through 'elements' and remove the elements which are in an omitted block.
875 // Precondition is that there is at least one omitted element block.
876 // The 'elements' list contains local element ids, not global.
877 // Since there are typically a small number of omitted blocks, do
878 // the following:
879 // For each omitted block, determine the min and max element id in
880 // that block. Iterate 'elements' vector and set the id to zero if
881 // min <= id <= max. Once all omitted blocks have been processed,
882 // then iterate the vector and compress out all zeros. Keep 'sides'
883 // array consistent.
884
885 // Get all element blocks in region...
886 bool omitted = false;
887 const Ioss::ElementBlockContainer &element_blocks = region->get_element_blocks();
888 for (const auto &block : element_blocks) {
889
890 if (Ioss::Utils::block_is_omitted(block)) {
891 int64_t min_id = block->get_offset() + 1;
892 int64_t max_id = min_id + block->entity_count() - 1;
893 for (size_t i = 0; i < elements.size(); i++) {
894 if (min_id <= elements[i] && elements[i] <= max_id) {
895 omitted = true;
896 elements[i] = 0;
897 sides[i] = 0;
898 }
899 }
900 }
901 }
902 if (remove_omitted_elements && omitted) {
903 elements.erase(std::remove(elements.begin(), elements.end(), 0), elements.end());
904 sides.erase(std::remove(sides.begin(), sides.end(), 0), sides.end());
905 }
906 }
907
908 void separate_surface_element_sides(Ioss::Int64Vector &element, Ioss::Int64Vector &sides,
909 Ioss::Region *region, Ioex::TopologyMap &topo_map,
910 Ioex::TopologyMap &side_map,
911 Ioss::SurfaceSplitType split_type,
912 const std::string &surface_name)
913 {
914 if (!element.empty()) {
915 Ioss::ElementBlock *block = nullptr;
916 // Topology of sides in current element block
917 const Ioss::ElementTopology *common_ftopo = nullptr;
918 const Ioss::ElementTopology *topo = nullptr; // Topology of current side
919 int64_t current_side = -1;
920
921 for (size_t iel = 0; iel < element.size(); iel++) {
922 int64_t elem_id = element[iel];
923 if (elem_id <= 0) {
924 IOSS_ERROR(fmt::format(
925 "ERROR: In sideset/surface '{}' an element with id {} is specified. Element "
926 "ids must be greater than zero. ({})",
927 surface_name, elem_id, __func__));
928 }
929 if (block == nullptr || !block->contains(elem_id)) {
930 block = region->get_element_block(elem_id);
931 SMART_ASSERT(block != nullptr);
932 SMART_ASSERT(!Ioss::Utils::block_is_omitted(block)); // Filtered out above.
933
934 // nullptr if hetero sides on element
935 common_ftopo = block->topology()->boundary_type(0);
936 if (common_ftopo != nullptr) {
937 topo = common_ftopo;
938 }
939 current_side = -1;
940 }
941
942 if (common_ftopo == nullptr && sides[iel] != current_side) {
943 current_side = sides[iel];
944 if (current_side <= 0 || current_side > block->topology()->number_boundaries()) {
945 IOSS_ERROR(fmt::format(
946 "ERROR: In sideset/surface '{}' for the element with id {} of topology '{}';\n\t"
947 "an invalid face index '{}' is specified.\n\tFace indices "
948 "must be between 1 and {}. ({})",
949 surface_name, fmt::group_digits(elem_id), block->topology()->name(), current_side,
950 block->topology()->number_boundaries(), __func__));
951 }
952 topo = block->topology()->boundary_type(sides[iel]);
953 SMART_ASSERT(topo != nullptr);
954 }
955 std::pair<std::string, const Ioss::ElementTopology *> name_topo;
956 if (split_type == Ioss::SPLIT_BY_TOPOLOGIES) {
957 name_topo = std::make_pair(block->topology()->name(), topo);
958 }
959 else if (split_type == Ioss::SPLIT_BY_ELEMENT_BLOCK) {
960 name_topo = std::make_pair(block->name(), topo);
961 }
962 topo_map[name_topo]++;
963 if (side_map[name_topo] == 0) {
964 side_map[name_topo] = sides[iel];
965 }
966 else if (side_map[name_topo] != sides[iel]) {
967 // Not a consistent side for all sides in this
968 // sideset. Set to large number. Note that maximum
969 // sides/element is 6, so don't have to worry about
970 // a valid element having 999 sides (unless go to
971 // arbitrary polyhedra some time...) Using a large
972 // number instead of -1 makes it easier to check the
973 // parallel consistency...
974 side_map[name_topo] = 999;
975 }
976 }
977 }
978 }
979
980 void write_reduction_attributes(int exoid, const Ioss::GroupingEntity *ge)
981 {
982 Ioss::NameList properties = ge->property_describe(Ioss::Property::Origin::ATTRIBUTE);
983
984 auto type = Ioex::map_exodus_type(ge->type());
985 auto id = ge->get_optional_property("id", 0);
986
987 double rval = 0.0;
988 int64_t ival = 0;
989 for (const auto &property_name : properties) {
990 auto prop = ge->get_property(property_name);
991
992 switch (prop.get_type()) {
993 case Ioss::Property::BasicType::REAL:
994 rval = prop.get_real();
995 ex_put_double_attribute(exoid, type, id, property_name.c_str(), 1, &rval);
996 break;
997 case Ioss::Property::BasicType::INTEGER:
998 ival = prop.get_int();
999 ex_put_integer_attribute(exoid, type, id, property_name.c_str(), 1, &ival);
1000 break;
1001 case Ioss::Property::BasicType::STRING:
1002 ex_put_text_attribute(exoid, type, id, property_name.c_str(), prop.get_string().c_str());
1003 break;
1004 case Ioss::Property::BasicType::VEC_INTEGER:
1005 ex_put_integer_attribute(exoid, type, id, property_name.c_str(), prop.get_vec_int().size(),
1006 Data(prop.get_vec_int()));
1007 break;
1008 case Ioss::Property::BasicType::VEC_DOUBLE:
1009 ex_put_double_attribute(exoid, type, id, property_name.c_str(),
1010 prop.get_vec_double().size(), Data(prop.get_vec_double()));
1011 break;
1012 default:; // Do nothing
1013 }
1014 }
1015 }
1016 } // namespace Ioex