Debian Codegraph @

packages/seacas/libraries/ioss/src/Ioss_DynamicTopologyFileControl.C

raw
1 // Copyright(C) 2024 National Technology & Engineering Solutions
2 // of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
3 // NTESS, the U.S. Government retains certain rights in this software.
4 //
5 // See packages/seacas/LICENSE for details
6
7 #include "Ioss_Assembly.h"
8 #include "Ioss_Blob.h"
9 #include "Ioss_ChangeSet.h"
10 #include "Ioss_ChangeSetFactory.h"
11 #include "Ioss_CodeTypes.h"
12 #include "Ioss_CommSet.h"
13 #include "Ioss_DBUsage.h"
14 #include "Ioss_DatabaseIO.h"
15 #include "Ioss_DynamicTopology.h"
16 #include "Ioss_DynamicTopologyFileControl.h"
17 #include "Ioss_EdgeBlock.h"
18 #include "Ioss_EdgeSet.h"
19 #include "Ioss_ElementBlock.h"
20 #include "Ioss_ElementSet.h"
21 #include "Ioss_EntityBlock.h"
22 #include "Ioss_EntityType.h"
23 #include "Ioss_FaceBlock.h"
24 #include "Ioss_FaceSet.h"
25 #include "Ioss_Field.h"
26 #include "Ioss_FileInfo.h"
27 #include "Ioss_GroupingEntity.h"
28 #include "Ioss_IOFactory.h"
29 #include "Ioss_NodeBlock.h"
30 #include "Ioss_NodeSet.h"
31 #include "Ioss_ParallelUtils.h"
32 #include "Ioss_Region.h"
33 #include "Ioss_SideBlock.h"
34 #include "Ioss_SideSet.h"
35 #include "Ioss_StructuredBlock.h"
36
37 #include <fmt/core.h>
38 #include <fmt/format.h>
39 #include <fmt/ostream.h>
40
41 #include <assert.h>
42 #include <climits>
43 #include <cstddef>
44 #include <functional>
45 #include <iomanip>
46 #include <sstream>
47
48 namespace {
49
50 bool file_exists(const Ioss::ParallelUtils &util, const std::string &filename,
51 const std::string &db_type, Ioss::DatabaseUsage db_usage)
52 {
53 int par_size = util.parallel_size();
54 int par_rank = util.parallel_rank();
55 bool is_parallel = par_size > 1;
56 std::string full_filename = filename;
57 if (is_parallel && (db_type == "exodusII" || db_type == "cgns") &&
58 (db_usage != Ioss::WRITE_HISTORY)) {
59 full_filename = Ioss::Utils::decode_filename(filename, par_rank, par_size);
60 }
61
62 std::string message;
63 Ioss::FileInfo file = Ioss::FileInfo(full_filename);
64 return file.parallel_exists(util.communicator(), message);
65 }
66
67 template <typename T>
68 void update_database_for_grouping_entities(const T &container, Ioss::DatabaseIO *db)
69 {
70 for (auto *entity : container) {
71 Ioss::GroupingEntity *ge = dynamic_cast<Ioss::GroupingEntity *>(entity);
72 assert(ge != nullptr);
73
74 if (ge->type() == Ioss::SIDESET) {
75 Ioss::SideSet *sset = dynamic_cast<Ioss::SideSet *>(ge);
76 assert(sset != nullptr);
77
78 sset->reset_database(db);
79 const auto &sblocks = sset->get_side_blocks();
80 for (const auto &sblock : sblocks) {
81 sblock->reset_database(db);
82 }
83 }
84 else {
85 ge->reset_database(db);
86 }
87 }
88 }
89
90 } // namespace
91
92 namespace Ioss {
93
94 DynamicTopologyFileControl::DynamicTopologyFileControl(Region *region)
95 : m_region(region), m_fileCyclicCount(region->get_file_cyclic_count()),
96 m_ifDatabaseExists(region->get_if_database_exists_behavior()),
97 m_dbChangeCount(region->get_topology_change_count())
98 {
99 if (nullptr == region) {
100 std::ostringstream errmsg;
101 fmt::print(errmsg, "ERROR: null region passed in as argument to DynamicTopologyFileControl");
102 IOSS_ERROR(errmsg);
103 }
104
105 m_ioDB = region->get_property("base_filename").get_string();
106 m_dbType = region->get_property("database_type").get_string();
107 }
108
109 const ParallelUtils &DynamicTopologyFileControl::util() const
110 {
111 return m_region->get_database()->util();
112 }
113
114 bool DynamicTopologyFileControl::file_exists(const std::string &filename,
115 const std::string &db_type,
116 Ioss::DatabaseUsage db_usage)
117 {
118 return ::file_exists(util(), filename, db_type, db_usage);
119 }
120
121 std::string DynamicTopologyFileControl::get_unique_linear_filename(Ioss::DatabaseUsage db_usage)
122 {
123 std::string filename = m_ioDB;
124
125 do {
126 // Run this loop at least once for all files. If this is an automatic
127 // restart, then make sure that the generated file does not already exist,
128 // so keep running the loop until we generate a filename that doesn't exist...
129 std::ostringstream tmp_filename;
130 tmp_filename << m_ioDB;
131
132 // Don't append the "-s000X" the first time in case the base filename doesn't
133 // exist -- we want write to the name specified by the user if at all possible and
134 // once that exists, then start adding on the suffix...
135 if (m_dbChangeCount > 1) {
136 tmp_filename << "-s" << std::setw(4) << std::setfill('0') << m_dbChangeCount;
137 }
138 filename = tmp_filename.str();
139 ++m_dbChangeCount;
140 } while (file_exists(filename, m_dbType, db_usage));
141 --m_dbChangeCount;
142 return filename;
143 }
144
145 std::string DynamicTopologyFileControl::get_internal_file_change_set_name(unsigned int step)
146 {
147 std::ostringstream change_setname;
148 change_setname << change_set_prefix();
149 change_setname << step;
150 return change_setname.str();
151 }
152
153 std::string DynamicTopologyFileControl::get_cyclic_database_filename(
154 const std::string &baseFileName, unsigned int fileCyclicCount, unsigned int step)
155 {
156 return ChangeSet::get_cyclic_database_filename(baseFileName, fileCyclicCount, step);
157 }
158
159 std::string
160 DynamicTopologyFileControl::get_linear_database_filename(const std::string &baseFileName,
161 unsigned int step)
162 {
163 return ChangeSet::get_linear_database_filename(baseFileName, step);
164 }
165
166 std::string DynamicTopologyFileControl::construct_database_filename(int &step,
167 Ioss::DatabaseUsage db_usage)
168 {
169 // Filename will be of the form -- ioDB-sxxxx where xxxx is step
170 // number. Assume maximum of 9999 steps (will do more, but won't have
171 // good lineup of step numbers.
172 // Check database for validity (filename and a type)
173 if (m_ioDB.empty() || m_dbType.empty()) {
174 std::string error_message;
175 if (m_dbType.empty())
176 error_message += "The database TYPE has not been defined\n";
177
178 if (m_ioDB.empty()) {
179 error_message += "The database FILENAME has not been defined\n";
180 }
181 std::ostringstream errmsg;
182 errmsg << error_message;
183 IOSS_ERROR(errmsg);
184 }
185 assert(!m_ioDB.empty());
186 assert(!m_dbType.empty());
187 std::string filename = m_ioDB;
188 if (m_fileCyclicCount > 0) {
189 // In this mode, we close the old file and open a new file
190 // every time this is called. The file suffix cycles through
191 // the first fileCyclicCount'th entries in A,B,C,D,E,F,...
192
193 // filename = get_cyclic_database_filename(m_ioDB, m_fileCyclicCount, step);
194 if (step == 0)
195 step++;
196
197 static std::string suffix = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
198 std::string tmp = "-" + suffix.substr((step - 1) % m_fileCyclicCount, 1);
199 filename += tmp;
200 m_properties.add(Ioss::Property("APPEND_OUTPUT", Ioss::DB_OVERWRITE));
201 }
202 else {
203 if (m_region->model_is_written()) {
204 // After the initial open, we want to add suffix if the topology changes
205 // during the run
206 m_ifDatabaseExists = Ioss::DB_ADD_SUFFIX_OVERWRITE;
207 }
208
209 // Handle complications of DB_APPEND mode...
210 // If in DB_APPEND mode, then we don't output metadata
211 // information, so some knowledge is needed at this level if
212 // we are appending. If user specified APPEND, but the file
213 // doesn't yet exist OR it does exist and we are not
214 // restarting, change the mode to OVERWRITE.
215 // 0. Must be restarting; either manual or automatic.
216 std::shared_ptr<DynamicTopologyObserver> observer =
217 m_region->get_mesh_modification_observer();
218
219 if (m_ifDatabaseExists == Ioss::DB_APPEND) {
220 if (!observer->is_restart_requested()) {
221 // Not restarting
222 m_ifDatabaseExists = Ioss::DB_OVERWRITE;
223 }
224 else if (!file_exists(m_ioDB, m_dbType, db_usage)) {
225 m_ifDatabaseExists = Ioss::DB_OVERWRITE;
226 }
227 }
228 if (step > 1 || (m_dbChangeCount > 1)) {
229 // Use the !is_input_event test since restart input files already have the
230 // -s000x extension...
231 if (m_ifDatabaseExists == Ioss::DB_APPEND) {
232 std::ostringstream tmp_filename;
233 tmp_filename << m_ioDB;
234 filename = m_ioDB;
235 if (m_dbChangeCount > 1) {
236 tmp_filename << "-s" << std::setw(4) << std::setfill('0') << m_dbChangeCount;
237 }
238 size_t inc = 0;
239 while (file_exists(tmp_filename.str(), m_dbType, db_usage)) {
240 filename = tmp_filename.str();
241 tmp_filename.clear();
242 tmp_filename.str("");
243 tmp_filename << m_ioDB << "-s" << std::setw(4) << std::setfill('0')
244 << m_dbChangeCount + (++inc);
245 }
246 if (inc > 0) {
247 m_dbChangeCount += (inc - 1);
248 }
249 else {
250 m_ifDatabaseExists = Ioss::DB_OVERWRITE;
251 }
252 }
253 else if (m_ifDatabaseExists == Ioss::DB_ADD_SUFFIX) {
254 filename = get_unique_linear_filename(db_usage);
255 }
256 else if (m_ifDatabaseExists == Ioss::DB_ADD_SUFFIX_OVERWRITE) {
257 if (m_dbChangeCount > 0) {
258 std::ostringstream tmp_filename;
259 tmp_filename << m_ioDB << "-s" << std::setw(4) << std::setfill('0')
260 << ++m_dbChangeCount;
261 filename = tmp_filename.str();
262 }
263 else {
264 filename = m_ioDB;
265 }
266 }
267 else {
268 filename = m_ioDB;
269 }
270 }
271 else if (m_ifDatabaseExists == Ioss::DB_ADD_SUFFIX) {
272 filename = get_unique_linear_filename(db_usage);
273 }
274 else {
275 filename = m_ioDB;
276 }
277
278 m_properties.add(Ioss::Property("APPEND_OUTPUT", m_ifDatabaseExists));
279 // A little complicated on deciding whether we are actually
280 // overwriting the database. The 'validate' routine for Results and
281 // History will call create_database once the parser block is
282 // ended. This routine will then create the database and the
283 // ioRegion_. However, the database will not really be opened or
284 // written to at this time. If the code is auto-restarting, then it will
285 // detect that the database exists and create a database with the
286 // -s000x extension.
287 // At this point, we need to skip the 'abort_if_exists' test if we
288 // are in this routine from the 'validate' and we are restarting
289 // since we won't really write to the file. So, the cases where we
290 // *don't* check are:
291 // -- is_input_event(db_usage)
292 // -- ifExists_ == DB_OVERWRITE || DB_ADD_SUFFIX_OVERWRITE || DB_APPEND
293 // -- is_automatic_restart() && step == 0 (coming from validate)
294 if (m_ifDatabaseExists != DB_OVERWRITE && m_ifDatabaseExists != DB_APPEND &&
295 m_ifDatabaseExists != DB_ADD_SUFFIX_OVERWRITE &&
296 !(step == 0 && observer->is_automatic_restart())) {
297 abort_if_exists(filename, m_dbType, db_usage);
298 }
299 }
300 return filename;
301 }
302
303 bool DynamicTopologyFileControl::abort_if_exists(const std::string &filename,
304 const std::string &db_type,
305 Ioss::DatabaseUsage db_usage)
306 {
307 // Check whether file with same name as database already exists. If so,
308 // print error message and stop...
309 // At the current time, only check on processor 0 and assume if it doesn't exist
310 // there, then it doesn't exist on other processors. Or, if it doesn't exist on
311 // processor 0, then it doesn't matter if it doesn't exist on other processors
312 // since we don't have all pieces...
313
314 bool exists = file_exists(filename, db_type, db_usage);
315 if (exists) {
316 std::ostringstream errmsg;
317 fmt::print(errmsg,
318 "ERROR: The database file named '{} exists"
319 "and would be overwritten if the code continued.\n\n"
320 "Input options specified that this file *not* be overwritten,\n"
321 "\tso you must rename or remove this file and restart the code.\n",
322 filename);
323 IOSS_ERROR(errmsg);
324 }
325 return exists;
326 }
327
328 Ioss::DatabaseIO *DynamicTopologyFileControl::clone_output_database(int steps)
329 {
330 auto current_db = m_region->get_database();
331
332 if (current_db->is_input())
333 return nullptr;
334
335 const Ioss::PropertyManager &current_properties = current_db->get_property_manager();
336 Ioss::NameList names = current_properties.describe();
337
338 // Iterate through properties and transfer to new output database...
339 for (const auto &name : names) {
340 if (!m_properties.exists(name))
341 m_properties.add(current_properties.get(name));
342 }
343
344 auto db_usage = current_db->usage();
345
346 std::string filename = construct_database_filename(steps, db_usage);
347
348 Ioss::DatabaseIO *db = Ioss::IOFactory::create(m_dbType, filename, db_usage,
349 current_db->util().communicator(), m_properties);
350
351 if (nullptr == db) {
352 std::ostringstream errmsg;
353 fmt::print(errmsg,
354 "ERROR: unable to create output database named '{}'"
355 " of type '{}'",
356 filename, m_dbType);
357 IOSS_ERROR(errmsg);
358 }
359
360 assert(db != nullptr);
361 if (!db->ok(true)) {
362 std::ostringstream errmsg;
363 fmt::print(errmsg,
364 "ERROR: unable to validate output database named '{}'"
365 " of type '{}'",
366 filename, m_dbType);
367 IOSS_ERROR(errmsg);
368 }
369
370 db->set_field_separator(current_db->get_field_separator());
371 db->set_surface_split_type(current_db->get_surface_split_type());
372 db->set_maximum_symbol_length(current_db->maximum_symbol_length());
373 db->set_int_byte_size_api(current_db->int_byte_size_data_size());
374
375 return db;
376 }
377
378 bool DynamicTopologyFileControl::replace_output_database(Ioss::DatabaseIO *db)
379 {
380 auto current_db = m_region->get_database();
381
382 if (current_db->is_input())
383 return false;
384
385 current_db->finalize_database();
386 current_db->closeDatabase();
387 delete current_db;
388
389 m_region->reset_database(db);
390 db->set_region(m_region);
391
392 update_database_for_grouping_entities(m_region->get_node_blocks(), db);
393 update_database_for_grouping_entities(m_region->get_edge_blocks(), db);
394 update_database_for_grouping_entities(m_region->get_face_blocks(), db);
395 update_database_for_grouping_entities(m_region->get_element_blocks(), db);
396 update_database_for_grouping_entities(m_region->get_sidesets(), db);
397 update_database_for_grouping_entities(m_region->get_nodesets(), db);
398 update_database_for_grouping_entities(m_region->get_edgesets(), db);
399 update_database_for_grouping_entities(m_region->get_facesets(), db);
400 update_database_for_grouping_entities(m_region->get_elementsets(), db);
401 update_database_for_grouping_entities(m_region->get_commsets(), db);
402 update_database_for_grouping_entities(m_region->get_structured_blocks(), db);
403 update_database_for_grouping_entities(m_region->get_assemblies(), db);
404 update_database_for_grouping_entities(m_region->get_blobs(), db);
405
406 return true;
407 }
408
409 void DynamicTopologyFileControl::clone_and_replace_output_database(int steps)
410 {
411 auto db = clone_output_database(steps);
412
413 if (nullptr != db)
414 replace_output_database(db);
415 }
416
417 void DynamicTopologyFileControl::add_output_database_change_set(IOSS_MAYBE_UNUSED int steps)
418 {
419 auto current_db = get_database();
420
421 std::ostringstream oss;
422 oss << change_set_prefix();
423 oss << m_dbChangeCount;
424
425 current_db->release_memory();
426 current_db->create_internal_change_set(oss.str());
427
428 m_dbChangeCount++;
429 }
430
431 DatabaseIO *DynamicTopologyFileControl::get_database() const { return m_region->get_database(); }
432
433 } // namespace Ioss