Debian Codegraph @

packages/seacas/libraries/ioss/src/Ioss_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_CodeTypes.h"
8 #include <cassert>
9 #include <cctype>
10 #include <cstdint>
11 #include <cstring>
12 #include <ctime>
13 #include <fmt/chrono.h>
14 #include <fmt/core.h>
15 #include <fmt/format.h>
16 #include <fmt/ostream.h>
17 #include <fmt/ranges.h>
18 #include <fstream>
19 #include <ostream>
20 #include <sstream>
21 #include <string>
22 #include <tokenize.h>
23 #include <vector>
24
25 #if !defined(__IOSS_WINDOWS__)
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
28 #endif
29
30 #ifndef _POSIX_SOURCE
31 #define _POSIX_SOURCE
32 #endif
33 #include <cstdio>
34
35 #include "Ioss_CompositeVariableType.h"
36 #include "Ioss_DatabaseIO.h"
37 #include "Ioss_ElementBlock.h"
38 #include "Ioss_ElementTopology.h"
39 #include "Ioss_EntityType.h"
40 #include "Ioss_Field.h"
41 #include "Ioss_FileInfo.h"
42 #include "Ioss_GroupingEntity.h"
43 #include "Ioss_IOFactory.h"
44 #include "Ioss_NodeBlock.h"
45 #include "Ioss_Property.h"
46 #include "Ioss_PropertyManager.h"
47 #include "Ioss_Region.h"
48 #include "Ioss_SideBlock.h"
49 #include "Ioss_State.h"
50 #include "Ioss_Utils.h"
51 #include "Ioss_VariableType.h"
52 #include "Ioss_use_fmt.h"
53
54 #if defined(__IOSS_WINDOWS__)
55 #include <io.h>
56
57 #define isatty _isatty
58 #define WIN32_LEAN_AND_MEAN
59 #ifndef NOMINMAX
60 #define NOMINMAX
61 #endif
62 #include <windows.h>
63 #else
64 #include <unistd.h>
65 #endif
66
67 std::ostream *Ioss::Utils::m_warningStream = &std::cerr;
68 std::ostream *Ioss::Utils::m_debugStream = &std::cerr;
69 std::ostream *Ioss::Utils::m_outputStream = &std::cerr;
70 std::string Ioss::Utils::m_preWarningText = "\nIOSS WARNING: ";
71
72 namespace {
73 auto initial_time = std::chrono::steady_clock::now();
74
75 ////////////////////////////////////////////////////////////////////////
76 bool is_separator(const char separator, const char value) { return separator == value; }
77
78 size_t match(const char *name1, const char *name2)
79 {
80 auto l1 = std::strlen(name1);
81 auto l2 = std::strlen(name2);
82 auto len = l1 < l2 ? l1 : l2;
83 for (size_t i = 0; i < len; i++) {
84 if (name1[i] != name2[i]) {
85 while (i > 0 && (isdigit(name1[i - 1]) != 0) && (isdigit(name2[i - 1]) != 0)) {
86 i--;
87 // Back up to first non-digit so to handle "evar0000, evar0001, ..., evar 1123"
88 }
89 return i;
90 }
91 }
92 return len;
93 }
94
95 size_t match(const std::string &name1, const std::string &name2)
96 {
97 return match(name1.c_str(), name2.c_str());
98 }
99
100 // Split 'str' into 'tokens' based on the 'separator' character.
101 // If 'str' starts with 1 or more 'separator', they are part of the
102 // first token and not used for splitting. If there are multiple
103 // 'separator' characters in a row, then the first is used to split
104 // and the subsequent 'separator' characters are put as leading
105 // characters of the next token.
106 // `__this___is_a_string__for_tokens` will split to 6 tokens:
107 // `__this` `__is` `a` `string` `_for` `tokens`
108 Ioss::NameList field_tokenize(const std::string &str, const char separator)
109 {
110 std::string curr_token;
111 // Skip leading separators...
112 size_t i = 0;
113 while (i < str.length() && is_separator(separator, str[i])) {
114 curr_token += str[i++];
115 }
116 Ioss::NameList tokens;
117 for (; i < str.length(); ++i) {
118 char curr_char = str[i];
119
120 // determine if current character is a separator
121 bool is_sep = is_separator(separator, curr_char);
122 if (is_sep && !curr_token.empty()) {
123 // we just completed a token
124 tokens.push_back(curr_token);
125 curr_token.clear();
126 while (i++ < str.length() && is_separator(separator, str[i])) {
127 curr_token += str[i];
128 }
129 i--;
130 }
131 else if (!is_sep) {
132 curr_token += curr_char;
133 }
134 }
135 if (!curr_token.empty()) {
136 tokens.push_back(curr_token);
137 }
138 return tokens;
139 }
140 } // namespace
141
142 void Ioss::Utils::set_all_streams(std::ostream &out_stream)
143 {
144 m_outputStream = &out_stream;
145 m_debugStream = &out_stream;
146 m_warningStream = &out_stream;
147 }
148
149 void Ioss::Utils::set_output_stream(std::ostream &out_stream) { m_outputStream = &out_stream; }
150
151 void Ioss::Utils::set_debug_stream(std::ostream &out_stream) { m_debugStream = &out_stream; }
152
153 void Ioss::Utils::set_warning_stream(std::ostream &out_stream) { m_warningStream = &out_stream; }
154
155 std::ostream &Ioss::Utils::get_output_stream() { return *m_outputStream; }
156
157 std::ostream &Ioss::Utils::get_warning_stream() { return *m_warningStream; }
158
159 std::ostream &Ioss::Utils::get_debug_stream() { return *m_debugStream; }
160
161 void Ioss::Utils::time_and_date(char *time_string, char *date_string, size_t length)
162 {
163 std::time_t t = std::time(nullptr);
164 std::string time = fmt::format("{:%H:%M:%S}", fmt::localtime(t));
165 std::string date;
166 if (length >= 10) {
167 date = fmt::format("{:%Y/%m/%d}", fmt::localtime(t));
168 }
169 else {
170 date = fmt::format("{:%y/%m/%d}", fmt::localtime(t));
171 }
172 copy_string(time_string, time, 9);
173 copy_string(date_string, date, length + 1);
174 }
175
176 bool Ioss::Utils::check_valid_change_set_name(const std::string &cs_name,
177 const Ioss::Region &region, int rank)
178 {
179 auto cs_names = region.get_database()->internal_change_set_describe();
180 auto it = std::find(cs_names.cbegin(), cs_names.cend(), cs_name);
181 if (it == cs_names.cend()) {
182 if (rank == 0) {
183 fmt::print(stderr,
184 "ERROR: Change set {}, not found in database {}. Valid change sets are:\n"
185 " {}\n",
186 cs_name, region.get_database()->get_filename(), fmt::join(cs_names, ", "));
187 }
188 return false;
189 }
190 return true;
191 }
192
193 void Ioss::Utils::check_non_null(void *ptr, const char *type, const std::string &name,
194 const std::string &func)
195 {
196 if (ptr == nullptr) {
197 std::ostringstream errmsg;
198 fmt::print(errmsg,
199 "INTERNAL ERROR: Could not find {} '{}'. Something is wrong in {}. Please report.\n",
200 type, name, func);
201 IOSS_ERROR(errmsg);
202 }
203 }
204
205 std::string Ioss::Utils::decode_filename(const std::string &filename, int processor,
206 int num_processors)
207 {
208 // Current format for per-processor file names is:
209 // PREFIX/basename.num_proc.cur_proc
210 // the 'cur_proc' field is padded to be the same width as
211 // the 'num_proc' field
212 // Examples: basename.8.1, basename.64.03, basename.128.001
213
214 // Create a std::string containing the total number of processors
215 if (num_processors > 1) {
216 size_t proc_width = number_width(num_processors);
217
218 std::string decoded_filename =
219 fmt::format("{}.{}.{:0{}}", filename, num_processors, processor, proc_width);
220 return decoded_filename;
221 }
222 return filename;
223 }
224
225 std::string Ioss::Utils::get_trailing_digits(const std::string &name)
226 {
227 size_t digits = name.find_last_not_of("0123456789");
228 if (digits != std::string::npos) {
229 return name.substr(digits + 1);
230 }
231 return std::string{};
232 }
233
234 int Ioss::Utils::get_number(const std::string &suffix)
235 {
236 int N = 0;
237 bool all_dig = suffix.find_first_not_of("0123456789") == std::string::npos;
238 if (all_dig) {
239 N = std::stoi(suffix);
240 }
241 return N;
242 }
243
244 int Ioss::Utils::extract_id(const std::string &name_id)
245 {
246 int id = 0;
247
248 auto tokens = Ioss::tokenize(name_id, "_");
249 if (tokens.size() > 1) {
250 // Check whether last token is an integer...
251 std::string str_id = tokens.back();
252 id = get_number(str_id);
253 }
254 return id;
255 }
256
257 std::string Ioss::Utils::format_id_list(const std::vector<size_t> &ids, const std::string &rng_sep,
258 const std::string &seq_sep)
259 {
260 // Based on function from cubit (but I wrote original cubit version long time ago... ;-)
261 if (ids.empty()) {
262 return "";
263 }
264
265 // PRECONDITION: `ids` is monotonically increasing -- will throw IOSS_ERROR if violated.
266 if (!std::is_sorted(ids.begin(), ids.end(), [](size_t a, size_t b) { return a <= b; })) {
267 std::ostringstream errmsg;
268 fmt::print(errmsg,
269 "INTERNAL ERROR: ({}) The `ids` vector is not in monotonically increasing order as "
270 "required.\n",
271 __func__);
272 IOSS_ERROR(errmsg);
273 }
274
275 size_t num = 0;
276 std::ostringstream ret_str;
277 while (num < ids.size()) {
278 fmt::print(ret_str, "{}{}", num == 0 ? "" : seq_sep, ids[num]);
279 size_t begin = ids[num]; // first id in range of 1 or more ids
280 size_t previous = ids[num]; // last id in range of 1 or more ids
281 // Gather a range or single value... (begin .. previous)
282 while (previous == ids[num] && ++num < ids.size() && ids[num] == previous + 1) {
283 previous++;
284 }
285
286 if (begin != previous) {
287 fmt::print(ret_str, "{}{}", previous == begin + 1 ? seq_sep : rng_sep, previous);
288 }
289 }
290 return ret_str.str();
291 }
292
293 std::string Ioss::Utils::encode_entity_name(const std::string &entity_type, int64_t id)
294 {
295 // ExodusII stores block, nodeset, and sideset ids as integers
296 // Sierra stores these as std::strings. The string is created by
297 // concatenating the type, the character '_' and the id.
298
299 return fmt::format("{}_{}", entity_type, id);
300 }
301
302 std::string Ioss::Utils::fixup_type(const std::string &base, int nodes_per_element, int spatial)
303 {
304 std::string type = base;
305 Ioss::Utils::fixup_name(type); // Convert to lowercase; replace spaces with '_'
306
307 // Fixup an exodusII kluge/ambiguity.
308 // The element block type does not fully define the element. For
309 // example, a block of type 'triangle' may have either 3 or 6
310 // nodes. To fix this, check the block type name and see if it
311 // ends with a number. If it does, assume it is OK; if not, append
312 // the 'nodes_per_element'.
313 if (type.empty() || isdigit(*(type.rbegin())) == 0) {
314 if (nodes_per_element > 1) {
315 type += std::to_string(nodes_per_element);
316 }
317 }
318
319 // Fixup an exodusII kludge. For triangular elements, the same
320 // name is used for 2D elements and 3D shell elements. Convert
321 // to unambiguous names for the IO Subsystem. The 2D name
322 // stays the same, the 3D name becomes 'trishell#'
323 if (spatial == 3) {
324 if (type == "triangle3") {
325 type = "trishell3";
326 }
327 else if (type == "triangle4") {
328 type = "trishell4";
329 }
330 else if (type == "triangle6") {
331 type = "trishell6";
332 }
333 else if (type == "tri3") {
334 type = "trishell3";
335 }
336 else if (type == "tri4") {
337 type = "trishell4";
338 }
339 else if (type == "tri6") {
340 type = "trishell6";
341 }
342 }
343
344 if (spatial == 2) {
345 if (type == "shell2") {
346 type = "shellline2d2";
347 }
348 else if (type == "rod2" || type == "bar2" || type == "truss2") {
349 type = "rod2d2";
350 }
351 else if (type == "shell3") {
352 type = "shellline2d3";
353 }
354 else if (type == "bar3" || type == "rod3" || type == "truss3") {
355 type = "rod2d3";
356 }
357 else if (type == "bar4" || type == "rod4" || type == "truss4") {
358 type = "rod2d4";
359 }
360 }
361
362 if (Ioss::Utils::substr_equal("super", type)) {
363 // A super element can have a varying number of nodes. Create
364 // an IO element type for this super element just so the IO
365 // system can read a mesh containing super elements. This
366 // allows the "omit volume" command to be used in the Sierra
367 // applications to skip creating a corresponding element block
368 // in the application.
369 type = "super" + std::to_string(nodes_per_element);
370 }
371 return type;
372 }
373
374 std::string Ioss::Utils::local_filename(const std::string &relative_filename,
375 const std::string &type,
376 const std::string &working_directory)
377 {
378 if (relative_filename[0] == '/' || type == "generated" || working_directory.empty()) {
379 return relative_filename;
380 }
381 std::string filename = working_directory;
382 filename += relative_filename;
383 return filename;
384 }
385
386 int Ioss::Utils::field_warning(const Ioss::GroupingEntity *ge, const Ioss::Field &field,
387 std::string_view inout)
388 {
389 if (field.get_name() != "ids") {
390 fmt::print(Ioss::WarnOut(), "{} '{}'. Unknown {} field '{}'\n", ge->type_string(), ge->name(),
391 inout, field.get_name());
392 }
393 return -4;
394 }
395
396 namespace {
397 const Ioss::VariableType *match_composite_field(Ioss::NameList &names,
398 Ioss::IntVector &which_names,
399 const char suffix_separator)
400 {
401 // ASSUME: Fields are in order...
402 // The field we are trying to match will be a composite field of
403 // type base_x_1, base_y_1, base_z_1, ...., base_y_3, base_z_3.
404 // The composite field type currently always has a numeric Real[N]
405 // type field as the last suffix and the other field as the first
406 // suffix.
407 // If we take the last suffix of the last name, it should give us
408 // the 'N' in the Real[N] field. Dividing 'which_names.size()' by
409 // 'N' will give the number of components in the inner field.
410
411 char suffix[2] = {suffix_separator, '\0'};
412
413 auto tokens = Ioss::tokenize(names[which_names.back()], suffix);
414
415 if (tokens.size() <= 2) {
416 return nullptr;
417 }
418
419 assert(tokens.size() > 2);
420
421 // Check that suffix is a number -- all digits
422 int N = Ioss::Utils::get_number(tokens.back());
423
424 if (N == 0) {
425 return nullptr;
426 }
427
428 if (which_names.size() % N != 0) {
429 return nullptr;
430 }
431
432 size_t inner_token = tokens.size() - 2;
433 size_t inner_comp = which_names.size() / N;
434
435 // Gather the first 'inner_ccomp' inner field suffices...
436 std::vector<Ioss::Suffix> suffices;
437 for (size_t i = 0; i < inner_comp; i++) {
438 auto ltokens = Ioss::tokenize(std::string(names[which_names[i]]), suffix);
439 // The second-last token is the suffix for this component...
440 Ioss::Suffix tmp(ltokens[inner_token]);
441 suffices.push_back(tmp);
442 }
443
444 // check that the suffices on the next copies of the inner field
445 // match the first copy...
446 size_t j = inner_comp;
447 for (int copy = 1; copy < N; copy++) {
448 for (size_t i = 0; i < inner_comp; i++) {
449 auto ltokens = Ioss::tokenize(std::string(names[which_names[j++]]), suffix);
450 // The second-last token is the suffix for this component...
451 if (suffices[i] != ltokens[inner_token]) {
452 return nullptr;
453 }
454 }
455 }
456
457 // All 'N' copies of the inner field match, now see the
458 // suffices actually defines a field...
459 const Ioss::VariableType *type = Ioss::VariableType::factory(suffices);
460 if (type != nullptr) {
461 type = Ioss::VariableType::factory(type->name(), N);
462 }
463 return type;
464 }
465
466 const Ioss::VariableType *match_single_field(Ioss::NameList &names, Ioss::IntVector &which_names,
467 const char suffix_separator,
468 bool ignore_realn_fields)
469 {
470 // Strip off the suffix from each name indexed in 'which_names'
471 // and see if it defines a valid type...
472 std::vector<Ioss::Suffix> suffices;
473
474 char suffix[2] = {suffix_separator, '\0'};
475
476 for (int which_name : which_names) {
477 auto tokens = Ioss::tokenize(names[which_name], suffix);
478 size_t num_tokens = tokens.size();
479
480 // The last token is the suffix for this component...
481 Ioss::Suffix tmp(tokens[num_tokens - 1]);
482 suffices.push_back(tmp);
483 }
484 const Ioss::VariableType *type = Ioss::VariableType::factory(suffices, ignore_realn_fields);
485 return type;
486 }
487
488 Ioss::Field get_next_field(Ioss::NameList &names, size_t count, Ioss::Field::RoleType fld_role,
489 const char suffix_separator, const int *truth_table,
490 bool ignore_realn_fields)
491 {
492 // NOTE: 'names' are all lowercase at this point.
493
494 // Assumption 1: To convert to a non-SCALAR type, the variable name
495 // must have an field_suffix_sep in the name separating the suffixes from
496 // the main name.
497
498 // Find first unused name (used names are empty())
499 size_t index = 0;
500 bool found_valid = false;
501 for (index = 0; index < names.size(); index++) {
502 assert(truth_table == nullptr || truth_table[index] == 1 || truth_table[index] == 0);
503 if ((truth_table == nullptr || truth_table[index] == 1) && !names[index].empty()) {
504 found_valid = true;
505 break;
506 }
507 }
508
509 if (!found_valid) {
510 // Return an invalid field...
511 return {"", Ioss::Field::INVALID, IOSS_SCALAR(), fld_role, 1};
512 }
513
514 // At this point, name[index] should be a valid potential field
515 // name and all names[i] with i < index are either already used or
516 // not valid for this grouping entity (truth_table entry == 0).
517 assert(index < names.size() && !names[index].empty() &&
518 (truth_table == nullptr || truth_table[index] == 1));
519 const auto &name = names[index];
520 auto name_length = name.length();
521
522 // Split the name up into tokens separated by the
523 // 'suffix_separator'. Note that the basename itself could
524 // contain a suffix_separator (back_stress_xx or
525 // back_stress_xx_01). Need to ignore embedded separators
526 // (back_stress) and also recognize composite variable types
527 // (back_stress_xx_01). At the current time, a composite variable
528 // type can only contain two non-composite variable types, so we
529 // only need to look to be concerned with the last 1 or 2 tokens...
530 auto tokens = field_tokenize(name, suffix_separator);
531 size_t num_tokens = tokens.size();
532
533 // Check that tokenizer did not return empty tokens...
534 bool invalid = tokens[0].empty() || tokens[num_tokens - 1].empty();
535 if (num_tokens == 1 || invalid) {
536 // It is not a (Sierra-generated) name for a non-SCALAR variable
537 // Return a SCALAR field
538 Ioss::Field field(name, Ioss::Field::REAL, IOSS_SCALAR(), fld_role, count);
539 field.set_index(index);
540 names[index] = "";
541 return field;
542 }
543
544 // KNOW: num_tokens > 1 at this point. Possible that we still
545 // just have a scalar with one or more embedded separator characters...
546 int suffix_size = 1;
547 if (num_tokens > 2) {
548 suffix_size = 2;
549 }
550
551 // If num_tokens > 2, then we can potentially have a composite
552 // variable type which would have a double suffix (_xx_01).
553
554 // Gather all names which match in the first
555 // (num_tokens-suffix_size) tokens and see if their suffices form
556 // a valid variable type...
557 while (suffix_size > 0) {
558 for (int i = 0; i <= 1; i++) {
559 bool same_length = (i == 0);
560 Ioss::IntVector which_names; // Contains index of names that potentially match as components
561 // of a higher-order type.
562 std::string base_name = tokens[0];
563 for (size_t it = 1; it < num_tokens - suffix_size; it++) {
564 base_name += suffix_separator;
565 base_name += tokens[it];
566 }
567 base_name += suffix_separator;
568 size_t bn_len = base_name.length(); // Length of basename portion only
569
570 // Add the current name...
571 which_names.push_back(index);
572
573 // Gather all other names that are valid for this entity, and
574 // match in the first 'bn_len' characters.
575 //
576 // Check that they have the same number of tokens,
577 // It is possible that the first name(s) that match with two
578 // suffices have a basename that match other names with only a
579 // single suffix lc_cam_x, lc_cam_y, lc_sfarea.
580 for (size_t id = index + 1; id < names.size(); id++) {
581 const auto &tst_name = names[id];
582 auto subtokens = field_tokenize(tst_name, suffix_separator);
583 if ((truth_table == nullptr || truth_table[id] == 1) && // Defined on this entity
584 Ioss::Utils::str_equal(name.substr(0, bn_len),
585 tst_name.substr(0, bn_len)) && // base portion must match
586 (!same_length || tst_name.length() == name_length) &&
587 subtokens.size() == num_tokens) {
588 which_names.push_back(id);
589 }
590 }
591
592 const Ioss::VariableType *type = nullptr;
593 if (suffix_size == 2) {
594 if (which_names.size() > 1) {
595 type = match_composite_field(names, which_names, suffix_separator);
596 }
597 }
598 else {
599 assert(suffix_size == 1);
600 type = match_single_field(names, which_names, suffix_separator, ignore_realn_fields);
601 }
602
603 if (type != nullptr) {
604 // A valid variable type was recognized.
605 // Mark the names which were used so they aren't used for another field on this entity.
606 // Create a field of that variable type.
607 assert(type->component_count() == static_cast<int>(which_names.size()));
608 Ioss::Field field(base_name.substr(0, bn_len - 1), Ioss::Field::REAL, type, fld_role,
609 count);
610 if (suffix_separator != '_') {
611 field.set_suffix_separator(suffix_separator);
612 }
613 // Are suffices upper or lowercase...
614 auto tmp = field_tokenize(names[which_names[0]], suffix_separator);
615
616 // If a composite variable, then need to check the interior suffix, not the last (which
617 // will be 1,2,...)
618 bool is_composite = dynamic_cast<const Ioss::CompositeVariableType *>(
619 field.transformed_storage()) != nullptr;
620
621 Ioss::Suffix suffix{tmp[tmp.size() - (is_composite ? 2 : 1)]};
622 field.set_suffices_uppercase(suffix.is_uppercase());
623 field.set_index(index);
624 for (const auto &which_name : which_names) {
625 names[which_name] = "";
626 }
627 return field;
628 }
629 if (suffix_size == 1 && !same_length) {
630 // Failure recognizing a higher-order field; just take the
631 // first field and return it as a scalar...
632 Ioss::Field field(name, Ioss::Field::REAL, IOSS_SCALAR(), fld_role, count);
633
634 // Are suffices upper or lowercase...
635 auto tmp = field_tokenize(names[which_names[0]], suffix_separator);
636 Ioss::Suffix suffix{tmp[tmp.size() - 1]};
637 field.set_suffices_uppercase(suffix.is_uppercase());
638 field.set_index(index);
639 names[index] = "";
640 return field;
641 }
642 }
643 suffix_size--;
644 }
645 return {"", Ioss::Field::INVALID, IOSS_SCALAR(), fld_role, 1};
646 }
647
648 // common
649 bool define_field(size_t nmatch, size_t match_length, Ioss::NameList &names, size_t index,
650 std::vector<Ioss::Suffix> &suffices, size_t entity_count,
651 Ioss::Field::RoleType fld_role, std::vector<Ioss::Field> &fields,
652 bool strip_trailing_, bool ignore_realn_fields, char suffix_separator)
653 {
654 // Try to define a field of size 'nmatch' with the suffices in 'suffices'.
655 // If this doesn't define a known field, then assume it is a scalar instead
656 // and return false.
657 if (nmatch > 1) {
658 const Ioss::VariableType *type = Ioss::VariableType::factory(suffices, ignore_realn_fields);
659 if (type == nullptr) {
660 nmatch = 1;
661 }
662 else {
663 auto name = names[index].substr(0, match_length);
664 auto suffix = suffix_separator;
665 if (strip_trailing_ && name.back() == '_') {
666 name = name.substr(0, name.length() - 1);
667 suffix = '_';
668 }
669 Ioss::Field field(name, Ioss::Field::REAL, type, fld_role, entity_count);
670 if (suffix != suffix_separator) {
671 field.set_suffix_separator(suffix);
672 }
673 // Are suffices upper or lowercase...
674 field.set_suffices_uppercase(suffices[0].is_uppercase());
675 if (field.is_valid()) {
676 fields.push_back(field);
677 }
678 for (size_t j = 0; j < nmatch; j++) {
679 names[index + j] = "";
680 }
681 return true;
682 }
683 }
684
685 // NOTE: nmatch could be reset inside previous if block.
686 // This is not an 'else' block, it is a new if block.
687 if (nmatch == 1) {
688 Ioss::Field field(names[index], Ioss::Field::REAL, IOSS_SCALAR(), fld_role, entity_count);
689 if (field.is_valid()) {
690 fields.push_back(field);
691 }
692 names[index] = "";
693 return false;
694 }
695 return false; // Can't get here... Quiet the compiler
696 }
697 } // namespace
698
699 // Read scalar fields off an input database and determine whether
700 // they are components of a higher order type (vector, tensor, ...).
701 void Ioss::Utils::get_fields(int64_t entity_count, // The number of objects in this entity.
702 Ioss::NameList &names, // Raw list of field names from exodus
703 Ioss::Field::RoleType fld_role, // Role of field
704 const Ioss::DatabaseIO *db,
705 int *local_truth, // Truth table for this entity;
706 // null if not applicable.
707 std::vector<Ioss::Field> &fields) // The fields that were found.
708 {
709 bool enable_field_recognition = db->get_field_recognition();
710 bool strip_trailing_ = db->get_field_strip_trailing_();
711 bool ignore_realn_fields = db->get_ignore_realn_fields();
712 char suffix_separator = db->get_field_separator();
713
714 if (!enable_field_recognition) {
715 // Create a separate field for each name.
716 for (size_t i = 0; i < names.size(); i++) {
717 if (!names[i].empty() && (local_truth == nullptr || local_truth[i] == 1)) {
718 Ioss::Field field(names[i], Ioss::Field::REAL, IOSS_SCALAR(), fld_role, entity_count);
719 field.set_index(i);
720 fields.push_back(field);
721 names[i] = "";
722 }
723 }
724 }
725 else if (suffix_separator != 0) {
726 while (true) {
727 // NOTE: 'get_next_field' determines storage type (vector, tensor,...)
728 Ioss::Field field = get_next_field(names, entity_count, fld_role, suffix_separator,
729 local_truth, ignore_realn_fields);
730 if (field.is_valid()) {
731 fields.push_back(field);
732 }
733 else {
734 break;
735 }
736 }
737 }
738 else {
739 // This routine is used if there is no field component separator. E.g.,
740 // fieldx, fieldy, fieldz instead of field_x field_y field_z
741 size_t nmatch = 1;
742 size_t ibeg = 0;
743 size_t pmat = 0;
744 std::vector<Ioss::Suffix> suffices;
745 top:
746
747 while (ibeg + nmatch < names.size()) {
748 if (local_truth != nullptr) {
749 while (ibeg < names.size() && local_truth[ibeg] == 0) {
750 ibeg++;
751 }
752 }
753 while (ibeg < names.size() && names[ibeg].empty()) {
754 ibeg++;
755 }
756 for (size_t i = ibeg + 1; i < names.size(); i++) {
757 auto mat = match(names[ibeg], names[i]);
758 if (local_truth != nullptr && local_truth[i] == 0) {
759 mat = 0;
760 }
761
762 // For all fields, the total length of the name is the same
763 // for all components of that field. The 'basename' of the
764 // field will also be the same for all cases.
765 //
766 // It is possible that the length of the match won't be the
767 // same for all components of a field since the match may
768 // include a portion of the suffix; (sigxx, sigxy, sigyy
769 // should match only 3 characters of the basename (sig), but
770 // sigxx and sigxy will match 4 characters) so consider a
771 // valid match if the match length is >= previous match length.
772 if ((names[ibeg].length() == names[i].length()) && mat > 0 && (pmat == 0 || mat >= pmat)) {
773 nmatch++;
774 if (nmatch == 2) {
775 // Get suffix for first field in the match
776 pmat = mat;
777 Ioss::Suffix tmp(&names[ibeg][pmat]);
778 suffices.push_back(tmp);
779 }
780 // Get suffix for next fields in the match
781 Ioss::Suffix tmp(&names[i][pmat]);
782 suffices.push_back(tmp);
783 }
784 else {
785
786 bool multi_component =
787 define_field(nmatch, pmat, names, ibeg, suffices, entity_count, fld_role, fields,
788 strip_trailing_, ignore_realn_fields, suffix_separator);
789 if (!multi_component) {
790 // Although we matched multiple suffices, it wasn't a
791 // higher-order field, so we only used 1 name instead of
792 // the 'nmatch' we thought we might use.
793 i = ibeg + 1;
794 }
795
796 // Cleanout the suffices vector.
797 clear(suffices);
798
799 // Reset for the next time through the while loop...
800 nmatch = 1;
801 pmat = 0;
802 ibeg = i;
803 break;
804 }
805 }
806 }
807 // We've gone through the entire list of names; see if what we
808 // have forms a multi-component field; if not, then define a
809 // scalar field and jump up to the loop again to handle the others
810 // that had been gathered.
811 if (ibeg < names.size()) {
812 if (local_truth == nullptr || local_truth[ibeg] == 1) {
813 bool multi_component =
814 define_field(nmatch, pmat, names, ibeg, suffices, entity_count, fld_role, fields,
815 strip_trailing_, ignore_realn_fields, suffix_separator);
816 clear(suffices);
817 if (nmatch > 1 && !multi_component) {
818 ibeg++;
819 goto top;
820 }
821 }
822 else {
823 ibeg++;
824 goto top;
825 }
826 }
827 }
828 }
829
830 bool Ioss::Utils::check_int_to_real_overflow(const Ioss::Field &field, int64_t *data,
831 size_t num_entity)
832 {
833 // Check all values in `data` to make sure that if they are converted to a double and
834 // back again, there will be no data loss. This requires that the value be less than 2^53.
835 static int64_t max_double = 2LL << 53;
836 assert(int64_t(double(max_double)) == max_double);
837 assert(int64_t(double(max_double + 1)) != max_double + 1);
838
839 size_t comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
840 for (size_t i = 0; i < num_entity * comp_count; i++) {
841 if (data[i] > max_double) {
842 fmt::print(
843 Ioss::WarnOut(),
844 "Field '{}' contains 64-bit integer data that is not representable as a double value.\n"
845 "\tThis value can not currently be stored in the exodus database without data loss.\n"
846 "\tThe first such value is at location {}, component {} (1-based) with value {}.\n",
847 field.get_name(), fmt::group_digits(i / comp_count + 1), i % comp_count + 1,
848 fmt::group_digits(data[i]));
849 return true;
850 }
851 }
852 return false;
853 }
854
855 std::string Ioss::Utils::platform_information()
856 {
857 #if !defined(__IOSS_WINDOWS__)
858 struct utsname sys_info
859 {
860 };
861 uname(&sys_info);
862 std::string info =
863 fmt::format("Node: {0}, OS: {1} {2}, {3}, Machine: {4}", sys_info.nodename, sys_info.sysname,
864 sys_info.release, sys_info.version, sys_info.machine);
865 #else
866 std::string info = "Node: Unknown, OS: Unknown, Machine: Unknown";
867 #endif
868 return info;
869 }
870
871 bool Ioss::Utils::block_is_omitted(Ioss::GroupingEntity *block)
872 {
873 bool omitted = block->get_optional_property("omitted", 0) == 1;
874 return omitted;
875 }
876
877 void Ioss::Utils::calculate_sideblock_membership(IntVector &face_is_member,
878 const Ioss::SideBlock *sd_blk,
879 size_t int_byte_size, const void *element,
880 const void *sides, int64_t number_sides,
881 const Ioss::Region *region)
882 {
883 assert(sd_blk != nullptr);
884
885 face_is_member.reserve(number_sides);
886
887 const ElementTopology *unknown = Ioss::ElementTopology::factory("unknown");
888
889 // Topology of faces in this face block...
890 const ElementTopology *ftopo = sd_blk->topology();
891
892 // Topology of parent element for faces in this face block
893 const ElementTopology *parent_topo = sd_blk->parent_element_topology();
894
895 // If split by element block then parent_block will be non-nullptr
896 const ElementBlock *parent_block = sd_blk->parent_element_block();
897
898 // The element block containing the face we are working on...
899 Ioss::ElementBlock *block = nullptr;
900
901 // Topology of face/edge in current element block
902 const ElementTopology *common_ftopo = nullptr;
903
904 // Topology of elements in the element block containing this element
905 const ElementTopology *block_topo = nullptr;
906
907 // Topology of the face we are currently working with...
908 const ElementTopology *topo = nullptr;
909
910 // The element side that the current face is on the element...
911 int current_side = -1;
912
913 for (int64_t iel = 0; iel < number_sides; iel++) {
914 int64_t elem_id = 0;
915 int side_id = 0;
916 if (int_byte_size == 4) {
917 elem_id = static_cast<const int *>(element)[iel];
918 side_id = static_cast<const int *>(sides)[iel];
919 }
920 else {
921 elem_id = static_cast<const int64_t *>(element)[iel];
922 side_id = static_cast<int>(static_cast<const int64_t *>(sides)[iel]);
923 }
924
925 // Get the element block containing this face...
926 if (block == nullptr || !block->contains(elem_id)) {
927 block = region->get_element_block(elem_id);
928 block_topo = block->topology();
929 // nullptr if hetero face/edge on element
930 common_ftopo = block->topology()->boundary_type(0);
931 if (common_ftopo != nullptr) {
932 topo = common_ftopo;
933 }
934 current_side = -1;
935 }
936
937 // If the element topology of the element block containing this
938 // face has heterogeneous topology (eg. wedge), then determine the
939 // topology corresponding to the current side..
940 if (common_ftopo == nullptr && side_id != current_side) {
941 current_side = side_id;
942 topo = block->topology()->boundary_type(side_id);
943 }
944
945 bool face_topo_match = ftopo == unknown || topo == ftopo;
946 bool block_topo_match = parent_topo == unknown || block_topo == parent_topo;
947 // See if the face topology and the parent element topology for
948 // the current face match the topology associated with this face block.
949 if (face_topo_match && block_topo_match && (parent_block == nullptr || parent_block == block) &&
950 !block_is_omitted(block)) {
951 // This face/edge belongs in the face/edge block
952 face_is_member.push_back(1);
953 }
954 else {
955 face_is_member.push_back(0);
956 }
957 }
958 }
959
960 int64_t Ioss::Utils::get_side_offset(const Ioss::ElementTopology *parent_topo,
961 const Ioss::ElementTopology *side_topo)
962 {
963 int64_t side_offset = 0;
964 if ((side_topo != nullptr) && (parent_topo != nullptr)) {
965 int side_topo_dim = side_topo->parametric_dimension();
966 int elem_topo_dim = parent_topo->parametric_dimension();
967 int elem_spat_dim = parent_topo->spatial_dimension();
968
969 if (side_topo_dim + 1 < elem_spat_dim && side_topo_dim < elem_topo_dim) {
970 side_offset = parent_topo->number_faces();
971 }
972 }
973 return side_offset;
974 }
975
976 int64_t Ioss::Utils::get_side_offset(const Ioss::SideBlock *sb)
977 {
978 const Ioss::ElementTopology *side_topo = sb->topology();
979 const Ioss::ElementTopology *parent_topo = sb->parent_element_topology();
980 return get_side_offset(parent_topo, side_topo);
981 }
982
983 std::string Ioss::Utils::shape_to_string(const Ioss::ElementShape &shape)
984 {
985 switch (shape) {
986 case Ioss::ElementShape::UNKNOWN: return {"Unknown"};
987 case Ioss::ElementShape::POINT: return {"Point"};
988 case Ioss::ElementShape::SPHERE: return {"Sphere"};
989 case Ioss::ElementShape::LINE: return {"Line"};
990 case Ioss::ElementShape::SPRING: return {"Spring"};
991 case Ioss::ElementShape::TRI: return {"Tri"};
992 case Ioss::ElementShape::QUAD: return {"Quad"};
993 case Ioss::ElementShape::TET: return {"Tet"};
994 case Ioss::ElementShape::PYRAMID: return {"Pyramid"};
995 case Ioss::ElementShape::WEDGE: return {"Wedge"};
996 case Ioss::ElementShape::HEX: return {"Hex"};
997 case Ioss::ElementShape::SUPER: return {"Super"};
998 }
999 return fmt::format("Invalid shape [{}]", unsigned(shape));
1000 }
1001
1002 std::string Ioss::Utils::entity_type_to_string(const Ioss::EntityType &type)
1003 {
1004 switch (type) {
1005 case Ioss::EntityType::NODEBLOCK: return {"NODEBLOCK"};
1006 case Ioss::EntityType::EDGEBLOCK: return {"EDGEBLOCK"};
1007 case Ioss::EntityType::FACEBLOCK: return {"FACEBLOCK"};
1008 case Ioss::EntityType::ELEMENTBLOCK: return {"ELEMENTBLOCK"};
1009 case Ioss::EntityType::NODESET: return {"NODESET"};
1010 case Ioss::EntityType::EDGESET: return {"EDGESET"};
1011 case Ioss::EntityType::FACESET: return {"FACESET"};
1012 case Ioss::EntityType::ELEMENTSET: return {"ELEMENTSET"};
1013 case Ioss::EntityType::SIDESET: return {"SIDESET"};
1014 case Ioss::EntityType::COMMSET: return {"COMMSET"};
1015 case Ioss::EntityType::SIDEBLOCK: return {"SIDEBLOCK"};
1016 case Ioss::EntityType::REGION: return {"REGION"};
1017 case Ioss::EntityType::SUPERELEMENT: return {"SUPERELEMENT"};
1018 case Ioss::EntityType::STRUCTUREDBLOCK: return {"STRUCTUREDBLOCK"};
1019 case Ioss::EntityType::ASSEMBLY: return {"ASSEMBLY"};
1020 case Ioss::EntityType::BLOB: return {"BLOB"};
1021 case Ioss::EntityType::INVALID_TYPE: return {"INVALID_TYPE"};
1022 }
1023 return fmt::format("Invalid entity type [{}]", unsigned(type));
1024 }
1025
1026 unsigned int Ioss::Utils::hash(const std::string &name)
1027 {
1028 // Hash function from Aho, Sethi, Ullman "Compilers: Principles,
1029 // Techniques, and Tools. Page 436
1030
1031 const char *symbol = name.c_str();
1032 unsigned int hashval;
1033 for (hashval = 0; *symbol != '\0'; symbol++) {
1034 hashval = (hashval << 4) + *symbol;
1035 auto g = hashval & 0xf0000000;
1036 if (g != 0) {
1037 hashval = hashval ^ (g >> 24);
1038 hashval = hashval ^ g;
1039 }
1040 }
1041 return hashval;
1042 }
1043
1044 double Ioss::Utils::timer()
1045 {
1046 auto now = std::chrono::steady_clock::now();
1047 return std::chrono::duration<double>(now - initial_time).count();
1048 }
1049
1050 void Ioss::Utils::input_file(const std::string &file_name, Ioss::NameList *lines,
1051 size_t max_line_length)
1052 {
1053 // Create an ifstream for the input file. This does almost the same
1054 // function as sierra::Env::input() except this is for a single
1055 // processor and the sierra::Env::input() is for parallel...
1056
1057 if (!file_name.empty()) {
1058 // Open the file and read into the vector...
1059 std::string input_line;
1060 std::ifstream infile(file_name);
1061 lines->push_back(file_name.substr(0, max_line_length));
1062 while (!std::getline(infile, input_line).fail()) {
1063 if (max_line_length == 0 || input_line.length() <= max_line_length) {
1064 lines->push_back(input_line);
1065 }
1066 else {
1067 // Split the line into pieces of length "max_line_length-1"
1068 // and append a "\" to all but the last. Don't worry about
1069 // splitting at whitespace...
1070 size_t ibeg = 0;
1071 do {
1072 std::string sub = input_line.substr(ibeg, max_line_length - 1);
1073 if (ibeg + max_line_length - 1 < input_line.length()) {
1074 sub += "\\";
1075 }
1076 lines->push_back(sub);
1077 ibeg += max_line_length - 1;
1078 } while (ibeg < input_line.length());
1079 }
1080 }
1081 }
1082 }
1083
1084 bool Ioss::Utils::str_equal(const std::string &s1, const std::string &s2)
1085 {
1086 return (s1.size() == s2.size()) &&
1087 std::equal(s1.begin(), s1.end(), s2.begin(),
1088 [](char a, char b) { return std::tolower(a) == std::tolower(b); });
1089 }
1090
1091 bool Ioss::Utils::substr_equal(const std::string &prefix, const std::string &str)
1092 {
1093 return (str.size() >= prefix.size()) && str_equal(prefix, str.substr(0, prefix.size()));
1094 }
1095
1096 std::string Ioss::Utils::capitalize(std::string name)
1097 {
1098 name[0] = std::toupper(name[0]);
1099 return name;
1100 }
1101
1102 std::string Ioss::Utils::uppercase(std::string name)
1103 {
1104 std::transform(name.begin(), name.end(), name.begin(),
1105 [](char c) { return static_cast<char>(std::toupper(c)); });
1106 return name;
1107 }
1108
1109 std::string Ioss::Utils::lowercase(std::string name)
1110 {
1111 std::transform(name.begin(), name.end(), name.begin(),
1112 [](char c) { return static_cast<char>(std::tolower(c)); });
1113 return name;
1114 }
1115
1116 bool Ioss::Utils::check_set_bool_property(const Ioss::PropertyManager &properties,
1117 const std::string &prop_name, bool &prop_value)
1118 {
1119 bool found_property = false;
1120 if (properties.exists(prop_name)) {
1121 found_property = true;
1122 if (properties.get(prop_name).get_type() == Ioss::Property::INTEGER) {
1123 prop_value = properties.get(prop_name).get_int() != 0;
1124 }
1125 else {
1126 std::string yesno = Ioss::Utils::uppercase(properties.get(prop_name).get_string());
1127 if (yesno == "TRUE" || yesno == "YES" || yesno == "ON") {
1128 prop_value = true;
1129 }
1130 else if (yesno == "FALSE" || yesno == "NO" || yesno == "OFF") {
1131 prop_value = false;
1132 }
1133 else {
1134 std::ostringstream errmsg;
1135 fmt::print(errmsg,
1136 "ERROR: Unrecognized value found for {}. "
1137 "Found '{}' which is not one of TRUE|FALSE|YES|NO|ON|OFF",
1138 prop_name, yesno);
1139 IOSS_ERROR(errmsg);
1140 }
1141 }
1142 }
1143 return found_property;
1144 }
1145
1146 void Ioss::Utils::fixup_name(char *name)
1147 {
1148 assert(name != nullptr);
1149
1150 size_t len = std::strlen(name);
1151 for (size_t i = 0; i < len; i++) {
1152 name[i] = static_cast<char>(tolower(name[i])); // guaranteed(?) to be ascii...
1153 if (name[i] == ' ') {
1154 name[i] = '_';
1155 }
1156 }
1157 }
1158
1159 void Ioss::Utils::fixup_name(std::string &name)
1160 {
1161 name = Ioss::Utils::lowercase(name);
1162
1163 size_t len = name.length();
1164 for (size_t i = 0; i < len; i++) {
1165 if (name[i] == ' ') {
1166 name[i] = '_';
1167 }
1168 }
1169 }
1170
1171 namespace {
1172
1173 /** \brief Hash function from Aho, Sethi, Ullman "Compilers: Principles,
1174 * Techniques, and Tools. Page 436
1175 */
1176 std::string two_letter_hash(const char *symbol)
1177 {
1178 const int HASHSIZE = 673; // Largest prime less than 676 (26*26)
1179 unsigned int hashval;
1180 for (hashval = 0; *symbol != '\0'; symbol++) {
1181 hashval = (hashval << 4) + *symbol;
1182 unsigned int g = hashval & 0xf0000000;
1183 if (g != 0) {
1184 hashval = hashval ^ (g >> 24);
1185 hashval = hashval ^ g;
1186 }
1187 }
1188
1189 // Convert to base-26 'number'
1190 hashval %= HASHSIZE;
1191 char word[3] = {char(hashval / 26 + 'a'), char(hashval % 26 + 'a'), '\0'};
1192 return {word};
1193 }
1194 } // namespace
1195
1196 std::string Ioss::Utils::variable_name_kluge(const std::string &name, size_t component_count,
1197 size_t copies, size_t max_var_len)
1198 {
1199
1200 // Width = 'max_var_len'.
1201 // Reserve space for suffix '_00...'
1202 // Reserve 3 for hash '.xx'
1203 size_t hash_len = 3;
1204 size_t comp_len = 3; // _00
1205 size_t copy_len = 0;
1206
1207 if (copies > 1) {
1208 assert(component_count % copies == 0);
1209 component_count /= copies;
1210 }
1211
1212 if (component_count <= 1) {
1213 comp_len = 0;
1214 }
1215 else {
1216 comp_len = number_width(component_count) + 1; // _00000
1217 }
1218
1219 if (copies <= 1) {
1220 copy_len = 0;
1221 }
1222 else {
1223 copy_len = number_width(copies) + 1; // _00000
1224 }
1225
1226 size_t maxlen = max_var_len - comp_len - copy_len;
1227
1228 std::string new_str = name;
1229 if (name.length() <= maxlen) {
1230 // If name fits without kluging, then just use name as it is
1231 // without adding on the hash...
1232 return lowercase(new_str);
1233 }
1234 // Know that the name is too long, try to shorten. Need room for
1235 // hash now.
1236 maxlen -= hash_len;
1237 size_t len = name.length();
1238
1239 // Take last 'maxlen' characters. Motivation for this is that the
1240 // beginning of the composed (or generated) variable name is the
1241 // names of the mechanics and mechanics instances in which this
1242 // variable is nested, so they will be similar for all variables at
1243 // the same scope and the differences will occur at the variable
1244 // name level...
1245 //
1246 // However, there will likely be variables at the
1247 // same level but in different scope that have the same name which
1248 // would cause a clash, so we *hope* that the hash will make those
1249 // scope names unique...
1250 std::string s = std::string(name).substr(len - maxlen, len);
1251 assert(s.length() <= maxlen);
1252 new_str = std::move(s);
1253
1254 // NOTE: The hash is not added if the name is not shortened.
1255 std::string hash_string = two_letter_hash(name.c_str());
1256 new_str += std::string(".");
1257 new_str += hash_string;
1258 return lowercase(new_str);
1259 }
1260
1261 void Ioss::Utils::generate_history_mesh(Ioss::Region *region)
1262 {
1263 Ioss::DatabaseIO *db = region->get_database();
1264 if (db->parallel_rank() == 0) {
1265 region->begin_mode(Ioss::STATE_DEFINE_MODEL);
1266
1267 // Node Block
1268 auto *nb = new Ioss::NodeBlock(db, "nodeblock_1", 1, 3);
1269 region->add(nb);
1270
1271 // Element Block
1272 auto *eb = new Ioss::ElementBlock(db, "e1", "sphere", 1);
1273 eb->property_add(Ioss::Property("id", 1));
1274 eb->property_add(Ioss::Property("guid", 1));
1275 region->add(eb);
1276 region->end_mode(Ioss::STATE_DEFINE_MODEL);
1277
1278 region->begin_mode(Ioss::STATE_MODEL);
1279 static double coord[3] = {1.1, 2.2, 3.3};
1280 static int ids[1] = {1};
1281 nb->put_field_data("ids", ids, sizeof(int));
1282 nb->put_field_data("mesh_model_coordinates", coord, 3 * sizeof(double));
1283
1284 static int connect[1] = {1};
1285 eb->put_field_data("ids", ids, sizeof(int));
1286 eb->put_field_data("connectivity", connect, 1 * sizeof(int));
1287
1288 region->end_mode(Ioss::STATE_MODEL);
1289 }
1290 }
1291
1292 // Safer than strcpy -- guarantees null termination
1293 void Ioss::Utils::copy_string(char *dest, char const *source, size_t elements)
1294 {
1295 char *d;
1296 for (d = dest; d + 1 < dest + elements && *source; d++, source++) {
1297 *d = *source;
1298 }
1299 *d = '\0';
1300 }
1301
1302 namespace {
1303 const int tab64[64] = {63, 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3,
1304 61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4,
1305 62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21,
1306 56, 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5};
1307 } // namespace
1308
1309 int Ioss::Utils::log_power_2(uint64_t value)
1310 {
1311 assert(value > 0);
1312 value = (value << 1) - 1;
1313 value |= value >> 1;
1314 value |= value >> 2;
1315 value |= value >> 4;
1316 value |= value >> 8;
1317 value |= value >> 16;
1318 value |= value >> 32;
1319 return tab64[(((value - (value >> 1)) * 0x07EDD5E59A4E28C2)) >> 58];
1320 }
1321
1322 int Ioss::Utils::term_width()
1323 {
1324 int cols = 0;
1325 if (isatty(fileno(stdout))) {
1326 #if defined(TIOCGWINSZ)
1327 struct winsize ts;
1328 ioctl(STDOUT_FILENO, TIOCGWINSZ, &ts);
1329 cols = ts.ws_col;
1330 #elif TIOCGSIZE
1331 struct ttysize ts;
1332 ioctl(STDOUT_FILENO, TIOCGSIZE, &ts);
1333 cols = ts.ts_cols;
1334 #endif /* TIOCGSIZE */
1335 }
1336 return cols != 0 ? cols : 100;
1337 }
1338
1339 std::string Ioss::Utils::get_type_from_file(const std::string &filename)
1340 {
1341 Ioss::FileInfo file(filename);
1342 auto extension = file.extension();
1343
1344 // If the extension is numeric, then we are probably dealing with a single file of a
1345 // set of FPP decomposed files (e.g. file.cgns.32.17). In that case, we tokenize
1346 // with "." as delimiter and see if last two tokens are all digits and if there
1347 // are at least 4 tokens (basename.extension.#proc.proc)...
1348 bool all_dig = extension.find_first_not_of("0123456789") == std::string::npos;
1349 if (all_dig) {
1350 auto tokens = Ioss::tokenize(filename, ".");
1351 if (tokens.size() >= 4) {
1352 const auto &proc_count = tokens[tokens.size() - 2];
1353 if (proc_count.find_first_not_of("0123456789") == std::string::npos) {
1354 extension = tokens[tokens.size() - 3];
1355 }
1356 }
1357 }
1358
1359 if (extension == "e" || extension == "g" || extension == "gen" || extension == "exo") {
1360 return "exodus";
1361 }
1362 if (extension == "cgns") {
1363 return "cgns";
1364 }
1365 // "exodus" is default...
1366 return "exodus";
1367 }
1368
1369 void Ioss::Utils::info_fields(const Ioss::GroupingEntity *ige, Ioss::Field::RoleType role,
1370 const std::string &header, const std::string &suffix, bool detail)
1371 {
1372 Ioss::NameList fields = ige->field_describe(role);
1373
1374 if (fields.empty()) {
1375 return;
1376 }
1377
1378 if (!header.empty()) {
1379 fmt::print("{}{}", header, suffix);
1380 }
1381 // Iterate through results fields. Get max width of a name...
1382 size_t max_width = 0;
1383 for (const auto &field_name : fields) {
1384 max_width = std::max(max_width, field_name.length());
1385 }
1386
1387 size_t width = Ioss::Utils::term_width();
1388 size_t cur_out = 8; // Tab width...
1389 if (!header.empty()) {
1390 cur_out = header.size() + suffix.size() + 16; // Assume 2 tabs...
1391 }
1392
1393 for (const auto &field_name : fields) {
1394 if (detail) {
1395 const auto &field_ref = ige->get_fieldref(field_name);
1396 #if defined(__NVCC__)
1397 std::cout << field_ref << suffix;
1398 #else
1399 fmt::print("{}{}", field_ref, suffix);
1400 #endif
1401 }
1402 else {
1403 const Ioss::VariableType *var_type = ige->get_field(field_name).raw_storage();
1404 int comp_count = var_type->component_count();
1405 fmt::print("{1:>{0}s}:{2} ", max_width, field_name, comp_count);
1406 cur_out += max_width + 4;
1407 if (cur_out + max_width >= width) {
1408 fmt::print("{}", suffix);
1409 cur_out = 8;
1410 }
1411 }
1412 }
1413 if (!header.empty()) {
1414 fmt::print("\n");
1415 }
1416 }
1417
1418 void Ioss::Utils::info_property(const Ioss::GroupingEntity *ige, Ioss::Property::Origin origin,
1419 const std::string &header, const std::string &suffix,
1420 bool print_empty)
1421 {
1422 Ioss::NameList properties = ige->property_describe(origin);
1423
1424 if (properties.empty()) {
1425 if (print_empty && !header.empty()) {
1426 fmt::print("{}{} *** No attributes ***\n", header, suffix);
1427 }
1428 return;
1429 }
1430
1431 if (!header.empty()) {
1432 fmt::print("{}{}", header, suffix);
1433 }
1434
1435 int num_out = 0;
1436 for (const auto &property_name : properties) {
1437 fmt::print("{:>s}: ", property_name);
1438 auto prop = ige->get_property(property_name);
1439 switch (prop.get_type()) {
1440 case Ioss::Property::BasicType::REAL: fmt::print("{}\t", prop.get_real()); break;
1441 case Ioss::Property::BasicType::INTEGER: fmt::print("{}\t", prop.get_int()); break;
1442 case Ioss::Property::BasicType::STRING: fmt::print("'{}'\t", prop.get_string()); break;
1443 case Ioss::Property::BasicType::VEC_INTEGER:
1444 fmt::print("{}\t", fmt::join(prop.get_vec_int(), " "));
1445 break;
1446 case Ioss::Property::BasicType::VEC_DOUBLE:
1447 fmt::print("{}\t", fmt::join(prop.get_vec_double(), " "));
1448 break;
1449 default:; // Do nothing
1450 }
1451 num_out++;
1452 if (num_out >= 3) {
1453 fmt::print("\n\t");
1454 num_out = 0;
1455 }
1456 }
1457 if (!header.empty()) {
1458 fmt::print("\n");
1459 }
1460 }
1461
1462 void Ioss::Utils::copyright(std::ostream &out, const std::string &year_range)
1463 {
1464 fmt::print(out,
1465 "\n"
1466 "Copyright(C) {} National Technology & Engineering Solutions of\n"
1467 "Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with\n"
1468 "NTESS, the U.S. Government retains certain rights in this software.\n"
1469 "\n"
1470 "Redistribution and use in source and binary forms, with or without\n"
1471 "modification, are permitted provided that the following conditions are\n"
1472 "met:\n"
1473 "\n"
1474 "* Redistributions of source code must retain the above copyright\n"
1475 " notice, this list of conditions and the following disclaimer.\n"
1476 "\n"
1477 "* Redistributions in binary form must reproduce the above\n"
1478 " copyright notice, this list of conditions and the following\n"
1479 " disclaimer in the documentation and/or other materials provided\n"
1480 " with the distribution.\n"
1481 "\n"
1482 "* Neither the name of NTESS nor the names of its\n"
1483 " contributors may be used to endorse or promote products derived\n"
1484 " from this software without specific prior written permission.\n"
1485 "\n"
1486 "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
1487 "\" AS IS \" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
1488 "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
1489 "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
1490 "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
1491 "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
1492 "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
1493 "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
1494 "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
1495 "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
1496 "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
1497 "\n",
1498 year_range);
1499 }