Debian Codegraph @

packages/seacas/libraries/ioss/src/cgns/Iocgns_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_Assembly.h"
8 #include "Ioss_Beam2.h"
9 #include "Ioss_Beam3.h"
10 #include "Ioss_CodeTypes.h"
11 #include "Ioss_FaceGenerator.h"
12 #include "Ioss_Hex20.h"
13 #include "Ioss_Hex27.h"
14 #include "Ioss_Hex8.h"
15 #include "Ioss_IOFactory.h"
16 #include "Ioss_Node.h"
17 #include "Ioss_Pyramid13.h"
18 #include "Ioss_Pyramid14.h"
19 #include "Ioss_Pyramid5.h"
20 #include "Ioss_Quad4.h"
21 #include "Ioss_Quad8.h"
22 #include "Ioss_Quad9.h"
23 #include "Ioss_Sort.h"
24 #include "Ioss_Spring2.h"
25 #include "Ioss_Spring3.h"
26 #include "Ioss_StructuredBlock.h"
27 #include "Ioss_Tet10.h"
28 #include "Ioss_Tet4.h"
29 #include "Ioss_Tri3.h"
30 #include "Ioss_Tri6.h"
31 #include "Ioss_Unknown.h"
32 #include "Ioss_Utils.h"
33 #include "Ioss_Wedge15.h"
34 #include "Ioss_Wedge18.h"
35 #include "Ioss_Wedge6.h"
36 #include <assert.h>
37 #include <fmt/chrono.h>
38 #include <fmt/core.h>
39 #include <fmt/format.h>
40 #include <stdint.h>
41 #include <stdlib.h>
42 #if !defined __NVCC__
43 #include <fmt/color.h>
44 #endif
45 #include "cgns/Iocgns_StructuredZoneData.h"
46 #include "cgns/Iocgns_Utils.h"
47 #include <cgnsconfig.h>
48 #include <cgnstypes.h>
49 #include <cmath>
50 #include <cstring>
51 #include <ctime>
52 #include <fmt/ostream.h>
53 #include <limits>
54 #include <numeric>
55 #include <ostream>
56 #include <set>
57 #include <string>
58 #include <tokenize.h>
59
60 #include "Ioss_DatabaseIO.h"
61 #include "Ioss_ElementBlock.h"
62 #include "Ioss_ElementTopology.h"
63 #include "Ioss_EntityBlock.h"
64 #include "Ioss_EntityType.h"
65 #include "Ioss_GroupingEntity.h"
66 #include "Ioss_MeshType.h"
67 #include "Ioss_NodeBlock.h"
68 #include "Ioss_ParallelUtils.h"
69 #include "Ioss_Property.h"
70 #include "Ioss_Region.h"
71 #include "Ioss_SideBlock.h"
72 #include "Ioss_SideSet.h"
73 #include "Ioss_VariableType.h"
74 #include "Ioss_ZoneConnectivity.h"
75 #include "robin_hash.h"
76 #include "robin_set.h"
77 #if CG_BUILD_PARALLEL
78 #include <pcgnslib.h>
79 #else
80 #include <cgnslib.h>
81 #endif
82
83 #include "cgns/Iocgns_Defines.h"
84
85 #define CGERR(funcall) \
86 do { \
87 if ((funcall) != CG_OK) { \
88 Iocgns::Utils::cgns_error(file_ptr, __FILE__, __func__, __LINE__, -1); \
89 } \
90 } while (0)
91
92 namespace {
93 #if defined(__IOSS_WINDOWS__) || defined(__CYGWIN__)
94 const char *strcasestr(const char *haystack, const char *needle)
95 {
96 std::string lneedle(Ioss::Utils::lowercase(needle));
97 std::string lhaystack(Ioss::Utils::lowercase(haystack));
98
99 auto pos = lhaystack.find(lneedle);
100 return pos != std::string::npos ? haystack + pos : nullptr;
101 }
102 #endif
103
104 int power_2(int count)
105 {
106 // Return the maximum power of two which is less than or equal to 'count'
107 // count = 15 -> returns 8
108 // count = 16 -> returns 16
109 // count = 17 -> returns 16
110
111 // Use brute force...
112 int pow2 = 1;
113 while (pow2 <= count) {
114 pow2 *= 2;
115 }
116 if (pow2 > count) {
117 pow2 /= 2;
118 }
119 return pow2;
120 }
121
122 struct Range
123 {
124 Range(int a, int b) : m_beg(a < b ? a : b), m_end(a < b ? b : a), m_reversed(b < a) {}
125
126 int m_beg;
127 int m_end;
128 bool m_reversed;
129 };
130
131 bool overlaps(const Range &a, const Range &b) { return a.m_beg <= b.m_end && b.m_beg <= a.m_end; }
132
133 Range subset_range(const Range &a, const Range &b)
134 {
135 Range ret(std::max(a.m_beg, b.m_beg), std::min(a.m_end, b.m_end));
136 ret.m_reversed = a.m_reversed || b.m_reversed;
137 return ret;
138 }
139
140 void bc_subset_range(const Ioss::StructuredBlock *block, Ioss::BoundaryCondition &bc)
141 {
142 Ioss::IJK_t ordinal;
143 ordinal[0] = block->get_property("ni").get_int();
144 ordinal[1] = block->get_property("nj").get_int();
145 ordinal[2] = block->get_property("nk").get_int();
146
147 Ioss::IJK_t offset;
148 offset[0] = block->get_property("offset_i").get_int();
149 offset[1] = block->get_property("offset_j").get_int();
150 offset[2] = block->get_property("offset_k").get_int();
151
152 // NOTE: Updates the range in bc
153
154 // Note that block range is nodes and m_ordinal[] is cells, so need to add 1 to range.
155 Range z_i(1 + offset[0], ordinal[0] + offset[0] + 1);
156 Range z_j(1 + offset[1], ordinal[1] + offset[1] + 1);
157 Range z_k(1 + offset[2], ordinal[2] + offset[2] + 1);
158
159 Range gc_i(bc.m_rangeBeg[0], bc.m_rangeEnd[0]);
160 Range gc_j(bc.m_rangeBeg[1], bc.m_rangeEnd[1]);
161 Range gc_k(bc.m_rangeBeg[2], bc.m_rangeEnd[2]);
162
163 Range gc_ii = subset_range(z_i, gc_i);
164 Range gc_jj = subset_range(z_j, gc_j);
165 Range gc_kk = subset_range(z_k, gc_k);
166
167 if (overlaps(z_i, gc_i) && overlaps(z_j, gc_j) && overlaps(z_k, gc_k)) {
168 bc.m_rangeBeg[0] = gc_ii.m_reversed ? gc_ii.m_end : gc_ii.m_beg;
169 bc.m_rangeEnd[0] = gc_ii.m_reversed ? gc_ii.m_beg : gc_ii.m_end;
170 bc.m_rangeBeg[1] = gc_jj.m_reversed ? gc_jj.m_end : gc_jj.m_beg;
171 bc.m_rangeEnd[1] = gc_jj.m_reversed ? gc_jj.m_beg : gc_jj.m_end;
172 bc.m_rangeBeg[2] = gc_kk.m_reversed ? gc_kk.m_end : gc_kk.m_beg;
173 bc.m_rangeEnd[2] = gc_kk.m_reversed ? gc_kk.m_beg : gc_kk.m_end;
174 }
175 else {
176 bc.m_rangeBeg = {{0, 0, 0}};
177 bc.m_rangeEnd = {{0, 0, 0}};
178 }
179 }
180
181 int extract_trailing_int(const char *name)
182 {
183 // 'name' consists of an arbitrary number of characters followed by
184 // zero or more digits. Return the integer value of the contiguous
185 // set of trailing digits.
186 // Example: Name42 returns 42; Name_52or_perhaps_3_43 returns 43.
187
188 size_t len = std::strlen(name);
189 int val = 0;
190 int mul = 1;
191 for (size_t d = len; d > 0; d--) {
192 if (isdigit(name[d - 1])) {
193 val += mul * (name[d - 1] - '0');
194 mul *= 10;
195 }
196 else {
197 break;
198 }
199 }
200 return val;
201 }
202
203 int proc_with_minimum_work(Iocgns::StructuredZoneData *zone, const std::vector<size_t> &work,
204 std::set<std::pair<int, int>> &proc_adam_map)
205 {
206 size_t min_work = std::numeric_limits<size_t>::max();
207 int min_proc = -1;
208 for (int i = 0; i < static_cast<int>(work.size()); i++) {
209 if (work[i] < min_work &&
210 proc_adam_map.find(std::make_pair(zone->m_adam->m_zone, i)) == proc_adam_map.end()) {
211 min_work = work[i];
212 min_proc = i;
213 if (min_work == 0) {
214 break;
215 }
216 }
217 }
218 return min_proc;
219 }
220 void add_bc_to_block(Ioss::StructuredBlock *block, const std::string &boco_name,
221 const std::string &fam_name, int ibc, cgsize_t *range,
222 CGNS_ENUMT(BCType_t) bocotype, bool is_parallel_io)
223 {
224 Ioss::SideSet *sset = block->get_database()->get_region()->get_sideset(fam_name);
225 if (sset == nullptr) {
226 if (block->get_database()->parallel_rank() == 0) {
227 fmt::print(Ioss::WarnOut(),
228 "On block '{}', found the boundary condition named '{}' in family '{}'.\n"
229 " This family was not previously defined at the top-level of the file"
230 " which is not normal.\n"
231 " Check your file to make sure this does not "
232 "indicate a problem with the mesh.\n",
233 block->name(), boco_name, fam_name);
234 }
235
236 // Need to create a new sideset since didn't see this earlier.
237 auto *db = block->get_database();
238 sset = new Ioss::SideSet(db, fam_name);
239
240 // Get all previous sidesets to make sure we set a unique id...
241 int64_t max_id = 0;
242 const auto &sidesets = db->get_region()->get_sidesets();
243 for (const auto &ss : sidesets) {
244 if (ss->property_exists("id")) {
245 auto id = ss->get_property("id").get_int();
246 max_id = (id > max_id) ? id : max_id;
247 }
248 }
249 sset->property_add(Ioss::Property("id", max_id + 10));
250 sset->property_add(Ioss::Property("guid", db->util().generate_guid(max_id + 10)));
251 db->get_region()->add(sset);
252 }
253
254 assert(sset != nullptr);
255
256 Ioss::IJK_t range_beg{{(int)std::min(range[0], range[3]), (int)std::min(range[1], range[4]),
257 (int)std::min(range[2], range[5])}};
258
259 Ioss::IJK_t range_end{{(int)std::max(range[0], range[3]), (int)std::max(range[1], range[4]),
260 (int)std::max(range[2], range[5])}};
261
262 // Determine overlap of surface with block (in parallel, a block may
263 // be split among multiple processors and the block face this is applied
264 // to may not exist on this decomposed block)
265 auto bc = Ioss::BoundaryCondition(boco_name, fam_name, range_beg, range_end);
266 std::string name = std::string(boco_name) + "/" + block->name();
267
268 bc_subset_range(block, bc);
269 if (!is_parallel_io && !bc.is_valid()) {
270 bc.m_rangeBeg = {{0, 0, 0}};
271 bc.m_rangeEnd = {{0, 0, 0}};
272 }
273 block->m_boundaryConditions.push_back(bc);
274 auto sb = new Ioss::SideBlock(block->get_database(), name, Ioss::Quad4::name, Ioss::Hex8::name,
275 block->m_boundaryConditions.back().get_face_count());
276 sb->set_parent_block(block);
277 sset->add(sb);
278
279 int base = block->get_property("base").get_int();
280 int zone = block->get_property("zone").get_int();
281 sb->property_add(Ioss::Property("base", base));
282 sb->property_add(Ioss::Property("zone", zone));
283 sb->property_add(Ioss::Property("section", ibc + 1));
284 sb->property_add(Ioss::Property("id", sset->get_property("id").get_int()));
285 sb->property_add(Ioss::Property(
286 "guid", block->get_database()->util().generate_guid(sset->get_property("id").get_int())));
287
288 // Set a property on the sideset specifying the boundary condition type (bocotype)
289 // In CGNS, the bocotype is an enum; we store it as the integer value of the enum.
290 if (sset->property_exists("bc_type")) {
291 // Check that the 'bocotype' value matches the value of the property.
292 auto old_bocotype = sset->get_property("bc_type").get_int();
293 if (old_bocotype != bocotype && bocotype != CGNS_ENUMV(FamilySpecified)) {
294 fmt::print(Ioss::WarnOut(),
295 "On sideset '{}', the boundary condition type was previously set to {}"
296 " which does not match the current value of {}. It will keep the old value.\n",
297 sset->name(), old_bocotype, static_cast<int>(bocotype));
298 }
299 }
300 else {
301 sset->property_add(Ioss::Property("bc_type", (int)bocotype));
302 }
303 }
304
305 void sync_transient_variables_fpp(Ioss::Region *region)
306 {
307 // With an fpp read, certain blocks may only be on certain
308 // processors -- This consistency is addressed elsewhere; however,
309 // if a block is not on a processor, then that block will not have
310 // any transient fields. Need to sync across all processors such
311 // that a block has the same fields on all processors.
312 //
313 // ASSUME: A block will have the same fields in the same order on
314 // all processors on which it exists.
315 //
316 // Do the gather all metadata to proc 0; consolidate and then
317 // broadcast back...
318 // Need: 'name' and 'VariableType'. Assume all are double and the
319 // size will be processor dependent.
320 auto &sblocks = region->get_structured_blocks();
321 std::vector<int> fld_count;
322 fld_count.reserve(2 * sblocks.size());
323 for (const auto &block : sblocks) {
324 fld_count.push_back(block->field_count(Ioss::Field::TRANSIENT));
325 const auto &nb = block->get_node_block();
326 fld_count.push_back(nb.field_count(Ioss::Field::TRANSIENT));
327 }
328 auto par = region->get_database()->util();
329 par.global_array_minmax(fld_count, Ioss::ParallelUtils::DO_MAX);
330
331 // Determine total number of fields on all blocks...
332 int tot_fld = std::accumulate(fld_count.begin(), fld_count.end(), 0);
333 // Assuming fields are the same on all processors that have fields...
334 std::vector<char> fld_names(tot_fld * 2 * (CGNS_MAX_NAME_LENGTH + 1), 0);
335
336 size_t offset = 0;
337 for (size_t i = 0; i < sblocks.size(); i++) {
338 const auto &block = sblocks[i];
339 Ioss::NameList fields = block->field_describe(Ioss::Field::TRANSIENT);
340 if (!fields.empty()) {
341 for (const auto &field_name : fields) {
342 const Ioss::Field &field = block->get_fieldref(field_name);
343 std::string type = field.raw_storage()->name();
344 Ioss::Utils::copy_string(&fld_names[offset], field_name, CGNS_MAX_NAME_LENGTH + 1);
345 offset += CGNS_MAX_NAME_LENGTH + 1;
346 Ioss::Utils::copy_string(&fld_names[offset], type, CGNS_MAX_NAME_LENGTH + 1);
347 offset += CGNS_MAX_NAME_LENGTH + 1;
348 }
349 }
350 else {
351 offset += (CGNS_MAX_NAME_LENGTH + 1) * 2 * fld_count[2 * i];
352 }
353 const auto &nb = block->get_node_block();
354 Ioss::NameList node_fields = nb.field_describe(Ioss::Field::TRANSIENT);
355 if (!node_fields.empty()) {
356 for (const auto &field_name : node_fields) {
357 const Ioss::Field &field = nb.get_fieldref(field_name);
358 std::string type = field.raw_storage()->name();
359 Ioss::Utils::copy_string(&fld_names[offset], field_name, CGNS_MAX_NAME_LENGTH + 1);
360 offset += CGNS_MAX_NAME_LENGTH + 1;
361 Ioss::Utils::copy_string(&fld_names[offset], type, CGNS_MAX_NAME_LENGTH + 1);
362 offset += CGNS_MAX_NAME_LENGTH + 1;
363 }
364 }
365 else {
366 offset += (CGNS_MAX_NAME_LENGTH + 1) * 2 * fld_count[2 * i + 1];
367 }
368 }
369
370 par.global_array_minmax(fld_names, Ioss::ParallelUtils::DO_MAX);
371
372 // Each processor now should have a consistent list of the field
373 // names. Now need to add the missing fields to the blocks that
374 // are not 'native' to this processor...
375 //
376 offset = 0;
377 for (size_t i = 0; i < sblocks.size(); i++) {
378 auto &block = sblocks[i];
379 if (block->field_count(Ioss::Field::TRANSIENT) != (size_t)fld_count[2 * i]) {
380 // Verify that either has 0 or correct number of fields...
381 assert(block->field_count(Ioss::Field::TRANSIENT) == 0);
382
383 // Extract the field name and storage type...
384 for (int nf = 0; nf < fld_count[2 * i]; nf++) {
385 std::string fld_name(&fld_names[offset]);
386 offset += CGNS_MAX_NAME_LENGTH + 1;
387 std::string fld_type(&fld_names[offset]);
388 offset += CGNS_MAX_NAME_LENGTH + 1;
389
390 block->field_add(Ioss::Field(std::move(fld_name), Ioss::Field::DOUBLE, fld_type,
391 Ioss::Field::TRANSIENT, 0));
392 }
393 }
394 else {
395 offset += (CGNS_MAX_NAME_LENGTH + 1) * 2 * fld_count[2 * i];
396 }
397 assert(block->field_count(Ioss::Field::TRANSIENT) == (size_t)fld_count[2 * i]);
398
399 auto &nb = block->get_node_block();
400 if (nb.field_count(Ioss::Field::TRANSIENT) != (size_t)fld_count[2 * i + 1]) {
401 // Verify that either has 0 or correct number of fields...
402 assert(nb.field_count(Ioss::Field::TRANSIENT) == 0);
403
404 // Extract the field name and storage type...
405 for (int nf = 0; nf < fld_count[2 * i + 1]; nf++) {
406 std::string fld_name(&fld_names[offset]);
407 offset += CGNS_MAX_NAME_LENGTH + 1;
408 std::string fld_type(&fld_names[offset]);
409 offset += CGNS_MAX_NAME_LENGTH + 1;
410
411 nb.field_add(
412 Ioss::Field(fld_name, Ioss::Field::DOUBLE, fld_type, Ioss::Field::TRANSIENT, 0));
413 }
414 }
415 else {
416 offset += (CGNS_MAX_NAME_LENGTH + 1) * 2 * fld_count[2 * i + 1];
417 }
418 assert(nb.field_count(Ioss::Field::TRANSIENT) == (size_t)fld_count[2 * i + 1]);
419 }
420 }
421
422 #if IOSS_DEBUG_OUTPUT
423 void output_table(const Ioss::ElementBlockContainer &ebs,
424 std::map<std::string, Ioss::FaceUnorderedSet> &boundary_faces)
425 {
426 // Get maximum name and face_count length...
427 size_t max_name = std::string("Block Name").length();
428 size_t max_face = std::string("Face Count").length();
429 for (auto &eb : ebs) {
430 const std::string &name = eb->name();
431 max_name = std::max(name.length(), max_name);
432 size_t face_width = Ioss::Utils::number_width(boundary_faces[name].size());
433 max_face = std::max(face_width, max_face);
434 }
435 max_name += 4; // Padding
436 max_face += 4;
437
438 fmt::print("\t+{2:-^{0}}+{2:-^{1}}+\n", max_name, max_face, "");
439 fmt::print("\t|{2:^{0}}|{3:^{1}}|\n", max_name, max_face, "Block Name", "Face Count");
440 fmt::print("\t+{2:-^{0}}+{2:-^{1}}+\n", max_name, max_face, "");
441 for (auto &eb : ebs) {
442 const std::string &name = eb->name();
443 fmt::print("\t|{2:^{0}}|{3:{1}} |\n", max_name, max_face - 2, name,
444 fmt::group_digits(boundary_faces[name].size()));
445 }
446 fmt::print("\t+{2:-^{0}}+{2:-^{1}}+\n", max_name, max_face, "");
447 }
448 #endif
449
450 } // namespace
451
452 std::pair<std::string, int> Iocgns::Utils::decompose_name(const std::string &name, bool is_parallel)
453 {
454 int proc = is_parallel ? -1 : 0;
455 std::string zname{name};
456
457 if (is_parallel) {
458 // Name should/might be of the form `basename_proc-#`. Strip
459 // off the `_proc-#` portion and return just the basename.
460 auto tokens = Ioss::tokenize(zname, "_");
461 zname = tokens[0];
462 if (tokens.size() >= 2) {
463 size_t idx = tokens.size() - 1;
464 if (tokens[idx].substr(0, 5) == "proc-") {
465 auto ptoken = Ioss::tokenize(tokens[idx], "-");
466 proc = std::stoi(ptoken[1]);
467 idx--;
468 zname = tokens[idx];
469 }
470 }
471 }
472 return std::make_pair(zname, proc);
473 }
474
475 std::string Iocgns::Utils::decompose_sb_name(const std::string &name)
476 {
477 std::string zname{name};
478
479 // Name should/might be of the form `zonename/sb_name`. Extract
480 // the 'sb_name' and return that
481 auto tokens = Ioss::tokenize(zname, "/");
482 if (tokens.size() >= 2) {
483 zname = tokens.back();
484 }
485 return zname;
486 }
487
488 void Iocgns::Utils::cgns_error(int cgnsid, const char *file, const char *function, int lineno,
489 int processor)
490 {
491 std::ostringstream errmsg;
492 fmt::print(errmsg, "CGNS error '{}' at line {} in file '{}' in function '{}'", cg_get_error(),
493 lineno, file, function);
494 if (processor >= 0) {
495 fmt::print(errmsg, " on processor {}", processor);
496 }
497 fmt::print(errmsg, ". Please report to [email protected] if you need help.");
498 if (cgnsid > 0) {
499 #if CG_BUILD_PARALLEL
500 // This can cause a hang if not all processors call this routine
501 // and then the error is not output...
502 // cgp_close(cgnsid);
503 #else
504 cg_close(cgnsid);
505 #endif
506 }
507 IOSS_ERROR(errmsg);
508 }
509
510 Ioss::MeshType Iocgns::Utils::check_mesh_type(int cgns_file_ptr)
511 {
512 // ========================================================================
513 // Get the number of zones (element/structured blocks) in the mesh...
514 int base = 1;
515 int num_zones = 0;
516 CGCHECKNP(cg_nzones(cgns_file_ptr, base, &num_zones));
517
518 CGNS_ENUMT(ZoneType_t) common_zone_type = CGNS_ENUMV(ZoneTypeNull);
519
520 for (int zone = 1; zone <= num_zones; zone++) {
521 CGNS_ENUMT(ZoneType_t) zone_type;
522 CGCHECKNP(cg_zone_type(cgns_file_ptr, base, zone, &zone_type));
523
524 if (common_zone_type == CGNS_ENUMV(ZoneTypeNull)) {
525 common_zone_type = zone_type;
526 }
527
528 if (common_zone_type != zone_type) {
529 #if IOSS_ENABLE_HYBRID
530 common_zone_type = CGNS_ENUMV(ZoneTypeUserDefined); // This is how we represent hybrid...
531 break;
532 #else
533 IOSS_ERROR(fmt::format("ERROR: CGNS: Zone {} is not the same zone type as previous zones."
534 " This is currently not allowed or supported (hybrid mesh).",
535 zone));
536 #endif
537 }
538 }
539
540 switch (common_zone_type) {
541 case CGNS_ENUMV(ZoneTypeUserDefined): return Ioss::MeshType::HYBRID;
542 case CGNS_ENUMV(Structured): return Ioss::MeshType::STRUCTURED;
543 case CGNS_ENUMV(Unstructured): return Ioss::MeshType::UNSTRUCTURED;
544 default: return Ioss::MeshType::UNKNOWN;
545 }
546 }
547
548 void Iocgns::Utils::update_db_zone_property(int cgns_file_ptr, const Ioss::Region *region,
549 int myProcessor, bool is_parallel, bool is_parallel_io)
550 {
551 // If an output file is closed/opened, make sure that the zones in the Region
552 // match the zones on the database (file). CGNS likes to sort the zones, so they
553 // might be in a different order after reopening. Update the 'db_zone_id' property...
554 int num_zones = 0;
555 int base = 1;
556 CGCHECK(cg_nzones(cgns_file_ptr, base, &num_zones));
557
558 // Read each zone and put names in a map indexed by zone id.
559 // Then iterate all of the region's structured blocks and element blocks
560 // and make sure that the zone exists in the map and then update the 'db_zone'
561 std::map<std::string, int> zones;
562
563 for (int zone = 1; zone <= num_zones; zone++) {
564 cgsize_t size[9];
565 char zname[CGNS_MAX_NAME_LENGTH + 1];
566 CGCHECK(cg_zone_read(cgns_file_ptr, base, zone, zname, size));
567 auto name_proc = decompose_name(std::string(zname), is_parallel && !is_parallel_io);
568 zones[name_proc.first] = zone;
569 }
570
571 const auto &sblocks = region->get_structured_blocks();
572 for (const auto &block : sblocks) {
573 if (is_parallel_io || block->is_active()) {
574 const std::string &name = block->name();
575 auto iter = zones.find(name);
576 if (iter != zones.end()) {
577 auto db_zone = (*iter).second;
578 block->property_update("db_zone", db_zone);
579 }
580 else {
581 IOSS_ERROR(
582 fmt::format("ERROR: CGNS: Structured Block '{}' was not found on the CGNS database on "
583 "processor {}.",
584 name, myProcessor));
585 }
586 }
587 }
588
589 const auto &eblocks = region->get_element_blocks();
590 for (const auto &block : eblocks) {
591 const std::string &name = block->name();
592 auto iter = zones.find(name);
593 if (iter != zones.end()) {
594 auto db_zone = (*iter).second;
595 block->property_update("db_zone", db_zone);
596 }
597 else {
598 IOSS_ERROR(fmt::format(
599 "ERROR: CGNS: Element Block '{}' was not found on the CGNS database on processor {}.",
600 name, myProcessor));
601 }
602 }
603 }
604
605 int Iocgns::Utils::get_db_zone(const Ioss::GroupingEntity *entity)
606 {
607 // Returns the zone of the entity as it appears on the cgns database.
608 // Usually, but not always the same as the IOSS zone...
609 // Can differ on fpp reads and maybe writes.
610 if (entity->property_exists("db_zone")) {
611 return entity->get_property("db_zone").get_int();
612 }
613 if (entity->property_exists("zone")) {
614 return entity->get_property("zone").get_int();
615 }
616 IOSS_ERROR(fmt::format(
617 "ERROR: CGNS: Entity '{}' of type '{}' does not have the 'zone' property assigned.",
618 entity->name(), entity->type_string()));
619 }
620
621 namespace {
622 const size_t CG_CELL_CENTER_FIELD_ID = 1ul << 30;
623 const size_t CG_VERTEX_FIELD_ID = 1ul << 31;
624 } // namespace
625
626 size_t Iocgns::Utils::index(const Ioss::Field &field) { return field.get_index() & 0x00ffffff; }
627
628 void Iocgns::Utils::set_field_index(const Ioss::Field &field, size_t index,
629 CGNS_ENUMT(GridLocation_t) location)
630 {
631 if (location == CGNS_ENUMV(CellCenter)) {
632 index |= CG_CELL_CENTER_FIELD_ID;
633 }
634 if (location == CGNS_ENUMV(Vertex)) {
635 index |= CG_VERTEX_FIELD_ID;
636 }
637 field.set_index(index);
638 }
639
640 bool Iocgns::Utils::is_cell_field(const Ioss::Field &field)
641 {
642 size_t index = field.get_index();
643 if (index & CG_VERTEX_FIELD_ID) {
644 return false;
645 }
646 if (index & CG_CELL_CENTER_FIELD_ID) {
647 return true;
648 }
649 return !(field.get_name() == "mesh_model_coordinates" ||
650 field.get_name() == "mesh_model_coordinates_x" ||
651 field.get_name() == "mesh_model_coordinates_y" ||
652 field.get_name() == "mesh_model_coordinates_z" ||
653 field.get_name() == "cell_node_ids"); // Default to cell field...
654 }
655
656 namespace {
657 #if CG_BUILD_PARALLEL
658 void union_zgc_range(Ioss::ZoneConnectivity &zgc_i, const Ioss::ZoneConnectivity &zgc_j)
659 {
660 assert(zgc_i.m_transform == zgc_j.m_transform);
661 for (int i = 0; i < 3; i++) {
662 if (zgc_i.m_ownerRangeBeg[i] <= zgc_i.m_ownerRangeEnd[i]) {
663 zgc_i.m_ownerRangeBeg[i] = std::min(zgc_i.m_ownerRangeBeg[i], zgc_j.m_ownerRangeBeg[i]);
664 zgc_i.m_ownerRangeEnd[i] = std::max(zgc_i.m_ownerRangeEnd[i], zgc_j.m_ownerRangeEnd[i]);
665 }
666 else {
667 zgc_i.m_ownerRangeBeg[i] = std::max(zgc_i.m_ownerRangeBeg[i], zgc_j.m_ownerRangeBeg[i]);
668 zgc_i.m_ownerRangeEnd[i] = std::min(zgc_i.m_ownerRangeEnd[i], zgc_j.m_ownerRangeEnd[i]);
669 }
670
671 if (zgc_i.m_donorRangeBeg[i] <= zgc_i.m_donorRangeEnd[i]) {
672 zgc_i.m_donorRangeBeg[i] = std::min(zgc_i.m_donorRangeBeg[i], zgc_j.m_donorRangeBeg[i]);
673 zgc_i.m_donorRangeEnd[i] = std::max(zgc_i.m_donorRangeEnd[i], zgc_j.m_donorRangeEnd[i]);
674 }
675 else {
676 zgc_i.m_donorRangeBeg[i] = std::max(zgc_i.m_donorRangeBeg[i], zgc_j.m_donorRangeBeg[i]);
677 zgc_i.m_donorRangeEnd[i] = std::min(zgc_i.m_donorRangeEnd[i], zgc_j.m_donorRangeEnd[i]);
678 }
679 }
680 }
681 #endif
682
683 void consolidate_zgc(IOSS_MAYBE_UNUSED const Ioss::Region &region)
684 {
685 // In parallel, the zgc are not necessarily consistent across processors...
686 // and the owner/donor ranges are processor specific.
687 // Need to make sure all processors have a consistent list of zgc and the
688 // owner/donor ranges contain the union of the ranges on each
689 // processor.
690 // ...Could do this on a per sb basis, but better to do all at once...
691 // Data:
692 // CGNS_MAX_NAME_LENGTH - connectionName -- CGNS_MAX_NAME_LENGTH char max
693 // 1 - int zone
694 // 1 - int donor_zone -- get by mapping donorName to zone
695 // 6 cgsize_t[6] ownerRange (can probably use 32-bit int...)
696 // 6 cgsize_t[6] donorRange (can probably use 32-bit int...)
697 // 3 int[3] transform; (values range from -3 to +3 (could store as single int)
698 // CGNS_MAX_NAME_LENGTH characters + 17 ints / connection.
699
700 IOSS_PAR_UNUSED(region);
701 #if CG_BUILD_PARALLEL
702 const int BYTE_PER_NAME = CGNS_MAX_NAME_LENGTH;
703 const int INT_PER_ZGC = 17;
704 // Gather all to processor 0, consolidate, and then scatter back...
705 int my_count = 0;
706 const auto &structured_blocks = region.get_structured_blocks();
707 for (const auto &sb : structured_blocks) {
708 my_count += std::count_if(
709 sb->m_zoneConnectivity.begin(), sb->m_zoneConnectivity.end(),
710 [](const Ioss::ZoneConnectivity &z) { return !z.is_from_decomp() && z.is_active(); });
711 }
712
713 std::vector<int> rcv_data_cnt;
714 region.get_database()->util().all_gather(
715 my_count, rcv_data_cnt); // Allgather instead of gather so can bail if count=0
716 int count = std::accumulate(rcv_data_cnt.begin(), rcv_data_cnt.end(), 0);
717 if (count == 0) {
718 for (auto &sb : structured_blocks) {
719 sb->m_zoneConnectivity.clear();
720 }
721 return;
722 }
723
724 std::vector<char> snd_zgc_name(my_count * BYTE_PER_NAME);
725 std::vector<int> snd_zgc_data(my_count * INT_PER_ZGC);
726
727 // Pack data for gathering to processor 0...
728 int off_name = 0;
729 int off_data = 0;
730 int off_cnt = 0;
731
732 // ========================================================================
733 auto pack_lambda = [&off_data, &off_name, &off_cnt, &snd_zgc_data,
734 &snd_zgc_name](const std::vector<Ioss::ZoneConnectivity> &zgc) {
735 for (const auto &z : zgc) {
736 if (!z.is_from_decomp() && z.is_active()) {
737 Ioss::Utils::copy_string(&snd_zgc_name[off_name], z.m_connectionName, BYTE_PER_NAME);
738 off_cnt++;
739 off_name += BYTE_PER_NAME;
740
741 snd_zgc_data[off_data++] = z.m_ownerZone;
742 snd_zgc_data[off_data++] = z.m_donorZone;
743
744 snd_zgc_data[off_data++] = z.m_ownerRangeBeg[0];
745 snd_zgc_data[off_data++] = z.m_ownerRangeBeg[1];
746 snd_zgc_data[off_data++] = z.m_ownerRangeBeg[2];
747 snd_zgc_data[off_data++] = z.m_ownerRangeEnd[0];
748 snd_zgc_data[off_data++] = z.m_ownerRangeEnd[1];
749 snd_zgc_data[off_data++] = z.m_ownerRangeEnd[2];
750
751 snd_zgc_data[off_data++] = z.m_donorRangeBeg[0];
752 snd_zgc_data[off_data++] = z.m_donorRangeBeg[1];
753 snd_zgc_data[off_data++] = z.m_donorRangeBeg[2];
754 snd_zgc_data[off_data++] = z.m_donorRangeEnd[0];
755 snd_zgc_data[off_data++] = z.m_donorRangeEnd[1];
756 snd_zgc_data[off_data++] = z.m_donorRangeEnd[2];
757
758 snd_zgc_data[off_data++] = z.m_transform[0];
759 snd_zgc_data[off_data++] = z.m_transform[1];
760 snd_zgc_data[off_data++] = z.m_transform[2];
761 }
762 }
763 };
764 // ========================================================================
765
766 off_data = off_name = off_cnt = 0;
767 for (const auto &sb : structured_blocks) {
768 pack_lambda(sb->m_zoneConnectivity);
769 }
770 assert(off_cnt == my_count);
771 assert(my_count == 0 || (off_data % my_count == 0));
772 assert(my_count == 0 || (off_data / my_count == INT_PER_ZGC));
773 assert(my_count == 0 || (off_name % my_count == 0 && off_name / my_count == BYTE_PER_NAME));
774
775 std::vector<char> rcv_zgc_name;
776 std::vector<int> rcv_zgc_data;
777 region.get_database()->util().gather(my_count, BYTE_PER_NAME, snd_zgc_name, rcv_zgc_name);
778 region.get_database()->util().gather(my_count, INT_PER_ZGC, snd_zgc_data, rcv_zgc_data);
779
780 // Processor 0 now has all the zgc instances from all blocks on all processors.
781 std::vector<Ioss::ZoneConnectivity> zgc;
782 if (region.get_database()->util().parallel_rank() == 0) {
783 zgc.reserve(count);
784
785 // Unpack data...
786 off_data = 0;
787 off_name = 0;
788 for (int i = 0; i < count; i++) {
789 std::string name{&rcv_zgc_name[off_name]};
790 off_name += BYTE_PER_NAME;
791 int zone = rcv_zgc_data[off_data++];
792 int donor = rcv_zgc_data[off_data++];
793 Ioss::IJK_t range_beg{
794 {rcv_zgc_data[off_data++], rcv_zgc_data[off_data++], rcv_zgc_data[off_data++]}};
795 Ioss::IJK_t range_end{
796 {rcv_zgc_data[off_data++], rcv_zgc_data[off_data++], rcv_zgc_data[off_data++]}};
797 Ioss::IJK_t donor_beg{
798 {rcv_zgc_data[off_data++], rcv_zgc_data[off_data++], rcv_zgc_data[off_data++]}};
799 Ioss::IJK_t donor_end{
800 {rcv_zgc_data[off_data++], rcv_zgc_data[off_data++], rcv_zgc_data[off_data++]}};
801 Ioss::IJK_t transform{
802 {rcv_zgc_data[off_data++], rcv_zgc_data[off_data++], rcv_zgc_data[off_data++]}};
803 zgc.emplace_back(name, zone, "", donor, transform, range_beg, range_end, donor_beg,
804 donor_end);
805 }
806 assert(off_data % count == 0);
807 assert(off_data / count == INT_PER_ZGC);
808 assert(off_name % count == 0 && off_name / count == BYTE_PER_NAME);
809
810 #if IOSS_DEBUG_OUTPUT
811 fmt::print(Ioss::DebugOut(), "ZGC_CONSOLIDATE: Before consolidation: ({})\n", zgc.size());
812 for (const auto &z : zgc) {
813 fmt::print(Ioss::DebugOut(), "\tOZ {}{}\n", z.m_ownerZone, z);
814 }
815 #endif
816
817 // Consolidate down to the minimum set that has the union of all ranges.
818 for (size_t i = 0; i < zgc.size(); i++) {
819 if (zgc[i].is_active()) {
820 auto owner_zone = zgc[i].m_ownerZone;
821 auto donor_zone = zgc[i].m_donorZone;
822
823 for (size_t j = i + 1; j < zgc.size(); j++) {
824 if (zgc[j].is_active() && zgc[j].m_connectionName == zgc[i].m_connectionName &&
825 zgc[j].m_ownerZone == owner_zone) {
826 if (zgc[j].m_donorZone == donor_zone) {
827 // Found another instance of the "same" zgc... Union the ranges
828 union_zgc_range(zgc[i], zgc[j]);
829 assert(zgc[i].is_valid());
830
831 // Flag the 'j' instance so it is processed only this time.
832 zgc[j].m_isActive = false;
833 }
834 else {
835 // We have a bad zgc -- name and owner_zone match, but not donor_zone.
836 IOSS_ERROR(fmt::format(
837 "ERROR: CGNS: Found zgc named '{}' on zone {} which has two different "
838 "donor zones: {} and {}\n",
839 zgc[i].m_connectionName, owner_zone, donor_zone, zgc[j].m_donorZone));
840 }
841 }
842 }
843 }
844 }
845
846 // Cull out all 'non-active' zgc instances (owner and donor zone <= 0)
847 zgc.erase(std::remove_if(zgc.begin(), zgc.end(),
848 [](Ioss::ZoneConnectivity &z) { return !z.is_active(); }),
849 zgc.end());
850
851 count = (int)zgc.size();
852 snd_zgc_name.resize(count * BYTE_PER_NAME);
853 snd_zgc_data.resize(count * INT_PER_ZGC);
854 // Now have a unique set of zgc over all processors with a union
855 // of the ranges on each individual processor. Pack the data
856 // and broadcast back to all processors so all processors can
857 // output the same data for Zone Connectivity.
858 off_data = off_name = off_cnt = 0;
859 pack_lambda(zgc);
860
861 assert(off_cnt == count);
862 assert(off_data % count == 0);
863 assert(off_data / count == INT_PER_ZGC);
864 assert(off_name % count == 0 && off_name / count == BYTE_PER_NAME);
865
866 #if IOSS_DEBUG_OUTPUT
867 fmt::print(Ioss::DebugOut(), "ZGC_CONSOLIDATE: After consolidation: ({})\n", zgc.size());
868 for (const auto &z : zgc) {
869 fmt::print(Ioss::DebugOut(), "\tOZ {}{}\n", z.m_ownerZone, z);
870 }
871 #endif
872 } // End of processor 0 only processing...
873
874 // Send the list of unique zgc instances to all processors so they can all output.
875 region.get_database()->util().broadcast(count);
876 snd_zgc_name.resize(count * BYTE_PER_NAME);
877 snd_zgc_data.resize(count * INT_PER_ZGC);
878 region.get_database()->util().broadcast(snd_zgc_name);
879 region.get_database()->util().broadcast(snd_zgc_data);
880
881 // Now clean out existing ZGC lists for all blocks and add on the consolidated instances.
882 // Also create a vector for mapping from zone to sb name.
883 Ioss::NameList sb_names(structured_blocks.size() + 1);
884 for (auto &sb : structured_blocks) {
885 sb->m_zoneConnectivity.clear();
886 auto zone = sb->get_property("zone").get_int();
887 assert(zone < (int)sb_names.size());
888 sb_names[zone] = sb->name();
889 }
890
891 // Unpack data and apply to the correct structured block.
892 off_data = 0;
893 off_name = 0;
894 for (int i = 0; i < count; i++) {
895 std::string name{&snd_zgc_name[off_name]};
896 off_name += BYTE_PER_NAME;
897 int zone = snd_zgc_data[off_data++];
898 assert(zone < (int)sb_names.size());
899 int donor = snd_zgc_data[off_data++];
900 assert(donor < (int)sb_names.size());
901 Ioss::IJK_t range_beg{
902 {snd_zgc_data[off_data++], snd_zgc_data[off_data++], snd_zgc_data[off_data++]}};
903 Ioss::IJK_t range_end{
904 {snd_zgc_data[off_data++], snd_zgc_data[off_data++], snd_zgc_data[off_data++]}};
905 Ioss::IJK_t donor_beg{
906 {snd_zgc_data[off_data++], snd_zgc_data[off_data++], snd_zgc_data[off_data++]}};
907 Ioss::IJK_t donor_end{
908 {snd_zgc_data[off_data++], snd_zgc_data[off_data++], snd_zgc_data[off_data++]}};
909 Ioss::IJK_t transform{
910 {snd_zgc_data[off_data++], snd_zgc_data[off_data++], snd_zgc_data[off_data++]}};
911
912 auto sb = structured_blocks[zone - 1];
913 assert(sb->get_property("zone").get_int() == zone);
914 sb->m_zoneConnectivity.emplace_back(name, zone, sb_names[donor], donor, transform, range_beg,
915 range_end, donor_beg, donor_end);
916 }
917 #endif
918 }
919 } // namespace
920
921 void Iocgns::Utils::output_assembly(int file_ptr, const Ioss::Assembly *assembly,
922 bool is_parallel_io, bool appending)
923 {
924 int base = 1;
925 int fam = 0;
926 CGERR(cg_family_write(file_ptr, base, assembly->name().c_str(), &fam));
927
928 int64_t id = assembly->get_optional_property("id", 0);
929 CGERR(cg_goto(file_ptr, base, "Family_t", fam, nullptr));
930 CGERR(cg_descriptor_write("FamVC_TypeId", "0"));
931 CGERR(cg_descriptor_write("FamVC_TypeName", "Unspecified"));
932 CGERR(cg_descriptor_write("FamVC_UserId", std::to_string(id).c_str()));
933 CGERR(cg_descriptor_write("FamVC_UserName", assembly->name().c_str()));
934
935 const auto &members = assembly->get_members();
936 // Now, iterate the members of the assembly and add the reference to the structured block
937 if (assembly->get_member_type() == Ioss::STRUCTUREDBLOCK) {
938 for (const auto &mem : members) {
939 base = mem->get_property("base").get_int();
940 const auto *sb = dynamic_cast<const Ioss::StructuredBlock *>(mem);
941 Ioss::Utils::check_dynamic_cast(sb);
942 if (is_parallel_io || sb->is_active()) {
943 int db_zone = get_db_zone(sb);
944 if (cg_goto(file_ptr, base, "Zone_t", db_zone, "end") == CG_OK) {
945 CGERR(cg_famname_write(assembly->name().c_str()));
946 }
947 }
948 }
949 }
950 else if (assembly->get_member_type() == Ioss::ELEMENTBLOCK) {
951 for (const auto &mem : members) {
952 if (appending) {
953 // Modifying an existing database so the element blocks
954 // should exist on the output database...
955 int db_zone = get_db_zone(mem);
956 if (cg_goto(file_ptr, base, "Zone_t", db_zone, "end") == CG_OK) {
957 CGERR(cg_famname_write(assembly->name().c_str()));
958 }
959 }
960 else {
961 // The element blocks have not yet been output. To make
962 // it easier when they are written, add a property that
963 // specifies what assembly they are in. Currently, the way
964 // CGNS represents assemblies limits membership to at most one
965 // assembly.
966 auto *new_mem = const_cast<Ioss::GroupingEntity *>(mem);
967 new_mem->property_add(Ioss::Property("assembly", assembly->name()));
968 }
969 }
970 }
971 }
972
973 void Iocgns::Utils::output_assemblies(int file_ptr, const Ioss::Region &region, bool is_parallel_io)
974 {
975 region.get_database()->progress("\tOutput Assemblies");
976 const auto &assemblies = region.get_assemblies();
977 for (const auto &assem : assemblies) {
978 output_assembly(file_ptr, assem, is_parallel_io);
979 }
980 }
981 void Iocgns::Utils::write_state_meta_data(int file_ptr, const Ioss::Region &region,
982 bool is_parallel_io)
983 {
984 // Write the metadata to the state file...
985 // Not everything is needed, we just need the zones output so we can put the FlowSolutionPointers
986 // node under the Zone nodes.
987 int base = 0;
988 int phys_dimension = region.get_property("spatial_dimension").get_int();
989 CGERR(cg_base_write(file_ptr, "Base", phys_dimension, phys_dimension, &base));
990
991 region.get_database()->progress("\tElement Blocks");
992 const Ioss::ElementBlockContainer &ebs = region.get_element_blocks();
993 for (auto &eb : ebs) {
994 const std::string &name = eb->name();
995 int db_zone = 0;
996 cgsize_t size[3] = {0, 0, 0};
997 size[1] = eb->get_property("zone_element_count").get_int();
998 size[0] = eb->get_property("zone_node_count").get_int();
999
1000 if (is_parallel_io) {}
1001
1002 CGERR(cg_zone_write(file_ptr, base, name.c_str(), size, CGNS_ENUMV(Unstructured), &db_zone));
1003 int prev_db_zone = get_db_zone(eb);
1004 if (db_zone != prev_db_zone) {
1005 IOSS_ERROR(fmt::format(
1006 "ERROR: CGNS: The 'db_zone' does not match in the state file {} and the base file {}.",
1007 db_zone, prev_db_zone));
1008 }
1009 }
1010
1011 region.get_database()->progress("\tStructured Blocks");
1012 const auto &structured_blocks = region.get_structured_blocks();
1013
1014 // If `is_parallel` and `!is_parallel_io`, then writing file-per-processor
1015 bool is_parallel = region.get_database()->util().parallel_size() > 1;
1016 int rank = region.get_database()->util().parallel_rank();
1017 for (const auto &sb : structured_blocks) {
1018 cgsize_t size[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
1019 if (is_parallel_io) {
1020 size[3] = sb->get_property("ni_global").get_int();
1021 size[4] = sb->get_property("nj_global").get_int();
1022 size[5] = sb->get_property("nk_global").get_int();
1023 }
1024 else {
1025 size[3] = sb->get_property("ni").get_int();
1026 size[4] = sb->get_property("nj").get_int();
1027 size[5] = sb->get_property("nk").get_int();
1028 }
1029 size[0] = size[3] + 1;
1030 size[1] = size[4] + 1;
1031 size[2] = size[5] + 1;
1032
1033 if (is_parallel_io || sb->is_active()) {
1034 std::string name = sb->name();
1035 if (is_parallel && !is_parallel_io) {
1036 name += "_proc-";
1037 name += std::to_string(rank);
1038 }
1039 int db_zone = 0;
1040 CGERR(cg_zone_write(file_ptr, base, name.c_str(), size, CGNS_ENUMV(Structured), &db_zone));
1041 if (db_zone != sb->get_property("db_zone").get_int()) {
1042 IOSS_ERROR(fmt::format(
1043 "ERROR: CGNS: The 'db_zone' does not match in the state file {} and the base file {}.",
1044 db_zone, sb->get_property("db_zone").get_int()));
1045 }
1046 }
1047 }
1048 }
1049
1050 size_t Iocgns::Utils::common_write_metadata(int file_ptr, const Ioss::Region &region,
1051 std::vector<size_t> &zone_offset, bool is_parallel_io)
1052 {
1053 #if !IOSS_ENABLE_HYBRID
1054 // Make sure mesh is not hybrid...
1055 if (region.mesh_type() == Ioss::MeshType::HYBRID) {
1056 IOSS_ERROR(fmt::format("ERROR: CGNS: The mesh on region '{}' is of type 'hybrid'."
1057 " This is currently not allowed or supported.",
1058 region.name()));
1059 }
1060 #endif
1061
1062 region.get_database()->progress("\tEnter common_write_metadata");
1063 int base = 0;
1064 int phys_dimension = region.get_property("spatial_dimension").get_int();
1065 CGERR(cg_base_write(file_ptr, "Base", phys_dimension, phys_dimension, &base));
1066
1067 CGERR(cg_goto(file_ptr, base, "end"));
1068 std::time_t t = std::time(nullptr);
1069 std::string date = fmt::format("{:%Y/%m/%d}", fmt::localtime(t));
1070 std::string time = fmt::format("{:%H:%M:%S}", fmt::localtime(t));
1071
1072 std::string code_version = region.get_optional_property("code_version", "unknown");
1073 std::string code_name = region.get_optional_property("code_name", "unknown");
1074
1075 std::string mpi_version{};
1076 #if CG_BUILD_PARALLEL
1077 {
1078 char version[MPI_MAX_LIBRARY_VERSION_STRING];
1079 int length = 0;
1080 MPI_Get_library_version(version, &length);
1081 mpi_version = fmt::format("MPI Version: {}", version);
1082 }
1083 #endif
1084
1085 std::string config = Iocgns::Utils::show_config();
1086 auto version = fmt::format(
1087 "Written by `{}-{}` on {} at {}\n{}{}\nIOSS: CGNS Writer version {}\nPlatform: {}", code_name,
1088 code_version, date, time, config, mpi_version, __DATE__, Ioss::Utils::platform_information());
1089
1090 #if CG_BUILD_PARALLEL
1091 if (is_parallel_io) {
1092 // Need to make sure the version string is the same on all
1093 // processors since they are all writing to the same file. There
1094 // was a difficult to track bug in which the
1095 // platform_information() contained different node info ("ser9"
1096 // and "ser43") on certain ranks which caused an HDF5 failure way
1097 // downstream -- basically at file close.
1098 region.get_database()->util().broadcast(version);
1099 }
1100 #endif
1101
1102 CGERR(cg_descriptor_write("Information", version.c_str()));
1103 CGERR(cg_goto(file_ptr, base, "end"));
1104 CGERR(cg_dataclass_write(CGNS_ENUMV(Dimensional)));
1105 CGERR(cg_units_write(CGNS_ENUMV(MassUnitsUserDefined), CGNS_ENUMV(LengthUnitsUserDefined),
1106 CGNS_ENUMV(TimeUnitsUserDefined), CGNS_ENUMV(TemperatureUnitsUserDefined),
1107 CGNS_ENUMV(AngleUnitsUserDefined)));
1108
1109 // Output the sidesets as Family_t nodes
1110 region.get_database()->progress("\tOutput Sidesets");
1111 const auto &sidesets = region.get_sidesets();
1112 for (const auto &ss : sidesets) {
1113 int fam = 0;
1114 CGERR(cg_family_write(file_ptr, base, ss->name().c_str(), &fam));
1115
1116 int bc_index = 0;
1117 CGNS_ENUMT(BCType_t) bocotype = CGNS_ENUMV(BCTypeNull);
1118 if (ss->property_exists("bc_type")) {
1119 bocotype = (CGNS_ENUMT(BCType_t))ss->get_property("bc_type").get_int();
1120 }
1121
1122 int64_t id = ss->get_optional_property("id", fam);
1123
1124 CGERR(cg_fambc_write(file_ptr, base, fam, "FamBC", bocotype, &bc_index));
1125 CGERR(cg_goto(file_ptr, base, "Family_t", fam, nullptr));
1126 CGERR(cg_descriptor_write("FamBC_TypeId", std::to_string(bocotype).c_str()));
1127 CGERR(cg_descriptor_write("FamBC_TypeName", cg_BCTypeName(bocotype)));
1128 CGERR(cg_descriptor_write("FamBC_UserId", std::to_string(id).c_str()));
1129 CGERR(cg_descriptor_write("FamBC_UserName", ss->name().c_str()));
1130 }
1131
1132 // NOTE: Element Block zone write is deferred to put_field_internal so can
1133 // generate the node count based on connectivity traversal...
1134 // Just getting processor element count here...
1135 region.get_database()->progress("\tElement Blocks");
1136 const auto &element_blocks = region.get_element_blocks();
1137
1138 size_t element_count = 0;
1139 for (const auto &eb : element_blocks) {
1140 int64_t local_count = eb->entity_count();
1141 #if CG_BUILD_PARALLEL
1142 if (is_parallel_io) {
1143 int64_t start = 0;
1144 MPI_Exscan(&local_count, &start, 1, Ioss::mpi_type(start), MPI_SUM,
1145 region.get_database()->util().communicator());
1146 // Of the cells/elements in this zone, this proc handles
1147 // those starting at 'proc_offset+1' to 'proc_offset+num_entity'
1148 eb->property_update("proc_offset", start);
1149 }
1150 #endif
1151 element_count += (size_t)local_count;
1152 }
1153
1154 region.get_database()->progress("\tStructured Blocks");
1155 const auto &structured_blocks = region.get_structured_blocks();
1156
1157 // If `is_parallel` and `!is_parallel_io`, then writing file-per-processor
1158 bool is_parallel = region.get_database()->util().parallel_size() > 1;
1159 int rank = region.get_database()->util().parallel_rank();
1160 int zone = 0;
1161 for (const auto &sb : structured_blocks) {
1162 cgsize_t size[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
1163 if (is_parallel_io) {
1164 size[3] = sb->get_property("ni_global").get_int();
1165 size[4] = sb->get_property("nj_global").get_int();
1166 size[5] = sb->get_property("nk_global").get_int();
1167 }
1168 else {
1169 size[3] = sb->get_property("ni").get_int();
1170 size[4] = sb->get_property("nj").get_int();
1171 size[5] = sb->get_property("nk").get_int();
1172 }
1173 size[0] = size[3] + 1;
1174 size[1] = size[4] + 1;
1175 size[2] = size[5] + 1;
1176
1177 if (is_parallel_io || sb->is_active()) {
1178 std::string name = sb->name();
1179 if (is_parallel && !is_parallel_io) {
1180 name += "_proc-";
1181 name += std::to_string(rank);
1182 }
1183 int db_zone = 0;
1184 CGERR(cg_zone_write(file_ptr, base, name.c_str(), size, CGNS_ENUMV(Structured), &db_zone));
1185 sb->property_update("db_zone", db_zone);
1186 // Add GridCoordinates Node...
1187 int grid_idx = 0;
1188 CGERR(cg_grid_write(file_ptr, base, db_zone, "GridCoordinates", &grid_idx));
1189 }
1190 else {
1191 sb->property_update("db_zone", -1);
1192 }
1193 zone++;
1194 assert(zone > 0);
1195 zone_offset[zone] = zone_offset[zone - 1] + sb->get_property("cell_count").get_int();
1196 sb->property_update("zone", zone);
1197 sb->property_update("base", base);
1198 }
1199
1200 // TODO: Are there multi-level assemblies in CGNS?
1201 // Output the assembly data.
1202 // The assembly itself is Family data at top level.
1203 // For each assembly, iterate members and add the 'FamilyName' node linking it to the Assembly
1204 output_assemblies(file_ptr, region, is_parallel_io);
1205
1206 region.get_database()->progress("\tMapping sb_name to zone");
1207 if (is_parallel_io || !is_parallel) { // Only for single file output or serial...
1208 // Create a vector for mapping from sb_name to zone -- used to update zgc instances
1209 std::map<std::string, int> sb_zone;
1210 for (const auto &sb : structured_blocks) {
1211 zone = sb->get_property("zone").get_int();
1212 sb_zone[sb->name()] = zone;
1213 }
1214
1215 // Update zgc instances to make sure the ownerZone and donorZone are
1216 // consistent with the zones on the output database (from cg_zone_write call)
1217 for (const auto &sb : structured_blocks) {
1218 int owner_zone = sb->get_property("zone").get_int();
1219 for (auto &zgc : sb->m_zoneConnectivity) {
1220 int donor_zone = sb_zone[zgc.m_donorName];
1221 zgc.m_ownerZone = owner_zone;
1222 zgc.m_ownerGUID = region.get_database()->util().generate_guid(owner_zone);
1223 zgc.m_donorZone = donor_zone;
1224 zgc.m_donorGUID = region.get_database()->util().generate_guid(donor_zone);
1225 }
1226 }
1227 }
1228
1229 region.get_database()->progress("\tConsolidate zgc");
1230 if (is_parallel_io) {
1231 consolidate_zgc(region);
1232 }
1233
1234 region.get_database()->progress("\tStructured Block Loop");
1235 for (const auto &sb : structured_blocks) {
1236 if (!is_parallel_io && !sb->is_active()) {
1237 continue;
1238 }
1239
1240 auto db_zone = get_db_zone(sb);
1241 std::string name = sb->name();
1242 if (is_parallel && !is_parallel_io) {
1243 name += "_proc-";
1244 name += std::to_string(rank);
1245 }
1246
1247 // Transfer boundary condition nodes...
1248 // The bc.m_ownerRange argument needs to be the union of the size on all processors
1249 // Instead of requiring that of the caller, do the union in this routine.
1250 // TODO: Calculate it outside of the loop...
1251 // Need to handle possible range == 0,0,0. Only affects the beg data...
1252 if (is_parallel_io) {
1253 region.get_database()->progress("\t\tBoundary Conditions");
1254 }
1255 CGNSIntVector bc_range(sb->m_boundaryConditions.size() * 6);
1256 size_t idx = 0;
1257 for (const auto &bc : sb->m_boundaryConditions) {
1258 for (size_t i = 0; i < 3; i++) {
1259 if (bc.m_rangeBeg[i] == 0) {
1260 bc_range[idx++] = std::numeric_limits<int>::min();
1261 }
1262 else {
1263 bc_range[idx++] = -bc.m_rangeBeg[i];
1264 }
1265 }
1266 for (size_t i = 0; i < 3; i++) {
1267 bc_range[idx++] = bc.m_rangeEnd[i];
1268 }
1269 }
1270
1271 if (is_parallel_io) {
1272 region.get_database()->util().global_array_minmax(bc_range, Ioss::ParallelUtils::DO_MAX);
1273 }
1274
1275 for (idx = 0; idx < bc_range.size(); idx += 6) {
1276 bc_range[idx + 0] = -bc_range[idx + 0];
1277 bc_range[idx + 1] = -bc_range[idx + 1];
1278 bc_range[idx + 2] = -bc_range[idx + 2];
1279 }
1280
1281 Ioss::IJK_t offset;
1282 offset[0] = sb->get_property("offset_i").get_int();
1283 offset[1] = sb->get_property("offset_j").get_int();
1284 offset[2] = sb->get_property("offset_k").get_int();
1285
1286 idx = 0;
1287 for (const auto &bc : sb->m_boundaryConditions) {
1288 int bc_idx = 0;
1289 if (!is_parallel_io) {
1290 bc_range[idx + 0] -= offset[0];
1291 bc_range[idx + 1] -= offset[1];
1292 bc_range[idx + 2] -= offset[2];
1293 bc_range[idx + 3] -= offset[0];
1294 bc_range[idx + 4] -= offset[1];
1295 bc_range[idx + 5] -= offset[2];
1296 }
1297
1298 if (is_parallel_io ||
1299 (bc_range[idx + 3] > 0 && bc_range[idx + 4] > 0 && bc_range[idx + 5] > 0)) {
1300 CGERR(cg_boco_write(file_ptr, base, db_zone, bc.m_bcName.c_str(),
1301 CGNS_ENUMV(FamilySpecified), CGNS_ENUMV(PointRange), 2, &bc_range[idx],
1302 &bc_idx));
1303 CGERR(
1304 cg_goto(file_ptr, base, name.c_str(), 0, "ZoneBC_t", 1, bc.m_bcName.c_str(), 0, "end"));
1305 CGERR(cg_famname_write(bc.m_famName.c_str()));
1306 CGERR(cg_boco_gridlocation_write(file_ptr, base, db_zone, bc_idx, CGNS_ENUMV(Vertex)));
1307 }
1308 idx += 6;
1309 }
1310 // Transfer Zone Grid Connectivity...
1311 if (is_parallel_io) {
1312 region.get_database()->progress("\t\tZone Grid Connectivity");
1313 }
1314
1315 // Used to detect duplicate zgc names in parallel but non-parallel-io case
1316 std::set<std::string> zgc_names;
1317
1318 for (const auto &zgc : sb->m_zoneConnectivity) {
1319 if (zgc.is_valid() &&
1320 (zgc.is_active() || (!is_parallel && zgc.m_donorProcessor != zgc.m_ownerProcessor))) {
1321 int zgc_idx = 0;
1322 std::array<cgsize_t, 6> owner_range{{zgc.m_ownerRangeBeg[0], zgc.m_ownerRangeBeg[1],
1323 zgc.m_ownerRangeBeg[2], zgc.m_ownerRangeEnd[0],
1324 zgc.m_ownerRangeEnd[1], zgc.m_ownerRangeEnd[2]}};
1325 std::array<cgsize_t, 6> donor_range{{zgc.m_donorRangeBeg[0], zgc.m_donorRangeBeg[1],
1326 zgc.m_donorRangeBeg[2], zgc.m_donorRangeEnd[0],
1327 zgc.m_donorRangeEnd[1], zgc.m_donorRangeEnd[2]}};
1328
1329 std::string donor_name = zgc.m_donorName;
1330 std::string connect_name = zgc.m_connectionName;
1331 std::string original_name = zgc.m_connectionName;
1332 if (is_parallel && !is_parallel_io) {
1333 if (zgc.is_from_decomp()) {
1334 connect_name = std::to_string(zgc.m_ownerGUID) + "--" + std::to_string(zgc.m_donorGUID);
1335 }
1336 else {
1337 auto iter = zgc_names.insert(connect_name);
1338 if (!iter.second) {
1339 // Name collision...
1340 for (char c = 'A'; c <= 'Z'; c++) {
1341 std::string potential = connect_name + c;
1342 iter = zgc_names.insert(potential);
1343 if (iter.second) {
1344 connect_name = potential;
1345 break;
1346 }
1347 }
1348 if (connect_name == zgc.m_connectionName) {
1349 bool done = false;
1350 for (char c1 = 'A'; c1 <= 'Z' && !done; c1++) {
1351 for (char c2 = 'A'; c2 <= 'Z' && !done; c2++) {
1352 std::string potential = connect_name + c1 + c2;
1353 iter = zgc_names.insert(potential);
1354 if (iter.second) {
1355 connect_name = potential;
1356 done = true;
1357 }
1358 }
1359 }
1360 if (connect_name == zgc.m_connectionName) {
1361 IOSS_ERROR(fmt::format(
1362 "ERROR: CGNS: Duplicate ZGC Name '{}' on zone '{}', processor {}\n",
1363 zgc.m_connectionName, sb->name(), zgc.m_ownerProcessor));
1364 }
1365 }
1366 }
1367 }
1368 donor_name += "_proc-";
1369 donor_name += std::to_string(zgc.m_donorProcessor);
1370 owner_range[0] -= zgc.m_ownerOffset[0];
1371 owner_range[1] -= zgc.m_ownerOffset[1];
1372 owner_range[2] -= zgc.m_ownerOffset[2];
1373 owner_range[3] -= zgc.m_ownerOffset[0];
1374 owner_range[4] -= zgc.m_ownerOffset[1];
1375 owner_range[5] -= zgc.m_ownerOffset[2];
1376
1377 donor_range[0] -= zgc.m_donorOffset[0];
1378 donor_range[1] -= zgc.m_donorOffset[1];
1379 donor_range[2] -= zgc.m_donorOffset[2];
1380 donor_range[3] -= zgc.m_donorOffset[0];
1381 donor_range[4] -= zgc.m_donorOffset[1];
1382 donor_range[5] -= zgc.m_donorOffset[2];
1383 }
1384
1385 if (is_parallel_io || !is_parallel) {
1386 if (zgc.m_ownerZone == zgc.m_donorZone && zgc.m_ownerRangeBeg == zgc.m_donorRangeBeg &&
1387 zgc.m_ownerRangeEnd == zgc.m_donorRangeEnd) {
1388 #if IOSS_DEBUG_OUTPUT
1389 fmt::print("Removing ZGC {} on zone {}\n", connect_name, db_zone);
1390 #endif
1391 continue;
1392 }
1393 }
1394
1395 CGERR(cg_1to1_write(file_ptr, base, db_zone, connect_name.c_str(), donor_name.c_str(),
1396 Data(owner_range), Data(donor_range), Data(zgc.m_transform), &zgc_idx));
1397
1398 if (zgc.is_from_decomp()) {
1399 CGERR(cg_goto(file_ptr, base, "Zone_t", db_zone, "ZoneGridConnectivity", 0,
1400 "GridConnectivity1to1_t", zgc_idx, "end"));
1401 CGERR(cg_descriptor_write("Decomp", "is_decomp"));
1402 }
1403 else if (original_name != connect_name) {
1404 CGERR(cg_goto(file_ptr, base, "Zone_t", db_zone, "ZoneGridConnectivity", 0,
1405 "GridConnectivity1to1_t", zgc_idx, "end"));
1406 CGERR(cg_descriptor_write("OriginalName", original_name.c_str()));
1407 }
1408 }
1409 }
1410 }
1411
1412 region.get_database()->progress("\tReturn from common_write_metadata");
1413 return element_count;
1414 }
1415
1416 std::string Iocgns::Utils::map_cgns_to_topology_type(CGNS_ENUMT(ElementType_t) type)
1417 {
1418 std::string topology = "unknown";
1419 switch (type) {
1420 case CGNS_ENUMV(NODE): topology = Ioss::Node::name; break;
1421 case CGNS_ENUMV(BAR_2): topology = Ioss::Beam2::name; break;
1422 case CGNS_ENUMV(BAR_3): topology = Ioss::Beam3::name; break;
1423 case CGNS_ENUMV(TRI_3): topology = Ioss::Tri3::name; break;
1424 case CGNS_ENUMV(TRI_6): topology = Ioss::Tri6::name; break;
1425 case CGNS_ENUMV(QUAD_4): topology = Ioss::Quad4::name; break;
1426 case CGNS_ENUMV(QUAD_8): topology = Ioss::Quad8::name; break;
1427 case CGNS_ENUMV(QUAD_9): topology = Ioss::Quad9::name; break;
1428 case CGNS_ENUMV(TETRA_4): topology = Ioss::Tet4::name; break;
1429 case CGNS_ENUMV(TETRA_10): topology = Ioss::Tet10::name; break;
1430 case CGNS_ENUMV(PYRA_5): topology = Ioss::Pyramid5::name; break;
1431 case CGNS_ENUMV(PYRA_13): topology = Ioss::Pyramid13::name; break;
1432 case CGNS_ENUMV(PYRA_14): topology = Ioss::Pyramid14::name; break;
1433 case CGNS_ENUMV(PENTA_6): topology = Ioss::Wedge6::name; break;
1434 case CGNS_ENUMV(PENTA_15): topology = Ioss::Wedge15::name; break;
1435 case CGNS_ENUMV(PENTA_18): topology = Ioss::Wedge18::name; break;
1436 case CGNS_ENUMV(HEXA_8): topology = Ioss::Hex8::name; break;
1437 case CGNS_ENUMV(HEXA_20): topology = Ioss::Hex20::name; break;
1438 case CGNS_ENUMV(HEXA_27): topology = Ioss::Hex27::name; break;
1439 default:
1440 fmt::print(Ioss::WarnOut(), "Found topology of type {} which is not currently supported.\n",
1441 cg_ElementTypeName(type));
1442 topology = Ioss::Unknown::name;
1443 }
1444 return topology;
1445 }
1446
1447 CGNS_ENUMT(ElementType_t) Iocgns::Utils::map_topology_to_cgns(const std::string &name)
1448 {
1449 CGNS_ENUMT(ElementType_t) topo = CGNS_ENUMV(ElementTypeNull);
1450 if (name == Ioss::Node::name) {
1451 topo = CGNS_ENUMV(NODE);
1452 }
1453 else if (name == Ioss::Spring2::name) {
1454 topo = CGNS_ENUMV(BAR_2);
1455 }
1456 else if (name == Ioss::Spring3::name) {
1457 topo = CGNS_ENUMV(BAR_3);
1458 }
1459 else if (name == Ioss::Beam2::name) {
1460 topo = CGNS_ENUMV(BAR_2);
1461 }
1462 else if (name == Ioss::Beam3::name) {
1463 topo = CGNS_ENUMV(BAR_3);
1464 }
1465 else if (name == Ioss::Tri3::name) {
1466 topo = CGNS_ENUMV(TRI_3);
1467 }
1468 else if (name == Ioss::Tri6::name) {
1469 topo = CGNS_ENUMV(TRI_6);
1470 }
1471 else if (name == Ioss::Quad4::name) {
1472 topo = CGNS_ENUMV(QUAD_4);
1473 }
1474 else if (name == Ioss::Quad8::name) {
1475 topo = CGNS_ENUMV(QUAD_8);
1476 }
1477 else if (name == Ioss::Quad9::name) {
1478 topo = CGNS_ENUMV(QUAD_9);
1479 }
1480 else if (name == Ioss::Tet4::name) {
1481 topo = CGNS_ENUMV(TETRA_4);
1482 }
1483 else if (name == Ioss::Tet10::name) {
1484 topo = CGNS_ENUMV(TETRA_10);
1485 }
1486 else if (name == Ioss::Pyramid5::name) {
1487 topo = CGNS_ENUMV(PYRA_5);
1488 }
1489 else if (name == Ioss::Pyramid13::name) {
1490 topo = CGNS_ENUMV(PYRA_13);
1491 }
1492 else if (name == Ioss::Pyramid14::name) {
1493 topo = CGNS_ENUMV(PYRA_14);
1494 }
1495 else if (name == Ioss::Wedge6::name) {
1496 topo = CGNS_ENUMV(PENTA_6);
1497 }
1498 else if (name == Ioss::Wedge15::name) {
1499 topo = CGNS_ENUMV(PENTA_15);
1500 }
1501 else if (name == Ioss::Wedge18::name) {
1502 topo = CGNS_ENUMV(PENTA_18);
1503 }
1504 else if (name == Ioss::Hex8::name) {
1505 topo = CGNS_ENUMV(HEXA_8);
1506 }
1507 else if (name == Ioss::Hex20::name) {
1508 topo = CGNS_ENUMV(HEXA_20);
1509 }
1510 else if (name == Ioss::Hex27::name) {
1511 topo = CGNS_ENUMV(HEXA_27);
1512 }
1513 else {
1514 fmt::print(Ioss::WarnOut(), "Found topology of type {} which is not currently supported.\n",
1515 name);
1516 }
1517 return topo;
1518 }
1519
1520 void Iocgns::Utils::write_flow_solution_metadata(int file_ptr, int base_ptr, Ioss::Region *region,
1521 int state, const int *vertex_solution_index,
1522 const int *cell_center_solution_index,
1523 bool is_parallel_io)
1524 {
1525 std::string c_name = fmt::format("CellCenterSolutionAtStep{:05}", state);
1526 std::string v_name = fmt::format("VertexSolutionAtStep{:05}", state);
1527 std::string step = std::to_string(state);
1528
1529 const auto &nblocks = region->get_node_blocks();
1530 const auto &nblock = nblocks[0];
1531 bool global_has_nodal_fields = nblock->field_count(Ioss::Field::TRANSIENT) > 0;
1532 bool is_file_per_state = (base_ptr >= 0);
1533
1534 // IF the `base_ptr` is positive, then we are in file-per-state option.
1535 // `file_ptr` points to the linked-to file where the state data is being
1536 // written and `base_ptr` points to the "base" file which has the mesh
1537 // metadata and links to the solution data "state" files.
1538 std::string linked_file_name;
1539 if (is_file_per_state) {
1540 linked_file_name = region->get_database()->get_filename();
1541 }
1542
1543 // Create a lambda to avoid code duplication for similar treatment
1544 // of structured blocks and element blocks.
1545 auto sol_lambda = [=](Ioss::EntityBlock *block, bool has_nodal_fields) {
1546 int base = block->get_property("base").get_int();
1547 int zone = get_db_zone(block);
1548 if (has_nodal_fields) {
1549 if (is_file_per_state) {
1550 // We are using file-per-state and we need to add a link from the base file (base_ptr)
1551 // to the state file (file_ptr).
1552 CGERR(cg_goto(base_ptr, base, "Zone_t", zone, "end"));
1553 std::string linkpath = "/Base/" + block->name() + "/" + v_name;
1554 CGERR(cg_link_write(v_name.c_str(), linked_file_name.c_str(), linkpath.c_str()));
1555 }
1556 CGERR(cg_sol_write(file_ptr, base, zone, v_name.c_str(), CGNS_ENUMV(Vertex),
1557 (int *)vertex_solution_index));
1558 CGERR(
1559 cg_goto(file_ptr, base, "Zone_t", zone, "FlowSolution_t", *vertex_solution_index, "end"));
1560 CGERR(cg_gridlocation_write(CGNS_ENUMV(Vertex)));
1561 CGERR(cg_descriptor_write("Step", step.c_str()));
1562 }
1563 if (block->field_count(Ioss::Field::TRANSIENT) > 0) {
1564 if (is_file_per_state) {
1565 // We are using file-per-state and we need to add a link from the base file (base_ptr)
1566 // to the state file (file_ptr).
1567 CGERR(cg_goto(base_ptr, base, "Zone_t", zone, "end"));
1568 std::string linkpath = "/Base/" + block->name() + "/" + c_name;
1569 CGERR(cg_link_write(c_name.c_str(), linked_file_name.c_str(), linkpath.c_str()));
1570 }
1571 CGERR(cg_sol_write(file_ptr, base, zone, c_name.c_str(), CGNS_ENUMV(CellCenter),
1572 (int *)cell_center_solution_index));
1573 CGERR(cg_goto(file_ptr, base, "Zone_t", zone, "FlowSolution_t", *cell_center_solution_index,
1574 "end"));
1575 CGERR(cg_descriptor_write("Step", step.c_str()));
1576 }
1577 };
1578
1579 // Use the lambda
1580 const auto &sblocks = region->get_structured_blocks();
1581 for (auto &block : sblocks) {
1582 if (is_parallel_io || block->is_active()) {
1583 const auto &nb = block->get_node_block();
1584 bool has_nodal_fields = global_has_nodal_fields || nb.field_count(Ioss::Field::TRANSIENT) > 0;
1585 sol_lambda(block, has_nodal_fields);
1586 }
1587 }
1588 // Use the lambda
1589 const auto &eblocks = region->get_element_blocks();
1590 for (auto &block : eblocks) {
1591 sol_lambda(block, global_has_nodal_fields);
1592 }
1593 }
1594
1595 int Iocgns::Utils::find_solution_index(int cgns_file_ptr, int base, int zone, int step,
1596 CGNS_ENUMT(GridLocation_t) location)
1597 {
1598 auto str_step = std::to_string(step);
1599 int nsols = 0;
1600 CGCHECKNP(cg_nsols(cgns_file_ptr, base, zone, &nsols));
1601 bool location_matches = false;
1602 for (int i = 0; i < nsols; i++) {
1603 CGNS_ENUMT(GridLocation_t) db_location;
1604 char db_name[CGNS_MAX_NAME_LENGTH + 1];
1605 CGCHECKNP(cg_sol_info(cgns_file_ptr, base, zone, i + 1, db_name, &db_location));
1606 if (location == db_location) {
1607 location_matches = true;
1608 // Check if steps match.
1609 // NOTE: Using non-standard "Descriptor_t" node in FlowSolution_t
1610 CGCHECKNP(cg_goto(cgns_file_ptr, base, "Zone_t", zone, "FlowSolution_t", i + 1, "end"));
1611 int descriptor_count = 0;
1612 CGCHECKNP(cg_ndescriptors(&descriptor_count));
1613
1614 bool found_step_descriptor = false;
1615 for (int d = 0; d < descriptor_count; d++) {
1616 char *db_step = nullptr;
1617 char name[CGNS_MAX_NAME_LENGTH + 1];
1618 CGCHECKNP(cg_descriptor_read(d + 1, name, &db_step));
1619 if (strcmp(name, "step") == 0) {
1620 found_step_descriptor = true;
1621 if (str_step == db_step) {
1622 cg_free(db_step);
1623 return i + 1;
1624 }
1625
1626 cg_free(db_step);
1627 break; // Found "step" descriptor, but wasn't correct step...
1628 }
1629 cg_free(db_step);
1630 }
1631 if (!found_step_descriptor) {
1632 // There was no Descriptor_t node with the name "step",
1633 // Try to decode the step from the FlowSolution_t name.
1634 // If `db_name` does not have `Step` or `step` in name,
1635 // then don't search
1636 if (strcasestr(db_name, "step") != nullptr) {
1637 int nstep = extract_trailing_int(db_name);
1638 if (nstep == step) {
1639 return i + 1;
1640 }
1641 }
1642 }
1643 }
1644 }
1645
1646 if (location_matches) {
1647 return step;
1648 }
1649
1650 fmt::print(Ioss::WarnOut(),
1651 "CGNS: Could not find valid solution index for step {}, zone {}, and location {}\n",
1652 step, zone, cg_GridLocationName(location));
1653 return 0;
1654 }
1655
1656 void Iocgns::Utils::add_sidesets(int cgns_file_ptr, Ioss::DatabaseIO *db)
1657 {
1658 static int fake_id =
1659 std::numeric_limits<int>::max(); // Used in case CGNS file does not specify an id.
1660
1661 int base = 1;
1662 int num_families = 0;
1663 CGCHECKNP(cg_nfamilies(cgns_file_ptr, base, &num_families));
1664
1665 for (int family = 1; family <= num_families; family++) {
1666 char name[CGNS_MAX_NAME_LENGTH + 1];
1667 CGNS_ENUMT(BCType_t) bocotype;
1668 int num_bc = 0;
1669 int num_geo = 0;
1670 CGCHECKNP(cg_family_read(cgns_file_ptr, base, family, name, &num_bc, &num_geo));
1671
1672 #if IOSS_DEBUG_OUTPUT
1673 if (db->parallel_rank() == 0) {
1674 fmt::print(Ioss::DebugOut(), "Family {} named {} has {} BC, and {} geometry references.\n",
1675 family, name, num_bc, num_geo);
1676 }
1677 #endif
1678 if (num_bc > 0) {
1679 // Create a sideset...
1680 std::string ss_name(name); // Use name here before cg_fambc_read call overwrites it...
1681
1682 CGCHECKNP(cg_fambc_read(cgns_file_ptr, base, family, 1, name, &bocotype));
1683
1684 CGCHECKNP(cg_goto(cgns_file_ptr, base, "Family_t", family, "end"));
1685 int ndescriptors = 0;
1686 int id = 0;
1687 CGCHECKNP(cg_ndescriptors(&ndescriptors));
1688 if (ndescriptors > 0) {
1689 for (int ndesc = 1; ndesc <= ndescriptors; ndesc++) {
1690 char dname[CGNS_MAX_NAME_LENGTH + 1];
1691 char *dtext;
1692 CGCHECKNP(cg_descriptor_read(ndesc, dname, &dtext));
1693 if (strcmp(dname, "FamBC_UserId") == 0) {
1694 // Convert text in `dtext` to integer...
1695 id = Ioss::Utils::get_number(dtext);
1696 cg_free(dtext);
1697 break;
1698 }
1699 cg_free(dtext);
1700 }
1701 }
1702 if (id == 0) {
1703 id = Ioss::Utils::extract_id(ss_name);
1704 if (id == 0 && ss_name != "Unspecified") {
1705 // Assign a fake_id to this sideset. No checking to make
1706 // sure there are no duplicates...
1707 id = fake_id--;
1708 }
1709 }
1710 if (id != 0) {
1711 auto *ss = new Ioss::SideSet(db, ss_name);
1712 ss->property_add(Ioss::Property("id", id));
1713 ss->property_add(Ioss::Property("guid", db->util().generate_guid(id)));
1714 ss->property_add(Ioss::Property("bc_type", bocotype));
1715 db->get_region()->add(ss);
1716 }
1717 else {
1718 if (db->parallel_rank() == 0) {
1719 fmt::print(Ioss::WarnOut(),
1720 "Skipping BC with name '{}' since FamBC_UserId is equal to 0.\n\n", ss_name);
1721 }
1722 }
1723 }
1724 }
1725 }
1726
1727 void Iocgns::Utils::add_assemblies(int cgns_file_ptr, Ioss::DatabaseIO *db)
1728 {
1729 int base = 1;
1730 int num_families = 0;
1731 CGCHECKNP(cg_nfamilies(cgns_file_ptr, base, &num_families));
1732
1733 for (int family = 1; family <= num_families; family++) {
1734 char name[CGNS_MAX_NAME_LENGTH + 1];
1735 int num_bc = 0;
1736 int num_geo = 0;
1737 CGCHECKNP(cg_family_read(cgns_file_ptr, base, family, name, &num_bc, &num_geo));
1738
1739 if (num_bc == 0 && num_geo == 0) {
1740 // See if this is an assembly -- will contain a 'FamVC_UserName' Descriptor_t node
1741 // The `Node Data` for that node will be the name of the assembly.
1742 // Assemblies will be created empty and then blocks/zones will be added during
1743 // the parsing of the zones.
1744 CGCHECKNP(cg_goto(cgns_file_ptr, base, "Family_t", family, "end"));
1745
1746 int ndescriptors = 0;
1747 CGCHECKNP(cg_ndescriptors(&ndescriptors));
1748 if (ndescriptors > 0) {
1749 int id = -1;
1750 std::string assem_name;
1751 for (int ndesc = 1; ndesc <= ndescriptors; ndesc++) {
1752 char dname[CGNS_MAX_NAME_LENGTH + 1];
1753 char *dtext = nullptr;
1754 CGCHECKNP(cg_descriptor_read(ndesc, dname, &dtext));
1755 if (strcmp(dname, "FamVC_UserId") == 0) {
1756 // Convert text in `dtext` to integer...
1757 id = Ioss::Utils::get_number(dtext);
1758 }
1759 else if (strcmp(dname, "FamVC_UserName") == 0) {
1760 assem_name = dtext;
1761 }
1762 cg_free(dtext);
1763 }
1764 if (!assem_name.empty() && assem_name != "Unspecified") {
1765 // Create an assembly with this name...
1766 auto *assem = new Ioss::Assembly(db, assem_name);
1767 db->get_region()->add(assem);
1768 if (id >= 0) {
1769 assem->property_add(Ioss::Property("id", id));
1770 }
1771
1772 #if IOSS_DEBUG_OUTPUT
1773 if (db->parallel_rank() == 0) {
1774 fmt::print(Ioss::DebugOut(),
1775 "Adding Family {} named {} as an assembly named {} with id {}.\n", family,
1776 name, assem_name, id);
1777 }
1778 #endif
1779 }
1780 }
1781 }
1782 }
1783 }
1784
1785 size_t Iocgns::Utils::resolve_nodes(Ioss::Region &region, int my_processor, bool is_parallel)
1786 {
1787 // Each structured block has its own set of "cell_nodes"
1788 // At block boundaries, there are duplicate nodes which need to be resolved for the
1789 // unstructured mesh output.
1790
1791 // We need to iterate all of the blocks and then each blocks zgc to determine
1792 // which nodes are shared between blocks. For all shared nodes, the node in the lowest
1793 // numbered zone is considered the "owner" and all other nodes are shared.
1794
1795 // At the end of the routine, each block knows where its nodes fit
1796 // into the implicit ordering of nodes on this processor. This is
1797 // given by:
1798 // implicit_location = block->m_blockLocalNodeIndex[i] (0 <= i < #nodes_in_block)
1799 // Where 0 <= implicit_location < #nodes_on_processor
1800
1801 // Create a vector of size which is the sum of the on-processor cell_nodes size for each block
1802 size_t num_total_cell_nodes = 0;
1803 auto &blocks = region.get_structured_blocks();
1804 for (auto &block : blocks) {
1805 size_t node_count = block->get_property("node_count").get_int();
1806 num_total_cell_nodes += node_count;
1807 }
1808
1809 int64_t ss_max = std::numeric_limits<int64_t>::max();
1810 std::vector<int64_t> cell_node_map(num_total_cell_nodes, ss_max);
1811
1812 // Each cell_node location in the cell_node_map is currently initialized to ss_max.
1813 // Iterate each block and then each blocks non-intra-block (i.e., not
1814 // due to proc decomps) zgc instances and update cell_node_map
1815 // such that for each shared node, it points to the owner nodes
1816 // location.
1817 for (auto &owner_block : blocks) {
1818 for (const auto &zgc : owner_block->m_zoneConnectivity) {
1819 if (!zgc.is_from_decomp() &&
1820 zgc.is_active()) { // Not due to processor decomposition and has faces.
1821 // NOTE: In parallel, the owner block should exist, but may not have
1822 // any cells on this processor. We can access its global i,j,k, but
1823 // don't store or access any "bulk" data on it.
1824 auto donor_block = region.get_structured_block(zgc.m_donorName);
1825 assert(donor_block != nullptr);
1826
1827 std::vector<int> i_range = zgc.get_range(1);
1828 std::vector<int> j_range = zgc.get_range(2);
1829 std::vector<int> k_range = zgc.get_range(3);
1830 for (auto &k : k_range) {
1831 for (auto &j : j_range) {
1832 for (auto &i : i_range) {
1833 Ioss::IJK_t owner_index{{i, j, k}};
1834 Ioss::IJK_t donor_index = zgc.transform(owner_index);
1835
1836 // The nodes as 'index' and 'owner' are contiguous and
1837 // should refer to the same node. 'owner' should be
1838 // the owner (unless it is already owned by another
1839 // block)
1840
1841 int64_t owner_global_offset = owner_block->get_global_node_offset(owner_index);
1842 int64_t donor_global_offset = donor_block->get_global_node_offset(donor_index);
1843
1844 if (owner_global_offset > donor_global_offset) {
1845 if (is_parallel && (zgc.m_donorProcessor != my_processor)) {
1846 size_t owner_block_local_offset =
1847 owner_block->get_block_local_node_offset(owner_index);
1848 owner_block->m_globalIdMap.emplace_back(owner_block_local_offset,
1849 donor_global_offset + 1);
1850 }
1851 else if (!is_parallel || (zgc.m_ownerProcessor != my_processor)) {
1852 size_t owner_local_offset = owner_block->get_local_node_offset(owner_index);
1853 int64_t donor_local_offset = donor_block->get_local_node_offset(donor_index);
1854
1855 if (cell_node_map[owner_local_offset] == ss_max) {
1856 cell_node_map[owner_local_offset] = donor_local_offset;
1857 }
1858 }
1859 }
1860 }
1861 }
1862 }
1863 }
1864 }
1865 }
1866
1867 // Now iterate cell_node_map. If an entry == ss_max, then it is
1868 // an owned node and needs to have its index into the unstructed
1869 // mesh node map set; otherwise, the value points to the owner
1870 // node, so the index at this location should be set to the owner
1871 // nodes index.
1872 size_t index = 0;
1873 for (auto &node : cell_node_map) {
1874 if (node == ss_max) {
1875 node = index++;
1876 }
1877 else {
1878 node = -node;
1879 }
1880 }
1881
1882 for (auto &node : cell_node_map) {
1883 if (node < 0) {
1884 node = cell_node_map[-node];
1885 }
1886 }
1887
1888 for (auto &block : blocks) {
1889 size_t node_count = block->get_property("node_count").get_int();
1890 block->m_blockLocalNodeIndex.resize(node_count);
1891
1892 size_t beg = block->get_node_offset();
1893 size_t end = beg + node_count;
1894 for (size_t idx = beg, i = 0; idx < end; idx++) {
1895 block->m_blockLocalNodeIndex[i++] = cell_node_map[idx];
1896 }
1897 }
1898 return index;
1899 }
1900
1901 std::vector<std::vector<std::pair<size_t, size_t>>>
1902 Iocgns::Utils::resolve_processor_shared_nodes(Ioss::Region &region, int my_processor)
1903 {
1904 // Determine which nodes are shared across processor boundaries.
1905 // Only need to check on block boundaries..
1906
1907 // We need to iterate all of the blocks and then each blocks zgc to determine
1908 // which nodes are shared between processors. For all shared nodes, the node in the lowest
1909 // numbered zone is considered the "owner" and all other nodes are shared.
1910
1911 auto &blocks = region.get_structured_blocks();
1912
1913 std::vector<std::vector<std::pair<size_t, size_t>>> shared_nodes(blocks.size() + 1);
1914
1915 for (auto &owner_block : blocks) {
1916 int owner_zone = owner_block->get_property("zone").get_int();
1917 for (const auto &zgc : owner_block->m_zoneConnectivity) {
1918 assert(zgc.m_donorProcessor >= 0);
1919 assert(zgc.m_ownerProcessor >= 0);
1920
1921 if (zgc.is_active() &&
1922 (zgc.m_donorProcessor != my_processor || zgc.m_ownerProcessor != my_processor)) {
1923 // NOTE: In parallel, the donor block should exist, but may not have
1924 // any cells on this processor. We can access its global i,j,k, but
1925 // don't store or access any "bulk" data on it.
1926 auto donor_block = region.get_structured_block(zgc.m_donorName);
1927 assert(donor_block != nullptr);
1928 int donor_zone = donor_block->get_property("zone").get_int();
1929 std::vector<int> i_range = zgc.get_range(1);
1930 std::vector<int> j_range = zgc.get_range(2);
1931 std::vector<int> k_range = zgc.get_range(3);
1932 for (auto &k : k_range) {
1933 for (auto &j : j_range) {
1934 for (auto &i : i_range) {
1935 Ioss::IJK_t owner_index{{i, j, k}};
1936 Ioss::IJK_t donor_index = zgc.transform(owner_index);
1937
1938 // The nodes as 'index' and 'owner' are contiguous and
1939 // should refer to the same node.
1940
1941 if (my_processor == zgc.m_ownerProcessor) {
1942 int64_t owner_offset = owner_block->get_block_local_node_offset(owner_index);
1943 shared_nodes[owner_zone].emplace_back(owner_offset, zgc.m_donorProcessor);
1944 }
1945 else if (my_processor == zgc.m_donorProcessor) {
1946 int64_t donor_offset = donor_block->get_block_local_node_offset(donor_index);
1947 shared_nodes[donor_zone].emplace_back(donor_offset, zgc.m_ownerProcessor);
1948 }
1949 }
1950 }
1951 }
1952 }
1953 }
1954 #if IOSS_DEBUG_OUTPUT
1955 fmt::print(Ioss::DebugOut(), "P{}, Block {} Shared Nodes: {}\n", my_processor,
1956 owner_block->name(), shared_nodes[owner_zone].size());
1957 #endif
1958 }
1959 return shared_nodes;
1960 }
1961
1962 void Iocgns::Utils::add_to_assembly(int cgns_file_ptr, Ioss::Region *region,
1963 Ioss::EntityBlock *block, int base, int zone)
1964 {
1965 // See if there is a 'FamilyName' node...
1966 if (cg_goto(cgns_file_ptr, base, "Zone_t", zone, "end") == CG_OK) {
1967 char name[CGNS_MAX_NAME_LENGTH + 1];
1968 if (cg_famname_read(name) == CG_OK) {
1969 auto *assem = region->get_assembly(name);
1970 if (assem != nullptr) {
1971 assem->add(block);
1972 block->property_add(Ioss::Property("assembly", assem->name()));
1973 }
1974 }
1975 }
1976 }
1977
1978 void Iocgns::Utils::add_structured_boundary_conditions(int cgns_file_ptr,
1979 Ioss::StructuredBlock *block,
1980 bool is_parallel_io)
1981 {
1982 // `is_parallel_io` is true if all processors reading single file.
1983 // `is_parallel_io` is false if serial, or each processor reading its own file (fpp)
1984 if (is_parallel_io) {
1985 add_structured_boundary_conditions_pio(cgns_file_ptr, block);
1986 }
1987 else {
1988 add_structured_boundary_conditions_fpp(cgns_file_ptr, block);
1989 }
1990 }
1991
1992 void Iocgns::Utils::add_structured_boundary_conditions_pio(int cgns_file_ptr,
1993 Ioss::StructuredBlock *block)
1994 {
1995 int base = block->get_property("base").get_int();
1996 int zone = get_db_zone(block);
1997
1998 // Called by Parallel run reading single file only.
1999 // Data needed:
2000 // * boco_name (CGNS_MAX_NAME_LENGTH + 1 chars)
2001 // * fam_name (CGNS_MAX_NAME_LENGTH + 1 chars)
2002 // * data (cgsize_t * 7) (bocotype + range[6])
2003
2004 int num_bcs = 0;
2005
2006 CGCHECKNP(cg_nbocos(cgns_file_ptr, base, zone, &num_bcs));
2007
2008 std::vector<int> bc_data(7 * num_bcs);
2009 std::vector<char> bc_names(2 * (CGNS_MAX_NAME_LENGTH + 1) * num_bcs);
2010
2011 for (int ibc = 0; ibc < num_bcs; ibc++) {
2012 cgsize_t range[6];
2013 char boco_name[CGNS_MAX_NAME_LENGTH + 1];
2014 char fam_name[CGNS_MAX_NAME_LENGTH + 1];
2015 CGNS_ENUMT(BCType_t) bocotype;
2016 CGNS_ENUMT(PointSetType_t) ptset_type;
2017 cgsize_t npnts;
2018 cgsize_t NormalListSize;
2019 CGNS_ENUMT(DataType_t) NormalDataType;
2020 int ndataset;
2021
2022 // All we really want from this is 'boco_name'
2023 CGCHECKNP(cg_boco_info(cgns_file_ptr, base, zone, ibc + 1, boco_name, &bocotype, &ptset_type,
2024 &npnts, nullptr, &NormalListSize, &NormalDataType, &ndataset));
2025
2026 if (bocotype == CGNS_ENUMV(FamilySpecified)) {
2027 // Get family name associated with this boco_name
2028 CGCHECKNP(
2029 cg_goto(cgns_file_ptr, base, "Zone_t", zone, "ZoneBC_t", 1, "BC_t", ibc + 1, "end"));
2030 CGCHECKNP(cg_famname_read(fam_name));
2031 }
2032 else {
2033 Ioss::Utils::copy_string(fam_name, boco_name);
2034 }
2035
2036 CGCHECKNP(cg_boco_read(cgns_file_ptr, base, zone, ibc + 1, range, nullptr));
2037
2038 // There are some BC that are applied on an edge or a vertex;
2039 // Don't want those (yet?), so filter them out at this time...
2040 {
2041 int same_count = (range[0] == range[3] ? 1 : 0) + (range[1] == range[4] ? 1 : 0) +
2042 (range[2] == range[5] ? 1 : 0);
2043 if (same_count != 1) {
2044 fmt::print(Ioss::WarnOut(),
2045 "CGNS: Skipping Boundary Condition '{}' on block '{}'. It is applied to "
2046 "{}. This code only supports surfaces.\n",
2047 boco_name, block->name(), (same_count == 2 ? "an edge" : "a vertex"));
2048 continue;
2049 }
2050 }
2051
2052 bool is_parallel_io = true;
2053 add_bc_to_block(block, boco_name, fam_name, ibc, range, bocotype, is_parallel_io);
2054 }
2055 }
2056
2057 void Iocgns::Utils::generate_boundary_faces(
2058 Ioss::Region *region, std::map<std::string, Ioss::FaceUnorderedSet> &boundary_faces,
2059 Ioss::Field::BasicType field_type)
2060 {
2061 // See if we already generated the faces for this model...
2062 Ioss::FaceGenerator face_generator(*region);
2063 if (field_type == Ioss::Field::INT32) {
2064 face_generator.generate_faces((int)0, true);
2065 }
2066 else {
2067 face_generator.generate_faces((int64_t)0, true);
2068 }
2069 const Ioss::ElementBlockContainer &ebs = region->get_element_blocks();
2070 for (auto &eb : ebs) {
2071 const std::string &name = eb->name();
2072 auto &boundary = boundary_faces[name];
2073 auto &faces = face_generator.faces(name);
2074 for (auto &face : faces) {
2075 if (face.element_count() == 1) {
2076 boundary.insert(face);
2077 }
2078 }
2079 }
2080 #if IOSS_DEBUG_OUTPUT
2081 output_table(ebs, boundary_faces);
2082 #endif
2083 }
2084
2085 void Iocgns::Utils::add_structured_boundary_conditions_fpp(int cgns_file_ptr,
2086 Ioss::StructuredBlock *block)
2087 {
2088 int base = block->get_property("base").get_int();
2089 int zone = get_db_zone(block);
2090
2091 // Called by both parallel fpp and serial runs.
2092 // In parallel, the 'cgns_file_ptr' is specific for each processor
2093
2094 int num_bcs = 0;
2095 CGCHECKNP(cg_nbocos(cgns_file_ptr, base, zone, &num_bcs));
2096
2097 for (int ibc = 0; ibc < num_bcs; ibc++) {
2098 char boco_name[CGNS_MAX_NAME_LENGTH + 1];
2099 char fam_name[CGNS_MAX_NAME_LENGTH + 1];
2100 CGNS_ENUMT(BCType_t) bocotype;
2101 CGNS_ENUMT(PointSetType_t) ptset_type;
2102 cgsize_t npnts;
2103 cgsize_t NormalListSize;
2104 CGNS_ENUMT(DataType_t) NormalDataType;
2105 int ndataset;
2106 cgsize_t range[6];
2107
2108 // All we really want from this is 'boco_name'
2109 CGCHECKNP(cg_boco_info(cgns_file_ptr, base, zone, ibc + 1, boco_name, &bocotype, &ptset_type,
2110 &npnts, nullptr, &NormalListSize, &NormalDataType, &ndataset));
2111
2112 if (bocotype == CGNS_ENUMV(FamilySpecified)) {
2113 // Get family name associated with this boco_name
2114 CGCHECKNP(
2115 cg_goto(cgns_file_ptr, base, "Zone_t", zone, "ZoneBC_t", 1, "BC_t", ibc + 1, "end"));
2116 CGCHECKNP(cg_famname_read(fam_name));
2117 }
2118 else {
2119 Ioss::Utils::copy_string(fam_name, boco_name);
2120 }
2121
2122 CGCHECKNP(cg_boco_read(cgns_file_ptr, base, zone, ibc + 1, range, nullptr));
2123
2124 // There are some BC that are applied on an edge or a vertex;
2125 // Don't want those (yet?), so filter them out at this time...
2126 int same_count = (range[0] == range[3] ? 1 : 0) + (range[1] == range[4] ? 1 : 0) +
2127 (range[2] == range[5] ? 1 : 0);
2128 if (same_count != 1) {
2129 fmt::print(Ioss::WarnOut(),
2130 "CGNS: Skipping Boundary Condition '{}' on block '{}'. It is applied to "
2131 "{}. This code only supports surfaces.\n",
2132 boco_name, block->name(), (same_count == 2 ? "an edge" : "a vertex"));
2133 continue;
2134 }
2135
2136 int num_proc = block->get_database()->util().parallel_size();
2137 if (num_proc > 1) {
2138 // Need to modify range with block offset to put into global space
2139 Ioss::IJK_t offset;
2140 offset[0] = block->get_property("offset_i").get_int();
2141 offset[1] = block->get_property("offset_j").get_int();
2142 offset[2] = block->get_property("offset_k").get_int();
2143 range[0] += offset[0];
2144 range[1] += offset[1];
2145 range[2] += offset[2];
2146 range[3] += offset[0];
2147 range[4] += offset[1];
2148 range[5] += offset[2];
2149 }
2150
2151 bool is_parallel_io = false;
2152 add_bc_to_block(block, boco_name, fam_name, ibc, range, bocotype, is_parallel_io);
2153 }
2154 }
2155
2156 void Iocgns::Utils::finalize_database(int cgns_file_ptr, const std::vector<double> &timesteps,
2157 Ioss::Region *region, int myProcessor, bool is_parallel_io)
2158 {
2159 int base = 1;
2160 CGCHECK(cg_biter_write(cgns_file_ptr, base, "TimeIterValues", timesteps.size()));
2161
2162 // Now write the timestep time values...
2163 CGCHECK(cg_goto(cgns_file_ptr, base, "BaseIterativeData_t", 1, "end"));
2164 cgsize_t dimtv[1] = {(cgsize_t)timesteps.size()};
2165 CGCHECK(cg_array_write("TimeValues", CGNS_ENUMV(RealDouble), 1, dimtv, Data(timesteps)));
2166
2167 // Output the ZoneIterativeData which maps a zones flow solutions to timesteps.
2168 // One per zone and the number of entries matches the number of timesteps...
2169 const auto &nblocks = region->get_node_blocks();
2170 auto &nblock = nblocks[0];
2171
2172 bool has_nodal_fields = nblock->field_count(Ioss::Field::TRANSIENT) > 0;
2173
2174 // Create a lambda to avoid code duplication for similar treatment
2175 // of structured blocks and element blocks.
2176 auto ziter = [=](Ioss::EntityBlock *block) {
2177 int zone = get_db_zone(block);
2178 std::vector<int> indices(timesteps.size());
2179 bool has_cell_center_fields = block->field_count(Ioss::Field::TRANSIENT) > 0;
2180 std::string base_type;
2181 if (has_nodal_fields && !has_cell_center_fields) {
2182 base_type = "VertexSolutionAtStep";
2183 }
2184 else if (!has_nodal_fields && has_cell_center_fields) {
2185 base_type = "CellCenterSolutionAtStep";
2186 }
2187 else {
2188 base_type = "SolutionAtStep";
2189 }
2190
2191 std::vector<char> names(32 * timesteps.size(), ' ');
2192 for (size_t state = 0; state < timesteps.size(); state++) {
2193 // This name is the "postfix" or common portion of all FlowSolution names...
2194 std::string name = fmt::format("{}{:05}", base_type, state + 1);
2195 Ioss::Utils::copy_string(&names[state * 32], name, 32);
2196 for (size_t i = name.size(); i < 32; i++) {
2197 names[state * 32 + i] = ' ';
2198 }
2199 }
2200
2201 cgsize_t dim[2] = {32, (cgsize_t)timesteps.size()};
2202 if (has_cell_center_fields || has_nodal_fields) {
2203 CGCHECK(cg_ziter_write(cgns_file_ptr, base, zone, "ZoneIterativeData"));
2204 CGCHECK(cg_goto(cgns_file_ptr, base, "Zone_t", zone, "ZoneIterativeData_t", 1, "end"));
2205 CGCHECK(cg_array_write("FlowSolutionPointers", CGNS_ENUMV(Character), 2, dim, Data(names)));
2206
2207 if (has_nodal_fields) {
2208 int index = 1;
2209 int increment = has_cell_center_fields ? 2 : 1;
2210 for (size_t state = 0; state < timesteps.size(); state++) {
2211 indices[state] = index;
2212 index += increment;
2213 }
2214
2215 CGCHECK(cg_array_write("VertexSolutionIndices", CGNS_ENUMV(Integer), 1, &dim[1],
2216 Data(indices)));
2217 CGCHECK(cg_descriptor_write("VertexPrefix", "Vertex"));
2218 }
2219 if (has_cell_center_fields) {
2220 int index = has_nodal_fields ? 2 : 1;
2221 int increment = has_nodal_fields ? 2 : 1;
2222 for (size_t state = 0; state < timesteps.size(); state++) {
2223 indices[state] = index;
2224 index += increment;
2225 }
2226
2227 CGCHECK(
2228 cg_array_write("CellCenterIndices", CGNS_ENUMV(Integer), 1, &dim[1], Data(indices)));
2229 CGCHECK(cg_descriptor_write("CellCenterPrefix", "CellCenter"));
2230 }
2231 }
2232 };
2233
2234 // Use the lambda...
2235 const auto &sblocks = region->get_structured_blocks();
2236 for (auto &block : sblocks) {
2237 if (is_parallel_io || block->is_active()) {
2238 ziter(block);
2239 }
2240 }
2241
2242 // Use the lambda...
2243 const auto &eblocks = region->get_element_blocks();
2244 for (auto &block : eblocks) {
2245 ziter(block);
2246 }
2247 }
2248
2249 void Iocgns::Utils::add_transient_variables(int cgns_file_ptr, const std::vector<double> &timesteps,
2250 Ioss::Region *region, int myProcessor,
2251 bool is_parallel_io)
2252 {
2253 // ==========================================
2254 // Add transient variables (if any) to all zones...
2255 // Create a lambda to avoid code duplication for similar treatment
2256 // of structured blocks and element blocks.
2257
2258 // Assuming that the fields on all steps are the same, but can vary
2259 // from zone to zone.
2260 auto sol_iter = [=](Ioss::EntityBlock *block) {
2261 int b = block->get_property("base").get_int();
2262 int z = get_db_zone(block);
2263
2264 int sol_count = 0;
2265 CGCHECK(cg_nsols(cgns_file_ptr, b, z, &sol_count));
2266 int sol_per_step = sol_count / (int)timesteps.size();
2267 assert(sol_count % (int)timesteps.size() == 0);
2268
2269 for (int sol = 1; sol <= sol_per_step; sol++) {
2270 char solution_name[CGNS_MAX_NAME_LENGTH + 1];
2271 CGNS_ENUMT(GridLocation_t) grid_loc;
2272 CGCHECK(cg_sol_info(cgns_file_ptr, b, z, sol, solution_name, &grid_loc));
2273
2274 int field_count = 0;
2275 CGCHECK(cg_nfields(cgns_file_ptr, b, z, sol, &field_count));
2276
2277 Ioss::NameList field_names;
2278 field_names.reserve(field_count);
2279 for (int field = 1; field <= field_count; field++) {
2280 CGNS_ENUMT(DataType_t) data_type;
2281 char field_name[CGNS_MAX_NAME_LENGTH + 1];
2282 CGCHECK(cg_field_info(cgns_file_ptr, b, z, sol, field, &data_type, field_name));
2283 field_names.emplace_back(field_name);
2284 }
2285
2286 // Convert raw field names into composite fields (a_x, a_y, a_z ==> 3D vector 'a')
2287 std::vector<Ioss::Field> fields;
2288 if (grid_loc == CGNS_ENUMV(CellCenter)) {
2289 size_t entity_count = block->entity_count();
2290 Ioss::Utils::get_fields(entity_count, field_names, Ioss::Field::TRANSIENT,
2291 region->get_database(), nullptr, fields);
2292 size_t index = 1;
2293 for (const auto &field : fields) {
2294 Utils::set_field_index(field, index, grid_loc);
2295 index += field.raw_storage()->component_count();
2296 block->field_add(field);
2297 }
2298 }
2299 else {
2300 assert(grid_loc == CGNS_ENUMV(Vertex));
2301 const Ioss::NodeBlock *cnb =
2302 (block->type() == Ioss::STRUCTUREDBLOCK)
2303 ? &(dynamic_cast<Ioss::StructuredBlock *>(block)->get_node_block())
2304 : region->get_node_blocks()[0];
2305 auto *nb = const_cast<Ioss::NodeBlock *>(cnb);
2306 if (nb == nullptr) {
2307 IOSS_ERROR(
2308 fmt::format("ERROR: CGNS: Null entity accessing nodeblock for structured block {}.",
2309 block->name()));
2310 }
2311 size_t entity_count = nb->entity_count();
2312 Ioss::Utils::get_fields(entity_count, field_names, Ioss::Field::TRANSIENT,
2313 region->get_database(), nullptr, fields);
2314 size_t index = 1;
2315 for (const auto &field : fields) {
2316 Utils::set_field_index(field, index, grid_loc);
2317 index += field.raw_storage()->component_count();
2318 nb->field_add(field);
2319 }
2320 }
2321 }
2322 };
2323 // ==========================================
2324
2325 if (!timesteps.empty()) {
2326 const auto &sblocks = region->get_structured_blocks();
2327 for (auto &block : sblocks) {
2328 if (is_parallel_io || block->is_active()) {
2329 sol_iter(block);
2330 }
2331 }
2332 const auto &eblocks = region->get_element_blocks();
2333 for (auto &block : eblocks) {
2334 sol_iter(block);
2335 }
2336 bool is_parallel = region->get_database()->util().parallel_size() > 1;
2337 if (is_parallel && !is_parallel_io) {
2338 sync_transient_variables_fpp(region);
2339 }
2340 }
2341 }
2342
2343 int Iocgns::Utils::get_step_times(int cgns_file_ptr, std::vector<double> &timesteps,
2344 Ioss::Region *region, double timeScaleFactor, int myProcessor)
2345 {
2346 int base = 1;
2347 int num_timesteps = 0;
2348 char bitername[CGNS_MAX_NAME_LENGTH + 1];
2349 int ierr = cg_biter_read(cgns_file_ptr, base, bitername, &num_timesteps);
2350 if (ierr == CG_NODE_NOT_FOUND) {
2351 return num_timesteps;
2352 }
2353 if (ierr == CG_ERROR) {
2354 Utils::cgns_error(cgns_file_ptr, __FILE__, __func__, __LINE__, myProcessor);
2355 }
2356
2357 if (num_timesteps <= 0) {
2358 return num_timesteps;
2359 }
2360
2361 // Read the timestep time values.
2362 CGCHECK(cg_goto(cgns_file_ptr, base, "BaseIterativeData_t", 1, "end"));
2363 std::vector<double> times(num_timesteps);
2364 CGCHECK(cg_array_read_as(1, CGNS_ENUMV(RealDouble), Data(times)));
2365
2366 timesteps.reserve(num_timesteps);
2367 for (int i = 0; i < num_timesteps; i++) {
2368 if (nullptr != region) {
2369 region->add_state(times[i] * timeScaleFactor);
2370 }
2371 timesteps.push_back(times[i]);
2372 }
2373 return num_timesteps;
2374 }
2375
2376 void Iocgns::Utils::set_line_decomposition(int cgns_file_ptr, const std::string &line_decomposition,
2377 std::vector<Iocgns::StructuredZoneData *> &zones,
2378 int rank, bool verbose)
2379 {
2380 // The "line_decomposition" string is a list of 0 or more BC
2381 // (Family) names. For all structured zones which this BC
2382 // touches, the ordinal of the face (i,j,k) will be set such that
2383 // a parallel decomposition will not split the zone along this
2384 // ordinal. For example, if the BC "wall1" has the definition
2385 // [1->1, 1->5, 1->8], then it is on the constant 'i' face of the
2386 // zone and therefore, the zone will *not* be split along the 'i'
2387 // ordinal.
2388
2389 // Get names of all valid 'bcs' on the mesh
2390 int base = 1;
2391 int num_families = 0;
2392 CGCHECKNP(cg_nfamilies(cgns_file_ptr, base, &num_families));
2393
2394 Ioss::NameList families;
2395 families.reserve(num_families);
2396 for (int family = 1; family <= num_families; family++) {
2397 char name[CGNS_MAX_NAME_LENGTH + 1];
2398 int num_bc = 0;
2399 int num_geo = 0;
2400 CGCHECKNP(cg_family_read(cgns_file_ptr, base, family, name, &num_bc, &num_geo));
2401 if (num_bc > 0) {
2402 Ioss::Utils::fixup_name(name);
2403 families.emplace_back(name);
2404 }
2405 }
2406
2407 // Slit into fields using the commas as delimiters
2408 auto bcs = Ioss::tokenize(line_decomposition, ",");
2409 for (auto &bc : bcs) {
2410 Ioss::Utils::fixup_name(bc);
2411 if (std::find(families.begin(), families.end(), bc) == families.end()) {
2412 std::ostringstream errmsg;
2413 fmt::print(errmsg,
2414 "ERROR: CGNS: The family/bc name '{}' specified as a line decomposition surface "
2415 "does not exist on this CGNS file.\n"
2416 " Valid names are: ",
2417 bc);
2418 for (const auto &fam : families) {
2419 fmt::print(errmsg, "'{}', ", fam);
2420 }
2421 IOSS_ERROR(errmsg);
2422 }
2423 }
2424
2425 for (auto &zone : zones) {
2426 // Read BCs applied to this zone and see if they match any of
2427 // the BCs in 'bcs' list. If so, determine the face the BC is
2428 // applied to and set the m_lineOrdinal to the ordinal
2429 // perpendicular to this face.
2430 int izone = zone->m_zone;
2431 int num_bcs;
2432 CGCHECKNP(cg_nbocos(cgns_file_ptr, base, izone, &num_bcs));
2433
2434 for (int ibc = 0; ibc < num_bcs; ibc++) {
2435 char boconame[CGNS_MAX_NAME_LENGTH + 1];
2436 CGNS_ENUMT(BCType_t) bocotype;
2437 CGNS_ENUMT(PointSetType_t) ptset_type;
2438 cgsize_t npnts;
2439 cgsize_t NormalListSize;
2440 CGNS_ENUMT(DataType_t) NormalDataType;
2441 int ndataset;
2442
2443 // All we really want from this is 'boconame'
2444 CGCHECKNP(cg_boco_info(cgns_file_ptr, base, izone, ibc + 1, boconame, &bocotype, &ptset_type,
2445 &npnts, nullptr, &NormalListSize, &NormalDataType, &ndataset));
2446
2447 if (bocotype == CGNS_ENUMV(FamilySpecified)) {
2448 // Need to get boconame from cg_famname_read
2449 CGCHECKNP(
2450 cg_goto(cgns_file_ptr, base, "Zone_t", izone, "ZoneBC_t", 1, "BC_t", ibc + 1, "end"));
2451 CGCHECKNP(cg_famname_read(boconame));
2452 }
2453
2454 Ioss::Utils::fixup_name(boconame);
2455 if (std::find(bcs.begin(), bcs.end(), boconame) != bcs.end()) {
2456 cgsize_t range[6];
2457 CGCHECKNP(cg_boco_read(cgns_file_ptr, base, izone, ibc + 1, range, nullptr));
2458
2459 // There are some BC that are applied on an edge or a vertex;
2460 // Don't want those, so filter them out at this time...
2461 bool i = range[0] == range[3];
2462 bool j = range[1] == range[4];
2463 bool k = range[2] == range[5];
2464
2465 int sum = (i ? 1 : 0) + (j ? 1 : 0) + (k ? 1 : 0);
2466 // Only set m_lineOrdinal if only a single ordinal selected.
2467 if (sum == 1) {
2468 unsigned int ordinal = 0;
2469 if (i) {
2470 ordinal = Ordinal::I;
2471 }
2472 else if (j) {
2473 ordinal = Ordinal::J;
2474 }
2475 else if (k) {
2476 ordinal = Ordinal::K;
2477 }
2478 zone->m_lineOrdinal |= ordinal;
2479 if (verbose && rank == 0) {
2480 fmt::print(Ioss::DebugOut(), "Setting line ordinal to {} on {} for surface: {}\n",
2481 zone->m_lineOrdinal, zone->m_name, boconame);
2482 if (zone->m_lineOrdinal == 7) {
2483 fmt::print(Ioss::DebugOut(),
2484 "NOTE: Zone {} with work {} will not be decomposed due to line ordinal "
2485 "setting.\n",
2486 zone->m_name, fmt::group_digits(zone->work()));
2487 }
2488 }
2489 }
2490 }
2491 }
2492 }
2493 }
2494
2495 void Iocgns::Utils::decompose_model(std::vector<Iocgns::StructuredZoneData *> &zones,
2496 int proc_count, int rank, double load_balance_threshold,
2497 bool verbose)
2498 {
2499 size_t work = 0;
2500 for (const auto &z : zones) {
2501 work += z->work();
2502 assert(z->is_active());
2503 }
2504
2505 double avg_work = (double)work / proc_count;
2506
2507 if (verbose) {
2508 auto num_active = zones.size();
2509 if (rank == 0) {
2510 fmt::print(
2511 Ioss::OUTPUT(),
2512 "Decomposing structured mesh with {} zones for {} processors.\nAverage workload is {}, "
2513 "Load Balance Threshold is {}, Work range {} to {}\n",
2514 num_active, proc_count, fmt::group_digits((size_t)avg_work), load_balance_threshold,
2515 fmt::group_digits((size_t)(avg_work / load_balance_threshold)),
2516 fmt::group_digits((size_t)(avg_work * load_balance_threshold)));
2517 }
2518 }
2519
2520 if (avg_work < 1.0) {
2521 IOSS_ERROR(
2522 fmt::format("ERROR: Model size too small to distribute over {} processors.\n", proc_count));
2523 }
2524
2525 if (verbose) {
2526 if (rank == 0) {
2527 fmt::print(Ioss::DebugOut(),
2528 "========================================================================\n");
2529 fmt::print(Ioss::DebugOut(), "Pre-Splitting: (Average = {}, LB Threshold = {}\n",
2530 fmt::group_digits((size_t)avg_work), load_balance_threshold);
2531 }
2532 }
2533 // Split all blocks where block->work() > avg_work * load_balance_threshold
2534 int new_zone_id =
2535 Utils::pre_split(zones, avg_work, load_balance_threshold, rank, proc_count, verbose);
2536
2537 // At this point, there should be no zone with block->work() > avg_work * load_balance_threshold
2538 if (verbose) {
2539 if (rank == 0) {
2540 fmt::print(Ioss::DebugOut(),
2541 "========================================================================\n");
2542 }
2543 }
2544 size_t num_split = 0;
2545 size_t px = 0;
2546 do {
2547 std::vector<size_t> work_vector(proc_count);
2548 Utils::assign_zones_to_procs(zones, work_vector, verbose);
2549
2550 // Calculate workload ratio for each processor...
2551 px = 0; // Number of processors where workload ratio exceeds threshold.
2552 std::vector<bool> exceeds(proc_count);
2553 for (size_t i = 0; i < work_vector.size(); i++) {
2554 double workload_ratio = double(work_vector[i]) / avg_work;
2555 if (workload_ratio > load_balance_threshold) {
2556 exceeds[i] = true;
2557 px++;
2558 if (verbose && rank == 0) {
2559 fmt::print(Ioss::DebugOut(), "{}",
2560 fmt::format(
2561 #if !defined __NVCC__
2562 fg(fmt::color::red),
2563 #endif
2564 "\nProcessor {} work: {}, workload ratio: {} (exceeds)", i,
2565 fmt::group_digits(work_vector[i]), workload_ratio));
2566 }
2567 }
2568 else {
2569 if (verbose && rank == 0) {
2570 fmt::print(Ioss::DebugOut(), "\nProcessor {} work: {}, workload ratio: {}", i,
2571 fmt::group_digits(work_vector[i]), workload_ratio);
2572 }
2573 }
2574 }
2575 if (verbose && rank == 0) {
2576 fmt::print(Ioss::DebugOut(), "\n\nWorkload threshold exceeded on {} processors.\n", px);
2577 }
2578 bool single_zone = zones.size() == 1;
2579 if (single_zone) { // GDS: Don't understand this code... !single_zone?
2580 auto active = std::count_if(zones.begin(), zones.end(),
2581 [](Iocgns::StructuredZoneData *a) { return a->is_active(); });
2582 if (active >= proc_count) {
2583 px = 0;
2584 }
2585 }
2586 num_split = 0;
2587 if (px > 0) {
2588 auto zone_new(zones);
2589 for (auto &zone : zones) {
2590 if (zone->is_active() && exceeds[zone->m_proc]) {
2591 // Since 'zones' is sorted from most work to least,
2592 // we just iterate zones and check whether the zone
2593 // is on a proc where the threshold was exceeded.
2594 // if so, split the block and set exceeds[proc] to false;
2595 // Exit the loop when num_split >= px.
2596 auto children = zone->split(new_zone_id, zone->work() / 2.0, rank, verbose);
2597 if (children.first != nullptr && children.second != nullptr) {
2598 zone_new.push_back(children.first);
2599 zone_new.push_back(children.second);
2600
2601 new_zone_id += 2;
2602 exceeds[zone->m_proc] = false;
2603 num_split++;
2604 if (num_split >= px) {
2605 break;
2606 }
2607 }
2608 }
2609 }
2610 std::swap(zone_new, zones);
2611 }
2612 if (verbose) {
2613 auto active = std::count_if(zones.begin(), zones.end(),
2614 [](Iocgns::StructuredZoneData *a) { return a->is_active(); });
2615 if (rank == 0) {
2616 fmt::print(Ioss::DebugOut(), "Number of active zones = {}, average work = {}\n", active,
2617 fmt::group_digits((size_t)avg_work));
2618 fmt::print(Ioss::DebugOut(),
2619 "========================================================================\n");
2620 }
2621 }
2622 } while (px > 0 && num_split > 0);
2623 }
2624
2625 void Iocgns::Utils::assign_zones_to_procs(std::vector<Iocgns::StructuredZoneData *> &all_zones,
2626 std::vector<size_t> &work_vector, bool verbose)
2627 {
2628 for (auto &zone : all_zones) {
2629 zone->m_proc = -1;
2630 }
2631
2632 // Sort zones based on work. Most work first.. Filtered to active only...
2633 std::vector<Iocgns::StructuredZoneData *> zones;
2634 std::copy_if(all_zones.begin(), all_zones.end(), std::back_inserter(zones),
2635 [](Iocgns::StructuredZoneData *z) { return z->is_active(); });
2636
2637 Ioss::sort(zones.begin(), zones.end(),
2638 [](Iocgns::StructuredZoneData *a, Iocgns::StructuredZoneData *b) {
2639 return a->work() > b->work();
2640 });
2641
2642 std::set<std::pair<int, int>> proc_adam_map;
2643
2644 // On first entry, work_vector will be all zeros. To avoid any
2645 // searching, assign the first `nproc` zones to the `nproc` entries
2646 // in `work_vector`. Avoids searching...
2647 if (zones.size() < work_vector.size()) {
2648 IOSS_ERROR(fmt::format(
2649 "IOCGNS error: Could not decompose mesh across {} processors based on constraints.",
2650 work_vector.size()));
2651 }
2652 assert(zones.size() >= work_vector.size());
2653 size_t i = 0;
2654 for (; i < work_vector.size(); i++) {
2655 auto &zone = zones[i];
2656 zone->m_proc = i;
2657 if (verbose) {
2658 fmt::print(Ioss::DebugOut(),
2659 "Assigning zone '{}' with work {} to processor {}. Changing work from {} to {}\n",
2660 zone->m_name, fmt::group_digits(zone->work()), zone->m_proc,
2661 fmt::group_digits(work_vector[i]),
2662 fmt::group_digits(zone->work() + work_vector[i]));
2663 }
2664 work_vector[i] += zone->work();
2665 proc_adam_map.insert(std::make_pair(zone->m_adam->m_zone, zone->m_proc));
2666 }
2667
2668 for (; i < zones.size(); i++) {
2669 auto &zone = zones[i];
2670
2671 // Assign zone to processor with minimum work that does not already have a zone with the same
2672 // adam zone...
2673 int proc = proc_with_minimum_work(zone, work_vector, proc_adam_map);
2674
2675 // See if any other zone on this processor has the same adam zone...
2676 if (proc >= 0) {
2677 auto success = proc_adam_map.insert(std::make_pair(zone->m_adam->m_zone, proc));
2678 if (success.second) {
2679 zone->m_proc = proc;
2680 if (verbose) {
2681 fmt::print(Ioss::DebugOut(),
2682 "Assigning zone '{}' with work {} to processor {}. Changing work from {} "
2683 "to {}\n",
2684 zone->m_name, fmt::group_digits(zone->work()), zone->m_proc,
2685 fmt::group_digits(work_vector[proc]),
2686 fmt::group_digits(zone->work() + work_vector[proc]));
2687 }
2688 work_vector[proc] += zone->work();
2689 }
2690 else {
2691 IOSS_ERROR(
2692 fmt::format("IOCGNS error: Could not assign zones to processors in {}", __func__));
2693 }
2694 }
2695 else {
2696 IOSS_ERROR(fmt::format("IOCGNS error: Could not assign zones to processors in {}", __func__));
2697 }
2698 }
2699 }
2700
2701 int Iocgns::Utils::pre_split(std::vector<Iocgns::StructuredZoneData *> &zones, double avg_work,
2702 double load_balance, int proc_rank, int proc_count, bool verbose)
2703 {
2704 auto original_zones(zones); // In case we need to call this again...
2705
2706 auto new_zones(zones);
2707 int new_zone_id = static_cast<int>(zones.size()) + 1;
2708
2709 // See if can split each zone over a set of procs...
2710 std::vector<int> splits(zones.size(), 1);
2711
2712 if ((int)zones.size() < proc_count) {
2713 for (size_t i = 0; i < zones.size(); i++) {
2714 auto zone = zones[i];
2715 if (zone->m_lineOrdinal != 7) {
2716 double work = zone->work();
2717 if (load_balance <= 1.2) {
2718 splits[i] = int(std::ceil(work / avg_work));
2719 }
2720 else {
2721 splits[i] = int(std::round(work / avg_work + 0.2));
2722 }
2723 splits[i] = splits[i] == 0 ? 1 : splits[i];
2724 }
2725 }
2726 }
2727
2728 int num_splits = std::accumulate(splits.begin(), splits.end(), 0);
2729 int diff = proc_count - num_splits;
2730 bool adjustment_needed = diff > 0;
2731
2732 if (num_splits != (int)zones.size()) {
2733 while (diff != 0) {
2734 // Adjust splits so sum is equal to proc_count.
2735 // Adjust the largest split count(s)
2736 int step = diff < 0 ? -1 : 1;
2737 size_t min_z = 0;
2738 double min_delta = 1.0e27;
2739 for (size_t i = 0; i < zones.size(); i++) {
2740 auto zone = zones[i];
2741 double work = zone->work();
2742
2743 if (splits[i] == 0) {
2744 continue;
2745 }
2746 if ((splits[i] + step) > 0) {
2747 double delta = std::abs(avg_work - work / (double)(splits[i] + step));
2748 if (delta < min_delta) {
2749 min_delta = delta;
2750 min_z = i;
2751 }
2752 }
2753 }
2754 splits[min_z] += step;
2755 diff -= step;
2756 }
2757 assert(diff == 0);
2758 assert(std::accumulate(splits.begin(), splits.end(), 0) == proc_count);
2759 }
2760
2761 // See if splits result in avg_work for all zones in range...
2762 double min_avg = avg_work / load_balance;
2763 double max_avg = avg_work * load_balance;
2764 bool adaptive_avg = true;
2765 if (!adjustment_needed) {
2766 for (size_t i = 0; i < zones.size(); i++) {
2767 auto zone = zones[i];
2768 double work = zone->work();
2769 if (splits[i] == 0) {
2770 adaptive_avg = false;
2771 break;
2772 }
2773 double zone_avg = work / (double)splits[i];
2774 if (zone_avg < min_avg || zone_avg > max_avg) {
2775 adaptive_avg = false;
2776 break;
2777 }
2778 }
2779 }
2780
2781 if (adaptive_avg) {
2782 for (size_t i = 0; i < zones.size(); i++) {
2783 auto zone = zones[i];
2784
2785 auto work_average = avg_work;
2786 int split_cnt = splits[i];
2787 if (split_cnt == 1) {
2788 continue;
2789 }
2790
2791 std::vector<std::pair<int, Iocgns::StructuredZoneData *>> active;
2792 active.emplace_back(split_cnt, zone);
2793 int num_active = 0;
2794 do {
2795 assert(!active.empty());
2796 split_cnt = active.back().first;
2797 zone = active.back().second;
2798 active.pop_back();
2799
2800 if (zone->is_active()) {
2801 if (split_cnt != 1) {
2802 int max_power_2 = power_2(split_cnt);
2803 if (max_power_2 == split_cnt) {
2804 work_average = zone->work() / 2.0;
2805 max_power_2 /= 2;
2806 }
2807 else {
2808 work_average = zone->work() / (double(split_cnt) / double(max_power_2));
2809 }
2810
2811 auto children = zone->split(new_zone_id, work_average, proc_rank, verbose);
2812 if (children.first != nullptr && children.second != nullptr) {
2813 new_zones.push_back(children.first);
2814 new_zones.push_back(children.second);
2815 new_zone_id += 2;
2816 active.emplace_back(split_cnt - max_power_2, children.second);
2817 active.emplace_back(max_power_2, children.first);
2818 num_active++;
2819 }
2820 }
2821 }
2822 if (num_active >=
2823 proc_count) { // Don't split a single zone into more than `proc_count` pieces
2824 break;
2825 }
2826 } while (!active.empty());
2827 }
2828 }
2829 else {
2830 for (auto &zone : zones) {
2831 if (zone->work() <= max_avg) {
2832 // This zone is already in `new_zones`; just skip doing anything else with it.
2833 }
2834 else {
2835 std::vector<std::pair<int, Iocgns::StructuredZoneData *>> active;
2836
2837 double work = zone->work();
2838 int split_cnt = int(work / avg_work);
2839 int num_active = 0;
2840
2841 // Find modulus of work % avg_work and split off that amount
2842 // which will be < avg_work.
2843 double mod_work = work - avg_work * split_cnt;
2844 if (mod_work > max_avg - avg_work) {
2845 auto children = zone->split(new_zone_id, mod_work, proc_rank, verbose);
2846 if (children.first != nullptr && children.second != nullptr) {
2847 new_zones.push_back(children.first);
2848 new_zones.push_back(children.second);
2849 new_zone_id += 2;
2850 num_active++;
2851 active.emplace_back(split_cnt, children.second);
2852 }
2853 else {
2854 active.emplace_back(split_cnt, zone);
2855 }
2856 }
2857 else {
2858 active.emplace_back(split_cnt, zone);
2859 }
2860
2861 // The work remaining on this zone should be approximately
2862 // equally divided among `split_cnt` processors.
2863 do {
2864 assert(!active.empty());
2865 split_cnt = active.back().first;
2866 zone = active.back().second;
2867 active.pop_back();
2868
2869 if (zone->is_active()) {
2870 int max_power_2 = power_2(split_cnt);
2871 double work_average = 0.0;
2872 if (max_power_2 == split_cnt) {
2873 work_average = zone->work() / 2.0;
2874 }
2875 else {
2876 work_average = zone->work() / (double(split_cnt) / double(max_power_2));
2877 }
2878
2879 if (max_power_2 != 1) {
2880 if (max_power_2 == split_cnt) {
2881 max_power_2 /= 2;
2882 }
2883 auto children = zone->split(new_zone_id, work_average, proc_rank, verbose);
2884 if (children.first != nullptr && children.second != nullptr) {
2885 new_zones.push_back(children.first);
2886 new_zones.push_back(children.second);
2887 new_zone_id += 2;
2888 active.emplace_back(split_cnt - max_power_2, children.second);
2889 active.emplace_back(max_power_2, children.first);
2890 num_active++;
2891 }
2892 }
2893 }
2894 if (num_active >=
2895 proc_count) { // Don't split a single zone into more than `proc_count` pieces
2896 break;
2897 }
2898 } while (!active.empty());
2899 }
2900 }
2901 }
2902 std::swap(new_zones, zones);
2903 size_t active = std::count_if(zones.begin(), zones.end(),
2904 [](const Iocgns::StructuredZoneData *z) { return z->is_active(); });
2905
2906 if (active < (size_t)proc_count && load_balance > 1.05) {
2907 // Tighten up the load_balance factor to get some decomposition going...
2908 double new_load_balance = (1.0 + load_balance) / 2.0;
2909
2910 // If any of the original zones were split the first time we called this routine,
2911 // we need to delete the zones created via splitting.
2912 // Also reset the parent zone to not have any children...
2913 for (auto &zone : zones) {
2914 if (!zone->is_active()) {
2915 zone->m_child1 = nullptr;
2916 zone->m_child2 = nullptr;
2917 }
2918 if (zone->m_adam != zone) {
2919 // Created via a split; delete...
2920 delete zone;
2921 }
2922 }
2923
2924 // Revert `zones` back to original version (with no zones split)
2925 zones = std::move(original_zones);
2926 new_zone_id = pre_split(zones, avg_work, new_load_balance, proc_rank, proc_count, verbose);
2927 }
2928 return new_zone_id;
2929 }
2930
2931 std::vector<Iocgns::ZoneBC> Iocgns::Utils::parse_zonebc_sideblocks(int cgns_file_ptr, int base,
2932 int zone, int myProcessor)
2933 {
2934 int num_bc;
2935 CGCHECK(cg_nbocos(cgns_file_ptr, base, zone, &num_bc));
2936
2937 std::vector<Iocgns::ZoneBC> zonebc;
2938 zonebc.reserve(num_bc);
2939
2940 for (int i = 0; i < num_bc; i++) {
2941 char boco_name[CGNS_MAX_NAME_LENGTH + 1];
2942 CGNS_ENUMT(BCType_t) boco_type;
2943 CGNS_ENUMT(PointSetType_t) ptset_type;
2944 cgsize_t num_pnts;
2945 cgsize_t normal_list_size; // ignore
2946 CGNS_ENUMT(DataType_t) normal_data_type; // ignore
2947 int num_dataset; // ignore
2948 CGCHECK(cg_boco_info(cgns_file_ptr, base, zone, i + 1, boco_name, &boco_type, &ptset_type,
2949 &num_pnts, nullptr, &normal_list_size, &normal_data_type, &num_dataset));
2950
2951 if (num_pnts != 2 || ptset_type != CGNS_ENUMV(PointRange)) {
2952 IOSS_ERROR(fmt::format(
2953 "CGNS: In Zone {}, boundary condition '{}' has a PointSetType of '{}' and {} points.\n"
2954 " The type must be 'PointRange' and there must be 2 points.",
2955 zone, boco_name, cg_PointSetTypeName(ptset_type), num_pnts));
2956 }
2957
2958 std::array<cgsize_t, 2> point_range;
2959 CGCHECK(cg_boco_read(cgns_file_ptr, base, zone, i + 1, Data(point_range), nullptr));
2960 zonebc.emplace_back(boco_name, point_range);
2961 }
2962 return zonebc;
2963 }
2964
2965 #ifdef CG_BUILD_HDF5
2966 extern "C" int H5get_libversion(unsigned *, unsigned *, unsigned *);
2967 #endif
2968
2969 std::string Iocgns::Utils::show_config()
2970 {
2971 std::stringstream config;
2972 fmt::print(config, "\tCGNS Library Version: {}\n", CGNS_DOTVERS);
2973 #if CG_BUILD_64BIT
2974 fmt::print(config, "\t\tDefault integer size is 64-bit.\n");
2975 #else
2976 fmt::print(config, "\t\tDefault integer size is 32-bit.\n");
2977 #endif
2978 #if defined(CGNS_SCOPE_ENUMS)
2979 fmt::print(config, "\t\tScoped Enums enabled\n");
2980 #else
2981 fmt::print(config, "\t\tScoped Enums NOT enabled\n");
2982 #endif
2983 #if defined(CG_COMPACT)
2984 fmt::print(config, "\t\tCompact Storage enabled\n");
2985 #else
2986 fmt::print(config, "\t\tCompact Storage NOT enabled\n");
2987 #endif
2988 #if CG_BUILD_PARALLEL
2989 fmt::print(config, "\t\tParallel enabled\n");
2990 #else
2991 fmt::print(config, "\t\tParallel NOT enabled\n");
2992 #endif
2993 #if CG_BUILD_HDF5
2994 unsigned major;
2995 unsigned minor;
2996 unsigned release;
2997 H5get_libversion(&major, &minor, &release);
2998 fmt::print(config, "\t\tHDF5 enabled ({}.{}.{})\n", major, minor, release);
2999 #else
3000 #error "Not defined..."
3001 #endif
3002 #if HDF5_HAVE_COLL_METADATA
3003 fmt::print(config, "\t\tUsing HDF5 Collective Metadata.\n");
3004 #else
3005 fmt::print(config, "\t\tHDF5 Collective Metadata NOT Available.\n");
3006 #endif
3007 #if HDF5_HAVE_MULTI_DATASET
3008 fmt::print(config, "\t\tHDF5 Multi-Dataset Available.\n\n");
3009 #else
3010 fmt::print(config, "\t\tHDF5 Multi-Dataset NOT Available.\n\n");
3011 #endif
3012 return config.str();
3013 }
3014
3015 namespace {
3016 void create_face(Ioss::FaceUnorderedSet &faces, size_t id, std::array<size_t, 4> &conn,
3017 size_t element, int local_face)
3018 {
3019 Ioss::Face face(id, conn);
3020 auto face_iter = faces.insert(face);
3021
3022 (*(face_iter.first)).add_element(element * 10 + local_face);
3023 }
3024 } // namespace
3025
3026 template <typename INT>
3027 void Iocgns::Utils::generate_block_faces(Ioss::ElementTopology *topo, size_t num_elem,
3028 const std::vector<INT> &connectivity,
3029 Ioss::FaceUnorderedSet &boundary,
3030 const std::vector<INT> &zone_local_zone_global)
3031 {
3032 // Only handle continuum elements at this time...
3033 if (topo->parametric_dimension() != 3) {
3034 return;
3035 }
3036
3037 int num_face_per_elem = topo->number_faces();
3038 assert(num_face_per_elem <= 6);
3039 std::array<Ioss::IntVector, 6> face_conn;
3040 std::array<int, 6> face_node_count{};
3041 for (int face = 0; face < num_face_per_elem; face++) {
3042 face_conn[face] = topo->face_connectivity(face + 1);
3043 face_node_count[face] = topo->face_type(face + 1)->number_corner_nodes();
3044 }
3045
3046 Ioss::FaceUnorderedSet all_faces;
3047 int num_node_per_elem = topo->number_nodes();
3048 for (size_t elem = 0, offset = 0; elem < num_elem; elem++, offset += num_node_per_elem) {
3049 for (int face = 0; face < num_face_per_elem; face++) {
3050 size_t id = 0;
3051 assert(face_node_count[face] <= 4);
3052 std::array<size_t, 4> conn = {{0, 0, 0, 0}};
3053 for (int j = 0; j < face_node_count[face]; j++) {
3054 size_t fnode = offset + face_conn[face][j];
3055 size_t lnode = connectivity[fnode]; // local since "connectivity_raw"
3056 conn[j] = lnode;
3057 id += Ioss::FaceGenerator::id_hash(lnode);
3058 }
3059 auto elem_id = zone_local_zone_global[elem];
3060 create_face(all_faces, id, conn, elem_id, face);
3061 }
3062 }
3063
3064 // All faces generated for this element block; now extract boundary faces...
3065 for (auto &face : all_faces) {
3066 if (face.element_count() == 1) {
3067 boundary.insert(face);
3068 }
3069 }
3070 }
3071
3072 template void Iocgns::Utils::generate_block_faces<int>(
3073 Ioss::ElementTopology *topo, size_t num_elem, const std::vector<int> &connectivity,
3074 Ioss::FaceUnorderedSet &boundary, const std::vector<int> &zone_local_zone_global);
3075 template void Iocgns::Utils::generate_block_faces<int64_t>(
3076 Ioss::ElementTopology *topo, size_t num_elem, const std::vector<int64_t> &connectivity,
3077 Ioss::FaceUnorderedSet &boundary, const std::vector<int64_t> &zone_local_zone_global);