Debian Codegraph @

packages/seacas/libraries/ioss/src/cgns/Iocgns_DatabaseIO.C

raw
1 // CGNS Assumptions:
2 // * All boundary conditions are listed as Family nodes at the "top" level.
3 // * Single element block per zone.
4 // * Single Base.
5 // * ZoneGridConnectivity is 1to1 with point lists for unstructured
6
7 // Copyright(C) 1999-2024 National Technology & Engineering Solutions
8 // of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
9 // NTESS, the U.S. Government retains certain rights in this software.
10 //
11 // See packages/seacas/LICENSE for details
12
13 #include "Ioss_CodeTypes.h"
14 #include "Ioss_Utils.h"
15 #include "cgns/Iocgns_DatabaseIO.h"
16 #include "cgns/Iocgns_Utils.h"
17 #include <array>
18 #include <bitset>
19 #include <cgnslib.h>
20 #include <cstddef>
21 #include <fmt/core.h>
22 #include <fmt/ostream.h>
23 #include <iostream>
24 #include <numeric>
25 #include <string>
26 #include <vector>
27 #ifndef CG_BUILD_PARALLEL
28 #include <cgnsconfig.h>
29 #endif
30 #if CG_BUILD_PARALLEL
31 #include <pcgnslib.h>
32 #endif
33
34 #include "cgns/Iocgns_Defines.h"
35
36 #if !defined(CGNSLIB_H)
37 #error "Could not include cgnslib.h"
38 #endif
39
40 #include "Ioss_Assembly.h"
41 #include "Ioss_CommSet.h"
42 #include "Ioss_DBUsage.h"
43 #include "Ioss_DataSize.h"
44 #include "Ioss_DatabaseIO.h"
45 #include "Ioss_EdgeBlock.h"
46 #include "Ioss_EdgeSet.h"
47 #include "Ioss_ElementBlock.h"
48 #include "Ioss_ElementSet.h"
49 #include "Ioss_ElementTopology.h"
50 #include "Ioss_EntityBlock.h"
51 #include "Ioss_EntityType.h"
52 #include "Ioss_FaceBlock.h"
53 #include "Ioss_FaceGenerator.h"
54 #include "Ioss_FaceSet.h"
55 #include "Ioss_Field.h"
56 #include "Ioss_FileInfo.h"
57 #include "Ioss_GroupingEntity.h"
58 #include "Ioss_Hex8.h"
59 #include "Ioss_Map.h"
60 #include "Ioss_MeshType.h"
61 #include "Ioss_NodeBlock.h"
62 #include "Ioss_NodeSet.h"
63 #include "Ioss_ParallelUtils.h"
64 #include "Ioss_Property.h"
65 #include "Ioss_PropertyManager.h"
66 #include "Ioss_Quad4.h"
67 #include "Ioss_Region.h"
68 #include "Ioss_SideBlock.h"
69 #include "Ioss_SideSet.h"
70 #include "Ioss_SmartAssert.h"
71 #include "Ioss_State.h"
72 #include "Ioss_StructuredBlock.h"
73 #include "Ioss_VariableType.h"
74 #include "Ioss_ZoneConnectivity.h"
75 #include "robin_hash.h"
76 #include "robin_set.h"
77 #include "tokenize.h"
78
79 // extern char hdf5_access[64];
80
81 namespace {
82 size_t global_to_zone_local_idx(size_t i, const Ioss::Map *block_map, const Ioss::Map &nodeMap,
83 bool isParallel)
84 {
85 auto global = block_map->map()[i + 1]; // 1-based index over all nodes in model (all procs)
86 if (isParallel) {
87 return nodeMap.global_to_local(global) - 1;
88 }
89 return global - 1;
90 }
91
92 #if CG_BUILD_PARALLEL
93 bool has_decomp_descriptor(int cgns_file_ptr, int base, int zone, int zgc_idx)
94 {
95 bool has_decomp_flag = false;
96 if (cg_goto(cgns_file_ptr, base, "Zone_t", zone, "ZoneGridConnectivity", 0,
97 "GridConnectivity1to1_t", zgc_idx, "end") == CG_OK) {
98 int ndescriptor = 0;
99 cg_ndescriptors(&ndescriptor);
100 if (ndescriptor > 0) {
101 for (int i = 0; i < ndescriptor; i++) {
102 char name[33];
103 char *text;
104 cg_descriptor_read(i + 1, name, &text);
105 if (strcmp(name, "Decomp") == 0) {
106 has_decomp_flag = true;
107 break;
108 }
109 cg_free(text);
110 }
111 }
112 }
113 return has_decomp_flag;
114 }
115
116 bool has_decomp_name_kluge(int cgns_file_ptr, int base, int zone, int zgc_idx)
117 {
118 // Check the `zgc_idx`-th ZGC node to see if the name matches the
119 // form described in the `name_is_decomp` function below. We want to
120 // see if there are *any* names that match this form and if so, we can
121 // use the kluge; otherwise we can't and need to rely on other heuristics.
122 char connectname[CGNS_MAX_NAME_LENGTH + 1];
123 char donorname[CGNS_MAX_NAME_LENGTH + 1];
124 std::array<cgsize_t, 6> range;
125 std::array<cgsize_t, 6> donor_range;
126 Ioss::IJK_t transform{};
127
128 cg_1to1_read(cgns_file_ptr, base, zone, zgc_idx, connectname, donorname, range.data(),
129 donor_range.data(), transform.data());
130
131 std::string name{connectname};
132 bool has_decomp_name = ((name.find_first_not_of("0123456789_-") == std::string::npos) &&
133 (name.find("--", 1 != std::string::npos)));
134
135 return has_decomp_name;
136 }
137
138 bool name_is_decomp(const std::string &name)
139 {
140 // Major kluge to deal with fpp files which don't have the
141 // decomp descriptor. Usually only required if the model is
142 // periodic...
143 //
144 // A zgc name that is generated as part of the decomposition process
145 // has the following characteristics:
146 // * is all [0-9_-] characters
147 // * has "--" in the middle (approx) of the name
148 return ((name.find_first_not_of("0123456789_-") == std::string::npos) &&
149 (name.find("--", 1 != std::string::npos)));
150 }
151
152 void zgc_check_descriptor(int cgns_file_ptr, int base, int zone, int zgc_idx,
153 Ioss::ZoneConnectivity &zgc)
154 {
155 if (cg_goto(cgns_file_ptr, base, "Zone_t", zone, "ZoneGridConnectivity", 0,
156 "GridConnectivity1to1_t", zgc_idx, "end") == CG_OK) {
157 int ndescriptor = 0;
158 cg_ndescriptors(&ndescriptor);
159 if (ndescriptor > 0) {
160 for (int i = 0; i < ndescriptor; i++) {
161 char name[33];
162 char *text = nullptr;
163 cg_descriptor_read(i + 1, name, &text);
164 if (strcmp(name, "OriginalName") == 0) {
165 zgc.m_connectionName = text;
166 cg_free(text);
167 break;
168 }
169 if (strcmp(name, "Decomp") == 0) {
170 zgc.m_fromDecomp = true;
171 cg_free(text);
172 break;
173 }
174 cg_free(text);
175 }
176 }
177 }
178 }
179
180 template <typename T> void pack(int &idx, std::vector<int> &pack, T *from, int count)
181 {
182 for (int i = 0; i < count; i++) {
183 pack[idx++] = from[i];
184 }
185 }
186 #endif
187
188 template <typename T> void unpack(int &idx, const T *pack, T *to, int count)
189 {
190 for (int i = 0; i < count; i++) {
191 to[i] = pack[idx++];
192 }
193 }
194
195 struct SBlock
196 {
197 SBlock() = default;
198 SBlock(char *names, const int *data) : name(std::string{names})
199 {
200 int idx = 0;
201 proc = data[idx++];
202 unpack(idx, data, Data(range), 3);
203 local_zone = data[idx++];
204 }
205 std::string name{};
206 int proc{-1};
207 int local_zone{};
208 std::vector<std::pair<int, int>> adjacency; // face, proc pairs
209 std::array<int, 3> range{{0, 0, 0}};
210 std::array<int, 3> glob_range{{0, 0, 0}};
211 std::array<int, 3> offset{{0, 0, 0}};
212 std::bitset<6> face_adj{};
213
214 #if CG_BUILD_PARALLEL
215 bool split() const { return face_adj.any(); }
216 #endif
217 };
218
219 #if CG_BUILD_PARALLEL
220 void add_zgc_fpp(int cgns_file_ptr, Ioss::StructuredBlock *block,
221 const std::map<std::string, int> &zone_name_map, int myProcessor,
222 bool isParallel)
223 {
224 int base = block->get_property("base").get_int();
225 int zone = block->get_property("zone").get_int();
226 int db_zone = Iocgns::Utils::get_db_zone(block);
227 int nconn = 0;
228 CGCHECK(cg_n1to1(cgns_file_ptr, base, db_zone, &nconn));
229
230 for (int ii = 0; ii < nconn; ii++) {
231 char connectname[CGNS_MAX_NAME_LENGTH + 1];
232 char donorname[CGNS_MAX_NAME_LENGTH + 1];
233 std::array<cgsize_t, 6> range{};
234 std::array<cgsize_t, 6> donor_range{};
235 Ioss::IJK_t transform{};
236
237 CGCHECK(cg_1to1_read(cgns_file_ptr, base, db_zone, ii + 1, connectname, donorname,
238 range.data(), donor_range.data(), transform.data()));
239
240 auto donorname_proc = Iocgns::Utils::decompose_name(donorname, isParallel);
241 std::string donor_name = donorname_proc.first;
242
243 // Get number of nodes shared with other "previous" zones...
244 // A "previous" zone will have a lower zone number this this zone...
245 int donor_zone = -1;
246 auto donor_iter = zone_name_map.find(donor_name);
247 if (donor_iter != zone_name_map.end()) {
248 donor_zone = (*donor_iter).second;
249 }
250 Ioss::IJK_t range_beg{{(int)range[0], (int)range[1], (int)range[2]}};
251 Ioss::IJK_t range_end{{(int)range[3], (int)range[4], (int)range[5]}};
252 Ioss::IJK_t donor_beg{{(int)donor_range[0], (int)donor_range[1], (int)donor_range[2]}};
253 Ioss::IJK_t donor_end{{(int)donor_range[3], (int)donor_range[4], (int)donor_range[5]}};
254
255 Ioss::IJK_t offset = block->get_ijk_offset();
256 range_beg[0] += offset[0];
257 range_beg[1] += offset[1];
258 range_beg[2] += offset[2];
259 range_end[0] += offset[0];
260 range_end[1] += offset[1];
261 range_end[2] += offset[2];
262
263 auto con_name = Iocgns::Utils::decompose_name(connectname, isParallel).first;
264 block->m_zoneConnectivity.emplace_back(con_name, zone, donor_name, donor_zone, transform,
265 range_beg, range_end, donor_beg, donor_end, offset);
266
267 block->m_zoneConnectivity.back().m_ownerProcessor = myProcessor;
268 block->m_zoneConnectivity.back().m_donorProcessor = donorname_proc.second;
269
270 if (isParallel) {
271 zgc_check_descriptor(cgns_file_ptr, base, db_zone, ii + 1,
272 block->m_zoneConnectivity.back());
273 }
274 }
275 }
276
277 int adjacent_block(const SBlock &b, int ijk, std::map<int, int> &proc_block_map)
278 {
279 // Find a block the the 'left|right|up|down|front|back' (ijk) of blocks[br]
280 if (b.face_adj[ijk]) {
281 for (auto adj : b.adjacency) {
282 if (adj.first == ijk) {
283 int proc = adj.second;
284 return proc_block_map[proc];
285 }
286 }
287 }
288 return -1;
289 }
290
291 void set_block_offset(size_t begin, size_t end, std::vector<SBlock> &blocks,
292 std::map<int, int> &proc_block_map)
293 {
294 for (size_t p = 0; p < (end - begin); p++) {
295 for (size_t j = begin; j < end; j++) {
296 auto &block = blocks[j];
297 // See which blocks are below/left/under this block which means
298 // that this blocks offset is affected.
299 for (int ijk = 0; ijk < 3; ijk++) {
300 int br = adjacent_block(block, ijk, proc_block_map);
301 if (br >= 0) {
302 block.offset[ijk] = blocks[br].offset[ijk] + blocks[br].range[ijk];
303 }
304 }
305 }
306 }
307 }
308
309 void set_global_extent(size_t begin, size_t end, std::vector<SBlock> &blocks,
310 std::map<int, int> &proc_block_map)
311 {
312 // Determine the global ijk extent for the block which is spread over multiple processors
313 // and is in the range [begin, end) in blocks.
314 Ioss::IJK_t global{0, 0, 0};
315 for (int ijk = 0; ijk < 3; ijk++) {
316 // Find a block in range [bbeg, bend) with no block to the "left|below|behind
317 for (size_t bb = begin; bb < end; bb++) {
318 if (blocks[bb].face_adj[ijk] == 0) {
319 // No blocks to min 'ijk' direction...
320 // Traverse all blocks toward max 'ijk' direction setting offsets and global range.
321 size_t iter = 0;
322 int br = bb;
323 do {
324 global[ijk] += blocks[br].range[ijk];
325 #if IOSS_DEBUG_OUTPUT
326 const auto b = blocks[br];
327 fmt::print(Ioss::DebugOut(), "Min {}: {} {} ({} {} {}) [{}]\n",
328 (ijk == 0 ? 'i'
329 : ijk == 1 ? 'j'
330 : 'k'),
331 b.name, b.face_adj[ijk], b.range[0], b.range[1], b.range[2],
332 b.face_adj.to_string('.', '+'));
333 #endif
334 br = adjacent_block(blocks[br], ijk + 3, proc_block_map);
335 if (++iter > end - begin) {
336 auto bp = adjacent_block(blocks[br], ijk + 3, proc_block_map);
337 IOSS_ERROR(
338 fmt::format("ERROR: CGNS: Block '{}' is in infinite loop calculating processor "
339 "adjacencies for direction "
340 "'{}' on processors {} and {}. Check decomposition.",
341 blocks[bb].name,
342 (ijk == 0 ? 'i'
343 : ijk == 1 ? 'j'
344 : 'k'),
345 blocks[bp].proc, blocks[br].proc));
346 }
347 } while (br >= 0);
348 break;
349 }
350 }
351 }
352 for (size_t bb = begin; bb < end; bb++) {
353 blocks[bb].glob_range = global;
354 }
355 }
356
357 int find_face(const std::array<cgsize_t, 6> &range)
358 {
359 // 0,1,2 == min x,y,z; 3,4,5 == Max x,y,z
360 bool is_x = range[0] == range[3];
361 bool is_y = range[1] == range[4];
362 #ifndef NDEBUG
363 bool is_z = range[2] == range[5];
364 #endif
365 SMART_ASSERT(is_x || is_y || is_z);
366 SMART_ASSERT((is_x ? 1 : 0) + (is_y ? 1 : 0) + (is_z ? 1 : 0) == 1);
367 int idx = is_x ? 0 : is_y ? 1 : 2;
368
369 // Which face on this block?
370 int face = idx;
371 if (range[idx] != 1) {
372 face += 3;
373 }
374 return face;
375 }
376
377 bool generate_inter_proc_adjacency(int cgns_file_ptr, int base, int zone, int myProcessor,
378 const std::string &zone_name, std::vector<int> &adjacency)
379 {
380 // Handle zone-grid-connectivity... At this point we only want
381 // the zgc that are inter-proc between the same "base zone".
382 // That is, the zgc which are result of parallel decomp.
383
384 // Stored in format: "-myproc, -local_zone, face, shared_proc" for each shared face.
385 bool zone_added = false;
386 int nconn = 0;
387 CGCHECK(cg_n1to1(cgns_file_ptr, base, zone, &nconn));
388
389 // See if any of the zgc have a "Decomp" descriptor node. If so, then
390 // We can unambiguously determine whether a ZGC is from decomp or is
391 // normal inter-zone ZGC. If the descriptor does not exist, then have
392 // to rely on heuristics...
393 bool has_decomp_flag = false;
394 bool has_decomp_names = false;
395 for (int i = 0; i < nconn; i++) {
396 if (has_decomp_descriptor(cgns_file_ptr, base, zone, i + 1)) {
397 has_decomp_flag = true;
398 }
399 if (has_decomp_name_kluge(cgns_file_ptr, base, zone, i + 1)) {
400 has_decomp_names = true;
401 }
402 }
403
404 #if IOSS_DEBUG_OUTPUT
405 fmt::print("[{}] CGNS DatabaseIO has decomp flag? {}; names? {}\n", myProcessor,
406 has_decomp_flag, has_decomp_names);
407 #endif
408
409 for (int i = 0; i < nconn; i++) {
410 char connectname[CGNS_MAX_NAME_LENGTH + 1];
411 char donorname[CGNS_MAX_NAME_LENGTH + 1];
412 std::array<cgsize_t, 6> range;
413 std::array<cgsize_t, 6> donor_range;
414 Ioss::IJK_t transform{};
415
416 CGCHECK(cg_1to1_read(cgns_file_ptr, base, zone, i + 1, connectname, donorname, range.data(),
417 donor_range.data(), transform.data()));
418
419 auto donorname_proc = Iocgns::Utils::decompose_name(donorname, true);
420 std::string donor_name = donorname_proc.first;
421 auto donor_proc = donorname_proc.second;
422
423 bool is_from_decomp = false;
424 if (has_decomp_flag) {
425 is_from_decomp = has_decomp_descriptor(cgns_file_ptr, base, zone, i + 1);
426 }
427 else {
428 is_from_decomp = donor_name == zone_name && donor_proc >= 0 && donor_proc != myProcessor &&
429 (!has_decomp_names || name_is_decomp(connectname));
430 }
431 #if IOSS_DEBUG_OUTPUT
432 fmt::print(
433 "[{}] ZGC Name: {}, Has decomp descriptor: {}. Name is decomp: {}. Is_from_decomp: {}\n",
434 myProcessor, connectname, has_decomp_flag, name_is_decomp(connectname), is_from_decomp);
435 #endif
436
437 if (is_from_decomp) {
438 // See if the descriptor named "Decomp" exists as a child of this ZGC.
439 // If so, then
440 // Determine which face of the zone on this processor is
441 // shared with the other processor...
442 int face = find_face(range);
443 adjacency.push_back(-myProcessor);
444 adjacency.push_back(-zone);
445 adjacency.push_back(face);
446 adjacency.push_back(donorname_proc.second);
447 zone_added = true;
448 }
449 }
450 return zone_added;
451 }
452
453 void set_adjacency(SBlock &b, std::vector<int> &adjacency)
454 {
455 // Stored in format: "-myproc, -local_zone, face, shared_proc" for each shared face.
456 for (size_t i = 0; i < adjacency.size(); i += 4) {
457 SMART_ASSERT(adjacency[i] <= 0); // -proc
458 if (adjacency[i] == -b.proc) {
459 SMART_ASSERT(adjacency[i + 1] < 0);
460 if (adjacency[i + 1] == -b.local_zone) {
461 b.adjacency.emplace_back(adjacency[i + 2], adjacency[i + 3]);
462 b.face_adj.set(adjacency[i + 2]);
463 }
464 }
465 else if (adjacency[i] < -b.proc) {
466 return;
467 }
468 }
469 }
470
471 void add_empty_bc(Ioss::SideSet *sset, Ioss::StructuredBlock *block, int base, int zone, int face,
472 const std::string &fam_name, const std::string &boco_name)
473 {
474 SMART_ASSERT(sset != nullptr);
475
476 Ioss::IJK_t empty_range{{0, 0, 0}};
477
478 auto sbc = Ioss::BoundaryCondition(boco_name, fam_name, empty_range, empty_range);
479 sbc.m_face = face;
480 block->m_boundaryConditions.push_back(sbc);
481
482 std::string name = boco_name + "/" + block->name();
483
484 auto sb =
485 new Ioss::SideBlock(block->get_database(), name, Ioss::Quad4::name, Ioss::Hex8::name, 0);
486 sb->set_parent_block(block);
487 sset->add(sb);
488 sb->property_add(Ioss::Property("base", base));
489 sb->property_add(Ioss::Property("zone", zone));
490 sb->property_add(Ioss::Property("section", face + 1));
491 sb->property_add(Ioss::Property("id", sset->get_property("id").get_int()));
492 sb->property_add(Ioss::Property(
493 "guid", block->get_database()->util().generate_guid(sset->get_property("id").get_int())));
494 }
495 #endif
496
497 size_t handle_block_ids(const Ioss::EntityBlock *eb, Ioss::Map &entity_map, void *ids,
498 size_t num_to_get, const Ioss::Field::BasicType &size)
499 {
500 /*!
501 * CGNS doesn't support element global ids, so the only use of this
502 * routine is the case where we may be translating from a mesh that
503 * *does* support global ids and we will then need to map those
504 * global ids back to local ids in, for example, the sideset element list.
505 *
506 * There will be two maps the 'entity_map.map' map is a 'direct lookup'
507 * map which maps current local position to global id and the
508 * 'entity_map.reverse' is an associative lookup which maps the
509 * global id to 'original local'. There is also a
510 * 'entity_map.reorder' which is direct lookup and maps current local
511 * position to original local.
512
513 * The ids coming in are the global ids; their position is the
514 * local id -1 (That is, data[0] contains the global id of local
515 * element 1 in this element block). The 'model-local' id is
516 * given by eb_offset + 1 + position:
517 *
518 * int local_position = entity_map.reverse[ElementMap[i+1]]
519 * (the entity_map.map and entity_map.reverse are 1-based)
520 *
521 * But, this assumes 1..numel elements are being output at the same
522 * time; we are actually outputting a blocks worth of elements at a
523 * time, so we need to consider the block offsets.
524 * So... local-in-block position 'i' is index 'eb_offset+i' in
525 * 'entity_map.map' and the 'local_position' within the element
526 * blocks data arrays is 'local_position-eb_offset'. With this, the
527 * position within the data array of this element block is:
528 *
529 * int eb_position =
530 * entity_map.reverse[entity_map.map[eb_offset+i+1]]-eb_offset-1
531 *
532 * NOTE: the maps are built an element block at a time...
533 */
534
535 // Overwrite this portion of the 'entity_map.map', but keep other
536 // parts as they were. We are adding elements starting at position
537 // 'eb_offset+offset' and ending at
538 // 'eb_offset+offset+num_to_get'. If the entire block is being
539 // processed, this reduces to the range 'eb_offset..eb_offset+my_element_count'
540
541 int64_t eb_offset = eb->get_offset();
542 if (size == Ioss::Field::INT64) {
543 entity_map.set_map(static_cast<int64_t *>(ids), num_to_get, eb_offset, true);
544 }
545 else {
546 entity_map.set_map(static_cast<int *>(ids), num_to_get, eb_offset, true);
547 }
548
549 return num_to_get;
550 }
551 } // namespace
552
553 namespace Iocgns {
554
555 DatabaseIO::DatabaseIO(Ioss::Region *region, const std::string &filename,
556 Ioss::DatabaseUsage db_usage, Ioss_MPI_Comm communicator,
557 const Ioss::PropertyManager &props)
558 : Ioss::DatabaseIO(region, filename, db_usage, communicator, props)
559 {
560 dbState = Ioss::STATE_UNKNOWN;
561
562 #if IOSS_DEBUG_OUTPUT
563 if (myProcessor == 0) {
564 fmt::print("CGNS DatabaseIO using {}-bit integers\n", CG_SIZEOF_SIZE);
565 }
566 #endif
567 if (!is_input()) {
568 if (properties.exists("FLUSH_INTERVAL")) {
569 m_flushInterval = properties.get("FLUSH_INTERVAL").get_int();
570 }
571
572 {
573 bool file_per_state = false;
574 Ioss::Utils::check_set_bool_property(properties, "FILE_PER_STATE", file_per_state);
575 if (file_per_state) {
576 set_file_per_state(true);
577 }
578 }
579 }
580
581 Ioss::DatabaseIO::openDatabase_nl();
582 }
583
584 DatabaseIO::~DatabaseIO()
585 {
586 for (const auto &gtb : m_globalToBlockLocalNodeMap) {
587 delete gtb.second;
588 }
589 try {
590 if (m_cgnsBasePtr > 0) {
591 CGCHECKM(cg_close(m_cgnsBasePtr));
592 m_cgnsBasePtr = -1;
593 }
594 closeDatabase_nl();
595 }
596 catch (...) {
597 }
598 }
599
600 int DatabaseIO::get_file_pointer() const
601 {
602 if (m_cgnsFilePtr < 0) {
603 openDatabase_nl();
604 }
605 return m_cgnsFilePtr;
606 }
607
608 void DatabaseIO::openDatabase_nl() const
609 {
610 if (m_cgnsFilePtr < 0) {
611 #if 0
612 // This is currently disabled due to a recent change in CGNS
613 // that changed how `hdf5_access` was dealt with... Since
614 // memory_read and memory_write are experimental in SEACAS/IOSS,
615 // I disabled until we can determine how best to handle this in
616 // current CGNS.
617 if ((is_input() && properties.exists("MEMORY_READ")) ||
618 (!is_input() && properties.exists("MEMORY_WRITE"))) {
619 Ioss::Utils::copy_string(hdf5_access, "PARALLEL");
620 }
621 #endif
622
623 CGCHECKM(cg_set_file_type(CG_FILE_HDF5));
624
625 int mode = is_input() ? CG_MODE_READ : CG_MODE_WRITE;
626 if (!is_input()) {
627 if (m_cgnsFilePtr == -2) {
628 // Writing multiple steps with a "flush" (cg_close() / cg_open())
629 mode = CG_MODE_MODIFY;
630 }
631 else {
632 // Check whether appending to existing file...
633 if (open_create_behavior() == Ioss::DB_APPEND ||
634 open_create_behavior() == Ioss::DB_MODIFY) {
635 // Append to file if it already exists -- See if the file exists.
636 Ioss::FileInfo file = Ioss::FileInfo(decoded_filename());
637 if (file.exists()) {
638 mode = CG_MODE_MODIFY;
639 }
640 }
641 }
642 }
643
644 #if CG_BUILD_PARALLEL
645 cgp_mpi_comm(Ioss::ParallelUtils::comm_self());
646 int ierr = cgp_open(decoded_filename().c_str(), mode, &m_cgnsFilePtr);
647 cgp_mpi_comm(util().communicator());
648 #else
649 int ierr = cg_open(decoded_filename().c_str(), mode, &m_cgnsFilePtr);
650 #endif
651 // Will not return if error...
652 check_valid_file_open(ierr);
653 #if 0
654 if ((is_input() && properties.exists("MEMORY_READ")) ||
655 (!is_input() && properties.exists("MEMORY_WRITE"))) {
656 Ioss::Utils::copy_string(hdf5_access, "NATIVE");
657 }
658 #endif
659
660 if (properties.exists("INTEGER_SIZE_API")) {
661 int isize = properties.get("INTEGER_SIZE_API").get_int();
662 if (isize == 8) {
663 set_int_byte_size_api(Ioss::USE_INT64_API);
664 }
665 if (isize == 4) {
666 set_int_byte_size_api(Ioss::USE_INT32_API);
667 }
668 }
669 else if (CG_SIZEOF_SIZE == 64) {
670 set_int_byte_size_api(Ioss::USE_INT64_API);
671 }
672
673 if (mode == CG_MODE_MODIFY && get_region() != nullptr) {
674 Utils::update_db_zone_property(m_cgnsFilePtr, get_region(), myProcessor, isParallel, false);
675 }
676 #if 0
677 // This isn't currently working since CGNS currently has chunking
678 // disabled for HDF5 files and compression requires chunking.
679 if (!is_input()) {
680 if (properties.exists("COMPRESSION_LEVEL")) {
681 int comp = properties.get("COMPRESSION_LEVEL").get_int();
682 cg_configure(CG_CONFIG_HDF5_COMPRESS, (void*)comp);
683 }
684 }
685 #endif
686 }
687 SMART_ASSERT(m_cgnsFilePtr >= 0);
688 }
689
690 void DatabaseIO::closeDatabase_nl() const
691 {
692 if (m_cgnsFilePtr > 0) {
693 CGCHECKM(cg_close(m_cgnsFilePtr));
694 close_dw();
695 m_cgnsFilePtr = -1;
696 }
697 }
698
699 bool DatabaseIO::check_valid_file_open(int status) const
700 {
701 int global_status = status;
702 if (isParallel) {
703 global_status = util().global_minmax(status, Ioss::ParallelUtils::DO_MAX);
704 }
705
706 if (global_status != CG_OK) {
707 Ioss::IntVector err_status;
708 if (isParallel) {
709 util().all_gather(status, err_status);
710 }
711 else {
712 err_status.push_back(status);
713 }
714
715 // See which processors could not open/create the file...
716 std::ostringstream errmsg;
717 int ok_count = 0;
718 if (isParallel) {
719 ok_count = std::count(err_status.begin(), err_status.end(), CG_OK);
720 if (ok_count == 0 && util().parallel_size() > 2) {
721 fmt::print(errmsg,
722 "ERROR: Unable to open CGNS decomposed database files:\n\t\t{} ...\n\t\t{}\n",
723 Ioss::Utils::decode_filename(get_filename(), 0, util().parallel_size()),
724 Ioss::Utils::decode_filename(get_filename(), util().parallel_size() - 1,
725 util().parallel_size()));
726 }
727 else {
728 fmt::print(errmsg, "ERROR: Unable to open CGNS decomposed database files:\n");
729 for (int i = 0; i < util().parallel_size(); i++) {
730 if (err_status[i] != CG_OK) {
731 fmt::print(errmsg, "\t\t{}\n",
732 Ioss::Utils::decode_filename(get_filename(), i, util().parallel_size()));
733 }
734 }
735 }
736 fmt::print(errmsg, " for {} access.\n", (is_input() ? "read" : "write"));
737 }
738 else {
739 fmt::print(errmsg, "ERROR: Unable to open CGNS database '{}' for {} access.\n",
740 get_filename(), (is_input() ? "read" : "write"));
741 }
742 if (status != CG_OK) {
743 if (ok_count != 0 || util().parallel_size() <= 2) {
744 fmt::print(errmsg, "[{}] CGNS Error: '{}'\n", myProcessor, cg_get_error());
745 }
746 else {
747 // Since error on all processors, assume the same error on all and only print
748 // the error from processor 0.
749 if (myProcessor == 0) {
750 fmt::print(errmsg, "CGNS Error: '{}'\n", cg_get_error());
751 }
752 }
753 }
754
755 IOSS_ERROR(errmsg);
756 }
757 return true;
758 }
759
760 void DatabaseIO::finalize_database() const
761 {
762 if (is_input()) {
763 return;
764 }
765
766 if (m_timesteps.empty()) {
767 return;
768 }
769
770 if (!m_dbFinalized) {
771 int file_ptr;
772 if (get_file_per_state()) {
773 file_ptr = m_cgnsBasePtr;
774 }
775 else {
776 file_ptr = get_file_pointer();
777 }
778 Utils::finalize_database(file_ptr, m_timesteps, get_region(), myProcessor, false);
779 m_dbFinalized = true;
780 }
781 }
782
783 int64_t DatabaseIO::node_global_to_local_nl(int64_t global, bool /*must_exist*/) const
784 {
785 return global;
786 }
787
788 int64_t DatabaseIO::element_global_to_local_nl(int64_t global) const { return global; }
789
790 void DatabaseIO::create_structured_block_fpp(IOSS_MAYBE_UNUSED int base,
791 IOSS_MAYBE_UNUSED int num_zones,
792 size_t & /* num_node */)
793 {
794 SMART_ASSERT(isParallel);
795 IOSS_PAR_UNUSED(base);
796 IOSS_PAR_UNUSED(num_zones);
797 #if CG_BUILD_PARALLEL
798 // Each processor may have a different set of zones. This routine
799 // will sync the information such that at return, each procesosr
800 // has a consistent set of structuredBlocks defined with the
801 // correct local and global, i,j,k ranges and offsets.
802 // First each processor sends their zone count to processor 0...
803
804 // name, proc (int) , cell-range (3 int), boundary-with
805
806 // First, get basenames of all zones on all processors so we can
807 // work with consistent set...
808 int id = 0;
809 int in = 0;
810 const int INT_PER_ZONE = 5; // proc, range[3], zone
811 const int OUT_INT_PER_ZONE = 10; // proc, range[3], glob_range[3], offset[3]
812 std::vector<int> zone_data(num_zones * INT_PER_ZONE);
813 std::vector<char> zone_names(num_zones * (CGNS_MAX_NAME_LENGTH + 1));
814 std::map<std::string, int> zone_id_map;
815 std::vector<int> adjacency;
816
817 for (int zone = 1; zone <= num_zones; zone++) {
818 cgsize_t size[9];
819 char zname[CGNS_MAX_NAME_LENGTH + 1];
820 CGCHECKM(cg_zone_read(get_file_pointer(), base, zone, zname, size));
821
822 SMART_ASSERT(size[0] - 1 == size[3]);
823 SMART_ASSERT(size[1] - 1 == size[4]);
824 SMART_ASSERT(size[2] - 1 == size[5]);
825
826 SMART_ASSERT(size[6] == 0);
827 SMART_ASSERT(size[7] == 0);
828 SMART_ASSERT(size[8] == 0);
829
830 auto name_proc = Iocgns::Utils::decompose_name(zname, isParallel);
831 std::string zone_name = name_proc.first;
832 int proc = name_proc.second;
833 SMART_ASSERT(proc == myProcessor);
834
835 zone_data[id++] = proc;
836 pack(id, zone_data, &size[3], 3); // Packing 3,4,5
837 Ioss::Utils::copy_string(&zone_names[in], zone_name, CGNS_MAX_NAME_LENGTH + 1);
838 in += CGNS_MAX_NAME_LENGTH + 1;
839 zone_id_map[zone_name] = zone;
840
841 // Handle zone-grid-connectivity... At this point we only want
842 // the zgc that are inter-proc between the same "base zone".
843 // That is, the zgc which are result of parallel decomp.
844
845 // Stored as -P, -Z, f1, p1, -P, -Z, f2, p2, ..., -P, -Z, f1, ...
846 generate_inter_proc_adjacency(get_file_pointer(), base, zone, myProcessor, zone_name,
847 adjacency);
848
849 zone_data[id++] = zone;
850 SMART_ASSERT(id % INT_PER_ZONE == 0);
851 }
852
853 // Now gather all information to processor 0
854 std::vector<char> all_names;
855 std::vector<int> all_data;
856 std::vector<int> all_adj;
857 util().gather(num_zones, CGNS_MAX_NAME_LENGTH + 1, zone_names, all_names);
858 int tot_zones = util().gather(num_zones, INT_PER_ZONE, zone_data, all_data);
859 util().gather((int)adjacency.size(), 1, adjacency, all_adj);
860
861 if (myProcessor == 0) {
862 std::vector<SBlock> blocks;
863 int off_name = 0;
864 int off_data = 0;
865 for (int i = 0; i < tot_zones; i++) {
866 blocks.emplace_back(&all_names[off_name], &all_data[off_data]);
867 off_name += CGNS_MAX_NAME_LENGTH + 1;
868 off_data += INT_PER_ZONE;
869
870 // Add inter-processor adjacency information to the block
871 auto &b = blocks.back();
872 set_adjacency(b, all_adj);
873 }
874 all_adj.clear();
875 all_adj.shrink_to_fit();
876
877 // Sort blocks to get similar zones adjacent -- will have same name, but different proc
878 Ioss::sort(blocks.begin(), blocks.end(), [](const SBlock &b1, const SBlock &b2) {
879 return (b1.name == b2.name ? b1.proc < b2.proc : b1.name < b2.name);
880 });
881
882 int proc_count = util().parallel_size();
883 std::vector<SBlock> resolved_blocks;
884
885 for (size_t i = 0; i < blocks.size(); i++) {
886 auto &b = blocks[i];
887 if (b.split()) {
888 // The blocks it is split with should be adjacent in list.
889 // Get range of indices referring to this block and build
890 // a map from processor to index, so build that now...
891 std::map<int, int> proc_block_map;
892 proc_block_map[b.proc] = i;
893 size_t j = i + 1;
894 for (; j < blocks.size(); j++) {
895 if (blocks[j].name != b.name) {
896 break;
897 }
898 proc_block_map[blocks[j].proc] = j;
899 }
900 auto bbeg = i;
901 auto bend = j;
902
903 // Get global ijk extent in each direction...
904 set_global_extent(bbeg, bend, blocks, proc_block_map);
905
906 // Iterate to get correct offset for these blocks on all processors...
907 set_block_offset(bbeg, bend, blocks, proc_block_map);
908
909 #if IOSS_DEBUG_OUTPUT
910 fmt::print(Ioss::DebugOut(),
911 "Range of blocks for {} is {} to {} Global I,J,K = {} {} {}\n", b.name, i,
912 j - 1, b.glob_range[0], b.glob_range[1], b.glob_range[2]);
913 #endif
914 // All processors need to know about it...
915 for (int p = 0; p < proc_count; p++) {
916 auto iter = proc_block_map.find(p);
917 if (iter == proc_block_map.end()) {
918 SBlock newb;
919 newb.name = b.name;
920 newb.proc = p;
921 newb.glob_range = b.glob_range;
922 resolved_blocks.push_back(newb);
923 }
924 else {
925 auto idx = (*iter).second;
926 SBlock newb = blocks[idx];
927 resolved_blocks.push_back(newb);
928 }
929 }
930 i = bend - 1;
931 }
932 else {
933 // If not split, then global size = local size and offset = 0
934 b.glob_range = b.range;
935
936 // All processors need to know about it...
937 for (int p = 0; p < proc_count; p++) {
938 SBlock newb;
939 newb.name = b.name;
940 newb.proc = p;
941 newb.glob_range = b.glob_range;
942 if (p == b.proc) {
943 newb.range = b.range;
944 }
945 resolved_blocks.push_back(newb);
946 }
947 }
948 }
949
950 int num_unique = (int)resolved_blocks.size() / proc_count;
951
952 #if IOSS_DEBUG_OUTPUT
953 for (const auto &b : resolved_blocks) {
954 fmt::print(Ioss::DebugOut(), "{} {} {} ({} {} {}) ({} {} {}) ({} {} {}) [{}]\n", b.name,
955 b.proc, b.local_zone, b.range[0], b.range[1], b.range[2], b.glob_range[0],
956 b.glob_range[1], b.glob_range[2], b.offset[0], b.offset[1], b.offset[2],
957 b.face_adj.to_string('.', '+'));
958 }
959 #endif
960
961 // Data now consistent for all zones. Send back to their "owning" processor
962 tot_zones = num_unique;
963 all_names.resize(num_unique * (CGNS_MAX_NAME_LENGTH + 1));
964 all_data.resize(resolved_blocks.size() * OUT_INT_PER_ZONE);
965 id = in = 0;
966 for (int off = 0; off < proc_count; off++) {
967 for (int b = 0; b < num_unique; b++) {
968 int idx = off + b * proc_count;
969 const auto &block = resolved_blocks[idx];
970 if (off == 0) {
971 Ioss::Utils::copy_string(&all_names[in], block.name, CGNS_MAX_NAME_LENGTH + 1);
972 in += CGNS_MAX_NAME_LENGTH + 1;
973 }
974 all_data[id++] = block.proc;
975 pack(id, all_data, block.range.data(), 3);
976 pack(id, all_data, block.glob_range.data(), 3);
977 pack(id, all_data, block.offset.data(), 3);
978 }
979 }
980 SMART_ASSERT(id % OUT_INT_PER_ZONE == 0);
981 }
982 util().broadcast(tot_zones);
983 zone_data.resize(tot_zones * OUT_INT_PER_ZONE);
984 all_names.resize(tot_zones * (CGNS_MAX_NAME_LENGTH + 1));
985 util().broadcast(all_names);
986 MPI_Scatter(Data(all_data), tot_zones * OUT_INT_PER_ZONE, MPI_INT, Data(zone_data),
987 tot_zones * OUT_INT_PER_ZONE, MPI_INT, 0, util().communicator());
988
989 // Each processor now has a consistent set of structured blocks.
990 // Create the Ioss::StructuredBlocks objects and add to region.
991 id = in = 0;
992 for (int i = 0; i < tot_zones; i++) {
993 std::string zone_name(&all_names[in]);
994 in += CGNS_MAX_NAME_LENGTH + 1;
995 Ioss::IJK_t local_ijk;
996 Ioss::IJK_t global_ijk;
997 Ioss::IJK_t offset_ijk;
998
999 zone_data[id++]; // proc field. Not currently used.
1000 unpack(id, Data(zone_data), local_ijk.data(), 3);
1001 unpack(id, Data(zone_data), global_ijk.data(), 3);
1002 unpack(id, Data(zone_data), offset_ijk.data(), 3);
1003
1004 Ioss::StructuredBlock *block =
1005 new Ioss::StructuredBlock(this, zone_name, 3, local_ijk, offset_ijk, global_ijk);
1006
1007 // See if this zone exists on this processor's file, or is just for interprocessor
1008 // consistency.
1009 int zone = tot_zones + i;
1010 bool native = false;
1011 auto iter = zone_id_map.find(zone_name);
1012 if (iter != zone_id_map.end()) {
1013 zone = (*iter).second;
1014 native = true;
1015 }
1016
1017 block->property_add(Ioss::Property("base", base));
1018 if (native) {
1019 block->property_add(Ioss::Property("db_zone", zone));
1020 }
1021 block->property_add(Ioss::Property("zone", i + 1));
1022 block->property_add(Ioss::Property("id", i + 1));
1023 // Note that 'zone' is not consistent among processors
1024 block->property_add(Ioss::Property("guid", util().generate_guid(i + 1)));
1025 get_region()->add(block);
1026 m_zoneNameMap[zone_name] = i + 1;
1027
1028 if (native) {
1029 // Handle zone-grid-connectivity...
1030 add_zgc_fpp(get_file_pointer(), block, m_zoneNameMap, myProcessor, isParallel);
1031
1032 // Handle boundary conditions...
1033 Utils::add_structured_boundary_conditions(get_file_pointer(), block, false);
1034 }
1035
1036 // See if this zone/block is a member of any assemblies...
1037 Utils::add_to_assembly(get_file_pointer(), get_region(), block, base, zone);
1038
1039 // Need to get a count of number of unique BC's.
1040 // Note that possible to assign multiple BC to a single face, so can't do this based on faces
1041 // Assume that if a BC is on multiple processors, then its name will be the same on all
1042 // processors.
1043 // * Gather all names to processor 0;
1044 // * Get unique ordered set
1045 // * Broadcast back to each processor
1046 int in_bc = 0;
1047 size_t num_bc = block->m_boundaryConditions.size();
1048 std::vector<char> bc_names(num_bc * (CGNS_MAX_NAME_LENGTH + 1));
1049 for (size_t ibc = 0; ibc < num_bc; ibc++) {
1050 std::string name = block->m_boundaryConditions[ibc].m_famName + "/" +
1051 block->m_boundaryConditions[ibc].m_bcName;
1052 Ioss::Utils::copy_string(&bc_names[in_bc], name, CGNS_MAX_NAME_LENGTH + 1);
1053 in_bc += CGNS_MAX_NAME_LENGTH + 1;
1054 }
1055 std::vector<char> all_bc_names;
1056 int tot_names = util().gather(num_bc, CGNS_MAX_NAME_LENGTH + 1, bc_names, all_bc_names);
1057
1058 if (myProcessor == 0) {
1059 int off_name = 0;
1060 Ioss::NameList bc;
1061 for (int ibc = 0; ibc < tot_names; ibc++) {
1062 bc.emplace_back(&all_bc_names[off_name]);
1063 off_name += CGNS_MAX_NAME_LENGTH + 1;
1064 }
1065 Ioss::Utils::uniquify(bc);
1066 tot_names = (int)bc.size();
1067 all_bc_names.clear();
1068 all_bc_names.shrink_to_fit();
1069 bc_names.resize(tot_names * (CGNS_MAX_NAME_LENGTH + 1));
1070 in_bc = 0;
1071 for (const auto &name : bc) {
1072 Ioss::Utils::copy_string(&bc_names[in_bc], name, CGNS_MAX_NAME_LENGTH + 1);
1073 in_bc += CGNS_MAX_NAME_LENGTH + 1;
1074 }
1075 }
1076 util().broadcast(tot_names);
1077 bc_names.resize(tot_names * (CGNS_MAX_NAME_LENGTH + 1));
1078 util().broadcast(bc_names);
1079
1080 Ioss::NameList bc;
1081 int off_name = 0;
1082 for (int ibc = 0; ibc < tot_names; ibc++) {
1083 bc.emplace_back(&bc_names[off_name]);
1084 off_name += CGNS_MAX_NAME_LENGTH + 1;
1085 }
1086 bc_names.clear();
1087 bc_names.shrink_to_fit();
1088
1089 // Each processor now has a unique set of BC names for this block.
1090 // Now create the missing (empty) BC on each processor.
1091 for (const auto &bc_name : bc) {
1092 auto split_name = Ioss::tokenize(bc_name, "/");
1093 SMART_ASSERT(split_name.size() == 2);
1094 bool has_name = false;
1095 for (auto &sbc : block->m_boundaryConditions) {
1096 if (sbc.m_bcName == split_name[1]) {
1097 has_name = true;
1098 break;
1099 }
1100 }
1101 if (!has_name) {
1102 // Create an empty BC with that name...
1103 int face = -1;
1104 Ioss::SideSet *sset = get_region()->get_sideset(split_name[0]);
1105 SMART_ASSERT(sset != nullptr);
1106 add_empty_bc(sset, block, base, zone, face, split_name[0], split_name[1]);
1107 }
1108 }
1109
1110 Ioss::sort(block->m_boundaryConditions.begin(), block->m_boundaryConditions.end(),
1111 [](const Ioss::BoundaryCondition &b1, const Ioss::BoundaryCondition &b2) {
1112 return (b1.m_bcName < b2.m_bcName);
1113 });
1114 }
1115
1116 // Need to iterate the blocks again and make the assembly information consistent
1117 // across processors.
1118 // If a block belongs to an assembly, it will have the property "assembly"
1119 // defined on it.
1120 // This assumes that a block can belong to at most one assembly.
1121 const auto &assemblies = get_region()->get_assemblies();
1122 if (!assemblies.empty()) {
1123 std::map<unsigned int, std::string> assembly_hash_map;
1124 for (const auto &assem : assemblies) {
1125 auto hash = Ioss::Utils::hash(assem->name());
1126 assembly_hash_map[hash] = assem->name();
1127 }
1128
1129 const auto &blocks = get_region()->get_structured_blocks();
1130 std::vector<unsigned int> assem_ids;
1131 assem_ids.reserve(blocks.size());
1132
1133 for (const auto &sb : blocks) {
1134 unsigned int hash = 0;
1135 if (sb->property_exists("assembly")) {
1136 std::string assembly = sb->get_property("assembly").get_string();
1137 hash = Ioss::Utils::hash(assembly);
1138 }
1139 assem_ids.push_back(hash);
1140 }
1141
1142 // Hash will be >= 0, so we will take the maximum over all
1143 // ranks and that will give the assembly (if any) that each block belongs to.
1144 util().global_array_minmax(assem_ids, Ioss::ParallelUtils::DO_MAX);
1145
1146 int idx = 0;
1147 for (const auto &sb : blocks) {
1148 unsigned assem_hash = assem_ids[idx++];
1149 std::string name = assembly_hash_map[assem_hash];
1150 auto *assembly = get_region()->get_assembly(name);
1151 assert(assembly != nullptr);
1152 if (!sb->property_exists("assembly")) {
1153 assembly->add(sb);
1154 Ioss::StructuredBlock *new_sb = const_cast<Ioss::StructuredBlock *>(sb);
1155 new_sb->property_add(Ioss::Property("assembly", assembly->name()));
1156 }
1157 SMART_ASSERT(sb->get_property("assembly").get_string() == assembly->name())
1158 (sb->get_property("assembly").get_string())(assembly->name());
1159 }
1160 }
1161 #endif
1162 }
1163
1164 void DatabaseIO::create_structured_block(int base, int zone, size_t &num_node)
1165 {
1166 SMART_ASSERT(!isParallel);
1167
1168 cgsize_t size[9];
1169 char zone_name[CGNS_MAX_NAME_LENGTH + 1];
1170 CGCHECKM(cg_zone_read(get_file_pointer(), base, zone, zone_name, size));
1171
1172 auto name_proc = Iocgns::Utils::decompose_name(zone_name, isParallel);
1173 std::string zname = name_proc.first;
1174 int proc = name_proc.second;
1175 if (proc != myProcessor) {
1176 IOSS_ERROR(fmt::format(
1177 "ERROR: CGNS: Zone {} has a name that specifies it should be on processor {}, but "
1178 "it is actually on processor {}",
1179 zone, proc, myProcessor));
1180 }
1181
1182 m_zoneNameMap[zname] = zone;
1183
1184 SMART_ASSERT(size[0] - 1 == size[3]);
1185 SMART_ASSERT(size[1] - 1 == size[4]);
1186 SMART_ASSERT(size[2] - 1 == size[5]);
1187
1188 SMART_ASSERT(size[6] == 0);
1189 SMART_ASSERT(size[7] == 0);
1190 SMART_ASSERT(size[8] == 0);
1191
1192 int index_dim = 0;
1193 CGCHECKM(cg_index_dim(get_file_pointer(), base, zone, &index_dim));
1194 // An Ioss::StructuredBlock corresponds to a CGNS_ENUMV(Structured) zone...
1195 auto *block = new Ioss::StructuredBlock(this, zname, index_dim, size[3], size[4], size[5]);
1196
1197 block->property_add(Ioss::Property("base", base));
1198 block->property_add(Ioss::Property("db_zone", zone));
1199 block->property_add(Ioss::Property("zone", zone));
1200 block->property_add(Ioss::Property("id", zone));
1201 block->property_add(Ioss::Property("guid", zone));
1202 get_region()->add(block);
1203
1204 num_node += block->get_property("node_count").get_int();
1205
1206 // Handle zone-grid-connectivity...
1207 int nconn = 0;
1208 CGCHECKM(cg_n1to1(get_file_pointer(), base, zone, &nconn));
1209 for (int i = 0; i < nconn; i++) {
1210 char connectname[CGNS_MAX_NAME_LENGTH + 1];
1211 char donorname[CGNS_MAX_NAME_LENGTH + 1];
1212 std::array<cgsize_t, 6> range;
1213 std::array<cgsize_t, 6> donor_range;
1214 Ioss::IJK_t transform{};
1215
1216 CGCHECKM(cg_1to1_read(get_file_pointer(), base, zone, i + 1, connectname, donorname,
1217 Data(range), Data(donor_range), Data(transform)));
1218
1219 auto donorname_proc = Iocgns::Utils::decompose_name(donorname, isParallel);
1220 std::string donor_name = donorname_proc.first;
1221
1222 // Get number of nodes shared with other "previous" zones...
1223 // A "previous" zone will have a lower zone number this this zone...
1224 int donor_zone = -1;
1225 auto donor_iter = m_zoneNameMap.find(donor_name);
1226 if (donor_iter != m_zoneNameMap.end()) {
1227 donor_zone = (*donor_iter).second;
1228 }
1229 Ioss::IJK_t range_beg{{(int)range[0], (int)range[1], (int)range[2]}};
1230 Ioss::IJK_t range_end{{(int)range[3], (int)range[4], (int)range[5]}};
1231 Ioss::IJK_t donor_beg{{(int)donor_range[0], (int)donor_range[1], (int)donor_range[2]}};
1232 Ioss::IJK_t donor_end{{(int)donor_range[3], (int)donor_range[4], (int)donor_range[5]}};
1233
1234 block->m_zoneConnectivity.emplace_back(connectname, zone, donor_name, donor_zone, transform,
1235 range_beg, range_end, donor_beg, donor_end);
1236
1237 block->m_zoneConnectivity.back().m_ownerProcessor = myProcessor;
1238 block->m_zoneConnectivity.back().m_donorProcessor = donorname_proc.second;
1239 }
1240
1241 // Handle boundary conditions...
1242 Utils::add_structured_boundary_conditions(get_file_pointer(), block, false);
1243
1244 // See if this zone/block is a member of any assemblies...
1245 Utils::add_to_assembly(get_file_pointer(), get_region(), block, base, zone);
1246 }
1247
1248 size_t DatabaseIO::finalize_structured_blocks()
1249 {
1250 const auto &blocks = get_region()->get_structured_blocks();
1251
1252 int proc_count = util().parallel_size();
1253 std::vector<int> my_offsets;
1254 std::vector<int> all_offsets;
1255
1256 if (proc_count > 1) {
1257 my_offsets.reserve(blocks.size() * 3 * proc_count);
1258 #ifndef NDEBUG
1259 int zone = 1;
1260 #endif
1261 for (const auto &sb : blocks) {
1262 SMART_ASSERT(sb->get_property("zone").get_int() ==
1263 zone++); // Modification of zone OK in SMART_ASSERT
1264 my_offsets.push_back(sb->get_property("offset_i").get_int());
1265 my_offsets.push_back(sb->get_property("offset_j").get_int());
1266 my_offsets.push_back(sb->get_property("offset_k").get_int());
1267 }
1268 util().all_gather(my_offsets, all_offsets);
1269 }
1270
1271 // If there are any Structured blocks, need to iterate them and their 1-to-1 connections
1272 // and update the donor_zone id for zones that had not yet been processed at the time of
1273 // definition...
1274
1275 // If parallel, then all need to update the donor offset field since that was not known
1276 // at time of definition...
1277 for (const auto &block : blocks) {
1278 for (auto &conn : block->m_zoneConnectivity) {
1279 if (conn.m_donorZone < 0) {
1280 auto donor_iter = m_zoneNameMap.find(conn.m_donorName);
1281 if (donor_iter == m_zoneNameMap.end()) {
1282 if (proc_count == 1) {
1283 // This is most likely a parallel decomposed model, but only a single
1284 // part is being accessed. Do the best we can without being able to
1285 // access the data on the other processor files...
1286 auto zname_proc = Iocgns::Utils::decompose_name(conn.m_donorName, true);
1287 conn.m_donorProcessor = zname_proc.second;
1288 auto donor_block = get_region()->get_structured_block(zname_proc.first);
1289 if (donor_block != nullptr) {
1290 conn.m_donorZone = Iocgns::Utils::get_db_zone(donor_block);
1291 }
1292 else {
1293 // Since we are only accessing a single file in a decomposed
1294 // set of fpp files, we can't access the donor zone on the
1295 // other processor(s), so we have to set the ZGC to inactive.
1296 conn.m_isActive = false;
1297 }
1298 }
1299 }
1300 else {
1301 SMART_ASSERT(donor_iter != m_zoneNameMap.end());
1302 conn.m_donorZone = (*donor_iter).second;
1303 }
1304 }
1305 if (proc_count > 1) {
1306 int offset = (conn.m_donorProcessor * blocks.size() + (conn.m_donorZone - 1)) * 3;
1307 Ioss::IJK_t donor_offset{
1308 {all_offsets[offset + 0], all_offsets[offset + 1], all_offsets[offset + 2]}};
1309
1310 conn.m_donorOffset = donor_offset;
1311 conn.m_donorRangeBeg[0] += donor_offset[0];
1312 conn.m_donorRangeBeg[1] += donor_offset[1];
1313 conn.m_donorRangeBeg[2] += donor_offset[2];
1314 conn.m_donorRangeEnd[0] += donor_offset[0];
1315 conn.m_donorRangeEnd[1] += donor_offset[1];
1316 conn.m_donorRangeEnd[2] += donor_offset[2];
1317 }
1318 conn.m_donorGUID = util().generate_guid(conn.m_donorZone, conn.m_donorProcessor);
1319 conn.m_ownerGUID = util().generate_guid(conn.m_ownerZone, conn.m_ownerProcessor);
1320 }
1321 }
1322
1323 size_t num_nodes = Utils::resolve_nodes(*get_region(), myProcessor, isParallel);
1324 return num_nodes;
1325 }
1326
1327 void DatabaseIO::create_unstructured_block(int base, int zone, size_t &num_node)
1328 {
1329 cgsize_t size[9];
1330 char zone_name[CGNS_MAX_NAME_LENGTH + 1];
1331 CGCHECKM(cg_zone_read(get_file_pointer(), base, zone, zone_name, size));
1332 m_zoneNameMap[zone_name] = zone;
1333
1334 size_t total_block_nodes = size[0];
1335 m_blockLocalNodeMap[zone].resize(total_block_nodes, -1);
1336
1337 // Determine number of "shared" nodes (shared with other zones)
1338 if (zone > 1) { // Donor zone is always lower numbered, so zone 1 has no donor zone.
1339 int nconn = 0;
1340 CGCHECKM(cg_nconns(get_file_pointer(), base, zone, &nconn));
1341 for (int i = 0; i < nconn; i++) {
1342 char connectname[CGNS_MAX_NAME_LENGTH + 1];
1343 CGNS_ENUMT(GridLocation_t) location;
1344 CGNS_ENUMT(GridConnectivityType_t) connect_type;
1345 CGNS_ENUMT(PointSetType_t) ptset_type;
1346 cgsize_t npnts = 0;
1347 char donorname[CGNS_MAX_NAME_LENGTH + 1];
1348 CGNS_ENUMT(ZoneType_t) donor_zonetype;
1349 CGNS_ENUMT(PointSetType_t) donor_ptset_type;
1350 CGNS_ENUMT(DataType_t) donor_datatype;
1351 cgsize_t ndata_donor;
1352
1353 CGCHECKM(cg_conn_info(get_file_pointer(), base, zone, i + 1, connectname, &location,
1354 &connect_type, &ptset_type, &npnts, donorname, &donor_zonetype,
1355 &donor_ptset_type, &donor_datatype, &ndata_donor));
1356
1357 if (connect_type != CGNS_ENUMV(Abutting1to1) || ptset_type != CGNS_ENUMV(PointList) ||
1358 donor_ptset_type != CGNS_ENUMV(PointListDonor)) {
1359 IOSS_ERROR(fmt::format("ERROR: CGNS: Zone {} adjacency data is not correct type. Require "
1360 "Abutting1to1 and PointList."
1361 " {}\t{}\t{}",
1362 zone, static_cast<int>(connect_type), static_cast<int>(ptset_type),
1363 static_cast<int>(donor_ptset_type)));
1364 }
1365
1366 // Verify data consistency...
1367 if (npnts != ndata_donor) {
1368 IOSS_ERROR(fmt::format(
1369 "ERROR: CGNS: Zone {} point count ({}) does not match donor point count ({}).", zone,
1370 npnts, ndata_donor));
1371 }
1372
1373 // Get number of nodes shared with other "previous" zones...
1374 // A "previous" zone will have a lower zone number this this zone...
1375 auto donor_iter = m_zoneNameMap.find(donorname);
1376 if (donor_iter != m_zoneNameMap.end() && (*donor_iter).second < zone) {
1377 #if IOSS_DEBUG_OUTPUT
1378 fmt::print("Zone {} shares {} nodes with {}\n", zone, npnts, donorname);
1379 #endif
1380 CGNSIntVector points(npnts);
1381 CGNSIntVector donors(npnts);
1382
1383 CGCHECKM(cg_conn_read(get_file_pointer(), base, zone, i + 1, Data(points), donor_datatype,
1384 Data(donors)));
1385
1386 // Fill in entries in m_blockLocalNodeMap for the shared nodes...
1387 const auto &donor_map = m_blockLocalNodeMap[(*donor_iter).second];
1388 auto &block_map = m_blockLocalNodeMap[zone];
1389 for (int j = 0; j < npnts; j++) {
1390 cgsize_t point = points[j];
1391 cgsize_t donor = donors[j];
1392 block_map[point - 1] = donor_map[donor - 1];
1393 }
1394 }
1395 }
1396 }
1397
1398 auto &block_map = m_blockLocalNodeMap[zone];
1399 size_t offset = num_node;
1400 for (size_t i = 0; i < total_block_nodes; i++) {
1401 if (block_map[i] == -1) {
1402 block_map[i] = offset++;
1403 }
1404 }
1405 num_node = offset;
1406
1407 size_t num_elem = size[1];
1408 m_zoneOffset[zone] = m_zoneOffset[zone - 1] + num_elem;
1409
1410 // NOTE: A Zone will have a single set of nodes, but can have
1411 // multiple sections each with their own element type...
1412 // Keep treating sections as element blocks until we
1413 // have handled 'size[1]' number of elements; the remaining
1414 // sections are then the boundary faces (?)
1415 int num_sections = 0;
1416 CGCHECKM(cg_nsections(get_file_pointer(), base, zone, &num_sections));
1417
1418 // ========================================================================
1419 // Read the ZoneBC_t node to get list of SideBlocks to define on this zone
1420 // The BC_t nodes in the ZoneBC_t give the element range for each SideBlock
1421 // which can be matched up below with the Elements_t nodes to get contents
1422 // of the SideBlocks.
1423 auto zonebc = Utils::parse_zonebc_sideblocks(get_file_pointer(), base, zone, myProcessor);
1424
1425 // ========================================================================
1426 // Read the sections and create an element block for the ones that
1427 // define elements. Some define boundary conditions...
1428 Ioss::ElementBlock *eblock = nullptr;
1429
1430 for (int is = 1; is <= num_sections; is++) {
1431 char section_name[CGNS_MAX_NAME_LENGTH + 1];
1432 CGNS_ENUMT(ElementType_t) e_type;
1433 cgsize_t el_start = 0;
1434 cgsize_t el_end = 0;
1435 int num_bndry = 0;
1436 int parent_flag = 0;
1437
1438 // Get the type of elements in this section...
1439 CGCHECKM(cg_section_read(get_file_pointer(), base, zone, is, section_name, &e_type, &el_start,
1440 &el_end, &num_bndry, &parent_flag));
1441
1442 cgsize_t num_entity = el_end - el_start + 1;
1443
1444 if (parent_flag == 0 && num_elem > 0) {
1445 num_elem -= num_entity;
1446 std::string element_topo = Utils::map_cgns_to_topology_type(e_type);
1447 #if IOSS_DEBUG_OUTPUT
1448 fmt::print("Added block {}: CGNS topology = '{}', IOSS topology = '{}' with {} elements\n",
1449 zone_name, cg_ElementTypeName(e_type), element_topo, num_entity);
1450 #endif
1451 eblock = new Ioss::ElementBlock(this, zone_name, element_topo, num_entity);
1452 eblock->property_add(Ioss::Property("base", base));
1453 eblock->property_add(Ioss::Property("zone", zone));
1454 eblock->property_add(Ioss::Property("db_zone", zone));
1455 eblock->property_add(Ioss::Property("id", zone));
1456 eblock->property_add(Ioss::Property("guid", zone));
1457 eblock->property_add(Ioss::Property("section", is));
1458 eblock->property_add(Ioss::Property("node_count", (int64_t)total_block_nodes));
1459 eblock->property_add(Ioss::Property("original_block_order", zone));
1460
1461 // See if this zone/block is a member of any assemblies...
1462 Utils::add_to_assembly(get_file_pointer(), get_region(), eblock, base, zone);
1463
1464 SMART_ASSERT(is == 1); // For now, assume each zone has only a single element block.
1465 bool added = get_region()->add(eblock);
1466 if (!added) {
1467 delete eblock;
1468 eblock = nullptr;
1469 }
1470 }
1471 else {
1472 // This is a boundary-condition -- sideset (?)
1473 // Search zonebc (if it exists) for an entry such that the element ranges overlap.
1474 Ioss::SideSet *sset = nullptr;
1475
1476 if (!zonebc.empty()) {
1477 size_t i = 0;
1478 for (; i < zonebc.size(); i++) {
1479 if (zonebc[i].range_beg >= el_start && zonebc[i].range_end <= el_end) {
1480 break;
1481 }
1482 }
1483 if (i < zonebc.size()) {
1484 // See if there is an existing sideset with this name...
1485 sset = get_region()->get_sideset(zonebc[i].name);
1486 }
1487 }
1488 else {
1489 sset = get_region()->get_sideset(section_name);
1490 }
1491
1492 if (sset != nullptr) {
1493 std::string block_name = fmt::format("{}/{}", zone_name, section_name);
1494 std::string face_topo = Utils::map_cgns_to_topology_type(e_type);
1495 #if IOSS_DEBUG_OUTPUT
1496 fmt::print("Added sideblock {} of topo '{}' with {} faces\n", block_name, face_topo,
1497 num_entity);
1498 #endif
1499 std::string parent_topo = eblock == nullptr ? "unknown" : eblock->topology()->name();
1500 auto sblk = new Ioss::SideBlock(this, block_name, face_topo, parent_topo, num_entity);
1501 // IF name is of form "surface_" + "#", then extract # and use as id...
1502 int id = Ioss::Utils::extract_id(block_name);
1503 if (id != 0) {
1504 sblk->property_add(Ioss::Property("id", id));
1505 sblk->property_add(Ioss::Property("guid", id));
1506 }
1507 else {
1508 sblk->property_add(Ioss::Property("id", zone));
1509 sblk->property_add(Ioss::Property("guid", zone));
1510 }
1511 sblk->property_add(Ioss::Property("base", base));
1512 sblk->property_add(Ioss::Property("zone", zone));
1513 sblk->property_add(Ioss::Property("section", is));
1514 if (eblock != nullptr) {
1515 sblk->set_parent_element_block(eblock);
1516 }
1517 sset->add(sblk);
1518 }
1519 }
1520 }
1521 }
1522
1523 void DatabaseIO::read_meta_data_nl()
1524 {
1525 // Determine the number of bases in the grid.
1526 // Currently only handle 1.
1527 int n_bases = 0;
1528 CGCHECKM(cg_nbases(get_file_pointer(), &n_bases));
1529 if (n_bases != 1) {
1530 IOSS_ERROR(
1531 "ERROR: CGNS: Too many bases; only support files with a single bases at this time");
1532 }
1533
1534 get_step_times_nl();
1535
1536 if (open_create_behavior() == Ioss::DB_APPEND) {
1537 return;
1538 }
1539
1540 // ========================================================================
1541 // Get the number of sidesets in the mesh...
1542 // Will be the 'families' that are of the type "FamilyBC_t"
1543 Utils::add_sidesets(get_file_pointer(), this);
1544
1545 // ========================================================================
1546 // Get the number of assemblies in the mesh...
1547 // Will be the 'families' that contain nodes of 'FamVC_*'
1548 Utils::add_assemblies(get_file_pointer(), this);
1549
1550 // ========================================================================
1551 // Get the number of zones (element blocks) in the mesh...
1552 int num_zones = 0;
1553 int base = 1;
1554 CGCHECKM(cg_nzones(get_file_pointer(), base, &num_zones));
1555 m_blockLocalNodeMap.resize(num_zones + 1); // Let's use 1-based zones...
1556 m_zoneOffset.resize(num_zones + 1); // Let's use 1-based zones...
1557
1558 // ========================================================================
1559 size_t num_node = 0;
1560 auto mesh_type = Utils::check_mesh_type(get_file_pointer());
1561
1562 if (isParallel && mesh_type == Ioss::MeshType::STRUCTURED) {
1563 // Handle the file-per-processor parallel case separately for
1564 // now. Hopefully can consolidate at some later time.
1565 create_structured_block_fpp(base, num_zones, num_node);
1566 }
1567 else {
1568 for (int zone = 1; zone <= num_zones; zone++) {
1569 if (mesh_type == Ioss::MeshType::STRUCTURED) {
1570 create_structured_block(base, zone, num_node);
1571 }
1572 else if (mesh_type == Ioss::MeshType::UNSTRUCTURED) {
1573 create_unstructured_block(base, zone, num_node);
1574 }
1575 #if IOSS_ENABLE_HYBRID
1576 else if (mesh_type == Ioss::MeshType::HYBRID) {
1577 }
1578 #endif
1579 else {
1580 IOSS_ERROR(fmt::format("ERROR: CGNS: Zone {} is not of type Unstructured or Structured "
1581 "which are the only types currently supported",
1582 zone));
1583 }
1584 }
1585 }
1586
1587 if (mesh_type == Ioss::MeshType::STRUCTURED || mesh_type == Ioss::MeshType::HYBRID) {
1588 num_node = finalize_structured_blocks();
1589 }
1590
1591 char basename[CGNS_MAX_NAME_LENGTH + 1];
1592 int cell_dimension = 0;
1593 int phys_dimension = 0;
1594 CGCHECKM(cg_base_read(get_file_pointer(), base, basename, &cell_dimension, &phys_dimension));
1595 if (phys_dimension != 3 && mesh_type == Ioss::MeshType::STRUCTURED) {
1596 IOSS_ERROR(fmt::format("ERROR: The model is {}D. Only 3D structured models are supported.",
1597 phys_dimension));
1598 }
1599
1600 auto *nblock = new Ioss::NodeBlock(this, "nodeblock_1", num_node, phys_dimension);
1601 nblock->property_add(Ioss::Property("base", base));
1602 get_region()->add(nblock);
1603 nodeCount = num_node;
1604
1605 Utils::add_transient_variables(get_file_pointer(), m_timesteps, get_region(), myProcessor,
1606 false);
1607 }
1608
1609 void DatabaseIO::write_meta_data()
1610 {
1611 int num_zones = get_region()->get_property("element_block_count").get_int() +
1612 get_region()->get_property("structured_block_count").get_int();
1613 m_bcOffset.resize(num_zones + 1); // use 1-based zones...
1614 m_zoneOffset.resize(num_zones + 1); // use 1-based zones...
1615
1616 elementCount =
1617 Utils::common_write_metadata(get_file_pointer(), *get_region(), m_zoneOffset, false);
1618 }
1619
1620 void DatabaseIO::get_step_times_nl()
1621 {
1622 Utils::get_step_times(get_file_pointer(), m_timesteps, get_region(), timeScaleFactor,
1623 myProcessor);
1624 }
1625
1626 std::vector<double> DatabaseIO::get_db_step_times_nl()
1627 {
1628 std::vector<double> timesteps;
1629
1630 Utils::get_step_times(get_file_pointer(), timesteps, nullptr, timeScaleFactor, myProcessor);
1631
1632 return timesteps;
1633 }
1634
1635 void DatabaseIO::write_adjacency_data()
1636 {
1637 // Determine adjacency information between unstructured blocks.
1638 // Could save this information from the input mesh, but then
1639 // could not read an exodus mesh and write a cgns mesh.
1640 // However, in long run may still want to read/save input adjacency
1641 // data if doing cgns -> cgns... For now, try generating information.
1642
1643 // If block I is adjacent to block J, then they will share at
1644 // least 1 "side" (face 3D or edge 2D).
1645 // Currently, assuming they are adjacent if they share at least one node...
1646 const auto &blocks = get_region()->get_element_blocks();
1647 for (auto I = blocks.cbegin(); I != blocks.cend(); I++) {
1648 int base = (*I)->get_property("base").get_int();
1649 int zone = Iocgns::Utils::get_db_zone(*I);
1650
1651 const auto &I_map = m_globalToBlockLocalNodeMap[zone];
1652
1653 for (auto J = I + 1; J != blocks.end(); J++) {
1654 int dzone = (*J)->get_property("zone").get_int();
1655 const auto &J_map = m_globalToBlockLocalNodeMap[dzone];
1656 CGNSIntVector point_list;
1657 CGNSIntVector point_list_donor;
1658 for (size_t i = 0; i < J_map->size(); i++) {
1659 auto global = J_map->map()[i + 1];
1660 // See if this global id exists in I_map...
1661 auto i_zone_local = I_map->global_to_local(global, false);
1662 if (i_zone_local > 0) {
1663 // Have a match between nodes used by two different blocks,
1664 // They are adjacent...
1665 point_list.push_back(i_zone_local);
1666 point_list_donor.push_back(i + 1);
1667 }
1668 }
1669
1670 // If point_list non_empty, then output this adjacency node...
1671 if (!point_list.empty()) {
1672 int gc_idx = 0;
1673 std::string name = fmt::format("{}_to_{}", (*I)->name(), (*J)->name());
1674 const auto &d1_name = (*J)->name();
1675 CGCHECKM(cg_conn_write(get_file_pointer(), base, zone, name.c_str(), CGNS_ENUMV(Vertex),
1676 CGNS_ENUMV(Abutting1to1), CGNS_ENUMV(PointList), point_list.size(),
1677 Data(point_list), d1_name.c_str(), CGNS_ENUMV(Unstructured),
1678 CGNS_ENUMV(PointListDonor), CGNS_ENUMV(DataTypeNull),
1679 point_list_donor.size(), Data(point_list_donor), &gc_idx));
1680
1681 name = fmt::format("{}_to_{}", (*J)->name(), (*I)->name());
1682 const auto &d2_name = (*I)->name();
1683
1684 CGCHECKM(cg_conn_write(get_file_pointer(), base, dzone, name.c_str(), CGNS_ENUMV(Vertex),
1685 CGNS_ENUMV(Abutting1to1), CGNS_ENUMV(PointList),
1686 point_list_donor.size(), Data(point_list_donor), d2_name.c_str(),
1687 CGNS_ENUMV(Unstructured), CGNS_ENUMV(PointListDonor),
1688 CGNS_ENUMV(DataTypeNull), point_list.size(), Data(point_list),
1689 &gc_idx));
1690 }
1691 }
1692 }
1693 }
1694
1695 bool DatabaseIO::begin_nl(Ioss::State state)
1696 {
1697 dbState = state;
1698 return true;
1699 }
1700
1701 void DatabaseIO::free_state_pointer()
1702 {
1703 // If this is the first state file created, then we need to save a reference
1704 // to the base CGNS file so we can update the metadata and create links to
1705 // the state files.
1706 if (m_cgnsBasePtr < 0) {
1707 m_cgnsBasePtr = m_cgnsFilePtr;
1708 m_cgnsFilePtr = -1;
1709 }
1710 closeDatabase_nl();
1711 }
1712
1713 void DatabaseIO::open_state_file(int state)
1714 {
1715 // Close current state file (if any)...
1716 free_state_pointer();
1717
1718 // Update filename to append state count...
1719 decodedFilename.clear();
1720
1721 Ioss::FileInfo db(originalDBFilename);
1722 std::string new_filename;
1723 if (!db.pathname().empty()) {
1724 new_filename += db.pathname() + "/";
1725 }
1726
1727 new_filename += fmt::format("{}-SolutionAtStep{:05}.{}", db.basename(), state, db.extension());
1728
1729 DBFilename = new_filename;
1730
1731 Iocgns::Utils::write_state_meta_data(get_file_pointer(), *get_region(), false);
1732 }
1733
1734 bool DatabaseIO::end_nl(Ioss::State state)
1735 {
1736 // Transitioning out of state 'state'
1737 switch (state) {
1738 case Ioss::STATE_DEFINE_MODEL:
1739 if (!is_input() && open_create_behavior() != Ioss::DB_APPEND &&
1740 open_create_behavior() != Ioss::DB_MODIFY) {
1741 write_meta_data();
1742 }
1743 if (!is_input() && (open_create_behavior() == Ioss::DB_APPEND ||
1744 open_create_behavior() == Ioss::DB_MODIFY)) {
1745 Utils::update_db_zone_property(m_cgnsFilePtr, get_region(), myProcessor, isParallel, false);
1746 }
1747
1748 break;
1749 case Ioss::STATE_MODEL:
1750 if (!is_input() && open_create_behavior() != Ioss::DB_APPEND &&
1751 open_create_behavior() != Ioss::DB_MODIFY) {
1752 write_adjacency_data();
1753 }
1754 break;
1755 case Ioss::STATE_DEFINE_TRANSIENT:
1756 if (!is_input() && open_create_behavior() != Ioss::DB_APPEND &&
1757 open_create_behavior() != Ioss::DB_MODIFY) {
1758 write_results_meta_data();
1759 }
1760 break;
1761 default: // ignore everything else...
1762 break;
1763 }
1764
1765 dbState = Ioss::STATE_UNKNOWN;
1766 return true;
1767 }
1768
1769 bool DatabaseIO::begin_state_nl(int state, double /* time */)
1770 {
1771 if (is_input()) {
1772 return true;
1773 }
1774 if (get_file_per_state()) {
1775 // Close current state file (if any); create new state file and output metadata...
1776 open_state_file(state);
1777 write_results_meta_data();
1778 }
1779 Utils::write_flow_solution_metadata(get_file_pointer(), m_cgnsBasePtr, get_region(), state,
1780 &m_currentVertexSolutionIndex,
1781 &m_currentCellCenterSolutionIndex, false);
1782
1783 return true;
1784 }
1785
1786 bool DatabaseIO::end_state_nl(int state, double time)
1787 {
1788 if (!is_input()) {
1789 m_timesteps.push_back(time);
1790 SMART_ASSERT(m_timesteps.size() == (size_t)state);
1791
1792 bool do_flush = true;
1793 if (m_flushInterval != 1) {
1794 if (m_flushInterval == 0 || state % m_flushInterval != 0) {
1795 do_flush = false;
1796 }
1797 }
1798
1799 if (do_flush) {
1800 flush_database_nl();
1801 }
1802 }
1803
1804 return true;
1805 }
1806
1807 void DatabaseIO::flush_database_nl() const
1808 {
1809 // For HDF5 files, it looks like we need to close the database between
1810 // writes if we want to have a valid database for external access or
1811 // to protect against a crash corrupting the file.
1812 Utils::finalize_database(get_file_pointer(), m_timesteps, get_region(), myProcessor, false);
1813 closeDatabase_nl();
1814 m_cgnsFilePtr = -2; // Tell openDatabase_nl that we want to append
1815 }
1816
1817 int64_t DatabaseIO::get_field_internal(const Ioss::Region *reg, const Ioss::Field &field,
1818 void * /* data */, size_t /* data_size */) const
1819 {
1820 return Ioss::Utils::field_warning(reg, field, "input");
1821 }
1822
1823 int64_t DatabaseIO::get_field_internal(const Ioss::NodeBlock *nb, const Ioss::Field &field,
1824 void *data, size_t data_size) const
1825 {
1826 // A CGNS DatabaseIO object can have two "types" of NodeBlocks:
1827 // * The normal "all nodes in the model" NodeBlock as used by Exodus
1828 // * A "nodes in a zone" NodeBlock which contains the subset of nodes
1829 // "owned" by a specific StructuredBlock or ElementBlock zone.
1830 //
1831 // Question: How to determine if the NodeBlock is the "global" Nodeblock
1832 // or a "sub" NodeBlock: Use the "is_nonglobal_nodeblock()" function.
1833 if (nb->is_nonglobal_nodeblock()) {
1834 return get_field_internal_sub_nb(nb, field, data, data_size);
1835 }
1836
1837 Ioss::Field::RoleType role = field.get_role();
1838 int base = nb->get_property("base").get_int();
1839 size_t num_to_get = field.verify(data_size);
1840 cgsize_t first = 1;
1841
1842 // Create a lambda to eliminate some duplicate code in coordinate outputs...
1843 auto coord_lambda = [&data, &first, base,
1844 this](const char *ordinate, int cgns_file_ptr,
1845 const std::vector<CGNSIntVector> &block_local_node_map) {
1846 auto *rdata = static_cast<double *>(data);
1847
1848 for (int zone = 1; zone < static_cast<int>(block_local_node_map.size()); zone++) {
1849 auto &block_map = block_local_node_map[zone];
1850 cgsize_t num_coord = block_map.size();
1851 std::vector<double> coord(num_coord);
1852 CGCHECK(cg_coord_read(cgns_file_ptr, base, zone, ordinate, CGNS_ENUMV(RealDouble), &first,
1853 &num_coord, Data(coord)));
1854
1855 // Map to global coordinate position...
1856 for (cgsize_t i = 0; i < num_coord; i++) {
1857 rdata[block_map[i]] = coord[i];
1858 }
1859 }
1860 };
1861 // End of lambda...
1862
1863 if (role == Ioss::Field::MESH) {
1864 if (field.get_name() == "mesh_model_coordinates_x") {
1865 // Use the lambda...
1866 coord_lambda("CoordinateX", get_file_pointer(), m_blockLocalNodeMap);
1867 }
1868
1869 else if (field.get_name() == "mesh_model_coordinates_y") {
1870 coord_lambda("CoordinateY", get_file_pointer(), m_blockLocalNodeMap);
1871 }
1872
1873 else if (field.get_name() == "mesh_model_coordinates_z") {
1874 coord_lambda("CoordinateZ", get_file_pointer(), m_blockLocalNodeMap);
1875 }
1876
1877 else if (field.get_name() == "mesh_model_coordinates") {
1878 int cell_dimension = 0;
1879 int phys_dimension = 0;
1880 char basename[CGNS_MAX_NAME_LENGTH + 1];
1881 CGCHECKM(
1882 cg_base_read(get_file_pointer(), base, basename, &cell_dimension, &phys_dimension));
1883
1884 auto *rdata = static_cast<double *>(data);
1885
1886 // Data required by upper classes store x0, y0, z0, ... xn,
1887 // yn, zn. Data stored in exodusII file is x0, ..., xn, y0,
1888 // ..., yn, z0, ..., zn so we have to allocate some scratch
1889 // memory to read in the data and then map into supplied
1890 // 'data'
1891 for (int zone = 1; zone < static_cast<int>(m_blockLocalNodeMap.size()); zone++) {
1892 auto &block_map = m_blockLocalNodeMap[zone];
1893 cgsize_t num_coord = block_map.size();
1894 std::vector<double> coord(num_coord);
1895
1896 // ========================================================================
1897 // Repetitive code for each coordinate direction; use a lambda to consolidate...
1898 auto blk_coord_lambda = [block_map, base, zone, &coord, first, num_coord, phys_dimension,
1899 &rdata,
1900 this](const char *ord_name, int ordinate, int cgns_file_ptr) {
1901 CGCHECK(cg_coord_read(cgns_file_ptr, base, zone, ord_name, CGNS_ENUMV(RealDouble),
1902 &first, &num_coord, Data(coord)));
1903
1904 // Map to global coordinate position...
1905 for (cgsize_t i = 0; i < num_coord; i++) {
1906 rdata[phys_dimension * block_map[i] + ordinate] = coord[i];
1907 }
1908 };
1909 // End of lambda...
1910 // ========================================================================
1911
1912 blk_coord_lambda("CoordinateX", 0, get_file_pointer());
1913
1914 if (phys_dimension >= 2) {
1915 blk_coord_lambda("CoordinateY", 1, get_file_pointer());
1916 }
1917
1918 if (phys_dimension >= 3) {
1919 blk_coord_lambda("CoordinateZ", 2, get_file_pointer());
1920 }
1921 }
1922 }
1923 else if (field.get_name() == "ids") {
1924 // Map the local ids in this node block
1925 // (1...node_count) to global node ids.
1926 if (field.get_type() == Ioss::Field::INT64) {
1927 auto *idata = static_cast<int64_t *>(data);
1928 std::iota(idata, idata + num_to_get, 1);
1929 }
1930 else {
1931 SMART_ASSERT(field.get_type() == Ioss::Field::INT32);
1932 int *idata = static_cast<int *>(data);
1933 std::iota(idata, idata + num_to_get, 1);
1934 }
1935 }
1936 else {
1937 num_to_get = Ioss::Utils::field_warning(nb, field, "input");
1938 }
1939 }
1940 else if (role == Ioss::Field::TRANSIENT) {
1941 // Locate the FlowSolution node corresponding to the correct state/step/time
1942 // TODO: do this at read_meta_data() and store...
1943 int step = get_region()->get_current_state();
1944
1945 for (int zone = 1; zone < static_cast<int>(m_blockLocalNodeMap.size()); zone++) {
1946 int solution_index =
1947 Utils::find_solution_index(get_file_pointer(), base, zone, step, CGNS_ENUMV(Vertex));
1948 auto &block_map = m_blockLocalNodeMap[zone];
1949 cgsize_t num_block_node = block_map.size();
1950
1951 auto *rdata = static_cast<double *>(data);
1952 cgsize_t range_min[1] = {1};
1953 cgsize_t range_max[1] = {num_block_node};
1954 int comp_count = field.get_component_count(Ioss::Field::InOut::INPUT);
1955 std::vector<double> cgns_data(num_block_node);
1956 if (comp_count == 1) {
1957 CGCHECKM(cg_field_read(get_file_pointer(), base, zone, solution_index,
1958 field.get_name().c_str(), CGNS_ENUMV(RealDouble), range_min,
1959 range_max, Data(cgns_data)));
1960
1961 // Map to global nodal field position...
1962 for (cgsize_t i = 0; i < num_block_node; i++) {
1963 rdata[block_map[i]] = cgns_data[i];
1964 }
1965 }
1966 else {
1967 for (int i = 0; i < comp_count; i++) {
1968 std::string var_name = get_component_name(field, Ioss::Field::InOut::INPUT, i + 1);
1969
1970 CGCHECKM(cg_field_read(get_file_pointer(), base, zone, solution_index, var_name.c_str(),
1971 CGNS_ENUMV(RealDouble), range_min, range_max, Data(cgns_data)));
1972 for (cgsize_t j = 0; j < num_block_node; j++) {
1973 auto global = block_map[j];
1974 rdata[comp_count * global + i] = cgns_data[j];
1975 }
1976 }
1977 }
1978 }
1979 }
1980 else {
1981 num_to_get = Ioss::Utils::field_warning(nb, field, "input");
1982 }
1983 return num_to_get;
1984 }
1985
1986 int64_t DatabaseIO::get_field_internal_sub_nb(const Ioss::NodeBlock *nb, const Ioss::Field &field,
1987 void *data, size_t data_size) const
1988 {
1989 // Reads field data on a NodeBlock which is a "sub" NodeBlock -- contains the nodes for a
1990 // StructuredBlock instead of for the entire model.
1991 // Currently only TRANSIENT fields are input this way. No valid reason, but that is the current
1992 // use case.
1993
1994 // In this routine, if isParallel, then reading
1995 // file-per-processor; not parallel io from single file.
1996 cgsize_t num_to_get = field.verify(data_size);
1997 if (isParallel && num_to_get == 0) {
1998 return 0;
1999 }
2000
2001 Ioss::Field::RoleType role = field.get_role();
2002 if (role == Ioss::Field::TRANSIENT) {
2003 // Get the StructuredBlock that this NodeBlock is contained in:
2004
2005 // Locate the FlowSolution node corresponding to the correct state/step/time
2006 // TODO: do this at read_meta_data() and store...
2007 int step = get_region()->get_current_state();
2008 int base = 1;
2009 const Ioss::GroupingEntity *sb = nb->contained_in();
2010 int zone = Iocgns::Utils::get_db_zone(sb);
2011 int solution_index =
2012 Utils::find_solution_index(get_file_pointer(), base, zone, step, CGNS_ENUMV(Vertex));
2013
2014 auto *rdata = static_cast<double *>(data);
2015 SMART_ASSERT(num_to_get == sb->get_property("node_count").get_int());
2016 cgsize_t rmin[3] = {0, 0, 0};
2017 cgsize_t rmax[3] = {0, 0, 0};
2018 if (num_to_get > 0) {
2019 rmin[0] = 1;
2020 rmin[1] = 1;
2021 rmin[2] = 1;
2022
2023 rmax[0] = rmin[0] + sb->get_property("ni").get_int();
2024 rmax[1] = rmin[1] + sb->get_property("nj").get_int();
2025 rmax[2] = rmin[2] + sb->get_property("nk").get_int();
2026
2027 SMART_ASSERT(num_to_get ==
2028 (rmax[0] - rmin[0] + 1) * (rmax[1] - rmin[1] + 1) * (rmax[2] - rmin[2] + 1));
2029 }
2030
2031 int comp_count = field.get_component_count(Ioss::Field::InOut::INPUT);
2032
2033 if (comp_count == 1) {
2034 CGCHECKM(cg_field_read(get_file_pointer(), base, zone, solution_index,
2035 field.get_name().c_str(), CGNS_ENUMV(RealDouble), rmin, rmax,
2036 rdata));
2037 }
2038 else {
2039 std::vector<double> cgns_data(num_to_get);
2040 for (int i = 0; i < comp_count; i++) {
2041 std::string var_name = get_component_name(field, Ioss::Field::InOut::INPUT, i + 1);
2042
2043 CGCHECKM(cg_field_read(get_file_pointer(), base, zone, solution_index, var_name.c_str(),
2044 CGNS_ENUMV(RealDouble), rmin, rmax, Data(cgns_data)));
2045 for (cgsize_t j = 0; j < num_to_get; j++) {
2046 rdata[comp_count * j + i] = cgns_data[j];
2047 }
2048 }
2049 }
2050 }
2051 // Ignoring all other field role types...
2052 return num_to_get;
2053 }
2054
2055 int64_t DatabaseIO::get_field_internal(const Ioss::EdgeBlock *eb, const Ioss::Field &field,
2056 void * /* data */, size_t /* data_size */) const
2057 {
2058 return Ioss::Utils::field_warning(eb, field, "input");
2059 }
2060
2061 int64_t DatabaseIO::get_field_internal(const Ioss::FaceBlock *fb, const Ioss::Field &field,
2062 void * /* data */, size_t /* data_size */) const
2063 {
2064 return Ioss::Utils::field_warning(fb, field, "input");
2065 }
2066
2067 int64_t DatabaseIO::get_field_internal(const Ioss::ElementBlock *eb, const Ioss::Field &field,
2068 void *data, size_t data_size) const
2069 {
2070 size_t num_to_get = field.verify(data_size);
2071 if (num_to_get > 0) {
2072
2073 int base = eb->get_property("base").get_int();
2074 int zone = Iocgns::Utils::get_db_zone(eb);
2075 int sect = eb->get_property("section").get_int();
2076 cgsize_t my_element_count = eb->entity_count();
2077 Ioss::Field::RoleType role = field.get_role();
2078
2079 if (role == Ioss::Field::MESH) {
2080 // Handle the MESH fields required for a CGNS file model.
2081 // (The 'genesis' portion)
2082
2083 if (field.get_name() == "connectivity" || field.get_name() == "connectivity_raw") {
2084 // TODO(gdsjaar): Need to map local to global...
2085 int element_nodes = eb->topology()->number_nodes();
2086 SMART_ASSERT(field.raw_storage()->component_count() == element_nodes);
2087
2088 if (my_element_count > 0) {
2089 int field_byte_size = (field.get_type() == Ioss::Field::INT32) ? 32 : 64;
2090 if (field_byte_size == CG_SIZEOF_SIZE) {
2091 auto *idata = reinterpret_cast<cgsize_t *>(data);
2092 CGCHECKM(cg_elements_read(get_file_pointer(), base, zone, sect, idata, nullptr));
2093 Utils::map_cgns_connectivity(eb->topology(), num_to_get, idata);
2094 }
2095 else {
2096 CGNSIntVector connect(element_nodes * num_to_get);
2097 CGCHECKM(
2098 cg_elements_read(get_file_pointer(), base, zone, sect, Data(connect), nullptr));
2099 if (field.get_type() == Ioss::Field::INT32) {
2100 auto *idata = reinterpret_cast<int *>(data);
2101 size_t i = 0;
2102 for (auto node : connect) {
2103 idata[i++] = node;
2104 }
2105 Utils::map_cgns_connectivity(eb->topology(), num_to_get, idata);
2106 }
2107 else {
2108 auto *idata = reinterpret_cast<int64_t *>(data);
2109 size_t i = 0;
2110 for (auto node : connect) {
2111 idata[i++] = node;
2112 }
2113 Utils::map_cgns_connectivity(eb->topology(), num_to_get, idata);
2114 }
2115 }
2116 }
2117
2118 // Now need to map block-local node connectivity to global nodes...
2119 // This is done for both connectivity and connectivity_raw
2120 // since the "global id" is the same as the "local id"
2121 // The connectivities we currently have are "block local"
2122 const auto &block_map = m_blockLocalNodeMap[zone];
2123 if (field.get_type() == Ioss::Field::INT32) {
2124 int *idata = static_cast<int *>(data);
2125 for (size_t i = 0; i < element_nodes * num_to_get; i++) {
2126 idata[i] = block_map[idata[i] - 1] + 1;
2127 }
2128 }
2129 else {
2130 auto *idata = static_cast<int64_t *>(data);
2131 for (size_t i = 0; i < element_nodes * num_to_get; i++) {
2132 idata[i] = block_map[idata[i] - 1] + 1;
2133 }
2134 }
2135 }
2136 else if (field.get_name() == "ids") {
2137 // Map the local ids in this element block
2138 // (eb_offset+1...eb_offset+1+my_element_count) to global element ids.
2139 size_t eb_offset_plus_one = eb->get_offset() + 1;
2140 if (field.get_type() == Ioss::Field::INT64) {
2141 auto *idata = static_cast<int64_t *>(data);
2142 std::iota(idata, idata + my_element_count, static_cast<int64_t>(eb_offset_plus_one));
2143 }
2144 else {
2145 SMART_ASSERT(field.get_type() == Ioss::Field::INT32);
2146 int *idata = static_cast<int *>(data);
2147 std::iota(idata, idata + my_element_count, static_cast<int>(eb_offset_plus_one));
2148 }
2149 }
2150 else if (field.get_name() == "implicit_ids") {
2151 size_t eb_offset_plus_one = eb->get_offset() + 1;
2152 if (field.get_type() == Ioss::Field::INT64) {
2153 auto *idata = static_cast<int64_t *>(data);
2154 std::iota(idata, idata + my_element_count, static_cast<int64_t>(eb_offset_plus_one));
2155 }
2156 else {
2157 SMART_ASSERT(field.get_type() == Ioss::Field::INT32);
2158 int *idata = static_cast<int *>(data);
2159 std::iota(idata, idata + my_element_count, static_cast<int>(eb_offset_plus_one));
2160 }
2161 }
2162 else {
2163 num_to_get = Ioss::Utils::field_warning(eb, field, "input");
2164 }
2165 }
2166 else if (role == Ioss::Field::TRANSIENT) {
2167 // Locate the FlowSolution node corresponding to the correct state/step/time
2168 // TODO: do this at read_meta_data() and store...
2169 int step = get_region()->get_current_state();
2170 int solution_index = Utils::find_solution_index(get_file_pointer(), base, zone, step,
2171 CGNS_ENUMV(CellCenter));
2172
2173 auto *rdata = static_cast<double *>(data);
2174 cgsize_t range_min[1] = {1};
2175 cgsize_t range_max[1] = {my_element_count};
2176
2177 int comp_count = field.get_component_count(Ioss::Field::InOut::INPUT);
2178 if (comp_count == 1) {
2179 CGCHECKM(cg_field_read(get_file_pointer(), base, zone, solution_index,
2180 field.get_name().c_str(), CGNS_ENUMV(RealDouble), range_min,
2181 range_max, rdata));
2182 }
2183 else {
2184 std::vector<double> cgns_data(my_element_count);
2185 for (int i = 0; i < comp_count; i++) {
2186 std::string var_name = get_component_name(field, Ioss::Field::InOut::INPUT, i + 1);
2187
2188 CGCHECKM(cg_field_read(get_file_pointer(), base, zone, solution_index, var_name.c_str(),
2189 CGNS_ENUMV(RealDouble), range_min, range_max, Data(cgns_data)));
2190 for (cgsize_t j = 0; j < my_element_count; j++) {
2191 rdata[comp_count * j + i] = cgns_data[j];
2192 }
2193 }
2194 }
2195 }
2196 else {
2197 num_to_get = Ioss::Utils::field_warning(eb, field, "output");
2198 }
2199 }
2200 return num_to_get;
2201 }
2202
2203 int64_t DatabaseIO::get_field_internal(const Ioss::StructuredBlock *sb, const Ioss::Field &field,
2204 void *data, size_t data_size) const
2205 {
2206 Ioss::Field::RoleType role = field.get_role();
2207 int base = sb->get_property("base").get_int();
2208 int zone = Iocgns::Utils::get_db_zone(sb);
2209
2210 cgsize_t num_to_get = field.verify(data_size);
2211
2212 // In this routine, if isParallel, then reading file-per-processor; not parallel io from single
2213 // file.
2214 if (isParallel && num_to_get == 0) {
2215 return 0;
2216 }
2217
2218 cgsize_t rmin[3] = {0, 0, 0};
2219 cgsize_t rmax[3] = {0, 0, 0};
2220
2221 bool cell_field = Utils::is_cell_field(field);
2222 if ((cell_field && sb->get_property("cell_count").get_int() == 0) ||
2223 (!cell_field && sb->get_property("node_count").get_int() == 0)) {
2224 return 0;
2225 }
2226
2227 if (cell_field) {
2228 SMART_ASSERT(num_to_get == sb->get_property("cell_count").get_int());
2229 if (num_to_get > 0) {
2230 rmin[0] = 1;
2231 rmin[1] = 1;
2232 rmin[2] = 1;
2233
2234 rmax[0] = rmin[0] + sb->get_property("ni").get_int() - 1;
2235 rmax[1] = rmin[1] + sb->get_property("nj").get_int() - 1;
2236 rmax[2] = rmin[2] + sb->get_property("nk").get_int() - 1;
2237 }
2238 }
2239 else {
2240 // cell nodal field.
2241 SMART_ASSERT(num_to_get == sb->get_property("node_count").get_int());
2242 if (num_to_get > 0) {
2243 rmin[0] = 1;
2244 rmin[1] = 1;
2245 rmin[2] = 1;
2246
2247 rmax[0] = rmin[0] + sb->get_property("ni").get_int();
2248 rmax[1] = rmin[1] + sb->get_property("nj").get_int();
2249 rmax[2] = rmin[2] + sb->get_property("nk").get_int();
2250 }
2251 }
2252
2253 SMART_ASSERT(num_to_get ==
2254 (rmax[0] - rmin[0] + 1) * (rmax[1] - rmin[1] + 1) * (rmax[2] - rmin[2] + 1));
2255
2256 auto *rdata = static_cast<double *>(data);
2257
2258 if (role == Ioss::Field::MESH) {
2259 if (field.get_name() == "mesh_model_coordinates_x") {
2260 CGCHECKM(cg_coord_read(get_file_pointer(), base, zone, "CoordinateX",
2261 CGNS_ENUMV(RealDouble), rmin, rmax, rdata));
2262 }
2263
2264 else if (field.get_name() == "mesh_model_coordinates_y") {
2265 CGCHECKM(cg_coord_read(get_file_pointer(), base, zone, "CoordinateY",
2266 CGNS_ENUMV(RealDouble), rmin, rmax, rdata));
2267 }
2268
2269 else if (field.get_name() == "mesh_model_coordinates_z") {
2270 CGCHECKM(cg_coord_read(get_file_pointer(), base, zone, "CoordinateZ",
2271 CGNS_ENUMV(RealDouble), rmin, rmax, rdata));
2272 }
2273
2274 else if (field.get_name() == "mesh_model_coordinates") {
2275 char basename[CGNS_MAX_NAME_LENGTH + 1];
2276 int cell_dimension = 0;
2277 int phys_dimension = 0;
2278 CGCHECKM(
2279 cg_base_read(get_file_pointer(), base, basename, &cell_dimension, &phys_dimension));
2280
2281 // Data required by upper classes store x0, y0, z0, ... xn,
2282 // yn, zn. Data stored in cgns file is x0, ..., xn, y0,
2283 // ..., yn, z0, ..., zn so we have to allocate some scratch
2284 // memory to read in the data and then map into supplied
2285 // 'data'
2286
2287 std::vector<double> coord(num_to_get);
2288
2289 // ========================================================================
2290 // Repetitive code for each coordinate direction; use a lambda to consolidate...
2291 auto coord_lambda = [base, zone, &coord, &rmin, &rmax, phys_dimension, num_to_get, &rdata,
2292 this](const char *ord_name, int ordinate, int cgns_file_ptr) {
2293 CGCHECK(cg_coord_read(cgns_file_ptr, base, zone, ord_name, CGNS_ENUMV(RealDouble), rmin,
2294 rmax, Data(coord)));
2295
2296 // Map to global coordinate position...
2297 for (cgsize_t i = 0; i < num_to_get; i++) {
2298 rdata[phys_dimension * i + ordinate] = coord[i];
2299 }
2300 };
2301 // End of lambda...
2302 // ========================================================================
2303
2304 coord_lambda("CoordinateX", 0, get_file_pointer());
2305
2306 if (phys_dimension >= 2) {
2307 coord_lambda("CoordinateY", 1, get_file_pointer());
2308 }
2309
2310 if (phys_dimension == 3) {
2311 coord_lambda("CoordinateZ", 2, get_file_pointer());
2312 }
2313 }
2314 else if (field.get_name() == "cell_node_ids") {
2315 if (field.get_type() == Ioss::Field::INT64) {
2316 auto *idata = static_cast<int64_t *>(data);
2317 sb->get_cell_node_ids(idata, true);
2318 }
2319 else {
2320 SMART_ASSERT(field.get_type() == Ioss::Field::INT32);
2321 int *idata = static_cast<int *>(data);
2322 sb->get_cell_node_ids(idata, true);
2323 }
2324 }
2325 else if (field.get_name() == "cell_ids") {
2326 if (field.get_type() == Ioss::Field::INT64) {
2327 auto *idata = static_cast<int64_t *>(data);
2328 sb->get_cell_ids(idata, true);
2329 }
2330 else {
2331 SMART_ASSERT(field.get_type() == Ioss::Field::INT32);
2332 int *idata = static_cast<int *>(data);
2333 sb->get_cell_ids(idata, true);
2334 }
2335 }
2336 else {
2337 num_to_get = Ioss::Utils::field_warning(sb, field, "input");
2338 }
2339 }
2340 else if (role == Ioss::Field::TRANSIENT) {
2341 int comp_count = field.get_component_count(Ioss::Field::InOut::INPUT);
2342
2343 int sol_index = 0;
2344 int step = get_region()->get_current_state();
2345 if (cell_field) {
2346 sol_index = Utils::find_solution_index(get_file_pointer(), base, zone, step,
2347 CGNS_ENUMV(CellCenter));
2348 }
2349 else {
2350 sol_index =
2351 Utils::find_solution_index(get_file_pointer(), base, zone, step, CGNS_ENUMV(Vertex));
2352 }
2353
2354 if (comp_count == 1) {
2355 CGCHECKM(cg_field_read(get_file_pointer(), base, zone, sol_index, field.get_name().c_str(),
2356 CGNS_ENUMV(RealDouble), rmin, rmax, rdata));
2357 }
2358 else {
2359 std::vector<double> cgns_data(num_to_get);
2360 for (int i = 0; i < comp_count; i++) {
2361 std::string var_name = get_component_name(field, Ioss::Field::InOut::INPUT, i + 1);
2362 CGCHECKM(cg_field_read(get_file_pointer(), base, zone, sol_index, var_name.c_str(),
2363 CGNS_ENUMV(RealDouble), rmin, rmax, Data(cgns_data)));
2364 for (cgsize_t j = 0; j < num_to_get; j++) {
2365 rdata[comp_count * j + i] = cgns_data[j];
2366 }
2367 }
2368 }
2369 }
2370 else {
2371 num_to_get = Ioss::Utils::field_warning(sb, field, "input");
2372 }
2373 return num_to_get;
2374 }
2375
2376 int64_t DatabaseIO::get_field_internal(const Ioss::NodeSet *ns, const Ioss::Field &field,
2377 void * /* data */, size_t /* data_size */) const
2378 {
2379 return Ioss::Utils::field_warning(ns, field, "input");
2380 }
2381 int64_t DatabaseIO::get_field_internal(const Ioss::EdgeSet *es, const Ioss::Field &field,
2382 void * /* data */, size_t /* data_size */) const
2383 {
2384 return Ioss::Utils::field_warning(es, field, "input");
2385 }
2386 int64_t DatabaseIO::get_field_internal(const Ioss::FaceSet *fs, const Ioss::Field &field,
2387 void * /* data */, size_t /* data_size */) const
2388 {
2389 return Ioss::Utils::field_warning(fs, field, "input");
2390 }
2391 int64_t DatabaseIO::get_field_internal(const Ioss::ElementSet *es, const Ioss::Field &field,
2392 void * /* data */, size_t /* data_size */) const
2393 {
2394 return Ioss::Utils::field_warning(es, field, "input");
2395 }
2396 int64_t DatabaseIO::get_field_internal(const Ioss::SideBlock *sb, const Ioss::Field &field,
2397 void *data, size_t data_size) const
2398 {
2399 int base = sb->get_property("base").get_int();
2400 int zone = Iocgns::Utils::get_db_zone(sb);
2401 int sect = sb->get_property("section").get_int();
2402
2403 int64_t num_to_get = field.verify(data_size);
2404 if (num_to_get > 0) {
2405 int64_t entity_count = sb->entity_count();
2406 if (num_to_get != entity_count) {
2407 IOSS_ERROR("ERROR: Partial field input not yet implemented for side blocks");
2408 }
2409 }
2410
2411 Ioss::Field::RoleType role = field.get_role();
2412 if (role == Ioss::Field::MESH) {
2413 if (field.get_name() == "element_side_raw" || field.get_name() == "element_side") {
2414
2415 // TODO(gdsjaar): ? Possibly rewrite using cgi_read_int_data so can skip reading element
2416 // connectivity
2417 int nodes_per_face = sb->topology()->number_nodes();
2418 CGNSIntVector elements(nodes_per_face * num_to_get); // Not needed, but can't skip
2419
2420 // The parent information will be formatted as:
2421 // * `num_to_get` parent elements,
2422 // * `num_to_get` zeros (other parent element for face, but on boundary so 0)
2423 // * `num_to_get` face_on_element
2424 // * `num_to_get` zeros (face on other parent element)
2425 CGNSIntVector parent(4 * num_to_get);
2426
2427 CGCHECKM(
2428 cg_elements_read(get_file_pointer(), base, zone, sect, Data(elements), Data(parent)));
2429
2430 // See if the file contained `parent` data -- Some mesh generators only write the face
2431 // connectivity information. We prefer the `parent/face_on_element` data, but if that does
2432 // not exist, then need to generate it based on the face connectivity information...
2433
2434 if (parent[0] == 0) {
2435 // Don't have the parent/face_on_element data ... generate.
2436 Ioss::Utils::clear(parent);
2437
2438 if (m_boundaryFaces.empty()) {
2439 Utils::generate_boundary_faces(get_region(), m_boundaryFaces, field.get_type());
2440 }
2441
2442 // Now, iterate the face connectivity vector and find a match in `m_boundaryFaces`
2443 int *i32data = reinterpret_cast<int *>(data);
2444 auto *i64data = reinterpret_cast<int64_t *>(data);
2445
2446 size_t offset = 0;
2447 size_t j = 0;
2448 const std::string &name = sb->parent_block()->name();
2449 auto &boundary = m_boundaryFaces[name];
2450 int num_corner_nodes = sb->topology()->number_corner_nodes();
2451 SMART_ASSERT(num_corner_nodes == 3 || num_corner_nodes == 4)(num_corner_nodes);
2452
2453 for (int64_t iface = 0; iface < num_to_get; iface++) {
2454 std::array<size_t, 4> conn = {{0, 0, 0, 0}};
2455
2456 for (int i = 0; i < num_corner_nodes; i++) {
2457 conn[i] = elements[offset + i];
2458 }
2459 offset += nodes_per_face;
2460
2461 Ioss::Face face(conn);
2462 // See if face is in m_boundaryFaces
2463 // If not, error
2464 // If so, then get parent element and element side.
2465 auto it = boundary.find(face);
2466 if (it != boundary.end()) {
2467 cgsize_t fid = (*it).element[0];
2468 #if IOSS_DEBUG_OUTPUT
2469 fmt::print("Connectivity: {} {} {} {} maps to element {}, face {}\n", conn[0],
2470 conn[1], conn[2], conn[3], fid / 10, fid % 10 + 1);
2471 #endif
2472 if (field.get_type() == Ioss::Field::INT32) {
2473 i32data[j++] = fid / 10;
2474 i32data[j++] = fid % 10 + 1;
2475 }
2476 else {
2477 i64data[j++] = fid / 10;
2478 i64data[j++] = fid % 10 + 1;
2479 }
2480 }
2481 else {
2482 IOSS_ERROR(
2483 fmt::format("ERROR: CGNS: Could not find face with connectivity {} {} {} {} on "
2484 "sideblock {} with parent {}.",
2485 conn[0], conn[1], conn[2], conn[3], sb->name(), name));
2486 }
2487 }
2488 }
2489 else {
2490 size_t offset = m_zoneOffset[zone - 1];
2491 if (field.get_type() == Ioss::Field::INT32) {
2492 int *idata = reinterpret_cast<int *>(data);
2493 size_t j = 0;
2494 for (int64_t i = 0; i < num_to_get; i++) {
2495 idata[j++] = parent[num_to_get * 0 + i] + offset; // Element
2496 idata[j++] = parent[num_to_get * 2 + i];
2497 SMART_ASSERT(parent[num_to_get * 1 + i] == 0);
2498 SMART_ASSERT(parent[num_to_get * 3 + i] == 0);
2499 }
2500 // Adjust face numbers to IOSS convention instead of CGNS convention...
2501 Utils::map_cgns_face_to_ioss(sb->parent_element_topology(), num_to_get, idata);
2502 }
2503 else {
2504 auto *idata = reinterpret_cast<int64_t *>(data);
2505 size_t j = 0;
2506 for (int64_t i = 0; i < num_to_get; i++) {
2507 idata[j++] = parent[num_to_get * 0 + i] + offset; // Element
2508 idata[j++] = parent[num_to_get * 2 + i];
2509 SMART_ASSERT(parent[num_to_get * 1 + i] == 0);
2510 SMART_ASSERT(parent[num_to_get * 3 + i] == 0);
2511 }
2512 // Adjust face numbers to IOSS convention instead of CGNS convention...
2513 Utils::map_cgns_face_to_ioss(sb->parent_element_topology(), num_to_get, idata);
2514 }
2515 }
2516 }
2517 else {
2518 num_to_get = Ioss::Utils::field_warning(sb, field, "input");
2519 }
2520 }
2521 else {
2522 num_to_get = Ioss::Utils::field_warning(sb, field, "input");
2523 }
2524 return num_to_get;
2525 }
2526
2527 int64_t DatabaseIO::get_field_internal(const Ioss::SideSet *fs, const Ioss::Field &field,
2528 void * /* data */, size_t /* data_size */) const
2529 {
2530 return Ioss::Utils::field_warning(fs, field, "input");
2531 }
2532 int64_t DatabaseIO::get_field_internal(const Ioss::CommSet *cs, const Ioss::Field &field,
2533 void * /* data */, size_t /* data_size */) const
2534 {
2535 return Ioss::Utils::field_warning(cs, field, "input");
2536 }
2537
2538 int64_t DatabaseIO::put_field_internal(const Ioss::Region *region, const Ioss::Field &field,
2539 void * /*data*/, size_t /*data_size*/) const
2540 {
2541 return Ioss::Utils::field_warning(region, field, "output");
2542 }
2543
2544 int64_t DatabaseIO::put_field_internal(const Ioss::StructuredBlock *sb, const Ioss::Field &field,
2545 void *data, size_t data_size) const
2546 {
2547 Ioss::Field::RoleType role = field.get_role();
2548 int base = sb->get_property("base").get_int();
2549 int zone = Iocgns::Utils::get_db_zone(sb);
2550
2551 cgsize_t num_to_get = field.verify(data_size);
2552
2553 // In this routine, if isParallel, then writing file-per-processor; not parallel io to single
2554 // file.
2555 if (isParallel && num_to_get == 0) {
2556 return 0;
2557 }
2558
2559 if (role == Ioss::Field::MESH) {
2560 bool cell_field = Utils::is_cell_field(field);
2561
2562 if (cell_field) {
2563 SMART_ASSERT(num_to_get == sb->get_property("cell_count").get_int());
2564 }
2565
2566 auto *rdata = static_cast<double *>(data);
2567
2568 int crd_idx = 0;
2569 if (field.get_name() == "mesh_model_coordinates_x") {
2570 SMART_ASSERT(!cell_field);
2571 CGCHECKM(cg_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2572 "CoordinateX", rdata, &crd_idx));
2573 }
2574
2575 else if (field.get_name() == "mesh_model_coordinates_y") {
2576 SMART_ASSERT(!cell_field);
2577 CGCHECKM(cg_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2578 "CoordinateY", rdata, &crd_idx));
2579 }
2580
2581 else if (field.get_name() == "mesh_model_coordinates_z") {
2582 SMART_ASSERT(!cell_field);
2583 CGCHECKM(cg_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2584 "CoordinateZ", rdata, &crd_idx));
2585 }
2586
2587 else if (field.get_name() == "mesh_model_coordinates") {
2588 SMART_ASSERT(!cell_field);
2589 int phys_dimension = get_region()->get_property("spatial_dimension").get_int();
2590
2591 // Data required by upper classes store x0, y0, z0, ... xn,
2592 // yn, zn. Data stored in cgns file is x0, ..., xn, y0,
2593 // ..., yn, z0, ..., zn so we have to allocate some scratch
2594 // memory to read in the data and then map into supplied
2595 // 'data'
2596 std::vector<double> coord(num_to_get);
2597
2598 // ========================================================================
2599 // Repetitive code for each coordinate direction; use a lambda to consolidate...
2600 auto coord_lambda = [&coord, num_to_get, phys_dimension, &rdata, base, zone,
2601 this](const char *ord_name, int ordinate, int cgns_file_ptr) {
2602 int crd_index = 0;
2603
2604 // Map to global coordinate position...
2605 for (cgsize_t i = 0; i < num_to_get; i++) {
2606 coord[i] = rdata[phys_dimension * i + ordinate];
2607 }
2608
2609 CGCHECK(cg_coord_write(cgns_file_ptr, base, zone, CGNS_ENUMV(RealDouble), ord_name,
2610 Data(coord), &crd_index));
2611 };
2612 // End of lambda...
2613 // ========================================================================
2614
2615 coord_lambda("CoordinateX", 0, get_file_pointer());
2616
2617 if (phys_dimension >= 2) {
2618 coord_lambda("CoordinateY", 1, get_file_pointer());
2619 }
2620 if (phys_dimension == 3) {
2621 coord_lambda("CoordinateZ", 2, get_file_pointer());
2622 }
2623 }
2624 else {
2625 num_to_get = Ioss::Utils::field_warning(sb, field, "output");
2626 }
2627 }
2628 else if (role == Ioss::Field::TRANSIENT) {
2629 auto *rdata = static_cast<double *>(data);
2630 int cgns_field = 0;
2631 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
2632 if (comp_count == 1) {
2633 CGCHECKM(cg_field_write(get_file_pointer(), base, zone, m_currentCellCenterSolutionIndex,
2634 CGNS_ENUMV(RealDouble), field.get_name().c_str(), rdata,
2635 &cgns_field));
2636 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(CellCenter));
2637 }
2638 else {
2639 std::vector<double> cgns_data(num_to_get);
2640 for (int i = 0; i < comp_count; i++) {
2641 for (cgsize_t j = 0; j < num_to_get; j++) {
2642 cgns_data[j] = rdata[comp_count * j + i];
2643 }
2644 std::string var_name = get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
2645
2646 CGCHECKM(cg_field_write(get_file_pointer(), base, zone, m_currentCellCenterSolutionIndex,
2647 CGNS_ENUMV(RealDouble), var_name.c_str(), Data(cgns_data),
2648 &cgns_field));
2649 if (i == 0) {
2650 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(CellCenter));
2651 }
2652 }
2653 }
2654 }
2655 else {
2656 num_to_get = Ioss::Utils::field_warning(sb, field, "output");
2657 }
2658
2659 return num_to_get;
2660 }
2661
2662 int64_t DatabaseIO::put_field_internal(const Ioss::ElementBlock *eb, const Ioss::Field &field,
2663 void *data, size_t data_size) const
2664 {
2665 size_t num_to_get = field.verify(data_size);
2666 if (num_to_get > 0) {
2667
2668 Ioss::Field::RoleType role = field.get_role();
2669
2670 if (role == Ioss::Field::MESH) {
2671 // Handle the MESH fields required for a CGNS file model.
2672 // (The 'genesis' portion)
2673 if (field.get_name() == "ids") {
2674 elemMap.set_size(elementCount);
2675 handle_block_ids(eb, elemMap, data, num_to_get, field.get_type());
2676 }
2677 else if (field.get_name() == "connectivity") {
2678 // This blocks zone has not been defined.
2679 // Get the "node block" for this element block...
2680 int element_nodes = eb->topology()->number_nodes();
2681 SMART_ASSERT(field.raw_storage()->component_count() == element_nodes);
2682
2683 Ioss::MapContainer nodes;
2684 nodes.reserve(element_nodes * num_to_get + 1);
2685 nodes.push_back(0); // Unknown whether one-to-one map.
2686
2687 if (field.get_type() == Ioss::Field::INT32) {
2688 auto *idata = reinterpret_cast<int *>(data);
2689 for (size_t i = 0; i < element_nodes * num_to_get; i++) {
2690 nodes.push_back(idata[i]);
2691 }
2692 }
2693 else {
2694 auto *idata = reinterpret_cast<int64_t *>(data);
2695 for (size_t i = 0; i < element_nodes * num_to_get; i++) {
2696 nodes.push_back(idata[i]);
2697 }
2698 }
2699 Ioss::Utils::uniquify(nodes, true);
2700 SMART_ASSERT(nodes[0] == 0);
2701
2702 // Now, we have the node count and cell count so we can create a zone...
2703 int base = 1;
2704 int zone = 0;
2705 cgsize_t size[3] = {0, 0, 0};
2706 size[1] = eb->entity_count();
2707 size[0] = nodes.size() - 1;
2708
2709 CGCHECKM(cg_zone_write(get_file_pointer(), base, eb->name().c_str(), size,
2710 CGNS_ENUMV(Unstructured), &zone));
2711 eb->property_update("db_zone", zone);
2712 eb->property_update("zone", zone);
2713 eb->property_update("id", zone);
2714 eb->property_update("guid", zone);
2715 eb->property_update("section", 1);
2716 eb->property_update("base", base);
2717 eb->property_update("zone_node_count", size[0]);
2718 eb->property_update("zone_element_count", size[1]);
2719
2720 if (eb->property_exists("assembly")) {
2721 std::string assembly = eb->get_property("assembly").get_string();
2722 CGCHECKM(cg_goto(get_file_pointer(), base, "Zone_t", zone, "end"));
2723 CGCHECKM(cg_famname_write(assembly.c_str()));
2724 }
2725
2726 // Now we have a valid zone so can update some data structures...
2727 m_zoneOffset[zone] = m_zoneOffset[zone - 1] + size[1];
2728 m_globalToBlockLocalNodeMap[zone] = new Ioss::Map("element", "unknown", myProcessor);
2729 m_globalToBlockLocalNodeMap[zone]->map().swap(nodes);
2730 m_globalToBlockLocalNodeMap[zone]->build_reverse_map_no_lock();
2731
2732 // Need to map global nodes to block-local node connectivity
2733 const auto &block_map = m_globalToBlockLocalNodeMap[zone];
2734 block_map->reverse_map_data(data, field, num_to_get * element_nodes);
2735
2736 if (eb->entity_count() > 0) {
2737 CGNS_ENUMT(ElementType_t) type = Utils::map_topology_to_cgns(eb->topology()->name());
2738 int sect = 0;
2739 int field_byte_size = (field.get_type() == Ioss::Field::INT32) ? 32 : 64;
2740 if (field_byte_size == CG_SIZEOF_SIZE) {
2741 Utils::unmap_cgns_connectivity(eb->topology(), num_to_get, (cgsize_t *)data);
2742 std::string element_type =
2743 fmt::format("{}Elements", Ioss::Utils::shape_to_string(eb->topology()->shape()));
2744 CGCHECKM(cg_section_write(get_file_pointer(), base, zone, element_type.c_str(), type,
2745 1, num_to_get, 0, (cgsize_t *)data, &sect));
2746 }
2747 else {
2748 CGNSIntVector connect;
2749 connect.reserve(element_nodes * num_to_get);
2750 if (field.get_type() == Ioss::Field::INT32) {
2751 auto *idata = reinterpret_cast<int *>(data);
2752 for (size_t i = 0; i < element_nodes * num_to_get; i++) {
2753 connect.push_back(idata[i]);
2754 }
2755 }
2756 else {
2757 auto *idata = reinterpret_cast<int64_t *>(data);
2758 for (size_t i = 0; i < element_nodes * num_to_get; i++) {
2759 connect.push_back(idata[i]);
2760 }
2761 }
2762 Utils::unmap_cgns_connectivity(eb->topology(), num_to_get, Data(connect));
2763 std::string element_type =
2764 fmt::format("{}Elements", Ioss::Utils::shape_to_string(eb->topology()->shape()));
2765 CGCHECKM(cg_section_write(get_file_pointer(), base, zone, element_type.c_str(), type,
2766 1, num_to_get, 0, Data(connect), &sect));
2767 }
2768 m_bcOffset[zone] += num_to_get;
2769 eb->property_update("section", sect);
2770 }
2771 }
2772 else {
2773 num_to_get = Ioss::Utils::field_warning(eb, field, "output");
2774 }
2775 }
2776 else if (role == Ioss::Field::TRANSIENT) {
2777 int base = eb->get_property("base").get_int();
2778 int zone = Iocgns::Utils::get_db_zone(eb);
2779 auto *rdata = static_cast<double *>(data);
2780 int cgns_field = 0;
2781 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
2782 if (comp_count == 1) {
2783 CGCHECKM(cg_field_write(get_file_pointer(), base, zone, m_currentCellCenterSolutionIndex,
2784 CGNS_ENUMV(RealDouble), field.get_name().c_str(), rdata,
2785 &cgns_field));
2786 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(CellCenter));
2787 }
2788 else {
2789 std::vector<double> cgns_data(num_to_get);
2790 for (int i = 0; i < comp_count; i++) {
2791 for (size_t j = 0; j < num_to_get; j++) {
2792 cgns_data[j] = rdata[comp_count * j + i];
2793 }
2794 std::string var_name = get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
2795
2796 CGCHECKM(cg_field_write(get_file_pointer(), base, zone,
2797 m_currentCellCenterSolutionIndex, CGNS_ENUMV(RealDouble),
2798 var_name.c_str(), Data(cgns_data), &cgns_field));
2799 if (i == 0) {
2800 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(CellCenter));
2801 }
2802 }
2803 }
2804 }
2805 else {
2806 num_to_get = Ioss::Utils::field_warning(eb, field, "output");
2807 }
2808 }
2809 return num_to_get;
2810 }
2811
2812 int64_t DatabaseIO::put_field_internal(const Ioss::FaceBlock *fb, const Ioss::Field &field,
2813 void * /* data */, size_t /* data_size */) const
2814 {
2815 return Ioss::Utils::field_warning(fb, field, "output");
2816 }
2817 int64_t DatabaseIO::put_field_internal(const Ioss::EdgeBlock *eb, const Ioss::Field &field,
2818 void * /* data */, size_t /* data_size */) const
2819 {
2820 return Ioss::Utils::field_warning(eb, field, "output");
2821 }
2822 int64_t DatabaseIO::put_field_internal(const Ioss::NodeBlock *nb, const Ioss::Field &field,
2823 void *data, size_t data_size) const
2824 {
2825 // A CGNS DatabaseIO object can have two "types" of NodeBlocks:
2826 // * The normal "all nodes in the model" NodeBlock as used by Exodus
2827 // * A "nodes in a zone" NodeBlock which contains the subset of nodes
2828 // "owned" by a specific StructuredBlock or ElementBlock zone.
2829 //
2830 // Question: How to determine if the NodeBlock is the "global" Nodeblock
2831 // or a "sub" NodeBlock: Use the "is_nonglobal_nodeblock()" function.
2832 if (nb->is_nonglobal_nodeblock()) {
2833 return put_field_internal_sub_nb(nb, field, data, data_size);
2834 }
2835
2836 // Instead of outputting a global nodeblock's worth of data,
2837 // the data is output a "zone" at a time.
2838 // The m_globalToBlockLocalNodeMap[zone] map is used (Ioss::Map pointer)
2839 // This map is built during the output of block connectivity,
2840 // so for cgns unstructured mesh, we need to output ElementBlock connectivity
2841 // prior to outputting nodal coordinates.
2842 for (const auto &z : m_globalToBlockLocalNodeMap) {
2843 if (z.second == nullptr) {
2844 IOSS_ERROR("ERROR: CGNS: The globalToBlockLocalNodeMap is not defined, so nodal fields "
2845 "cannot be output.");
2846 }
2847 }
2848
2849 Ioss::Field::RoleType role = field.get_role();
2850 int base = 1;
2851 cgsize_t num_to_get = field.verify(data_size);
2852
2853 if (role == Ioss::Field::MESH) {
2854 if (field.get_name() == "ids") {
2855 // Only needed for parallel, but will be sequential in serial, so no space saving to not
2856 // use.
2857 nodeMap.set_size(num_to_get);
2858 if (int_byte_size_api() == 4) {
2859 nodeMap.set_map(static_cast<int *>(data), num_to_get, 0);
2860 }
2861 else {
2862 nodeMap.set_map(static_cast<int64_t *>(data), num_to_get, 0);
2863 }
2864 }
2865 else if (field.get_name() == "mesh_model_coordinates" ||
2866 field.get_name() == "mesh_model_coordinates_x" ||
2867 field.get_name() == "mesh_model_coordinates_y" ||
2868 field.get_name() == "mesh_model_coordinates_z") {
2869
2870 // 'rdata' is of size number-nodes-on-this-rank
2871 auto *rdata = static_cast<double *>(data);
2872
2873 if (field.get_name() == "mesh_model_coordinates") {
2874 int spatial_dim = nb->get_property("component_degree").get_int();
2875 for (const auto &block : m_globalToBlockLocalNodeMap) {
2876 auto zone = block.first;
2877 // NOTE: 'block_map' is 1-based indexing
2878 const auto &block_map = block.second;
2879 std::vector<double> x(block_map->size());
2880 std::vector<double> y(block_map->size());
2881 std::vector<double> z(block_map->size());
2882
2883 for (size_t i = 0; i < block_map->size(); i++) {
2884 auto idx = global_to_zone_local_idx(i, block_map, nodeMap, isParallel);
2885 SMART_ASSERT(idx < (size_t)num_to_get)(i)(idx)(num_to_get);
2886 x[i] = rdata[idx * spatial_dim + 0];
2887 if (spatial_dim > 1) {
2888 y[i] = rdata[idx * spatial_dim + 1];
2889 }
2890 if (spatial_dim > 2) {
2891 z[i] = rdata[idx * spatial_dim + 2];
2892 }
2893 }
2894
2895 // Create the zone
2896 // Output this zones coordinates...
2897 int crd_idx = 0;
2898 CGCHECKM(cg_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2899 "CoordinateX", Data(x), &crd_idx));
2900
2901 if (spatial_dim > 1) {
2902 CGCHECKM(cg_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2903 "CoordinateY", Data(y), &crd_idx));
2904 }
2905
2906 if (spatial_dim > 2) {
2907 CGCHECKM(cg_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2908 "CoordinateZ", Data(z), &crd_idx));
2909 }
2910 }
2911 }
2912 else {
2913 // Outputting only a single coordinate value...
2914 for (const auto &block : m_globalToBlockLocalNodeMap) {
2915 auto zone = block.first;
2916 // NOTE: 'block_map' is 1-based indexing
2917 const auto &block_map = block.second;
2918 std::vector<double> xyz(block_map->size());
2919
2920 for (size_t i = 0; i < block_map->size(); i++) {
2921 auto idx = global_to_zone_local_idx(i, block_map, nodeMap, isParallel);
2922 SMART_ASSERT(idx < (size_t)num_to_get)(i)(idx)(num_to_get);
2923 xyz[i] = rdata[idx];
2924 }
2925
2926 std::string cgns_name = "Invalid";
2927 if (field.get_name() == "mesh_model_coordinates_x") {
2928 cgns_name = "CoordinateX";
2929 }
2930 else if (field.get_name() == "mesh_model_coordinates_y") {
2931 cgns_name = "CoordinateY";
2932 }
2933 else if (field.get_name() == "mesh_model_coordinates_z") {
2934 cgns_name = "CoordinateZ";
2935 }
2936 // Create the zone
2937 // Output this zones coordinates...
2938 int crd_idx = 0;
2939 CGCHECKM(cg_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2940 cgns_name.c_str(), Data(xyz), &crd_idx));
2941 }
2942 }
2943 }
2944 else {
2945 num_to_get = Ioss::Utils::field_warning(nb, field, "output");
2946 }
2947 }
2948 else if (role == Ioss::Field::TRANSIENT) {
2949 auto *rdata = static_cast<double *>(data);
2950 int cgns_field = 0;
2951
2952 for (const auto &block : m_globalToBlockLocalNodeMap) {
2953 auto zone = block.first;
2954 // NOTE: 'block_map' has one more entry than node_count.
2955 // First entry is for something else. 'block_map' is
2956 // 1-based.
2957 const auto &block_map = block.second;
2958 std::vector<double> blk_data(block_map->size());
2959
2960 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
2961
2962 if (comp_count == 1) {
2963 for (size_t j = 0; j < block_map->size(); j++) {
2964 auto idx = global_to_zone_local_idx(j, block_map, nodeMap, isParallel);
2965 blk_data[j] = rdata[idx];
2966 }
2967 CGCHECKM(cg_field_write(get_file_pointer(), base, zone, m_currentVertexSolutionIndex,
2968 CGNS_ENUMV(RealDouble), field.get_name().c_str(), Data(blk_data),
2969 &cgns_field));
2970 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(Vertex));
2971 }
2972 else {
2973 for (int i = 0; i < comp_count; i++) {
2974 for (size_t j = 0; j < block_map->size(); j++) {
2975 auto idx = global_to_zone_local_idx(j, block_map, nodeMap, isParallel);
2976 blk_data[j] = rdata[comp_count * idx + i];
2977 }
2978 std::string var_name = get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
2979 CGCHECKM(cg_field_write(get_file_pointer(), base, zone, m_currentVertexSolutionIndex,
2980 CGNS_ENUMV(RealDouble), var_name.c_str(), Data(blk_data),
2981 &cgns_field));
2982 if (i == 0) {
2983 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(Vertex));
2984 }
2985 }
2986 }
2987 }
2988 }
2989 else {
2990 num_to_get = Ioss::Utils::field_warning(nb, field, "output");
2991 }
2992 return num_to_get;
2993 }
2994
2995 int64_t DatabaseIO::put_field_internal_sub_nb(const Ioss::NodeBlock *nb, const Ioss::Field &field,
2996 void *data, size_t data_size) const
2997 {
2998 // Outputs field data on a NodeBlock which is a "sub" NodeBlock -- contains the nodes for a
2999 // StructuredBlock instead of for the entire model.
3000 // Currently only TRANSIENT fields are output this way. No valid reason, but that is the
3001 // current use case.
3002
3003 // Get the StructuredBlock that this NodeBlock is contained in:
3004 const Ioss::GroupingEntity *sb = nb->contained_in();
3005 int zone = Iocgns::Utils::get_db_zone(sb);
3006 cgsize_t num_to_get = field.verify(data_size);
3007
3008 // In this routine, if isParallel, then writing file-per-processor; not parallel io to single
3009 // file.
3010 if (isParallel && num_to_get == 0) {
3011 return 0;
3012 }
3013
3014 Ioss::Field::RoleType role = field.get_role();
3015 if (role == Ioss::Field::TRANSIENT) {
3016 int base = 1;
3017 auto *rdata = static_cast<double *>(data);
3018 int cgns_field = 0;
3019 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
3020
3021 if (comp_count == 1) {
3022 CGCHECKM(cg_field_write(get_file_pointer(), base, zone, m_currentVertexSolutionIndex,
3023 CGNS_ENUMV(RealDouble), field.get_name().c_str(), rdata,
3024 &cgns_field));
3025 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(Vertex));
3026 }
3027 else {
3028 std::vector<double> cgns_data(num_to_get);
3029 for (int i = 0; i < comp_count; i++) {
3030 for (cgsize_t j = 0; j < num_to_get; j++) {
3031 cgns_data[j] = rdata[comp_count * j + i];
3032 }
3033 std::string var_name = get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
3034
3035 CGCHECKM(cg_field_write(get_file_pointer(), base, zone, m_currentVertexSolutionIndex,
3036 CGNS_ENUMV(RealDouble), var_name.c_str(), Data(cgns_data),
3037 &cgns_field));
3038 if (i == 0) {
3039 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(Vertex));
3040 }
3041 }
3042 }
3043 }
3044 // Ignoring all other field role types...
3045 return num_to_get;
3046 }
3047
3048 int64_t DatabaseIO::put_field_internal(const Ioss::NodeSet *ns, const Ioss::Field &field,
3049 void * /* data */, size_t /* data_size */) const
3050 {
3051 return Ioss::Utils::field_warning(ns, field, "output");
3052 }
3053 int64_t DatabaseIO::put_field_internal(const Ioss::EdgeSet *es, const Ioss::Field &field,
3054 void * /* data */, size_t /* data_size */) const
3055 {
3056 return Ioss::Utils::field_warning(es, field, "output");
3057 }
3058 int64_t DatabaseIO::put_field_internal(const Ioss::FaceSet *fs, const Ioss::Field &field,
3059 void * /* data */, size_t /* data_size */) const
3060 {
3061 return Ioss::Utils::field_warning(fs, field, "output");
3062 }
3063 int64_t DatabaseIO::put_field_internal(const Ioss::ElementSet *es, const Ioss::Field &field,
3064 void * /* data */, size_t /* data_size */) const
3065 {
3066 return Ioss::Utils::field_warning(es, field, "output");
3067 }
3068 int64_t DatabaseIO::put_field_internal(const Ioss::SideBlock *sb, const Ioss::Field &field,
3069 void *data, size_t data_size) const
3070 {
3071 const Ioss::EntityBlock *parent_block = sb->parent_block();
3072 if (parent_block == nullptr) {
3073 IOSS_ERROR(fmt::format(
3074 "ERROR: CGNS: SideBlock '{}' does not have a parent-block specified. This is "
3075 "required for CGNS output.",
3076 sb->name()));
3077 }
3078
3079 int base = parent_block->get_property("base").get_int();
3080 int zone = Iocgns::Utils::get_db_zone(parent_block);
3081 auto num_to_get = field.verify(data_size);
3082
3083 if (num_to_get == 0) {
3084 return num_to_get;
3085 }
3086
3087 Ioss::Field::RoleType role = field.get_role();
3088
3089 if (role == Ioss::Field::MESH) {
3090 // Handle the MESH fields required for a CGNS file model.
3091 // (The 'genesis' portion)
3092 if (field.get_name() == "element_side") {
3093 CGNS_ENUMT(ElementType_t) type = Utils::map_topology_to_cgns(sb->topology()->name());
3094 int sect = 0;
3095
3096 cgsize_t cg_start = m_bcOffset[zone] + 1;
3097 cgsize_t cg_end = m_bcOffset[zone] + num_to_get;
3098 m_bcOffset[zone] += num_to_get;
3099
3100 // NOTE: Currently not writing the "ElementConnectivity" data for the
3101 // boundary condition. It isn't used in the read and don't have
3102 // the data so would have to generate it. This may cause problems
3103 // with codes that use the downstream data if they base the BC off
3104 // of the nodes instead of the element/side info.
3105 // Get name from parent sideset... This is name of the ZoneBC entry
3106 auto &name = sb->owner()->name();
3107 // This is the name of the BC_t node
3108 auto sb_name = Iocgns::Utils::decompose_sb_name(sb->name());
3109
3110 CGNSIntVector point_range{cg_start, cg_end};
3111 CGCHECKM(cg_boco_write(get_file_pointer(), base, zone, name.c_str(),
3112 CGNS_ENUMV(FamilySpecified), CGNS_ENUMV(PointRange), 2,
3113 Data(point_range), &sect));
3114 CGCHECKM(
3115 cg_goto(get_file_pointer(), base, "Zone_t", zone, "ZoneBC_t", 1, "BC_t", sect, "end"));
3116 CGCHECKM(cg_famname_write(name.c_str()));
3117
3118 int phys_dimension = get_region()->get_property("spatial_dimension").get_int();
3119 auto location = phys_dimension == 2 ? CGNS_ENUMV(EdgeCenter) : CGNS_ENUMV(FaceCenter);
3120 CGCHECKM(cg_boco_gridlocation_write(get_file_pointer(), base, zone, sect, location));
3121
3122 CGCHECKM(cg_section_partial_write(get_file_pointer(), base, zone, sb_name.c_str(), type,
3123 cg_start, cg_end, 0, &sect));
3124
3125 sb->property_update("section", sect);
3126
3127 size_t offset = m_zoneOffset[zone - 1];
3128 CGNSIntVector parent(4 * num_to_get);
3129
3130 if (field.get_type() == Ioss::Field::INT32) {
3131 int *idata = reinterpret_cast<int *>(data);
3132 size_t j = 0;
3133 for (size_t i = 0; i < num_to_get; i++) {
3134 cgsize_t element = elemMap.global_to_local(idata[j++]) - offset;
3135 parent[num_to_get * 0 + i] = element;
3136 parent[num_to_get * 2 + i] = idata[j++]; // side
3137 }
3138 // Adjust face numbers to IOSS convention instead of CGNS convention...
3139 Utils::map_ioss_face_to_cgns(sb->parent_element_topology(), num_to_get, parent);
3140 }
3141 else {
3142 auto *idata = reinterpret_cast<int64_t *>(data);
3143 size_t j = 0;
3144 for (size_t i = 0; i < num_to_get; i++) {
3145 cgsize_t element = elemMap.global_to_local(idata[j++]) - offset;
3146 parent[num_to_get * 0 + i] = element; // Element
3147 parent[num_to_get * 2 + i] = idata[j++];
3148 }
3149 // Adjust face numbers to IOSS convention instead of CGNS convention...
3150 Utils::map_ioss_face_to_cgns(sb->parent_element_topology(), num_to_get, parent);
3151 }
3152
3153 CGCHECKM(cg_parent_data_write(get_file_pointer(), base, zone, sect, Data(parent)));
3154 return num_to_get;
3155 }
3156 else if (field.get_name() == "distribution_factors") {
3157 static bool warning_output = false;
3158 if (!warning_output) {
3159 fmt::print(Ioss::WarnOut(),
3160 "For CGNS output, the sideset distribution factors are not output.\n");
3161 warning_output = true;
3162 }
3163 return 0;
3164 }
3165 num_to_get = Ioss::Utils::field_warning(sb, field, "output");
3166 }
3167 else {
3168 num_to_get = Ioss::Utils::field_warning(sb, field, "output");
3169 }
3170 return num_to_get;
3171 }
3172
3173 int64_t DatabaseIO::put_field_internal(const Ioss::SideSet * /* ss */,
3174 const Ioss::Field & /* field */, void * /* data */,
3175 size_t /* data_size */) const
3176 {
3177 return 0;
3178 }
3179 int64_t DatabaseIO::put_field_internal(const Ioss::CommSet *cs, const Ioss::Field &field,
3180 void * /* data */, size_t /* data_size */) const
3181 {
3182 return Ioss::Utils::field_warning(cs, field, "output");
3183 }
3184
3185 void DatabaseIO::write_results_meta_data() {}
3186
3187 unsigned DatabaseIO::entity_field_support() const
3188 {
3189 return Ioss::NODEBLOCK | Ioss::ELEMENTBLOCK | Ioss::STRUCTUREDBLOCK | Ioss::NODESET |
3190 Ioss::SIDESET | Ioss::REGION;
3191 }
3192
3193 } // namespace Iocgns