Debian Codegraph @

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

raw
1 // CGNS Assumptions:
2 // * All boundary conditions are listed as Family nodes at the "top" level.
3 // * Single Base.
4 // * ZoneGridConnectivity is 1to1 with point lists for unstructured
5
6 // Copyright(C) 1999-2024 National Technology & Engineering Solutions
7 // of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
8 // NTESS, the U.S. Government retains certain rights in this software.
9 //
10 // See packages/seacas/LICENSE for details
11
12 #include <cgnsconfig.h>
13 #if CG_BUILD_PARALLEL
14 #include "cgns/Iocgns_Defines.h"
15
16 #include "Ioss_CodeTypes.h"
17 #include "Ioss_Sort.h"
18 #include "Ioss_Utils.h"
19 #include "cgns/Iocgns_ParallelDatabaseIO.h"
20 #include "cgns/Iocgns_Utils.h"
21 #include <cassert>
22 #include <cstddef>
23 #include <ctime>
24 #include <fmt/ostream.h>
25 #include <fstream>
26 #include <iostream>
27 #include <mpi.h>
28 #include <numeric>
29 #include <string>
30 #include <sys/select.h>
31 #include <vector>
32
33 #include <pcgnslib.h>
34
35 #if !defined(CGNSLIB_H)
36 #error "Could not include cgnslib.h"
37 #endif
38
39 #include "Ioss_CommSet.h"
40 #include "Ioss_DBUsage.h"
41 #include "Ioss_DatabaseIO.h"
42 #include "Ioss_ElementBlock.h"
43 #include "Ioss_ElementTopology.h"
44 #include "Ioss_EntityType.h"
45 #include "Ioss_Field.h"
46 #include "Ioss_FileInfo.h"
47 #include "Ioss_IOFactory.h"
48 #include "Ioss_NodeBlock.h"
49 #include "Ioss_ParallelUtils.h"
50 #include "Ioss_Property.h"
51 #include "Ioss_Region.h"
52 #include "Ioss_SideBlock.h"
53 #include "Ioss_SideSet.h"
54 #include "Ioss_State.h"
55 #include "Ioss_StructuredBlock.h"
56 #include "Ioss_Utils.h"
57 #include "Ioss_VariableType.h"
58
59 using GL_IdVector = std::vector<std::pair<int, int>>;
60
61 namespace {
62 MPI_Datatype cgns_mpi_type()
63 {
64 #if CG_SIZEOF_SIZE == 8
65 return MPI_LONG_LONG_INT;
66 #else
67 return MPI_INT;
68 #endif
69 }
70
71 void map_local_to_global_implicit(CGNSIntVector &data, size_t count,
72 const CGNSIntVector &global_implicit_map)
73 {
74 for (size_t i = 0; i < count; i++) {
75 data[i] = global_implicit_map[data[i] - 1];
76 }
77 }
78
79 GL_IdVector gather_nodes_to_proc0(Ioss::Map &global_id_map, int processor, int64_t offset,
80 const Ioss::ParallelUtils &util, size_t min_id,
81 size_t max_id = std::numeric_limits<size_t>::max())
82 {
83 GL_IdVector I_nodes;
84 GL_IdVector I_nodes_recv;
85 for (size_t i = 0; i < global_id_map.size(); i++) {
86 auto global_id = global_id_map.map()[i + 1];
87 if ((size_t)global_id >= min_id && (size_t)global_id <= max_id) {
88 I_nodes.emplace_back((int)global_id, (int)i + 1 + offset);
89 }
90 }
91
92 std::vector<int> recv_count;
93 util.gather(2 * (int)I_nodes.size(), recv_count);
94 std::vector<int> recv_off(recv_count);
95
96 auto count = std::accumulate(recv_count.begin(), recv_count.end(), 0);
97 if (processor == 0) {
98 I_nodes_recv.resize(count / 2);
99 Ioss::Utils::generate_index(recv_off);
100 }
101
102 MPI_Gatherv(Data(I_nodes), (int)I_nodes.size() * 2, MPI_INT, Data(I_nodes_recv),
103 Data(recv_count), Data(recv_off), MPI_INT, 0, util.communicator());
104
105 if (processor == 0) {
106 Ioss::sort(I_nodes_recv.begin(), I_nodes_recv.end());
107 }
108 return I_nodes_recv;
109 }
110
111 GL_IdVector intersect(const GL_IdVector &I, const GL_IdVector &J)
112 {
113 // Find all common global_ids (entry.first) between 'I' and 'J'.
114 // When found, store the proc-zone-local position (entry.second)
115 // in 'common'
116 // PRECONDITION: 'I' and 'J' are sorted.
117
118 auto min_size = std::min(I.size(), J.size());
119 GL_IdVector common;
120 common.reserve(min_size);
121
122 auto II = I.begin();
123 auto JJ = J.begin();
124 while (II != I.end() && JJ != J.end()) {
125 if ((*II).first < (*JJ).first) {
126 ++II;
127 }
128 else {
129 if (!((*JJ).first < (*II).first)) {
130 common.emplace_back((*II).second, (*JJ).second);
131 ++II;
132 }
133 ++JJ;
134 }
135 }
136 common.shrink_to_fit();
137 return common;
138 }
139 } // namespace
140
141 namespace Iocgns {
142
143 ParallelDatabaseIO::ParallelDatabaseIO(Ioss::Region *region, const std::string &filename,
144 Ioss::DatabaseUsage db_usage, Ioss_MPI_Comm communicator,
145 const Ioss::PropertyManager &props)
146 : Ioss::DatabaseIO(region, filename, db_usage, communicator, props)
147 {
148 usingParallelIO = true;
149 dbState = Ioss::STATE_UNKNOWN;
150
151 #if IOSS_DEBUG_OUTPUT
152 if (myProcessor == 0) {
153 fmt::print("CGNS ParallelDatabaseIO using {}-bit integers.\n"
154 " using the parallel CGNS library and API.\n",
155 CG_SIZEOF_SIZE);
156 }
157 #endif
158 if (!is_input()) {
159 if (properties.exists("FLUSH_INTERVAL")) {
160 m_flushInterval = properties.get("FLUSH_INTERVAL").get_int();
161 }
162
163 {
164 bool file_per_state = false;
165 Ioss::Utils::check_set_bool_property(properties, "FILE_PER_STATE", file_per_state);
166 if (file_per_state) {
167 set_file_per_state(true);
168 }
169 }
170 }
171
172 Ioss::DatabaseIO::openDatabase_nl();
173 }
174
175 ParallelDatabaseIO::~ParallelDatabaseIO()
176 {
177 for (const auto &gtb : m_globalToBlockLocalNodeMap) {
178 delete gtb.second;
179 }
180 try {
181 closeBaseDatabase_nl();
182 closeDatabase_nl();
183 }
184 catch (...) {
185 }
186 }
187
188 int ParallelDatabaseIO::get_file_pointer() const
189 {
190 if (m_cgnsFilePtr < 0) {
191 openDatabase_nl();
192 }
193 return m_cgnsFilePtr;
194 }
195
196 void ParallelDatabaseIO::openDatabase_nl() const
197 {
198 if (m_cgnsFilePtr < 0) {
199 int mode = is_input() ? CG_MODE_READ : CG_MODE_WRITE;
200 if (!is_input()) {
201 if (m_cgnsFilePtr == -2) {
202 // Writing multiple steps with a "flush" (cg_close() / cg_open())
203 mode = CG_MODE_MODIFY;
204 }
205 else {
206 // Check whether appending to existing file...
207 if (open_create_behavior() == Ioss::DB_APPEND ||
208 open_create_behavior() == Ioss::DB_MODIFY) {
209 // Append to file if it already exists -- See if the file exists.
210 Ioss::FileInfo file = Ioss::FileInfo(decoded_filename());
211 if (file.exists()) {
212 mode = CG_MODE_MODIFY;
213 }
214 }
215 }
216 }
217
218 bool do_timer = false;
219 Ioss::Utils::check_set_bool_property(properties, "IOSS_TIME_FILE_OPEN_CLOSE", do_timer);
220 double t_begin = (do_timer ? Ioss::Utils::timer() : 0);
221
222 CGCHECKM(cg_set_file_type(CG_FILE_HDF5));
223
224 #if CGNS_VERSION > 3320
225 CGCHECKM(cgp_mpi_comm(util().communicator()));
226 #else
227 // Older versions of cgp_mpi_comm returned an internal NO_ERROR
228 // value which is equal to -1.
229 cgp_mpi_comm(util().communicator());
230 #endif
231 CGCHECKM(cgp_pio_mode(CGP_COLLECTIVE));
232 Ioss::DatabaseIO::openDatabase_nl();
233 int ierr = cgp_open(get_dw_name().c_str(), mode, &m_cgnsFilePtr);
234
235 if (do_timer) {
236 double t_end = Ioss::Utils::timer();
237 double duration = util().global_minmax(t_end - t_begin, Ioss::ParallelUtils::DO_MAX);
238 if (myProcessor == 0) {
239 fmt::print(Ioss::DebugOut(), "{} File Open Time = {}\n", is_input() ? "Input" : "Output",
240 duration);
241 }
242 }
243
244 if (ierr != CG_OK) {
245 // NOTE: Code will not continue past this call...
246 std::ostringstream errmsg;
247 fmt::print(errmsg, "ERROR: Problem opening file '{}' for {} access. CGNS Error: '{}'",
248 get_filename(), (is_input() ? "read" : "write"), cg_get_error());
249 IOSS_ERROR(errmsg);
250 }
251
252 if (properties.exists("INTEGER_SIZE_API")) {
253 int isize = properties.get("INTEGER_SIZE_API").get_int();
254 if (isize == 8) {
255 set_int_byte_size_api(Ioss::USE_INT64_API);
256 }
257 if (isize == 4) {
258 set_int_byte_size_api(Ioss::USE_INT32_API);
259 }
260 }
261 else if (CG_SIZEOF_SIZE == 64) {
262 set_int_byte_size_api(Ioss::USE_INT64_API);
263 }
264
265 if (mode == CG_MODE_MODIFY && get_region() != nullptr) {
266 Utils::update_db_zone_property(m_cgnsFilePtr, get_region(), myProcessor, true, true);
267 }
268 #if 0
269 // This isn't currently working since CGNS currently has chunking
270 // disabled for HDF5 files and compression requires chunking.
271 if (!is_input()) {
272 if (properties.exists("COMPRESSION_LEVEL")) {
273 int comp = properties.get("COMPRESSION_LEVEL").get_int();
274 cg_configure(CG_CONFIG_HDF5_COMPRESS, (void*)comp);
275 }
276 }
277 #endif
278 }
279 assert(m_cgnsFilePtr >= 0);
280 }
281
282 void ParallelDatabaseIO::closeBaseDatabase_nl() const
283 {
284 if (m_cgnsBasePtr > 0) {
285 bool do_timer = false;
286 Ioss::Utils::check_set_bool_property(properties, "IOSS_TIME_FILE_OPEN_CLOSE", do_timer);
287 double t_begin = (do_timer ? Ioss::Utils::timer() : 0);
288
289 CGCHECKM(cg_close(m_cgnsBasePtr));
290 m_cgnsBasePtr = -1;
291
292 if (do_timer) {
293 double t_end = Ioss::Utils::timer();
294 double duration = util().global_minmax(t_end - t_begin, Ioss::ParallelUtils::DO_MAX);
295 if (myProcessor == 0) {
296 fmt::print(Ioss::DebugOut(), "{} Base File Close Time = {}\n",
297 is_input() ? "Input" : "Output", duration);
298 }
299 }
300 }
301 }
302
303 void ParallelDatabaseIO::closeDatabase_nl() const
304 {
305 if (m_cgnsFilePtr > 0) {
306 bool do_timer = false;
307 Ioss::Utils::check_set_bool_property(properties, "IOSS_TIME_FILE_OPEN_CLOSE", do_timer);
308 double t_begin = (do_timer ? Ioss::Utils::timer() : 0);
309
310 CGCHECKM(cgp_close(m_cgnsFilePtr));
311
312 if (do_timer) {
313 double t_end = Ioss::Utils::timer();
314 double duration = util().global_minmax(t_end - t_begin, Ioss::ParallelUtils::DO_MAX);
315 if (myProcessor == 0) {
316 fmt::print(Ioss::DebugOut(), "{} File Close Time = {}\n", is_input() ? "Input" : "Output",
317 duration);
318 }
319 }
320 close_dw();
321 m_cgnsFilePtr = -1;
322 }
323 }
324
325 void ParallelDatabaseIO::finalize_database() const
326 {
327 if (is_input()) {
328 return;
329 }
330
331 if (m_timesteps.empty()) {
332 return;
333 }
334
335 if (!m_dbFinalized) {
336 int file_ptr;
337 if (get_file_per_state()) {
338 file_ptr = m_cgnsBasePtr;
339 }
340 else {
341 file_ptr = get_file_pointer();
342 }
343 Utils::finalize_database(file_ptr, m_timesteps, get_region(), myProcessor, true);
344 m_dbFinalized = true;
345 }
346 }
347
348 void ParallelDatabaseIO::release_memory_nl()
349 {
350 nodeMap.release_memory();
351 elemMap.release_memory();
352 try {
353 decomp.reset();
354 }
355 catch (...) {
356 }
357 }
358
359 int64_t ParallelDatabaseIO::node_global_to_local_nl(int64_t global, bool /* must_exist */) const
360 {
361 // TODO: Fix
362 return global;
363 }
364
365 int64_t ParallelDatabaseIO::element_global_to_local_nl(int64_t global) const
366 {
367 // TODO: Fix
368 return global;
369 }
370
371 void ParallelDatabaseIO::read_meta_data_nl()
372 {
373 openDatabase_nl();
374
375 // Determine the number of bases in the grid.
376 // Currently only handle 1.
377 int n_bases = 0;
378 CGCHECKM(cg_nbases(get_file_pointer(), &n_bases));
379 if (n_bases != 1) {
380 std::ostringstream errmsg;
381 fmt::print(errmsg,
382 "CGNS: Too many bases ({}); only support files with a single base at this time",
383 n_bases);
384 IOSS_ERROR(errmsg);
385 }
386
387 get_step_times_nl();
388
389 if (open_create_behavior() == Ioss::DB_APPEND) {
390 return;
391 }
392
393 m_meshType = Utils::check_mesh_type(get_file_pointer());
394
395 // In CGNS, there are duplicated nodes at block boundaries.
396 // We typically only want to retain one copy of these and ignore the other.
397 properties.add(Ioss::Property("RETAIN_FREE_NODES", "NO"));
398
399 if (int_byte_size_api() == 8) {
400 decomp = std::make_unique<DecompositionData<int64_t>>(properties, util().communicator());
401 }
402 else {
403 decomp = std::make_unique<DecompositionData<int>>(properties, util().communicator());
404 }
405 assert(decomp != nullptr);
406 decomp->decompose_model(get_file_pointer(), m_meshType);
407
408 // ========================================================================
409 // Get the number of assemblies in the mesh...
410 // Will be the 'families' that contain nodes of 'FamVC_*'
411 Utils::add_assemblies(get_file_pointer(), this);
412
413 if (m_meshType == Ioss::MeshType::STRUCTURED) {
414 handle_structured_blocks();
415 }
416 else if (m_meshType == Ioss::MeshType::UNSTRUCTURED) {
417 handle_unstructured_blocks();
418 }
419 #if IOSS_ENABLE_HYBRID
420 else if (mesh_type == Ioss::MeshType::HYBRID) {
421 }
422 #endif
423 else {
424 std::ostringstream errmsg;
425 fmt::print(errmsg, "ERROR: CGNS: Mesh is not Unstructured or Structured which are the only "
426 "types currently supported");
427 IOSS_ERROR(errmsg);
428 }
429
430 Utils::add_transient_variables(get_file_pointer(), m_timesteps, get_region(), myProcessor,
431 true);
432 }
433
434 void ParallelDatabaseIO::handle_unstructured_blocks()
435 {
436 get_region()->property_add(
437 Ioss::Property("global_node_count", (int64_t)decomp->global_node_count()));
438 get_region()->property_add(
439 Ioss::Property("global_element_count", (int64_t)decomp->global_elem_count()));
440
441 nodeCount = decomp->ioss_node_count();
442 elementCount = decomp->ioss_elem_count();
443
444 // ========================================================================
445 // Get the number of families in the mesh...
446 // Will treat these as sidesets if they are of the type "FamilyBC_t"
447 Utils::add_sidesets(get_file_pointer(), this);
448
449 // ========================================================================
450 // Get the number of zones (element blocks) in the mesh...
451 int base = 1;
452 int i = 0;
453 for (auto &block : decomp->m_elementBlocks) {
454 std::string element_topo = block.topologyType;
455 auto *eblock = new Ioss::ElementBlock(this, block.name(), element_topo, block.ioss_count());
456 eblock->property_add(Ioss::Property("base", base));
457 eblock->property_add(Ioss::Property("zone", block.zone()));
458 eblock->property_add(Ioss::Property("id", block.zone()));
459 eblock->property_add(Ioss::Property("guid", util().generate_guid(block.zone())));
460 eblock->property_add(Ioss::Property("section", block.section()));
461 eblock->property_add(Ioss::Property("original_block_order", i++));
462 get_region()->add(eblock);
463 #if IOSS_DEBUG_OUTPUT
464 fmt::print(Ioss::DebugOut(), "Added block {}, IOSS topology = '{}' with {} element.\n",
465 block.name(), element_topo, block.ioss_count());
466 #endif
467 // See if this zone/block is a member of any assemblies...
468 Utils::add_to_assembly(get_file_pointer(), get_region(), eblock, base, block.zone());
469 }
470
471 // ========================================================================
472 // Have sidesets, now create sideblocks for each sideset...
473 int id = 0;
474 for (auto &sset : decomp->m_sideSets) {
475 // See if there is an Ioss::SideSet with a matching name...
476 Ioss::SideSet *ioss_sset = get_region()->get_sideset(sset.ss_name());
477 if (ioss_sset != nullptr) {
478 auto zone = decomp->m_zones[sset.zone()];
479 std::string block_name = fmt::format("{}/{}", zone.m_name, sset.name());
480 std::string face_topo = sset.topologyType;
481 #if IOSS_DEBUG_OUTPUT
482 fmt::print(Ioss::DebugOut(),
483 "Processor {}: Added sideblock '{}' of topo {} with {} faces to sset '{}'\n",
484 myProcessor, block_name, face_topo, sset.ioss_count(), ioss_sset->name());
485 #endif
486 const auto &block = decomp->m_elementBlocks[sset.parentBlockIndex];
487
488 std::string parent_topo = block.topologyType;
489 Ioss::SideBlock *sblk =
490 new Ioss::SideBlock(this, block_name, face_topo, parent_topo, sset.ioss_count());
491 sblk->property_add(Ioss::Property("id", id));
492 sblk->property_add(Ioss::Property("guid", util().generate_guid(id + 1)));
493 sblk->property_add(Ioss::Property("base", 1));
494 sblk->property_add(Ioss::Property("zone", sset.zone()));
495 sblk->property_add(Ioss::Property("section", sset.section()));
496 Ioss::ElementBlock *eblock = get_region()->get_element_block(block.name());
497 if (eblock != nullptr) {
498 sblk->set_parent_element_block(eblock);
499 }
500 ioss_sset->add(sblk);
501 }
502 id++; // Really just index into m_sideSets list.
503 }
504
505 auto *nblock = new Ioss::NodeBlock(this, "nodeblock_1", nodeCount, 3);
506
507 nblock->property_add(Ioss::Property("base", base));
508 get_region()->add(nblock);
509
510 // Create a single node commset
511 auto *commset =
512 new Ioss::CommSet(this, "commset_node", "node", decomp->get_commset_node_size());
513 commset->property_add(Ioss::Property("id", 1));
514 commset->property_add(Ioss::Property("guid", util().generate_guid(1)));
515
516 get_region()->add(commset);
517 }
518
519 size_t ParallelDatabaseIO::finalize_structured_blocks()
520 {
521 // If there are any Structured blocks, need to iterate them and their 1-to-1 connections
522 // and update the donor_zone id for zones that had not yet been processed at the time of
523 // definition...
524 const auto &blocks = get_region()->get_structured_blocks();
525 for (auto &block : blocks) {
526 int64_t guid = block->get_property("guid").get_int();
527 for (auto &conn : block->m_zoneConnectivity) {
528 if (conn.m_donorZone < 0) {
529 auto donor_iter = m_zoneNameMap.find(conn.m_donorName);
530 assert(donor_iter != m_zoneNameMap.end());
531 conn.m_donorZone = (*donor_iter).second;
532 }
533 conn.m_donorGUID = util().generate_guid(conn.m_donorZone, conn.m_donorProcessor);
534 conn.m_ownerGUID = guid;
535 }
536 }
537
538 size_t num_nodes = Utils::resolve_nodes(*get_region(), myProcessor, true);
539 return num_nodes;
540 }
541
542 void ParallelDatabaseIO::handle_structured_blocks()
543 {
544 int base = 1;
545
546 Utils::add_sidesets(get_file_pointer(), this);
547
548 char basename[CGNS_MAX_NAME_LENGTH + 1];
549 int cell_dimension = 0;
550 int phys_dimension = 0;
551 CGCHECKM(cg_base_read(get_file_pointer(), base, basename, &cell_dimension, &phys_dimension));
552
553 // Iterate all structured blocks and set the intervals to zero
554 // if the m_proc field does not match current processor...
555 const auto &zones = decomp->m_structuredZones;
556
557 for (auto &zone : zones) {
558 if (zone->m_adam == zone) {
559 // This is a "root" zone from the undecomposed mesh...
560 // Now see if there are any non-empty blocks with
561 // this m_adam on this processor. If exists, then create
562 // a StructuredBlock; otherwise, create an empty block.
563 auto block_name = zone->m_name;
564
565 Ioss::StructuredBlock *block = nullptr;
566 Ioss::IJK_t zeros{{0, 0, 0}};
567 for (auto &pzone : zones) {
568 if (pzone->m_proc == myProcessor && pzone->m_adam == zone) {
569 // Create a non-empty structured block on this processor...
570 block = new Ioss::StructuredBlock(this, block_name, phys_dimension, pzone->m_ordinal,
571 pzone->m_offset, pzone->m_adam->m_ordinal);
572
573 for (auto &zgc : pzone->m_zoneConnectivity) {
574 // Update donor_zone to point to adam zone instead of child.
575 auto dz = zones[zgc.m_donorZone - 1];
576 assert(dz->m_zone == zgc.m_donorZone);
577 auto oz = zones[zgc.m_ownerZone - 1];
578 assert(oz->m_zone == zgc.m_ownerZone);
579 zgc.m_donorZone = dz->m_adam->m_zone;
580 zgc.m_ownerZone = oz->m_adam->m_zone;
581 block->m_zoneConnectivity.push_back(zgc);
582 }
583 break;
584 }
585 }
586 if (block == nullptr) {
587 // There is no block on this processor corresponding to the m_adam
588 // block. Create an empty block...
589 block = new Ioss::StructuredBlock(this, block_name, phys_dimension, zeros, zeros,
590 zone->m_adam->m_ordinal);
591 for (auto &zgc : zone->m_zoneConnectivity) {
592 zgc.m_isActive = false;
593 // Update donor_zone to point to adam zone instead of child.
594 auto dz = zones[zgc.m_donorZone - 1];
595 assert(dz->m_zone == zgc.m_donorZone);
596 auto oz = zones[zgc.m_ownerZone - 1];
597 assert(oz->m_zone == zgc.m_ownerZone);
598 zgc.m_donorZone = dz->m_adam->m_zone;
599 zgc.m_ownerZone = oz->m_adam->m_zone;
600 block->m_zoneConnectivity.push_back(zgc);
601 }
602 }
603 assert(block != nullptr);
604 get_region()->add(block);
605
606 block->property_add(Ioss::Property("base", base));
607 block->property_add(Ioss::Property("zone", zone->m_adam->m_zone));
608 block->property_add(Ioss::Property("db_zone", zone->m_adam->m_zone));
609 block->property_add(Ioss::Property("id", zone->m_adam->m_zone));
610 int64_t guid = util().generate_guid(zone->m_adam->m_zone);
611 block->property_add(Ioss::Property("guid", guid));
612
613 // See if this zone/block is a member of any assemblies...
614 Utils::add_to_assembly(get_file_pointer(), get_region(), block, base, zone->m_adam->m_zone);
615
616 #if IOSS_DEBUG_OUTPUT
617 fmt::print(Ioss::DebugOut(), "Added block {}, Structured with ID = {}, GUID = {}\n",
618 block_name, zone->m_adam->m_zone, guid);
619 #endif
620 }
621 }
622
623 // ========================================================================
624 // Iterate each StructuredBlock, get its zone. For that zone, get the number of
625 // boundary conditions and then iterate those and create sideblocks in the
626 // corresponding sideset.
627 const auto &sbs = get_region()->get_structured_blocks();
628 for (const auto &block : sbs) {
629 // Handle boundary conditions...
630 Utils::add_structured_boundary_conditions(get_file_pointer(), block, true);
631 }
632
633 size_t node_count = finalize_structured_blocks();
634 auto *nblock = new Ioss::NodeBlock(this, "nodeblock_1", node_count, phys_dimension);
635 nblock->property_add(Ioss::Property("base", base));
636 get_region()->add(nblock);
637 }
638
639 void ParallelDatabaseIO::resolve_zone_shared_nodes(const CGNSIntVector &nodes,
640 CGNSIntVector &connectivity_map,
641 size_t &owned_node_count,
642 size_t &owned_node_offset) const
643 {
644 // Determine number of processors that have nodes for this zone.
645 // Avoid mpi_comm_split call if possible.
646 int have_nodes = nodes.empty() ? 0 : 1;
647 int shared_zone_proc_count = 0;
648 MPI_Allreduce(&have_nodes, &shared_zone_proc_count, 1, Ioss::mpi_type(int(0)), MPI_SUM,
649 util().communicator());
650
651 if (shared_zone_proc_count <= 1) {
652 // There are no shared nodes in this zone.
653 owned_node_count = nodes.size();
654 std::iota(connectivity_map.begin(), connectivity_map.end(), 1);
655 return;
656 }
657
658 have_nodes = have_nodes == 0 ? MPI_UNDEFINED : 1;
659 Ioss_MPI_Comm pcomm;
660 MPI_Comm_split(util().communicator(), have_nodes, myProcessor, &pcomm);
661
662 if (have_nodes == 1) {
663 // From here on down, only processors that have nodes are involved...
664 // This zone has nodes/cells on two or more processors. Need to determine
665 // which nodes are shared.
666
667 Ioss::ParallelUtils pm(pcomm);
668 size_t proc_count = pm.parallel_size();
669 assert((int)proc_count == shared_zone_proc_count);
670
671 // Distribute each node to an "owning" processor based on its id
672 // and assuming a linear distribution (e.g., if on 3 processors, each
673 // proc will "own" 1/3 of the id range.
674 // nodes is sorted.
675 int64_t min = nodes[0];
676 int64_t max = nodes.back();
677 min = pm.global_minmax(min, Ioss::ParallelUtils::DO_MIN);
678 max = pm.global_minmax(max, Ioss::ParallelUtils::DO_MAX);
679
680 std::vector<int> p_count(proc_count);
681 size_t per_proc = (max - min + proc_count) / proc_count;
682 size_t proc = 0;
683 int64_t top = min + per_proc;
684
685 // NOTE: nodes is sorted...
686 for (const auto &node : nodes) {
687 while (node >= top) {
688 top += per_proc;
689 proc++;
690 }
691 assert(proc < proc_count);
692 p_count[proc]++;
693 }
694
695 // Tell each processor how many nodes it will be getting...
696 // Each processor will be responsible for a subsetted range of the overall range.
697 // This processor, should range from min + my_proc*per_proc to min + (my_proc+1)*per_proc.
698 std::vector<int> r_count(proc_count);
699 MPI_Alltoall(Data(p_count), 1, Ioss::mpi_type(int(0)), Data(r_count), 1,
700 Ioss::mpi_type(int(0)), pcomm);
701
702 std::vector<int> recv_disp(proc_count);
703 std::vector<int> send_disp(proc_count);
704 size_t sums = 0;
705 size_t sumr = 0;
706 for (size_t p = 0; p < proc_count; p++) {
707 recv_disp[p] = sumr;
708 sumr += r_count[p];
709
710 send_disp[p] = sums;
711 sums += p_count[p];
712 }
713 CGNSIntVector r_nodes(sumr);
714 Ioss::MY_Alltoallv(nodes, p_count, send_disp, r_nodes, r_count, recv_disp, pcomm);
715
716 // Iterate r_nodes list to find duplicate nodes...
717 auto delta = min + pm.parallel_rank() * per_proc;
718 std::vector<int> dup_nodes(per_proc);
719 for (auto &r_node : r_nodes) {
720 auto n = r_node - delta;
721 assert(n < per_proc);
722 dup_nodes[n]++;
723 if (dup_nodes[n] > 1) {
724 r_node = 0;
725 }
726 }
727
728 // Send filtered list back to original processors -- store in 'u_nodes'
729 // This is set of unique block nodes owned by this processor.
730 // If an entry in 'u_nodes' is 0, then that is a non-owned shared node.
731 CGNSIntVector u_nodes(nodes.size());
732 Ioss::MY_Alltoallv(r_nodes, r_count, recv_disp, u_nodes, p_count, send_disp, pcomm);
733
734 // Count non-zero entries in u_nodes...
735 int64_t local_node_count =
736 std::count_if(u_nodes.cbegin(), u_nodes.cend(), [](int64_t i) { return i > 0; });
737 owned_node_count = local_node_count; // Calling code wants to know this
738
739 // Determine offset into the zone node block for each processors "chunk"
740 int64_t local_node_offset = 0;
741 MPI_Exscan(&local_node_count, &local_node_offset, 1, Ioss::mpi_type(local_node_count),
742 MPI_SUM, pcomm);
743 owned_node_offset = local_node_offset; // Calling code wants to know this
744
745 // This generates the position of each owned node in this zone consistent
746 // over all processors that this zone is active on.
747 for (auto &u_node : u_nodes) {
748 if (u_node > 0) {
749 u_node = ++local_node_offset; // 1-based local node id for all owned nodes.
750 }
751 }
752
753 // u_nodes now contains the global -> block-local node map for all owned nodes
754 // on the processor.
755 // The zeroes in u_nodes are shared nodes on the processor boundary.
756 // Resend nodes and u_nodes so can resolve the ids of the shared nodes.
757 CGNSIntVector g_to_zone_local(sumr);
758 Ioss::MY_Alltoallv(nodes, p_count, send_disp, r_nodes, r_count, recv_disp, pcomm);
759 Ioss::MY_Alltoallv(u_nodes, p_count, send_disp, g_to_zone_local, r_count, recv_disp, pcomm);
760
761 // Iterate g_to_zone_local to find a zero entry.
762 for (size_t i = 0; i < g_to_zone_local.size(); i++) {
763 if (g_to_zone_local[i] == 0) {
764 // The global id is r_nodes[i] which must also appear earlier in the list...
765 for (size_t j = 0; j < i; j++) {
766 if (r_nodes[j] == r_nodes[i]) {
767 g_to_zone_local[i] = g_to_zone_local[j];
768 break;
769 }
770 }
771 }
772 }
773
774 // Now, send updated g_to_zone_local back to original processors...
775 Ioss::MY_Alltoallv(g_to_zone_local, r_count, recv_disp, u_nodes, p_count, send_disp, pcomm);
776
777 // At this point:
778 // 'nodes' contains the global node ids that are referenced in this zones connectivity.
779 // 'u_nodes' contains the zone-local 1-based position of that node in this zones node list.
780 //
781 //
782 #ifndef NDEBUG
783 for (const auto &u_node : u_nodes) {
784 assert(u_node > 0);
785 }
786 #endif
787 std::swap(connectivity_map, u_nodes);
788 MPI_Comm_free(&pcomm);
789 }
790 }
791
792 void ParallelDatabaseIO::write_meta_data()
793 {
794 int num_zones = get_region()->get_property("element_block_count").get_int() +
795 get_region()->get_property("structured_block_count").get_int();
796 m_bcOffset.resize(num_zones + 1); // use 1-based zones...
797 m_zoneOffset.resize(num_zones + 1); // use 1-based zones...
798
799 elementCount =
800 Utils::common_write_metadata(get_file_pointer(), *get_region(), m_zoneOffset, true);
801 }
802
803 void ParallelDatabaseIO::get_step_times_nl()
804 {
805 Utils::get_step_times(get_file_pointer(), m_timesteps, get_region(), timeScaleFactor,
806 myProcessor);
807 }
808
809 std::vector<double> ParallelDatabaseIO::get_db_step_times_nl()
810 {
811 std::vector<double> timesteps;
812
813 Utils::get_step_times(get_file_pointer(), timesteps, nullptr, timeScaleFactor, myProcessor);
814
815 return timesteps;
816 }
817
818 void ParallelDatabaseIO::write_adjacency_data()
819 {
820 // Determine adjacency information between unstructured blocks.
821 // If block I is adjacent to block J, then they will share at
822 // least 1 "side" (face 3D or edge 2D).
823 // Currently, assuming they are adjacent if they share at least one node...
824
825 // TODO: All calculations are done on processor 0 instead of being distributed.
826 // this will not scale well...
827
828 const auto &blocks = get_region()->get_element_blocks();
829 if (blocks.size() <= 1) {
830 return; // No adjacent blocks if only one block...
831 }
832
833 // =================
834 // Determine the minimum and maximum global node id for each zone.
835 // This will be used When determining whether 2 zones are
836 // connected by checking whether the global id node ranges overlap
837 std::vector<int64_t> zone_min_id(blocks.size() + 1, std::numeric_limits<int64_t>::max());
838 std::vector<int64_t> zone_max_id(blocks.size() + 1, std::numeric_limits<int64_t>::min());
839
840 for (const auto &block : blocks) {
841 int zone = block->get_property("zone").get_int();
842 assert((size_t)zone < blocks.size() + 1);
843
844 const auto &I_map = m_globalToBlockLocalNodeMap[zone];
845
846 // Get min and max global node id for each zone...
847 if (I_map->size() > 0) {
848 auto min_max = std::minmax_element(std::next(I_map->map().begin()), I_map->map().end());
849 zone_min_id[zone] = *(min_max.first);
850 zone_max_id[zone] = *(min_max.second);
851 }
852 }
853
854 // Get min/max over all processors for each zone...
855 util().global_array_minmax(zone_min_id, Ioss::ParallelUtils::DO_MIN);
856 util().global_array_minmax(zone_max_id, Ioss::ParallelUtils::DO_MAX);
857 // =================
858
859 auto node_offset = get_processor_zone_node_offset();
860
861 // Now iterate the blocks again. If the node ranges overlap, then
862 // there is a possibility that there are contiguous nodes; if the
863 // ranges don't overlap, then no possibility...
864 for (auto I = blocks.cbegin(); I != std::prev(blocks.cend()); I++) {
865 int base = (*I)->get_property("base").get_int();
866 int zone = (*I)->get_property("zone").get_int();
867
868 // See how many zone I nodes Proc x has that can potentially
869 // overlap with the zones I+1 to end. This will be all nodes
870 // with id > min(zone_min_id[I+1..])
871 auto min_I = std::min_element(&zone_min_id[zone + 1], &zone_min_id[blocks.size()]);
872 auto I_nodes = gather_nodes_to_proc0(*m_globalToBlockLocalNodeMap[zone], myProcessor,
873 node_offset[zone - 1], util(), *min_I);
874
875 for (auto J = I + 1; J != blocks.end(); J++) {
876 cgsize_t dzone = (*J)->get_property("zone").get_int();
877
878 if (zone_min_id[dzone] <= zone_max_id[zone] && zone_max_id[dzone] >= zone_min_id[zone]) {
879 // Now gather all zone J nodes that can potentially overlap
880 // with zone I to processor 0...
881 auto J_nodes = gather_nodes_to_proc0(*m_globalToBlockLocalNodeMap[dzone], myProcessor,
882 node_offset[dzone - 1], util(), zone_min_id[zone],
883 zone_max_id[zone]);
884 GL_IdVector common;
885 if (myProcessor == 0) {
886 common = intersect(I_nodes, J_nodes);
887
888 #if IOSS_DEBUG_OUTPUT
889 fmt::print(Ioss::DebugOut(), "Zone {}: {}, Donor Zone {}: {} Common: {}\n\t", zone,
890 I_nodes.size(), dzone, J_nodes.size(), common.size());
891
892 for (const auto &p : common) {
893 fmt::print(Ioss::DebugOut(), "{}, ", p.first);
894 }
895 fmt::print(Ioss::DebugOut(), "\n\t");
896 for (const auto &p : common) {
897 fmt::print(Ioss::DebugOut(), "{}, ", p.second);
898 }
899 fmt::print(Ioss::DebugOut(), "\n");
900 #endif
901 }
902
903 int size = (int)common.size();
904 util().broadcast(size);
905
906 if (size > 0) {
907 // This 'cg_conn_write' should probably be a parallel
908 // function. Since one does not exist, we output the same
909 // data on all processors. Seems to work, but is klugy.
910
911 common.resize(size);
912 util().broadcast(common);
913
914 CGNSIntVector point_list;
915 CGNSIntVector point_list_donor;
916 point_list.reserve(common.size());
917 point_list_donor.reserve(common.size());
918
919 for (auto &pnt : common) {
920 point_list.push_back(pnt.first);
921 point_list_donor.push_back(pnt.second);
922 }
923
924 int gc_idx = 0;
925 std::string name = fmt::format("{}_to_{}", (*I)->name(), (*J)->name());
926 const auto &d1_name = (*J)->name();
927
928 CGCHECKM(cg_conn_write(get_file_pointer(), base, zone, name.c_str(), CGNS_ENUMV(Vertex),
929 CGNS_ENUMV(Abutting1to1), CGNS_ENUMV(PointList),
930 point_list.size(), Data(point_list), d1_name.c_str(),
931 CGNS_ENUMV(Unstructured), CGNS_ENUMV(PointListDonor),
932 CGNS_ENUMV(DataTypeNull), point_list_donor.size(),
933 Data(point_list_donor), &gc_idx));
934
935 name = fmt::format("{}_to_{}", (*J)->name(), (*I)->name());
936 const auto &d2_name = (*I)->name();
937
938 CGCHECKM(cg_conn_write(
939 get_file_pointer(), base, dzone, name.c_str(), CGNS_ENUMV(Vertex),
940 CGNS_ENUMV(Abutting1to1), CGNS_ENUMV(PointList), point_list_donor.size(),
941 Data(point_list_donor), d2_name.c_str(), CGNS_ENUMV(Unstructured),
942 CGNS_ENUMV(PointListDonor), CGNS_ENUMV(DataTypeNull), point_list.size(),
943 Data(point_list), &gc_idx));
944 }
945 }
946 }
947 }
948 }
949
950 bool ParallelDatabaseIO::begin_nl(Ioss::State state)
951 {
952 dbState = state;
953 return true;
954 }
955
956 void ParallelDatabaseIO::free_state_pointer()
957 {
958 // If this is the first state file created, then we need to save a reference
959 // to the base CGNS file so we can update the metadata and create links to
960 // the state files (if we are using the file-per-state option)
961 if (m_cgnsBasePtr < 0) {
962 m_cgnsBasePtr = m_cgnsFilePtr;
963 m_cgnsFilePtr = -1;
964 }
965 closeDatabase_nl();
966 }
967
968 void ParallelDatabaseIO::open_state_file(int state)
969 {
970 // Close current state file (if any)...
971 free_state_pointer();
972
973 // Update filename to append state count...
974 decodedFilename.clear();
975
976 Ioss::FileInfo db(originalDBFilename);
977 std::string new_filename;
978 if (!db.pathname().empty()) {
979 new_filename += db.pathname() + "/";
980 }
981
982 new_filename += fmt::format("{}-SolutionAtStep{:05}.{}", db.basename(), state, db.extension());
983
984 DBFilename = new_filename;
985
986 Iocgns::Utils::write_state_meta_data(get_file_pointer(), *get_region(), true);
987 }
988
989 bool ParallelDatabaseIO::end_nl(Ioss::State state)
990 {
991 // Transitioning out of state 'state'
992 switch (state) {
993 case Ioss::STATE_DEFINE_MODEL:
994 if (!is_input() && open_create_behavior() != Ioss::DB_APPEND &&
995 open_create_behavior() != Ioss::DB_MODIFY) {
996 write_meta_data();
997 }
998 if (!is_input() && open_create_behavior() == Ioss::DB_APPEND) {
999 Utils::update_db_zone_property(m_cgnsFilePtr, get_region(), myProcessor, isParallel, true);
1000 }
1001 break;
1002 case Ioss::STATE_MODEL:
1003 if (!is_input() && open_create_behavior() != Ioss::DB_APPEND &&
1004 open_create_behavior() != Ioss::DB_MODIFY) {
1005 write_adjacency_data();
1006 }
1007 break;
1008 case Ioss::STATE_DEFINE_TRANSIENT:
1009 if (!is_input() && open_create_behavior() != Ioss::DB_APPEND &&
1010 open_create_behavior() != Ioss::DB_MODIFY) {
1011 write_results_meta_data();
1012 }
1013 break;
1014 default: // ignore everything else...
1015 break;
1016 }
1017 return true;
1018 }
1019
1020 bool ParallelDatabaseIO::begin_state_nl(int state, double /* time */)
1021 {
1022 if (is_input()) {
1023 return true;
1024 }
1025 if (get_file_per_state()) {
1026 // Close current state file (if any); create new state file and output metadata...
1027 open_state_file(state);
1028 write_results_meta_data();
1029 }
1030 Utils::write_flow_solution_metadata(get_file_pointer(), m_cgnsBasePtr, get_region(), state,
1031 &m_currentVertexSolutionIndex,
1032 &m_currentCellCenterSolutionIndex, true);
1033 m_dbFinalized = false;
1034 return true;
1035 }
1036
1037 bool ParallelDatabaseIO::end_state_nl(int state, double time)
1038 {
1039 if (!is_input()) {
1040 m_timesteps.push_back(time);
1041 assert(m_timesteps.size() == (size_t)state);
1042 }
1043
1044 if (!is_input()) {
1045 bool do_flush = true;
1046 if (m_flushInterval != 1) {
1047 if (m_flushInterval == 0 || state % m_flushInterval != 0) {
1048 do_flush = false;
1049 }
1050 }
1051
1052 if (do_flush) {
1053 flush_database_nl();
1054 }
1055 }
1056
1057 return true;
1058 }
1059
1060 void ParallelDatabaseIO::flush_database_nl() const
1061 {
1062 // For HDF5 files, it looks like we need to close the database between
1063 // writes if we want to have a valid database for external access or
1064 // to protect against a crash corrupting the file.
1065 finalize_database();
1066 closeDatabase_nl();
1067 m_cgnsFilePtr = -2; // Tell openDatabase_nl that we want to append
1068 }
1069
1070 const Ioss::Map &ParallelDatabaseIO::get_map(entity_type type) const
1071 {
1072 if (m_meshType == Ioss::MeshType::UNSTRUCTURED) {
1073 switch (type) {
1074 case entity_type::NODE: {
1075 size_t offset = decomp->decomp_node_offset();
1076 size_t count = decomp->decomp_node_count();
1077 return get_map(nodeMap, nodeCount, offset, count, entity_type::NODE);
1078 }
1079 case entity_type::ELEM: {
1080 size_t offset = decomp->decomp_elem_offset();
1081 size_t count = decomp->decomp_elem_count();
1082 return get_map(elemMap, elementCount, offset, count, entity_type::ELEM);
1083 }
1084 }
1085 }
1086 else {
1087 assert(1 == 0);
1088 }
1089 std::ostringstream errmsg;
1090 fmt::print(errmsg, "INTERNAL ERROR: Invalid map type. "
1091 "Something is wrong in the Iocgns::ParallelDatabaseIO::get_map() function. "
1092 "Please report.\n");
1093 IOSS_ERROR(errmsg);
1094 }
1095
1096 const Ioss::Map &ParallelDatabaseIO::get_map(Ioss::Map &entity_map, int64_t entity_count,
1097 int64_t file_offset, int64_t file_count,
1098 entity_type type) const
1099
1100 {
1101 // Allocate space for node number map and read it in...
1102 // Can be called multiple times, allocate 1 time only
1103 if (entity_map.map().empty()) {
1104 entity_map.set_size(entity_count);
1105
1106 if (is_input()) {
1107 Ioss::MapContainer file_data(file_count);
1108
1109 // For cgns, my file_data is just nodes from file_offset to file_offset+file_count
1110 std::iota(file_data.begin(), file_data.end(), file_offset + 1);
1111
1112 if (type == entity_type::NODE)
1113 decomp->communicate_node_data(Data(file_data), &entity_map.map()[1], 1);
1114 else if (type == entity_type::ELEM)
1115 decomp->communicate_element_data(Data(file_data), &entity_map.map()[1], 1);
1116
1117 // Check for sequential node map.
1118 // If not, build the reverse G2L node map...
1119 (void)entity_map.is_sequential(true);
1120 entity_map.build_reverse_map();
1121 }
1122 else {
1123 // Output database; entity_map.map not set yet... Build a default map.
1124 entity_map.set_default(entity_count);
1125 }
1126 }
1127 return entity_map;
1128 }
1129
1130 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::Region * /* reg */,
1131 const Ioss::Field & /* field */, void * /* data */,
1132 size_t /* data_size */) const
1133 {
1134 return -1;
1135 }
1136
1137 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::NodeBlock *nb,
1138 const Ioss::Field &field, void *data,
1139 size_t data_size) const
1140 {
1141 // A CGNS DatabaseIO object can have two "types" of NodeBlocks:
1142 // * The normal "all nodes in the model" NodeBlock as used by Exodus
1143 // * A "nodes in a zone" NodeBlock which contains the subset of nodes
1144 // "owned" by a specific StructuredBlock or ElementBlock zone.
1145 //
1146 // Question: How to determine if the NodeBlock is the "global" Nodeblock
1147 // or a "sub" NodeBlock: Use the "is_nonglobal_nodeblock()" function.
1148 if (nb->is_nonglobal_nodeblock()) {
1149 return get_field_internal_sub_nb(nb, field, data, data_size);
1150 }
1151
1152 size_t num_to_get = field.verify(data_size);
1153
1154 Ioss::Field::RoleType role = field.get_role();
1155 if (role == Ioss::Field::MESH) {
1156 if (field.get_name() == "mesh_model_coordinates_x" ||
1157 field.get_name() == "mesh_model_coordinates_y" ||
1158 field.get_name() == "mesh_model_coordinates_z" ||
1159 field.get_name() == "mesh_model_coordinates") {
1160 decomp->get_node_coordinates(get_file_pointer(), (double *)data, field);
1161 }
1162
1163 else if (field.get_name() == "ids") {
1164 // Map the local ids in this node block
1165 // (1...node_count) to global node ids.
1166 get_map(entity_type::NODE).map_implicit_data(data, field, num_to_get, 0);
1167 }
1168 // The 1..global_node_count id. In a parallel-decomposed run,
1169 // it maps the node back to its implicit position in the serial
1170 // undecomposed mesh file. This is ONLY provided for backward-
1171 // compatibility and should not be used unless absolutely required.
1172 else if (field.get_name() == "implicit_ids") {
1173 size_t offset = decomp->decomp_node_offset();
1174 size_t count = decomp->decomp_node_count();
1175 if (int_byte_size_api() == 4) {
1176 std::vector<int> file_ids(count);
1177 std::iota(file_ids.begin(), file_ids.end(), offset + 1);
1178 decomp->communicate_node_data(Data(file_ids), (int *)data, 1);
1179 }
1180 else {
1181 std::vector<int64_t> file_ids(count);
1182 std::iota(file_ids.begin(), file_ids.end(), offset + 1);
1183 decomp->communicate_node_data(Data(file_ids), (int64_t *)data, 1);
1184 }
1185 }
1186
1187 else if (field.get_name() == "connectivity") {
1188 // Do nothing, just handles an idiosyncrasy of the GroupingEntity
1189 }
1190 else if (field.get_name() == "connectivity_raw") {
1191 // Do nothing, just handles an idiosyncrasy of the GroupingEntity
1192 }
1193 else if (field.get_name() == "owning_processor") {
1194 // If parallel, then set the "locally_owned" property on the nodeblocks.
1195 Ioss::CommSet *css = get_region()->get_commset("commset_node");
1196 if (int_byte_size_api() == 8) {
1197 auto *idata = static_cast<int64_t *>(data);
1198 std::fill(idata, idata + nodeCount, myProcessor);
1199
1200 // Cannot call:
1201 // `css->get_field_data("entity_processor_raw", ent_proc);`
1202 // directly since it will cause a deadlock (in threaded code),
1203 // expand out into corresponding `get_field_internal` call.
1204 Ioss::Field ep_field = css->get_field("entity_processor_raw");
1205 std::vector<int64_t> ent_proc(ep_field.raw_count() *
1206 ep_field.raw_storage()->component_count());
1207 size_t ep_data_size = ent_proc.size() * sizeof(int64_t);
1208 get_field_internal(css, ep_field, Data(ent_proc), ep_data_size);
1209 for (size_t i = 0; i < ent_proc.size(); i += 2) {
1210 int64_t node = ent_proc[i + 0];
1211 int64_t proc = ent_proc[i + 1];
1212 if (proc < idata[node - 1]) {
1213 idata[node - 1] = proc;
1214 }
1215 }
1216 }
1217 else {
1218 int *idata = static_cast<int *>(data);
1219 std::fill(idata, idata + nodeCount, myProcessor);
1220
1221 Ioss::Field ep_field = css->get_field("entity_processor_raw");
1222 std::vector<int> ent_proc(ep_field.raw_count() *
1223 ep_field.raw_storage()->component_count());
1224 size_t ep_data_size = ent_proc.size() * sizeof(int);
1225 get_field_internal(css, ep_field, Data(ent_proc), ep_data_size);
1226 for (size_t i = 0; i < ent_proc.size(); i += 2) {
1227 int node = ent_proc[i + 0];
1228 int proc = ent_proc[i + 1];
1229 if (proc < idata[node - 1]) {
1230 idata[node - 1] = proc;
1231 }
1232 }
1233 }
1234 }
1235 else {
1236 num_to_get = Ioss::Utils::field_warning(nb, field, "input");
1237 }
1238 }
1239 else if (role == Ioss::Field::TRANSIENT) {
1240 // Locate the FlowSolution node corresponding to the correct state/step/time
1241 // TODO: do this at read_meta_data() and store...
1242 int step = get_region()->get_current_state();
1243 int comp_count = field.get_component_count(Ioss::Field::InOut::INPUT);
1244
1245 if (comp_count == 1) {
1246 decomp->get_node_field(get_file_pointer(), step, Utils::index(field), (double *)data);
1247 }
1248 else {
1249 std::vector<double> ioss_tmp(num_to_get);
1250 for (int i = 0; i < comp_count; i++) {
1251 decomp->get_node_field(get_file_pointer(), step, Utils::index(field) + i, Data(ioss_tmp));
1252
1253 size_t index = i;
1254 auto *rdata = static_cast<double *>(data);
1255 for (size_t j = 0; j < num_to_get; j++) {
1256 rdata[index] = ioss_tmp[j];
1257 index += comp_count;
1258 }
1259 }
1260 }
1261 }
1262 else {
1263 num_to_get = Ioss::Utils::field_warning(nb, field, "input");
1264 }
1265 return num_to_get;
1266 }
1267
1268 int64_t ParallelDatabaseIO::get_field_internal_sub_nb(const Ioss::NodeBlock *nb,
1269 const Ioss::Field &field, void *data,
1270 size_t data_size) const
1271 {
1272 // Reads field data on a NodeBlock which is a "sub" NodeBlock -- contains the nodes for a
1273 // StructuredBlock instead of for the entire model.
1274 // Currently only TRANSIENT fields are input this way. No valid reason, but that is the current
1275 // use case.
1276
1277 // Get the StructuredBlock that this NodeBlock is contained in:
1278 const Ioss::GroupingEntity *sb = nb->contained_in();
1279 int zone = Iocgns::Utils::get_db_zone(sb);
1280 cgsize_t num_to_get = field.verify(data_size);
1281
1282 Ioss::Field::RoleType role = field.get_role();
1283 if (role == Ioss::Field::TRANSIENT) {
1284 // Locate the FlowSolution node corresponding to the correct state/step/time
1285 // TODO: do this at read_meta_data() and store...
1286 int step = get_region()->get_current_state();
1287
1288 int base = 1;
1289 int solution_index =
1290 Utils::find_solution_index(get_file_pointer(), base, zone, step, CGNS_ENUMV(Vertex));
1291
1292 auto *rdata = static_cast<double *>(data);
1293 assert(num_to_get == sb->get_property("node_count").get_int());
1294 cgsize_t rmin[3] = {0, 0, 0};
1295 cgsize_t rmax[3] = {0, 0, 0};
1296 if (num_to_get > 0) {
1297 rmin[0] = sb->get_property("offset_i").get_int() + 1;
1298 rmin[1] = sb->get_property("offset_j").get_int() + 1;
1299 rmin[2] = sb->get_property("offset_k").get_int() + 1;
1300
1301 rmax[0] = rmin[0] + sb->get_property("ni").get_int();
1302 rmax[1] = rmin[1] + sb->get_property("nj").get_int();
1303 rmax[2] = rmin[2] + sb->get_property("nk").get_int();
1304
1305 assert(num_to_get ==
1306 (rmax[0] - rmin[0] + 1) * (rmax[1] - rmin[1] + 1) * (rmax[2] - rmin[2] + 1));
1307 }
1308
1309 int field_offset = Utils::index(field);
1310 int comp_count = field.get_component_count(Ioss::Field::InOut::INPUT);
1311 if (comp_count == 1) {
1312 CGCHECKM(cgp_field_read_data(get_file_pointer(), base, zone, solution_index, field_offset,
1313 rmin, rmax, rdata));
1314 }
1315 else {
1316 std::vector<double> cgns_data(num_to_get);
1317 for (int i = 0; i < comp_count; i++) {
1318 CGCHECKM(cgp_field_read_data(get_file_pointer(), base, zone, solution_index,
1319 field_offset + i, rmin, rmax, Data(cgns_data)));
1320 for (cgsize_t j = 0; j < num_to_get; j++) {
1321 rdata[comp_count * j + i] = cgns_data[j];
1322 }
1323 }
1324 }
1325 }
1326 // Ignoring all other field role types...
1327 return num_to_get;
1328 }
1329
1330 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::EdgeBlock * /* nb */,
1331 const Ioss::Field & /* field */, void * /* data */,
1332 size_t /* data_size */) const
1333 {
1334 return -1;
1335 }
1336 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::FaceBlock * /* nb */,
1337 const Ioss::Field & /* field */, void * /* data */,
1338 size_t /* data_size */) const
1339 {
1340 return -1;
1341 }
1342
1343 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::StructuredBlock *sb,
1344 const Ioss::Field &field, void *data,
1345 size_t data_size) const
1346 {
1347 Ioss::Field::RoleType role = field.get_role();
1348 cgsize_t base = sb->get_property("base").get_int();
1349 cgsize_t zone = sb->get_property("zone").get_int();
1350
1351 cgsize_t num_to_get = field.verify(data_size);
1352
1353 cgsize_t rmin[3] = {0, 0, 0};
1354 cgsize_t rmax[3] = {0, 0, 0};
1355
1356 bool cell_field = Utils::is_cell_field(field);
1357 if (cell_field) {
1358 assert(num_to_get == sb->get_property("cell_count").get_int());
1359 if (num_to_get > 0) {
1360 rmin[0] = sb->get_property("offset_i").get_int() + 1;
1361 rmin[1] = sb->get_property("offset_j").get_int() + 1;
1362 rmin[2] = sb->get_property("offset_k").get_int() + 1;
1363
1364 rmax[0] = rmin[0] + sb->get_property("ni").get_int() - 1;
1365 rmax[1] = rmin[1] + sb->get_property("nj").get_int() - 1;
1366 rmax[2] = rmin[2] + sb->get_property("nk").get_int() - 1;
1367 }
1368 }
1369 else {
1370 // cell nodal field.
1371 assert(num_to_get == sb->get_property("node_count").get_int());
1372 if (num_to_get > 0) {
1373 rmin[0] = sb->get_property("offset_i").get_int() + 1;
1374 rmin[1] = sb->get_property("offset_j").get_int() + 1;
1375 rmin[2] = sb->get_property("offset_k").get_int() + 1;
1376
1377 rmax[0] = rmin[0] + sb->get_property("ni").get_int();
1378 rmax[1] = rmin[1] + sb->get_property("nj").get_int();
1379 rmax[2] = rmin[2] + sb->get_property("nk").get_int();
1380 }
1381 }
1382
1383 assert(num_to_get == 0 || num_to_get == (rmax[0] - rmin[0] + 1) * (rmax[1] - rmin[1] + 1) *
1384 (rmax[2] - rmin[2] + 1));
1385 double *rdata = num_to_get > 0 ? static_cast<double *>(data) : nullptr;
1386
1387 if (role == Ioss::Field::MESH) {
1388
1389 if (field.get_name() == "mesh_model_coordinates_x") {
1390 CGCHECKM(cgp_coord_read_data(get_file_pointer(), base, zone, 1, rmin, rmax, rdata));
1391 }
1392
1393 else if (field.get_name() == "mesh_model_coordinates_y") {
1394 CGCHECKM(cgp_coord_read_data(get_file_pointer(), base, zone, 2, rmin, rmax, rdata));
1395 }
1396
1397 else if (field.get_name() == "mesh_model_coordinates_z") {
1398 CGCHECKM(cgp_coord_read_data(get_file_pointer(), base, zone, 3, rmin, rmax, rdata));
1399 }
1400
1401 else if (field.get_name() == "mesh_model_coordinates") {
1402 char basename[CGNS_MAX_NAME_LENGTH + 1];
1403 int cell_dimension = 0;
1404 int phys_dimension = 0;
1405 CGCHECKM(
1406 cg_base_read(get_file_pointer(), base, basename, &cell_dimension, &phys_dimension));
1407
1408 // Data required by upper classes store x0, y0, z0, ... xn,
1409 // yn, zn. Data stored in cgns file is x0, ..., xn, y0,
1410 // ..., yn, z0, ..., zn so we have to allocate some scratch
1411 // memory to read in the data and then map into supplied
1412 // 'data'
1413 std::vector<double> coord(num_to_get);
1414 CGCHECKM(cgp_coord_read_data(get_file_pointer(), base, zone, 1, rmin, rmax, Data(coord)));
1415
1416 // Map to global coordinate position...
1417 for (cgsize_t i = 0; i < num_to_get; i++) {
1418 rdata[phys_dimension * i + 0] = coord[i];
1419 }
1420
1421 if (phys_dimension >= 2) {
1422 CGCHECKM(cgp_coord_read_data(get_file_pointer(), base, zone, 2, rmin, rmax, Data(coord)));
1423
1424 // Map to global coordinate position...
1425 for (cgsize_t i = 0; i < num_to_get; i++) {
1426 rdata[phys_dimension * i + 1] = coord[i];
1427 }
1428 }
1429
1430 if (phys_dimension == 3) {
1431 CGCHECKM(cgp_coord_read_data(get_file_pointer(), base, zone, 3, rmin, rmax, Data(coord)));
1432
1433 // Map to global coordinate position...
1434 for (cgsize_t i = 0; i < num_to_get; i++) {
1435 rdata[phys_dimension * i + 2] = coord[i];
1436 }
1437 }
1438 }
1439 else if (field.get_name() == "cell_node_ids") {
1440 if (field.get_type() == Ioss::Field::INT64) {
1441 auto *idata = static_cast<int64_t *>(data);
1442 sb->get_cell_node_ids(idata, true);
1443 }
1444 else {
1445 assert(field.get_type() == Ioss::Field::INT32);
1446 int *idata = static_cast<int *>(data);
1447 sb->get_cell_node_ids(idata, true);
1448 }
1449 }
1450 else if (field.get_name() == "cell_ids") {
1451 if (field.get_type() == Ioss::Field::INT64) {
1452 auto *idata = static_cast<int64_t *>(data);
1453 sb->get_cell_ids(idata, true);
1454 }
1455 else {
1456 assert(field.get_type() == Ioss::Field::INT32);
1457 int *idata = static_cast<int *>(data);
1458 sb->get_cell_ids(idata, true);
1459 }
1460 }
1461 else {
1462 num_to_get = Ioss::Utils::field_warning(sb, field, "input");
1463 }
1464 }
1465 else if (role == Ioss::Field::TRANSIENT) {
1466 int comp_count = field.get_component_count(Ioss::Field::InOut::INPUT);
1467
1468 int sol_index = 0;
1469 int step = get_region()->get_current_state();
1470 if (cell_field) {
1471 sol_index = Utils::find_solution_index(get_file_pointer(), base, zone, step,
1472 CGNS_ENUMV(CellCenter));
1473 }
1474 else {
1475 sol_index =
1476 Utils::find_solution_index(get_file_pointer(), base, zone, step, CGNS_ENUMV(Vertex));
1477 }
1478 int field_offset = Utils::index(field);
1479
1480 if (comp_count == 1) {
1481 CGCHECKM(cgp_field_read_data(get_file_pointer(), base, zone, sol_index, field_offset, rmin,
1482 rmax, rdata));
1483 }
1484 else {
1485 std::vector<double> cgns_data(num_to_get);
1486 for (int i = 0; i < comp_count; i++) {
1487 CGCHECKM(cgp_field_read_data(get_file_pointer(), base, zone, sol_index, field_offset + i,
1488 rmin, rmax, Data(cgns_data)));
1489 for (cgsize_t j = 0; j < num_to_get; j++) {
1490 rdata[comp_count * j + i] = cgns_data[j];
1491 }
1492 }
1493 }
1494 }
1495 else {
1496 num_to_get = Ioss::Utils::field_warning(sb, field, "input");
1497 }
1498 return num_to_get;
1499 }
1500
1501 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::ElementBlock *eb,
1502 const Ioss::Field &field, void *data,
1503 size_t data_size) const
1504 {
1505 int base = eb->get_property("base").get_int();
1506 int zone = eb->get_property("zone").get_int();
1507 size_t num_to_get = field.verify(data_size);
1508 auto role = field.get_role();
1509
1510 if (role == Ioss::Field::MESH) {
1511 // Handle the MESH fields required for a CGNS file model.
1512 // (The 'genesis' portion)
1513
1514 if (field.get_name() == "connectivity_raw" || field.get_name() == "connectivity") {
1515
1516 // The connectivity is stored in a 1D array.
1517 // The element_node index varies fastest
1518 int order = eb->get_property("original_block_order").get_int();
1519 decomp->get_block_connectivity(get_file_pointer(), data, order);
1520 if (field.get_type() == Ioss::Field::INT32) {
1521 auto *idata = reinterpret_cast<int *>(data);
1522 Utils::map_cgns_connectivity(eb->topology(), num_to_get, idata);
1523 }
1524 else {
1525 auto *idata = reinterpret_cast<int64_t *>(data);
1526 Utils::map_cgns_connectivity(eb->topology(), num_to_get, idata);
1527 }
1528 }
1529 else if (field.get_name() == "ids" || field.get_name() == "implicit_ids") {
1530 // Map the local ids in this element block
1531 // (1..element_count) to global element ids.
1532 get_map(entity_type::ELEM).map_implicit_data(data, field, num_to_get, eb->get_offset());
1533 }
1534 else {
1535 num_to_get = Ioss::Utils::field_warning(eb, field, "input");
1536 }
1537 }
1538 else if (role == Ioss::Field::TRANSIENT) {
1539 // Locate the FlowSolution node corresponding to the correct state/step/time
1540 // TODO: do this at read_meta_data() and store...
1541 int step = get_region()->get_current_state();
1542 int solution_index =
1543 Utils::find_solution_index(get_file_pointer(), base, zone, step, CGNS_ENUMV(CellCenter));
1544
1545 int order = eb->get_property("original_block_order").get_int();
1546
1547 // Read into a double variable
1548 // TODO: Support other field types...
1549 size_t num_entity = eb->entity_count();
1550 std::vector<double> temp(num_entity);
1551
1552 // get number of components, cycle through each component
1553 size_t comp_count = field.get_component_count(Ioss::Field::InOut::INPUT);
1554 for (size_t i = 0; i < comp_count; i++) {
1555 int field_offset = Utils::index(field) + i;
1556 decomp->get_element_field(get_file_pointer(), solution_index, order, field_offset,
1557 Data(temp));
1558
1559 // Transfer to 'data' array.
1560 size_t k = 0;
1561 assert(field.get_type() == Ioss::Field::REAL);
1562 auto *rvar = static_cast<double *>(data);
1563 for (size_t j = i; j < num_entity * comp_count; j += comp_count) {
1564 rvar[j] = temp[k++];
1565 }
1566 assert(k == num_entity);
1567 }
1568 }
1569 else {
1570 num_to_get = Ioss::Utils::field_warning(eb, field, "unknown");
1571 }
1572 return num_to_get;
1573 }
1574
1575 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::NodeSet * /* ns */,
1576 const Ioss::Field & /* field */, void * /* data */,
1577 size_t /* data_size */) const
1578 {
1579 return -1;
1580 }
1581 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::EdgeSet * /* ns */,
1582 const Ioss::Field & /* field */, void * /* data */,
1583 size_t /* data_size */) const
1584 {
1585 return -1;
1586 }
1587 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::FaceSet * /* ns */,
1588 const Ioss::Field & /* field */, void * /* data */,
1589 size_t /* data_size */) const
1590 {
1591 return -1;
1592 }
1593 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::ElementSet * /* ns */,
1594 const Ioss::Field & /* field */, void * /* data */,
1595 size_t /* data_size */) const
1596 {
1597 return -1;
1598 }
1599 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::SideBlock *sb,
1600 const Ioss::Field &field, void *data,
1601 size_t data_size) const
1602 {
1603 int id = sb->get_property("id").get_int();
1604 const auto &sset = decomp->m_sideSets[id];
1605
1606 auto num_to_get = field.verify(data_size);
1607 if (num_to_get > 0) {
1608 int64_t entity_count = sb->entity_count();
1609 if (num_to_get != entity_count) {
1610 std::ostringstream errmsg;
1611 fmt::print(errmsg, "ERROR: Partial field input not yet implemented for side blocks");
1612 IOSS_ERROR(errmsg);
1613 }
1614 }
1615
1616 Ioss::Field::RoleType role = field.get_role();
1617 if (role == Ioss::Field::MESH) {
1618 if (field.get_name() == "element_side_raw" || field.get_name() == "element_side") {
1619
1620 decomp->get_sideset_element_side(get_file_pointer(), sset, data);
1621 return num_to_get;
1622 }
1623 else {
1624 num_to_get = Ioss::Utils::field_warning(sb, field, "input");
1625 }
1626 }
1627 else {
1628 num_to_get = Ioss::Utils::field_warning(sb, field, "input");
1629 }
1630 return num_to_get;
1631 }
1632
1633 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::SideSet * /* fs */,
1634 const Ioss::Field & /* field */, void * /* data */,
1635 size_t /* data_size */) const
1636 {
1637 return -1;
1638 }
1639 int64_t ParallelDatabaseIO::get_field_internal(const Ioss::CommSet *cs, const Ioss::Field &field,
1640 void *data, size_t data_size) const
1641 {
1642 size_t num_to_get = field.verify(data_size);
1643
1644 // Return the <entity (node or side), processor> pair
1645 if (field.get_name() == "entity_processor" || field.get_name() == "entity_processor_raw") {
1646
1647 // Check type -- node or side
1648 std::string type = cs->get_property("entity_type").get_string();
1649
1650 if (type == "node") {
1651
1652 bool do_map = field.get_name() == "entity_processor";
1653 // Convert local node id to global node id and store in 'data'
1654 const Ioss::MapContainer &map = get_map(entity_type::NODE).map();
1655 if (int_byte_size_api() == 4) {
1656 decomp->get_node_entity_proc_data(static_cast<int *>(data), map, do_map);
1657 }
1658 else {
1659 decomp->get_node_entity_proc_data(static_cast<int64_t *>(data), map, do_map);
1660 }
1661 }
1662 else {
1663 std::ostringstream errmsg;
1664 fmt::print(errmsg, "ERROR: Invalid commset type {}", type);
1665 IOSS_ERROR(errmsg);
1666 }
1667 }
1668 else if (field.get_name() == "ids") {
1669 // Do nothing, just handles an idiosyncrasy of the GroupingEntity
1670 }
1671 else {
1672 num_to_get = Ioss::Utils::field_warning(cs, field, "input");
1673 }
1674 return num_to_get;
1675 }
1676
1677 int64_t ParallelDatabaseIO::handle_element_ids(const Ioss::ElementBlock *eb, void *ids,
1678 size_t num_to_get, size_t offset,
1679 size_t count) const
1680 {
1681 bool in_define = (dbState == Ioss::STATE_MODEL) || (dbState == Ioss::STATE_DEFINE_MODEL);
1682 if (in_define) {
1683 if (m_elemGlobalImplicitMap.empty()) {
1684 m_elemGlobalImplicitMap.resize(elementCount);
1685 }
1686 // Build the implicit_global map used to map an elements
1687 // local-implicit position to the global-implicit
1688 // position. Primarily used for sideset elements.
1689 // Elements starting at 'eb_offset' map to the global implicit
1690 // position of 'offset'
1691 int64_t eb_offset = eb->get_offset();
1692 for (size_t i = 0; i < count; i++) {
1693 m_elemGlobalImplicitMap[eb_offset + i] = offset + i + 1;
1694 }
1695 }
1696
1697 elemMap.set_size(elementCount);
1698 int64_t eb_offset = eb->get_offset();
1699 if (int_byte_size_api() == 4) {
1700 elemMap.set_map(static_cast<int *>(ids), num_to_get, eb_offset, in_define);
1701 }
1702 else {
1703 elemMap.set_map(static_cast<int64_t *>(ids), num_to_get, eb_offset, in_define);
1704 }
1705 return num_to_get;
1706 }
1707
1708 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::Region * /* region */,
1709 const Ioss::Field & /* field */, void * /* data */,
1710 size_t /* data_size */) const
1711 {
1712 return -1;
1713 }
1714
1715 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::NodeBlock *nb,
1716 const Ioss::Field &field, void *data,
1717 size_t data_size) const
1718 {
1719 // A CGNS DatabaseIO object can have two "types" of NodeBlocks:
1720 // * The normal "all nodes in the model" NodeBlock as used by Exodus
1721 // * A "nodes in a zone" NodeBlock which contains the subset of nodes
1722 // "owned" by a specific StructuredBlock or ElementBlock zone.
1723 //
1724 // Question: How to determine if the NodeBlock is the "global" Nodeblock
1725 // or a "sub" NodeBlock: Use the "is_nonglobal_nodeblock()" function.
1726 if (nb->is_nonglobal_nodeblock()) {
1727 return put_field_internal_sub_nb(nb, field, data, data_size);
1728 }
1729
1730 Ioss::Field::RoleType role = field.get_role();
1731 cgsize_t base = 1;
1732 size_t num_to_get = field.verify(data_size);
1733
1734 // Instead of outputting a global nodeblock's worth of data,
1735 // the data is output a "zone" at a time.
1736 // The m_globalToBlockLocalNodeMap[zone] map is used (Ioss::Map pointer)
1737 // This map is built during the output of block connectivity,
1738 // so for cgns unstructured mesh, we need to output ElementBlock connectivity
1739 // prior to outputting nodal coordinates.
1740 for (const auto &z : m_globalToBlockLocalNodeMap) {
1741 if (z.second == nullptr) {
1742 std::ostringstream errmsg;
1743 fmt::print(errmsg,
1744 "ERROR: CGNS: The globalToBlockLocalNodeMap is not defined, so nodal fields "
1745 "cannot be output.");
1746 IOSS_ERROR(errmsg);
1747 }
1748 }
1749
1750 if (role == Ioss::Field::MESH) {
1751 if (field.get_name() == "ids") {
1752 // The ids coming in are the global ids; their position is the
1753 // local id -1 (That is, data[0] contains the global id of local
1754 // node 1)
1755 handle_node_ids(data, num_to_get);
1756 }
1757 else if (field.get_name() == "mesh_model_coordinates" ||
1758 field.get_name() == "mesh_model_coordinates_x" ||
1759 field.get_name() == "mesh_model_coordinates_y" ||
1760 field.get_name() == "mesh_model_coordinates_z") {
1761 auto *rdata = static_cast<double *>(data);
1762
1763 std::vector<int64_t> node_offset = get_processor_zone_node_offset();
1764
1765 if (field.get_name() == "mesh_model_coordinates") {
1766 int spatial_dim = nb->get_property("component_degree").get_int();
1767
1768 // Output all coordinates, a zone's worth of data at a time...
1769
1770 for (const auto &block : m_globalToBlockLocalNodeMap) {
1771 auto zone = block.first;
1772 // NOTE: 'block_map' has one more entry than node_count. First entry is for something
1773 // else. But, ->size() returns correct size (ignoring first entry)
1774 // 'block_map' is 1-based.
1775 const auto &block_map = block.second;
1776 std::vector<double> x(block_map->size());
1777 std::vector<double> y(block_map->size());
1778 std::vector<double> z(block_map->size());
1779
1780 for (size_t i = 0; i < block_map->size(); i++) {
1781 auto global = block_map->map()[i + 1];
1782 auto local = nodeMap.global_to_local(global) - 1;
1783 assert(local >= 0 && local < (int64_t)num_to_get);
1784
1785 x[i] = rdata[local * spatial_dim + 0];
1786 if (spatial_dim > 1) {
1787 y[i] = rdata[local * spatial_dim + 1];
1788 }
1789 if (spatial_dim > 2) {
1790 z[i] = rdata[local * spatial_dim + 2];
1791 }
1792 }
1793
1794 // Create the zone
1795 // Output this zones coordinates...
1796 int crd_idx = 0;
1797 CGCHECKM(cgp_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
1798 "CoordinateX", &crd_idx));
1799 cgsize_t start = node_offset[zone - 1] + 1;
1800 cgsize_t finish = start + block_map->size() - 1;
1801
1802 auto xx = block_map->size() > 0 ? Data(x) : nullptr;
1803 CGCHECKM(
1804 cgp_coord_write_data(get_file_pointer(), base, zone, crd_idx, &start, &finish, xx));
1805
1806 if (spatial_dim > 1) {
1807 CGCHECKM(cgp_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
1808 "CoordinateY", &crd_idx));
1809 auto yy = block_map->size() > 0 ? Data(y) : nullptr;
1810 CGCHECKM(cgp_coord_write_data(get_file_pointer(), base, zone, crd_idx, &start,
1811 &finish, yy));
1812 }
1813
1814 if (spatial_dim > 2) {
1815 CGCHECKM(cgp_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
1816 "CoordinateZ", &crd_idx));
1817 auto zz = block_map->size() > 0 ? Data(z) : nullptr;
1818 CGCHECKM(cgp_coord_write_data(get_file_pointer(), base, zone, crd_idx, &start,
1819 &finish, zz));
1820 }
1821 }
1822 }
1823 else {
1824 // Outputting only a single coordinate value...
1825 for (const auto &block : m_globalToBlockLocalNodeMap) {
1826 auto zone = block.first;
1827 // NOTE: 'block_map' has one more entry than node_count. First entry is for something
1828 // else.
1829 // 'block_map' is 1-based.
1830 const auto &block_map = block.second;
1831 std::vector<double> xyz(block_map->size());
1832
1833 for (size_t i = 0; i < block_map->size(); i++) {
1834 auto global = block_map->map()[i + 1];
1835 auto local = nodeMap.global_to_local(global) - 1;
1836 xyz[i] = rdata[local];
1837 }
1838
1839 std::string cgns_name = "Invalid";
1840 if (field.get_name() == "mesh_model_coordinates_x") {
1841 cgns_name = "CoordinateX";
1842 }
1843 else if (field.get_name() == "mesh_model_coordinates_y") {
1844 cgns_name = "CoordinateY";
1845 }
1846 else if (field.get_name() == "mesh_model_coordinates_z") {
1847 cgns_name = "CoordinateZ";
1848 }
1849 // Create the zone
1850 // Output this zones coordinates...
1851 int crd_idx = 0;
1852 CGCHECKM(cgp_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
1853 cgns_name.c_str(), &crd_idx));
1854 cgsize_t start = node_offset[zone - 1] + 1;
1855 cgsize_t finish = start + block_map->size() - 1;
1856 auto xx = block_map->size() > 0 ? Data(xyz) : nullptr;
1857 CGCHECKM(
1858 cgp_coord_write_data(get_file_pointer(), base, zone, crd_idx, &start, &finish, xx));
1859 }
1860 }
1861 }
1862 else {
1863 num_to_get = Ioss::Utils::field_warning(nb, field, "output");
1864 }
1865 }
1866 else if (role == Ioss::Field::TRANSIENT) {
1867 // Instead of outputting a global nodeblock's worth of data,
1868 // the data is output a "zone" at a time.
1869 // The m_globalToBlockLocalNodeMap[zone] map is used (Ioss::Map pointer)
1870 // This map is built during the output of block connectivity,
1871 // so for cgns unstructured mesh, we need to output ElementBlock connectivity
1872 // prior to outputting nodal coordinates.
1873 std::vector<int64_t> node_offset = get_processor_zone_node_offset();
1874
1875 size_t comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
1876
1877 double *rdata = num_to_get > 0 ? static_cast<double *>(data) : nullptr;
1878
1879 for (const auto &block : m_globalToBlockLocalNodeMap) {
1880 auto zone = block.first;
1881 // NOTE: 'block_map' has one more entry than node_count.
1882 // First entry is for something else. 'block_map' is
1883 // 1-based.
1884 const auto &block_map = block.second;
1885 std::vector<double> blk_data(block_map->size());
1886
1887 cgsize_t start = node_offset[zone - 1] + 1;
1888 cgsize_t finish = start + block_map->size() - 1;
1889
1890 for (size_t i = 0; i < comp_count; i++) {
1891 for (size_t j = 0; j < block_map->size(); j++) {
1892 auto global = block_map->map()[j + 1];
1893 auto local = nodeMap.global_to_local(global) - 1;
1894 assert(local >= 0 && local < (int64_t)num_to_get);
1895 blk_data[j] = rdata[local * comp_count + i];
1896 }
1897 std::string var_name = (comp_count > 1)
1898 ? get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1)
1899 : field.get_name();
1900 int cgns_field = 0;
1901 CGCHECKM(cgp_field_write(get_file_pointer(), base, zone, m_currentVertexSolutionIndex,
1902 CGNS_ENUMV(RealDouble), var_name.c_str(), &cgns_field));
1903
1904 CGCHECKM(cgp_field_write_data(get_file_pointer(), base, zone,
1905 m_currentVertexSolutionIndex, cgns_field, &start, &finish,
1906 Data(blk_data)));
1907 if (i == 0)
1908 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(Vertex));
1909 }
1910 }
1911 }
1912 else {
1913 num_to_get = Ioss::Utils::field_warning(nb, field, "output");
1914 }
1915 return num_to_get;
1916 }
1917
1918 int64_t ParallelDatabaseIO::put_field_internal_sub_nb(const Ioss::NodeBlock *nb,
1919 const Ioss::Field &field, void *data,
1920 size_t data_size) const
1921 {
1922 // Outputs field data on a NodeBlock which is a "sub" NodeBlock -- contains the nodes for a
1923 // StructuredBlock instead of for the entire model.
1924 // Currently only TRANSIENT fields are output this way. No valid reason, but that is the
1925 // current use case.
1926
1927 // Get the StructuredBlock that this NodeBlock is contained in:
1928 const Ioss::GroupingEntity *sb = nb->contained_in();
1929 int zone = Iocgns::Utils::get_db_zone(sb);
1930 cgsize_t num_to_get = field.verify(data_size);
1931
1932 Ioss::Field::RoleType role = field.get_role();
1933 if (role == Ioss::Field::TRANSIENT) {
1934 int base = 1;
1935 auto *rdata = static_cast<double *>(data);
1936 int cgns_field = 0;
1937 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
1938
1939 cgsize_t rmin[3] = {0, 0, 0};
1940 cgsize_t rmax[3] = {0, 0, 0};
1941
1942 assert(num_to_get == sb->get_property("node_count").get_int());
1943 if (num_to_get > 0) {
1944 rmin[0] = sb->get_property("offset_i").get_int() + 1;
1945 rmin[1] = sb->get_property("offset_j").get_int() + 1;
1946 rmin[2] = sb->get_property("offset_k").get_int() + 1;
1947
1948 rmax[0] = rmin[0] + sb->get_property("ni").get_int();
1949 rmax[1] = rmin[1] + sb->get_property("nj").get_int();
1950 rmax[2] = rmin[2] + sb->get_property("nk").get_int();
1951 }
1952
1953 if (comp_count == 1) {
1954 CGCHECKM(cgp_field_write(get_file_pointer(), base, zone, m_currentVertexSolutionIndex,
1955 CGNS_ENUMV(RealDouble), field.get_name().c_str(), &cgns_field));
1956 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(Vertex));
1957
1958 CGCHECKM(cgp_field_write_data(get_file_pointer(), base, zone, m_currentVertexSolutionIndex,
1959 cgns_field, rmin, rmax, rdata));
1960 }
1961 else {
1962 std::vector<double> cgns_data(num_to_get);
1963 for (int i = 0; i < comp_count; i++) {
1964 for (cgsize_t j = 0; j < num_to_get; j++) {
1965 cgns_data[j] = rdata[comp_count * j + i];
1966 }
1967 std::string var_name = get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
1968
1969 CGCHECKM(cgp_field_write(get_file_pointer(), base, zone, m_currentVertexSolutionIndex,
1970 CGNS_ENUMV(RealDouble), var_name.c_str(), &cgns_field));
1971 if (i == 0) {
1972 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(Vertex));
1973 }
1974
1975 CGCHECKM(cgp_field_write_data(get_file_pointer(), base, zone,
1976 m_currentVertexSolutionIndex, cgns_field, rmin, rmax,
1977 Data(cgns_data)));
1978 }
1979 }
1980 }
1981 // Ignoring all other field role types...
1982 return num_to_get;
1983 }
1984
1985 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::ElementBlock *eb,
1986 const Ioss::Field &field, void *data,
1987 size_t data_size) const
1988 {
1989 size_t num_to_get = field.verify(data_size);
1990
1991 Ioss::Field::RoleType role = field.get_role();
1992
1993 if (role == Ioss::Field::MESH) {
1994 // Handle the MESH fields required for a CGNS file model.
1995 // (The 'genesis' portion)
1996 if (field.get_name() == "ids") {
1997 size_t proc_offset = eb->get_property("proc_offset").get_int();
1998 handle_element_ids(eb, data, num_to_get, proc_offset, num_to_get);
1999 }
2000 else if (field.get_name() == "connectivity") {
2001 // This blocks zone has not been defined.
2002 // Get the "node block" for this element block...
2003 size_t element_nodes = eb->topology()->number_nodes();
2004 assert((size_t)field.raw_storage()->component_count() == element_nodes);
2005
2006 CGNSIntVector nodes;
2007 nodes.reserve(element_nodes * num_to_get);
2008
2009 if (field.get_type() == Ioss::Field::INT32) {
2010 int *idata = num_to_get > 0 ? reinterpret_cast<int *>(data) : nullptr;
2011 for (size_t i = 0; i < element_nodes * num_to_get; i++) {
2012 nodes.push_back(idata[i]);
2013 }
2014 }
2015 else {
2016 int64_t *idata = num_to_get > 0 ? reinterpret_cast<int64_t *>(data) : nullptr;
2017 for (size_t i = 0; i < element_nodes * num_to_get; i++) {
2018 nodes.push_back(idata[i]);
2019 }
2020 }
2021 Ioss::Utils::uniquify(nodes);
2022
2023 // Resolve zone-shared nodes (nodes used in this zone, but are
2024 // shared on processor boundaries).
2025 // This routine determines the mapping of each global id node
2026 // in 'nodes' to the zone-local position.
2027 // This mapping is in 'connectivity_map' and is correct for all
2028 // nodes on this processor whether they are owned or shared.
2029 //
2030 // 'resolve_zone_shared_nodes' also returns the number of nodes owned on this
2031 // processor, and the 'offset' of this processors chunk of nodes into the overall
2032 // set of nodes for the zone. Each processors chunk of nodes is contiguous
2033 //
2034 // The 'nodes' and 'connectivity_map' vectors are used later below to generate
2035 // the map of which global node data is written by this processor for this zone.
2036 CGNSIntVector connectivity_map(nodes.size());
2037 size_t owned_node_count = 0;
2038 size_t owned_node_offset = 0;
2039 resolve_zone_shared_nodes(nodes, connectivity_map, owned_node_count, owned_node_offset);
2040
2041 // Get total count on all processors...
2042 // Note that there will be shared nodes on processor boundaries that need to be
2043 // accounted for...
2044 cgsize_t size[3] = {0, 0, 0};
2045 size[0] = owned_node_count;
2046 size[1] = eb->entity_count();
2047
2048 MPI_Allreduce(MPI_IN_PLACE, size, 3, cgns_mpi_type(), MPI_SUM, util().communicator());
2049
2050 // Now, we have the node count and cell count so we can create a zone...
2051 int base = 1;
2052 int zone = 0;
2053
2054 CGCHECKM(cg_zone_write(get_file_pointer(), base, eb->name().c_str(), size,
2055 CGNS_ENUMV(Unstructured), &zone));
2056 eb->property_update("zone", zone);
2057 eb->property_update("id", zone);
2058 eb->property_update("guid", util().generate_guid(zone));
2059 eb->property_update("section", 1);
2060 eb->property_update("base", base);
2061 eb->property_update("zone_node_count", size[0]);
2062 eb->property_update("zone_element_count", size[1]);
2063
2064 if (eb->property_exists("assembly")) {
2065 std::string assembly = eb->get_property("assembly").get_string();
2066 CGCHECKM(cg_goto(get_file_pointer(), base, "Zone_t", zone, "end"));
2067 CGCHECKM(cg_famname_write(assembly.c_str()));
2068 }
2069
2070 if (size[1] > 0) {
2071 CGNS_ENUMT(ElementType_t) type = Utils::map_topology_to_cgns(eb->topology()->name());
2072 int sect = 0;
2073 std::string element_type =
2074 fmt::format("{}Elements", Ioss::Utils::shape_to_string(eb->topology()->shape()));
2075 CGCHECKM(cgp_section_write(get_file_pointer(), base, zone, element_type.c_str(), type, 1,
2076 size[1], 0, &sect));
2077
2078 int64_t start = 0;
2079 MPI_Exscan(&num_to_get, &start, 1, Ioss::mpi_type(start), MPI_SUM, util().communicator());
2080 // Of the cells/elements in this zone, this proc handles
2081 // those starting at 'proc_offset+1' to 'proc_offset+num_entity'
2082 eb->property_update("proc_offset", start);
2083
2084 // Map connectivity global ids to zone-local 1-based ids.
2085 CGNSIntVector connect;
2086 connect.reserve(num_to_get * element_nodes);
2087
2088 if (field.get_type() == Ioss::Field::INT32) {
2089 int *idata = num_to_get > 0 ? reinterpret_cast<int *>(data) : nullptr;
2090 for (size_t i = 0; i < num_to_get * element_nodes; i++) {
2091 auto id = idata[i];
2092 auto iter = std::lower_bound(nodes.cbegin(), nodes.cend(), id);
2093 assert(iter != nodes.end());
2094 auto cur_pos = iter - nodes.cbegin();
2095 connect.push_back(connectivity_map[cur_pos]);
2096 }
2097 }
2098 else {
2099 int64_t *idata = num_to_get > 0 ? reinterpret_cast<int64_t *>(data) : nullptr;
2100 for (size_t i = 0; i < num_to_get * element_nodes; i++) {
2101 auto id = idata[i];
2102 auto iter = std::lower_bound(nodes.cbegin(), nodes.cend(), id);
2103 assert(iter != nodes.cend());
2104 auto cur_pos = iter - nodes.cbegin();
2105 connect.push_back(connectivity_map[cur_pos]);
2106 }
2107 }
2108
2109 Utils::unmap_cgns_connectivity(eb->topology(), num_to_get, Data(connect));
2110 CGCHECKM(cgp_elements_write_data(get_file_pointer(), base, zone, sect, start + 1,
2111 start + num_to_get, Data(connect)));
2112
2113 int64_t eb_size = num_to_get;
2114 MPI_Allreduce(MPI_IN_PLACE, &eb_size, 1, Ioss::mpi_type(eb_size), MPI_SUM,
2115 util().communicator());
2116
2117 m_bcOffset[zone] += eb_size;
2118 eb->property_update("section", sect);
2119 }
2120
2121 // The 'nodes' map needs to be updated to filter out any nodes
2122 // that are not owned by this processor. Currently contains both
2123 // owned and shared so we could update the connectivity...
2124 // The 'connectivity_map' value indicates whether it is owned or shared --
2125 // if 'connectivity_map[i] > owned_node_offset, then it is owned; otherwise shared.
2126 if (!nodes.empty()) {
2127 for (size_t i = 0; i < nodes.size(); i++) {
2128 if (connectivity_map[i] <= (cgsize_t)owned_node_offset) {
2129 nodes[i] = std::numeric_limits<cgsize_t>::max();
2130 }
2131 }
2132 connectivity_map.clear();
2133 connectivity_map.shrink_to_fit();
2134
2135 Ioss::Utils::uniquify(nodes);
2136 if (nodes.back() == std::numeric_limits<cgsize_t>::max()) {
2137 nodes.pop_back();
2138 }
2139 nodes.shrink_to_fit();
2140 }
2141 assert(nodes.size() == owned_node_count);
2142
2143 // Now we have a valid zone so can update some data structures...
2144 m_zoneOffset[zone] = m_zoneOffset[zone - 1] + size[1];
2145 m_globalToBlockLocalNodeMap[zone] =
2146 new Ioss::Map("node", get_filename() + "::" + eb->name(), myProcessor);
2147 m_globalToBlockLocalNodeMap[zone]->map().reserve(nodes.size() + 1);
2148 m_globalToBlockLocalNodeMap[zone]->map().push_back(1); // Non one-to-one map
2149 for (auto &i : nodes) {
2150 m_globalToBlockLocalNodeMap[zone]->map().push_back(i);
2151 }
2152 }
2153 else {
2154 num_to_get = Ioss::Utils::field_warning(eb, field, "output");
2155 }
2156 }
2157 else if (role == Ioss::Field::TRANSIENT) {
2158 double *rdata = num_to_get > 0 ? static_cast<double *>(data) : nullptr;
2159
2160 int base = eb->get_property("base").get_int();
2161 int zone = eb->get_property("zone").get_int();
2162
2163 cgsize_t start = eb->get_property("proc_offset").get_int();
2164 cgsize_t range_min[1] = {start + 1};
2165 cgsize_t range_max[1] = {(cgsize_t)start + (cgsize_t)num_to_get};
2166
2167 // get number of components, cycle through each component
2168 size_t comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
2169 if (comp_count == 1) {
2170 int cgns_field = 0;
2171 CGCHECKM(cgp_field_write(get_file_pointer(), base, zone, m_currentCellCenterSolutionIndex,
2172 CGNS_ENUMV(RealDouble), field.get_name().c_str(), &cgns_field));
2173 CGCHECKM(cgp_field_write_data(get_file_pointer(), base, zone,
2174 m_currentCellCenterSolutionIndex, cgns_field, range_min,
2175 range_max, rdata));
2176 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(CellCenter));
2177 }
2178 else {
2179 std::vector<double> cgns_data(num_to_get);
2180 for (size_t i = 0; i < comp_count; i++) {
2181 for (size_t j = 0; j < num_to_get; j++) {
2182 cgns_data[j] = rdata[comp_count * j + i];
2183 }
2184 std::string var_name = get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
2185 int cgns_field = 0;
2186 CGCHECKM(cgp_field_write(get_file_pointer(), base, zone, m_currentCellCenterSolutionIndex,
2187 CGNS_ENUMV(RealDouble), var_name.c_str(), &cgns_field));
2188 CGCHECKM(cgp_field_write_data(get_file_pointer(), base, zone,
2189 m_currentCellCenterSolutionIndex, cgns_field, range_min,
2190 range_max, Data(cgns_data)));
2191 if (i == 0) {
2192 Utils::set_field_index(field, cgns_field, CGNS_ENUMV(CellCenter));
2193 }
2194 }
2195 }
2196 }
2197 else {
2198 num_to_get = Ioss::Utils::field_warning(eb, field, "unknown");
2199 }
2200 return num_to_get;
2201 }
2202
2203 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::StructuredBlock *sb,
2204 const Ioss::Field &field, void *data,
2205 size_t data_size) const
2206 {
2207 Ioss::Field::RoleType role = field.get_role();
2208 cgsize_t base = sb->get_property("base").get_int();
2209 cgsize_t zone = Iocgns::Utils::get_db_zone(sb);
2210
2211 cgsize_t num_to_get = field.verify(data_size);
2212
2213 cgsize_t rmin[3] = {0, 0, 0};
2214 cgsize_t rmax[3] = {0, 0, 0};
2215
2216 bool cell_field = Utils::is_cell_field(field);
2217
2218 if (cell_field) {
2219 assert(num_to_get == sb->get_property("cell_count").get_int());
2220 if (num_to_get > 0) {
2221 rmin[0] = sb->get_property("offset_i").get_int() + 1;
2222 rmin[1] = sb->get_property("offset_j").get_int() + 1;
2223 rmin[2] = sb->get_property("offset_k").get_int() + 1;
2224
2225 rmax[0] = rmin[0] + sb->get_property("ni").get_int() - 1;
2226 rmax[1] = rmin[1] + sb->get_property("nj").get_int() - 1;
2227 rmax[2] = rmin[2] + sb->get_property("nk").get_int() - 1;
2228 }
2229 }
2230 else {
2231 // cell nodal field.
2232 assert(num_to_get == sb->get_property("node_count").get_int());
2233 if (num_to_get > 0) {
2234 rmin[0] = sb->get_property("offset_i").get_int() + 1;
2235 rmin[1] = sb->get_property("offset_j").get_int() + 1;
2236 rmin[2] = sb->get_property("offset_k").get_int() + 1;
2237
2238 rmax[0] = rmin[0] + sb->get_property("ni").get_int();
2239 rmax[1] = rmin[1] + sb->get_property("nj").get_int();
2240 rmax[2] = rmin[2] + sb->get_property("nk").get_int();
2241 }
2242 }
2243
2244 assert(num_to_get == 0 || num_to_get == (rmax[0] - rmin[0] + 1) * (rmax[1] - rmin[1] + 1) *
2245 (rmax[2] - rmin[2] + 1));
2246 double *rdata = num_to_get > 0 ? static_cast<double *>(data) : nullptr;
2247
2248 if (role == Ioss::Field::MESH) {
2249 int crd_idx = 0;
2250 if (field.get_name() == "mesh_model_coordinates_x") {
2251 CGCHECKM(cgp_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2252 "CoordinateX", &crd_idx));
2253 CGCHECKM(cgp_coord_write_data(get_file_pointer(), base, zone, crd_idx, rmin, rmax, rdata));
2254 }
2255
2256 else if (field.get_name() == "mesh_model_coordinates_y") {
2257 CGCHECKM(cgp_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2258 "CoordinateY", &crd_idx));
2259 CGCHECKM(cgp_coord_write_data(get_file_pointer(), base, zone, crd_idx, rmin, rmax, rdata));
2260 }
2261
2262 else if (field.get_name() == "mesh_model_coordinates_z") {
2263 CGCHECKM(cgp_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble),
2264 "CoordinateZ", &crd_idx));
2265 CGCHECKM(cgp_coord_write_data(get_file_pointer(), base, zone, crd_idx, rmin, rmax, rdata));
2266 }
2267
2268 else if (field.get_name() == "mesh_model_coordinates") {
2269 int phys_dimension = get_region()->get_property("spatial_dimension").get_int();
2270
2271 std::vector<double> coord(num_to_get);
2272
2273 // ========================================================================
2274 // Repetitive code for each coordinate direction; use a lambda to consolidate...
2275 auto coord_lambda = [&coord, phys_dimension, rmax, rmin, base, zone, &rdata, num_to_get,
2276 this](const char *ordinate, int ordinal) {
2277 // Data required by upper classes store x0, y0, z0, ... xn,
2278 // yn, zn. Data stored in cgns file is x0, ..., xn, y0,
2279 // ..., yn, z0, ..., zn so we have to allocate some scratch
2280 // memory to read in the data and then map into supplied
2281 // 'data'
2282 // Map to global coordinate position...
2283 for (cgsize_t i = 0; i < num_to_get; i++) {
2284 coord[i] = rdata[phys_dimension * i + ordinal];
2285 }
2286
2287 int idx = 0;
2288 CGCHECKM(cgp_coord_write(get_file_pointer(), base, zone, CGNS_ENUMV(RealDouble), ordinate,
2289 &idx));
2290 CGCHECKM(
2291 cgp_coord_write_data(get_file_pointer(), base, zone, idx, rmin, rmax, Data(coord)));
2292 };
2293 // ========================================================================
2294
2295 coord_lambda("CoordinateX", 0);
2296
2297 if (phys_dimension >= 2) {
2298 coord_lambda("CoordinateY", 1);
2299 }
2300
2301 if (phys_dimension == 3) {
2302 coord_lambda("CoordinateZ", 2);
2303 }
2304 }
2305 else {
2306 num_to_get = Ioss::Utils::field_warning(sb, field, "output");
2307 }
2308 }
2309 else if (role == Ioss::Field::TRANSIENT) {
2310 int cgns_field = 0;
2311 int comp_count = field.get_component_count(Ioss::Field::InOut::OUTPUT);
2312 int sol_index = 0;
2313 CGNS_ENUMT(GridLocation_t) location;
2314 if (cell_field) {
2315 sol_index = m_currentCellCenterSolutionIndex;
2316 location = CGNS_ENUMV(CellCenter);
2317 }
2318 else {
2319 sol_index = m_currentVertexSolutionIndex;
2320 location = CGNS_ENUMV(Vertex);
2321 }
2322 if (comp_count == 1) {
2323 CGCHECKM(cgp_field_write(get_file_pointer(), base, zone, sol_index, CGNS_ENUMV(RealDouble),
2324 field.get_name().c_str(), &cgns_field));
2325 Utils::set_field_index(field, cgns_field, location);
2326
2327 CGCHECKM(cgp_field_write_data(get_file_pointer(), base, zone, sol_index, cgns_field, rmin,
2328 rmax, rdata));
2329 }
2330 else {
2331 std::vector<double> cgns_data(num_to_get);
2332 for (int i = 0; i < comp_count; i++) {
2333 for (cgsize_t j = 0; j < num_to_get; j++) {
2334 cgns_data[j] = rdata[comp_count * j + i];
2335 }
2336 std::string var_name = get_component_name(field, Ioss::Field::InOut::OUTPUT, i + 1);
2337
2338 CGCHECKM(cgp_field_write(get_file_pointer(), base, zone, sol_index,
2339 CGNS_ENUMV(RealDouble), var_name.c_str(), &cgns_field));
2340 if (i == 0) {
2341 Utils::set_field_index(field, cgns_field, location);
2342 }
2343
2344 CGCHECKM(cgp_field_write_data(get_file_pointer(), base, zone, sol_index, cgns_field, rmin,
2345 rmax, Data(cgns_data)));
2346 }
2347 }
2348 }
2349 else {
2350 num_to_get = Ioss::Utils::field_warning(sb, field, "output");
2351 }
2352 return num_to_get;
2353 }
2354
2355 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::FaceBlock * /* nb */,
2356 const Ioss::Field & /* field */, void * /* data */,
2357 size_t /* data_size */) const
2358 {
2359 return -1;
2360 }
2361 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::EdgeBlock * /* nb */,
2362 const Ioss::Field & /* field */, void * /* data */,
2363 size_t /* data_size */) const
2364 {
2365 return -1;
2366 }
2367 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::NodeSet * /* ns */,
2368 const Ioss::Field & /* field */, void * /* data */,
2369 size_t /* data_size */) const
2370 {
2371 return -1;
2372 }
2373 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::EdgeSet * /* ns */,
2374 const Ioss::Field & /* field */, void * /* data */,
2375 size_t /* data_size */) const
2376 {
2377 return -1;
2378 }
2379 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::FaceSet * /* ns */,
2380 const Ioss::Field & /* field */, void * /* data */,
2381 size_t /* data_size */) const
2382 {
2383 return -1;
2384 }
2385 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::ElementSet * /* ns */,
2386 const Ioss::Field & /* field */, void * /* data */,
2387 size_t /* data_size */) const
2388 {
2389 return -1;
2390 }
2391 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::SideBlock *sb,
2392 const Ioss::Field &field, void *data,
2393 size_t data_size) const
2394 {
2395 const Ioss::EntityBlock *parent_block = sb->parent_block();
2396 if (parent_block == nullptr) {
2397 std::ostringstream errmsg;
2398 fmt::print(errmsg,
2399 "ERROR: CGNS: SideBlock {} does not have a parent-block specified. This is "
2400 "required for CGNS output.",
2401 sb->name());
2402 IOSS_ERROR(errmsg);
2403 }
2404
2405 int base = parent_block->get_property("base").get_int();
2406 int zone = parent_block->get_property("zone").get_int();
2407 auto num_to_get = field.verify(data_size);
2408
2409 Ioss::Field::RoleType role = field.get_role();
2410
2411 if (role == Ioss::Field::MESH) {
2412 // Handle the MESH fields required for a CGNS file model.
2413 // (The 'genesis' portion)
2414 if (field.get_name() == "element_side") {
2415 CGNS_ENUMT(ElementType_t) type = Utils::map_topology_to_cgns(sb->topology()->name());
2416 int sect = 0;
2417
2418 int64_t size = num_to_get;
2419 MPI_Allreduce(MPI_IN_PLACE, &size, 1, Ioss::mpi_type(size), MPI_SUM, util().communicator());
2420
2421 int cg_start = m_bcOffset[zone] + 1;
2422 int cg_end = m_bcOffset[zone] + size;
2423
2424 // NOTE: Currently not writing the "ElementConnectivity" data for the
2425 // boundary condition. It isn't used in the read and don't have
2426 // the data so would have to generate it. This may cause problems
2427 // with codes that use the downstream data if they base the BC off
2428 // of the nodes instead of the element/side info.
2429 // Get name from parent sideset... This is name of the ZoneBC entry
2430 auto &name = sb->owner()->name();
2431 // This is the name of the BC_t node
2432 auto sb_name = Iocgns::Utils::decompose_sb_name(sb->name());
2433
2434 CGNSIntVector point_range{cg_start, cg_end};
2435 CGCHECKM(cg_boco_write(get_file_pointer(), base, zone, name.c_str(),
2436 CGNS_ENUMV(FamilySpecified), CGNS_ENUMV(PointRange), 2,
2437 Data(point_range), &sect));
2438 CGCHECKM(
2439 cg_goto(get_file_pointer(), base, "Zone_t", zone, "ZoneBC_t", 1, "BC_t", sect, "end"));
2440 CGCHECKM(cg_famname_write(name.c_str()));
2441
2442 int phys_dimension = get_region()->get_property("spatial_dimension").get_int();
2443 auto location = phys_dimension == 2 ? CGNS_ENUMV(EdgeCenter) : CGNS_ENUMV(FaceCenter);
2444 CGCHECKM(cg_boco_gridlocation_write(get_file_pointer(), base, zone, sect, location));
2445
2446 CGCHECKM(cgp_section_write(get_file_pointer(), base, zone, sb_name.c_str(), type, cg_start,
2447 cg_end, 0, &sect));
2448
2449 sb->property_update("section", sect);
2450
2451 CGNSIntVector parent(4 * num_to_get);
2452
2453 if (field.get_type() == Ioss::Field::INT32) {
2454 int *idata = reinterpret_cast<int *>(data);
2455 size_t j = 0;
2456 for (size_t i = 0; i < num_to_get; i++) {
2457 parent[num_to_get * 0 + i] = elemMap.global_to_local(idata[j++]); // Element
2458 parent[num_to_get * 2 + i] = idata[j++];
2459 }
2460 }
2461 else {
2462 auto *idata = reinterpret_cast<int64_t *>(data);
2463 size_t j = 0;
2464 for (size_t i = 0; i < num_to_get; i++) {
2465 parent[num_to_get * 0 + i] = elemMap.global_to_local(idata[j++]); // Element
2466 parent[num_to_get * 2 + i] = idata[j++];
2467 }
2468 }
2469 // Adjust face numbers to CGNS convention instead of IOSS convention...
2470 Utils::map_ioss_face_to_cgns(sb->parent_element_topology(), num_to_get, parent);
2471 map_local_to_global_implicit(parent, num_to_get, m_elemGlobalImplicitMap);
2472
2473 int64_t local_face_count = num_to_get;
2474 int64_t local_face_offset = 0;
2475 MPI_Exscan(&local_face_count, &local_face_offset, 1, Ioss::mpi_type(local_face_count),
2476 MPI_SUM, util().communicator());
2477 cg_start = m_bcOffset[zone] + local_face_offset + 1;
2478 cg_end = cg_start + local_face_count - 1;
2479
2480 auto xx = num_to_get > 0 ? Data(parent) : nullptr;
2481 if (num_to_get == 0) {
2482 cg_start = cg_end = 0;
2483 }
2484 CGCHECKM(cgp_parent_data_write(get_file_pointer(), base, zone, sect, cg_start, cg_end, xx));
2485 m_bcOffset[zone] += size;
2486 }
2487 else if (field.get_name() == "distribution_factors") {
2488 static bool warning_output = false;
2489 if (!warning_output) {
2490 if (myProcessor == 0) {
2491 fmt::print(Ioss::WarnOut(),
2492 "For CGNS output, the sideset distribution factors are not output.\n");
2493 }
2494 warning_output = true;
2495 }
2496 return 0;
2497 }
2498 else {
2499 num_to_get = Ioss::Utils::field_warning(sb, field, "output");
2500 }
2501 }
2502 else {
2503 num_to_get = Ioss::Utils::field_warning(sb, field, "output");
2504 }
2505 return num_to_get;
2506 }
2507 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::SideSet * /* fs */,
2508 const Ioss::Field & /* field */, void * /* data */,
2509 size_t /* data_size */) const
2510 {
2511 return -1;
2512 }
2513 int64_t ParallelDatabaseIO::put_field_internal(const Ioss::CommSet * /* cs */,
2514 const Ioss::Field & /* field*/, void * /*data*/,
2515 size_t /*data_size*/) const
2516 {
2517 return -1;
2518 }
2519
2520 void ParallelDatabaseIO::write_results_meta_data() {}
2521
2522 unsigned ParallelDatabaseIO::entity_field_support() const
2523 {
2524 return Ioss::NODEBLOCK | Ioss::ELEMENTBLOCK | Ioss::STRUCTUREDBLOCK | Ioss::NODESET |
2525 Ioss::SIDESET | Ioss::REGION;
2526 }
2527
2528 int64_t ParallelDatabaseIO::handle_node_ids(void *ids, int64_t num_to_get) const
2529 {
2530 /*!
2531 * There are two modes we need to support in this routine:
2532 * 1. Initial definition of node map (local->global) and
2533 * nodeMap.reverse (global->local).
2534 * 2. Redefinition of node map via 'reordering' of the original
2535 * map when the nodes on this processor are the same, but their
2536 * order is changed (or count because of ghosting)
2537 *
2538 * So, there will be two maps the 'nodeMap.map' map is a 'direct lookup'
2539 * map which maps current local position to global id and the
2540 * 'nodeMap.reverse' is an associative lookup which maps the
2541 * global id to 'original local'. There is also a
2542 * 'nodeMap.reorder' which is direct lookup and maps current local
2543 * position to original local.
2544
2545 * The ids coming in are the global ids; their position is the
2546 * "local id-1" (That is, data[0] contains the global id of local
2547 * node 1 in this node block).
2548 *
2549 * int local_position = nodeMap.reverse[NodeMap[i+1]]
2550 * (the nodeMap.map and nodeMap.reverse are 1-based)
2551 *
2552 * To determine which map to update on a call to this function, we
2553 * use the following heuristics:
2554 * -- If the database state is 'STATE_MODEL:', then update the
2555 * 'nodeMap.reverse' and 'nodeMap.map'
2556 *
2557 * -- If the database state is not STATE_MODEL, then leave the
2558 * 'nodeMap.reverse' and 'nodeMap.map' alone since they correspond to the
2559 * information already written to the database. [May want to add a
2560 * STATE_REDEFINE_MODEL]
2561 *
2562 * -- In both cases, update the nodeMap.reorder
2563 *
2564 * NOTE: The mapping is done on TRANSIENT fields only; MODEL fields
2565 * should be in the original order...
2566 */
2567 if (!nodeMap.defined()) {
2568 nodeMap.set_size(num_to_get);
2569
2570 bool in_define = (dbState == Ioss::STATE_MODEL) || (dbState == Ioss::STATE_DEFINE_MODEL);
2571 if (nodeMap.is_sequential()) {
2572 if (int_byte_size_api() == 4) {
2573 nodeMap.set_map(static_cast<int *>(ids), num_to_get, 0, in_define);
2574 }
2575 else {
2576 nodeMap.set_map(static_cast<int64_t *>(ids), num_to_get, 0, in_define);
2577 }
2578 }
2579
2580 // Only a single nodeblock and all set
2581 assert(get_region()->get_property("node_block_count").get_int() == 1);
2582 nodeMap.set_defined(true);
2583 }
2584 return num_to_get;
2585 }
2586
2587 std::vector<int64_t> ParallelDatabaseIO::get_processor_zone_node_offset() const
2588 {
2589 size_t num_zones = m_globalToBlockLocalNodeMap.size();
2590 std::vector<int64_t> node_count(num_zones);
2591 std::vector<int64_t> node_offset(num_zones);
2592
2593 for (const auto &block : m_globalToBlockLocalNodeMap) {
2594 auto zone = block.first;
2595 const auto &block_map = block.second;
2596 node_count[zone - 1] = block_map->size();
2597 }
2598 MPI_Exscan(Data(node_count), Data(node_offset), num_zones, Ioss::mpi_type(node_count[0]),
2599 MPI_SUM, util().communicator());
2600
2601 return node_offset;
2602 }
2603
2604 } // namespace Iocgns
2605 #else
2606 /*
2607 * Prevent warning in some versions of ranlib(1) because the object
2608 * file has no symbols.
2609 */
2610 const char ioss_cgns_parallel_database_unused_symbol_dummy = '\0';
2611 #endif