v0.16.3
Loading...
Searching...
No Matches
ageing_field_tags.cpp
Go to the documentation of this file.
1/** \file ageing_field_tags.cpp
2 * \brief Write the history tags of the Amentum ageing UMAT on mesh vertices,
3 * from text files of nodal values indexed by vertex GLOBAL_ID.
4 *
5 * See doc/development/field_tags.md and doc/development/field_tags_tool.md.
6 */
7
8#include <MoFEM.hpp>
9#include <cmath>
10#include <cstring>
11#include <filesystem>
12#include <fstream>
13#include <iomanip>
14#include <sstream>
15#include <unordered_set>
16
17using namespace MoFEM;
18namespace fs = std::filesystem;
19
20static char help[] =
21 "Write the nodal history tags MED_IRRA_ALLIRRA_<k>, MED_TEMP_ALLNEUT_<k>\n"
22 "and MED_CORR_ALLNEUT_<k> of the Amentum ageing UMAT from files\n"
23 "<fvs_dir>/<prefix><label>.fvs with lines \"GLOBAL_ID, value\".\n\n";
24
25/** True if name is <prefix>_<k>, k an unsigned integer. */
26static bool isStepTag(const std::string &name, const std::string &prefix) {
27 const auto start = prefix.size() + 1;
28 return name.size() > start && name.compare(0, prefix.size(), prefix) == 0 &&
29 name[prefix.size()] == '_' &&
30 std::all_of(name.begin() + start, name.end(),
31 [](unsigned char c) { return std::isdigit(c); });
32}
33
35
36 AgeingFieldTags(MoFEM::Interface &m_field) : mField(m_field) {}
37
39
40private:
42
43 /** One history read by the UMAT, one file per label. Step k is the k-th
44 * label in ascending order, stored in tag <tagPrefix>_<k>. */
45 struct Quantity {
46 std::string name;
47 std::string option; ///< Option giving the file name prefix.
48 std::string filePrefix;
49 std::string tagPrefix;
50 bool accumulated; ///< Does not decrease in time.
51 bool percent; ///< Given in percent.
52 std::map<int, fs::path> files; ///< Label to file.
53 std::vector<std::vector<double>> values; ///< By step, then by node.
54 };
55
56 std::array<Quantity, 3> quantities{
57 {{"dose", "-irra_prefix", "D_", "MED_IRRA_ALLIRRA", true, false},
58 {"temperature", "-temp_prefix", "T_", "MED_TEMP_ALLNEUT", false, false},
59 {"weight loss", "-corr_prefix", "WL_", "MED_CORR_ALLNEUT", true, true}}};
60
62 double labelTime = 1; ///< Time of label 1, full-power years.
63
64 Range nodes; ///< Corner nodes of 3D elements.
65 std::vector<int> nodeIds; ///< GLOBAL_ID of each node.
66 std::unordered_map<int, int> nodeIndex; ///< GLOBAL_ID to index in nodes.
67 std::unordered_set<int> otherIds; ///< GLOBAL_IDs of other vertices.
68
73 MoFEMErrorCode readFile(const fs::path &file, std::vector<double> &values,
74 int &skipped) const;
80};
81
97
100 if (mField.get_comm_size() != 1)
102 "Run on one rank, on the mesh before partitioning");
103
104 // PetscOptionsString leaves the value unchanged when the option is not set.
105 char mesh_file[PETSC_MAX_PATH_LEN] = "mesh.h5m";
106 char output_file[PETSC_MAX_PATH_LEN] = "";
107 char fvs_dir[PETSC_MAX_PATH_LEN] = ".";
108 char history_file[PETSC_MAX_PATH_LEN] = "";
109 std::array<std::array<char, PETSC_MAX_PATH_LEN>, 3> prefixes{};
110 for (int q = 0; q != quantities.size(); ++q)
111 std::strncpy(prefixes[q].data(), quantities[q].filePrefix.c_str(),
112 PETSC_MAX_PATH_LEN - 1);
113
114 PetscOptionsBegin(mField.get_comm(), "", "Ageing UMAT field tags", "none");
115 CHKERR PetscOptionsString("-file_name", "input mesh", "", "mesh.h5m",
116 mesh_file, PETSC_MAX_PATH_LEN, PETSC_NULLPTR);
117 CHKERR PetscOptionsString("-output_file", "output mesh", "", "", output_file,
118 PETSC_MAX_PATH_LEN, PETSC_NULLPTR);
119 CHKERR PetscOptionsString("-fvs_dir", "directory of the nodal files", "", ".",
120 fvs_dir, PETSC_MAX_PATH_LEN, PETSC_NULLPTR);
121 for (int q = 0; q != quantities.size(); ++q)
122 CHKERR PetscOptionsString(quantities[q].option.c_str(), "file name prefix",
123 "", quantities[q].filePrefix.c_str(),
124 prefixes[q].data(), PETSC_MAX_PATH_LEN,
125 PETSC_NULLPTR);
126 CHKERR PetscOptionsString("-history_file", "ageing history file to write", "",
127 "", history_file, PETSC_MAX_PATH_LEN,
128 PETSC_NULLPTR);
129 CHKERR PetscOptionsReal("-label_time", "time of label 1, full-power years",
130 "", labelTime, &labelTime, PETSC_NULLPTR);
131 PetscOptionsEnd();
132
133 meshFile = mesh_file;
134 outputFile = output_file;
135 fvsDir = fvs_dir;
136 historyFile = history_file;
137 for (int q = 0; q != quantities.size(); ++q)
138 quantities[q].filePrefix = prefixes[q].data();
139
140 if (outputFile.empty())
142 "Give the output mesh with -output_file");
143 std::error_code ec;
144 if (fs::equivalent(meshFile, outputFile, ec))
146 "-output_file %s is the input mesh; give another name",
147 outputFile.c_str());
149}
150
153 if (!fs::is_directory(fvsDir))
154 SETERRQ(mField.get_comm(), MOFEM_NOT_FOUND, "No directory %s (-fvs_dir)",
155 fvsDir.c_str());
156
157 const std::string ext = ".fvs";
158 for (auto &q : quantities) {
159 const auto &prefix = q.filePrefix;
160 for (const auto &entry : fs::directory_iterator(fvsDir)) {
161 const auto name = entry.path().filename().string();
162 if (name.size() <= prefix.size() + ext.size() ||
163 name.compare(0, prefix.size(), prefix) != 0 ||
164 name.compare(name.size() - ext.size(), ext.size(), ext) != 0)
165 continue;
166 const auto label =
167 name.substr(prefix.size(), name.size() - prefix.size() - ext.size());
168 if (!std::all_of(label.begin(), label.end(),
169 [](unsigned char c) { return std::isdigit(c); }))
170 continue;
171 const auto [it, inserted] =
172 q.files.emplace(std::stoi(label), entry.path());
173 if (!inserted)
175 "%s and %s have the same label", it->second.c_str(),
176 entry.path().c_str());
177 }
178 if (q.files.empty())
180 "No %s files %s<label>.fvs in %s (%s)", q.name.c_str(),
181 prefix.c_str(), fvsDir.c_str(), q.option.c_str());
182 }
183
184 auto labels = [](const Quantity &q) {
185 std::string list;
186 for (const auto &f : q.files)
187 list += (list.empty() ? "" : " ") + std::to_string(f.first);
188 return list;
189 };
190 const auto &first = quantities[0];
191 for (const auto &q : quantities)
192 if (labels(q) != labels(first))
194 "File labels differ: %s has %s, %s has %s",
195 first.filePrefix.c_str(), labels(first).c_str(),
196 q.filePrefix.c_str(), labels(q).c_str());
197
198 MOFEM_LOG("WORLD", Sev::inform)
199 << "Labels " << labels(first) << " are steps 0 to "
200 << first.files.size() - 1;
202}
203
206 auto &moab = mField.get_moab();
207 Range vols, verts;
208 CHKERR moab.get_entities_by_dimension(0, 3, vols);
209 if (vols.empty())
211 "%s has no 3D elements", meshFile.c_str());
212 CHKERR moab.get_connectivity(vols, nodes, true);
213 CHKERR moab.get_entities_by_type(0, MBVERTEX, verts);
214
215 nodeIds.resize(nodes.size());
216 CHKERR moab.tag_get_data(moab.globalId_tag(), nodes, nodeIds.data());
217 for (int i = 0; i != nodeIds.size(); ++i) {
218 if (nodeIds[i] <= 0)
220 "A node has GLOBAL_ID %d; number the vertices first, for "
221 "example by reading the MED file with read_med",
222 nodeIds[i]);
223 if (!nodeIndex.emplace(nodeIds[i], i).second)
225 "GLOBAL_ID %d is on two nodes", nodeIds[i]);
226 }
227
228 const auto others = subtract(verts, nodes);
229 std::vector<int> other_ids(others.size());
230 CHKERR moab.tag_get_data(moab.globalId_tag(), others, other_ids.data());
231 otherIds.insert(other_ids.begin(), other_ids.end());
232
233 MOFEM_LOG("WORLD", Sev::inform)
234 << nodes.size() << " corner nodes of " << vols.size()
235 << " 3D elements in " << meshFile;
237}
238
241 for (auto &q : quantities) {
242 int skipped = 0;
243 for (const auto &f : q.files) {
244 int file_skipped;
245 q.values.emplace_back();
246 CHKERR readFile(f.second, q.values.back(), file_skipped);
247 skipped += file_skipped;
248 }
249 MOFEM_LOG("WORLD", Sev::inform)
250 << "Read " << q.files.size() << " " << q.name << " files";
251 if (skipped)
252 MOFEM_LOG("WORLD", Sev::inform)
253 << "Skipped " << skipped << " " << q.name
254 << " values of vertices that are not corner nodes of 3D elements";
255 }
257}
258
259/** Values of the nodes from lines "GLOBAL_ID, value", separated by a comma,
260 * spaces or both. Blank lines and lines starting with # are skipped. Values
261 * of other vertices are skipped and counted. */
263 std::vector<double> &values,
264 int &skipped) const {
266 std::ifstream in(file);
267 if (!in)
268 SETERRQ(mField.get_comm(), MOFEM_OPERATION_UNSUCCESSFUL, "Cannot open %s",
269 file.c_str());
270
271 values.assign(nodes.size(), 0);
272 std::vector<bool> seen(nodes.size(), false);
273 std::unordered_set<int> seen_other;
274 skipped = 0;
275
276 std::string line;
277 for (int line_nb = 1; std::getline(in, line); ++line_nb) {
278 const auto start = line.find_first_not_of(" \t\r");
279 if (start == std::string::npos || line[start] == '#')
280 continue;
281 std::replace(line.begin(), line.end(), ',', ' ');
282 std::istringstream is(line);
283 int id;
284 double value;
285 if (!(is >> id >> value) || !(is >> std::ws).eof())
287 "%s:%d: expected \"GLOBAL_ID, value\"", file.c_str(), line_nb);
288 if (!std::isfinite(value))
290 "%s:%d: value is not finite", file.c_str(), line_nb);
291
292 bool twice = false;
293 if (const auto it = nodeIndex.find(id); it != nodeIndex.end()) {
294 twice = seen[it->second];
295 seen[it->second] = true;
296 values[it->second] = value;
297 } else if (otherIds.count(id)) {
298 twice = !seen_other.insert(id).second;
299 ++skipped;
300 } else {
302 "%s:%d: GLOBAL_ID %d is not a vertex of the mesh", file.c_str(),
303 line_nb, id);
304 }
305 if (twice)
307 "%s:%d: GLOBAL_ID %d given twice", file.c_str(), line_nb, id);
308 }
309
310 std::vector<int> missing;
311 for (int i = 0; i != seen.size(); ++i)
312 if (!seen[i])
313 missing.push_back(nodeIds[i]);
314 if (!missing.empty()) {
315 std::string first;
316 for (int i = 0; i != std::min<int>(missing.size(), 5); ++i)
317 first += " " + std::to_string(missing[i]);
319 "%s: no value for %zu nodes, GLOBAL_ID%s%s", file.c_str(),
320 missing.size(), first.c_str(), missing.size() > 5 ? " ..." : "");
321 }
323}
324
325/** Log the range of each quantity. Warn, without stopping, where dose or
326 * weight loss decreases and where weight loss looks like a fraction. */
329 for (const auto &q : quantities) {
330 double min = std::numeric_limits<double>::max();
331 double max = std::numeric_limits<double>::lowest();
332 int step = 0;
333 for (const auto &f : q.files) {
334 const auto [lo, hi] =
335 std::minmax_element(q.values[step].begin(), q.values[step].end());
336 MOFEM_LOG("WORLD", Sev::verbose)
337 << q.tagPrefix << "_" << step << " label " << f.first << " from "
338 << *lo << " to " << *hi;
339 min = std::min(min, *lo);
340 max = std::max(max, *hi);
341 ++step;
342 }
343 MOFEM_LOG("WORLD", Sev::inform)
344 << q.name << " from " << min << " to " << max;
345
346 if (q.accumulated) {
347 int decreasing = 0;
348 for (int k = 1; k < q.values.size(); ++k)
349 for (int i = 0; i != nodes.size(); ++i)
350 decreasing += q.values[k][i] < q.values[k - 1][i];
351 if (decreasing)
352 MOFEM_LOG("WORLD", Sev::warning)
353 << q.name << " decreases from one step to the next at "
354 << decreasing << " node values";
355 }
356 if (q.percent && max > 0 && max <= 1)
357 MOFEM_LOG("WORLD", Sev::warning)
358 << q.name << " is at most 1; the UMAT expects percent "
359 << "(10.0 is 10 %), not a fraction";
360 }
362}
363
364/** Delete the history tags of the input mesh, of any step, so the output
365 * holds only the steps of the files. Then set the tags on the nodes. */
368 auto &moab = mField.get_moab();
369
370 std::vector<Tag> tags;
371 CHKERR moab.tag_get_tags(tags);
372 int deleted = 0;
373 for (auto th : tags) {
374 std::string name;
375 CHKERR moab.tag_get_name(th, name);
376 for (const auto &q : quantities)
377 if (isStepTag(name, q.tagPrefix)) {
378 CHKERR moab.tag_delete(th);
379 ++deleted;
380 break;
381 }
382 }
383 if (deleted)
384 MOFEM_LOG("WORLD", Sev::inform)
385 << "Deleted " << deleted << " history tags of the input mesh";
386
387 for (const auto &q : quantities) {
388 for (int k = 0; k != q.values.size(); ++k) {
389 const auto name = q.tagPrefix + "_" + std::to_string(k);
390 Tag th;
391 CHKERR moab.tag_get_handle(name.c_str(), 1, MB_TYPE_DOUBLE, th,
392 MB_TAG_CREAT | MB_TAG_DENSE | MB_TAG_EXCL);
393 CHKERR moab.tag_set_data(th, nodes, q.values[k].data());
394 }
395 MOFEM_LOG("WORLD", Sev::inform)
396 << "Set " << q.tagPrefix << "_0 to " << q.tagPrefix << "_"
397 << q.values.size() - 1 << " on " << nodes.size() << " nodes";
398 }
400}
401
402/** Lines "time step", time = label * labelTime. */
405 if (!historyFile.empty()) {
406 std::ofstream out(historyFile);
407 out << std::setprecision(12);
408 int step = 0;
409 for (const auto &f : quantities[0].files)
410 out << f.first * labelTime << " " << step++ << "\n";
411 out.close();
412 if (!out)
414 "Cannot write %s", historyFile.c_str());
415 MOFEM_LOG("WORLD", Sev::inform) << "Wrote " << historyFile;
416 }
418}
419
423 CHKERR testing->addTestCommandLine("", 1, "one_hex",
424 [this]() { return checkOneHex(); });
425 CHKERR testing->runTests();
427}
428
429/** Test one_hex: run on meshes/one_hex_with_tags.h5m with the files D_, T_
430 * and WL_ of meshes/fvs_one_hex and -label_time 0.5. At the vertex with
431 * GLOBAL_ID i and label L the files give dose i + 10 L, temperature
432 * 300 + i + L and weight loss i / 2 + L, for labels 0, 5 and 12. The output
433 * is read back. */
437 const std::vector<int> labels{0, 5, 12};
438 const std::array<std::function<double(int, int)>, 3> expected{
439 [](int i, int l) { return i + 10. * l; },
440 [](int i, int l) { return 300. + i + l; },
441 [](int i, int l) { return 0.5 * i + l; }};
442
443 moab::Core mb;
444 CHKERR mb.load_file(outputFile.c_str());
445 Range verts, vols;
446 CHKERR mb.get_entities_by_type(0, MBVERTEX, verts);
447 CHKERR mb.get_entities_by_dimension(0, 3, vols);
448 std::vector<int> ids(verts.size());
449 CHKERR mb.tag_get_data(mb.globalId_tag(), verts, ids.data());
450
451 int nb_tags = 0, on_elements = 0;
452 double error = 0;
453 std::vector<Tag> tags;
454 CHKERR mb.tag_get_tags(tags);
455 for (auto th : tags) {
456 std::string name;
457 CHKERR mb.tag_get_name(th, name);
458 for (int q = 0; q != quantities.size(); ++q) {
459 const auto &prefix = quantities[q].tagPrefix;
460 if (!isStepTag(name, prefix))
461 continue;
462 ++nb_tags;
463 for (auto e : vols) {
464 double v;
465 on_elements += mb.tag_get_data(th, &e, 1, &v) == MB_SUCCESS;
466 }
467 const int step = std::stoi(name.substr(prefix.size() + 1));
468 if (step >= labels.size())
469 continue;
470 std::vector<double> values(verts.size());
471 CHKERR mb.tag_get_data(th, verts, values.data());
472 for (int i = 0; i != verts.size(); ++i)
473 error = std::max(
474 error, std::abs(values[i] - expected[q](ids[i], labels[step])));
475 }
476 }
477
478 std::ifstream in(historyFile);
479 int lines = 0;
480 double history_error = 0, time;
481 int step;
482 while (in >> time >> step) {
483 if (lines < labels.size())
484 history_error =
485 std::max(history_error, std::abs(time - 0.5 * labels[lines]) +
486 std::abs(step - lines));
487 ++lines;
488 }
489
490 CHKERR testing->checkValue<TestType::SCALAR>(
491 "history tags", nb_tags, quantities.size() * labels.size(), {0, 0});
492 CHKERR testing->checkValue<TestType::SCALAR>("history tags on elements",
493 on_elements, 0, {0, 0});
494 CHKERR testing->checkValue<TestType::SCALAR>("nodal values", error, 0,
495 {1e-12, 0});
496 CHKERR testing->checkValue<TestType::SCALAR>("history lines", lines,
497 labels.size(), {0, 0});
498 CHKERR testing->checkValue<TestType::SCALAR>("history times and steps",
499 history_error, 0, {1e-12, 0});
501}
502
503int main(int argc, char *argv[]) {
504 MoFEM::Core::Initialize(&argc, &argv, (char *)0, help);
505
506 try {
507 moab::Core mb_instance;
508 moab::Interface &moab = mb_instance;
509 MoFEM::Core core(moab);
510 MoFEM::Interface &m_field = core;
511
512 MOFEM_LOG_CHANNEL("WORLD");
513 MOFEM_LOG_TAG("WORLD", "ageing_field_tags");
515 }
517
519
520 return 0;
521}
std::map< EntityHandle, int > labels
std::vector< int > label
moab::Interface & mb
It it
Definition Schur.cpp:2568
SmartPetscObj< Vec > values
std::string name
int main()
static char help[]
static bool isStepTag(const std::string &name, const std::string &prefix)
#define CATCH_ERRORS
Catch errors.
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
@ MOFEM_NOT_FOUND
Definition definitions.h:33
@ MOFEM_OPERATION_UNSUCCESSFUL
Definition definitions.h:34
@ MOFEM_DATA_INCONSISTENCY
Definition definitions.h:31
@ MOFEM_INVALID_DATA
Definition definitions.h:36
@ MOFEM_NOT_IMPLEMENTED
Definition definitions.h:32
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define CHKERR
Inline error check.
#define MOFEM_LOG(channel, severity)
Log.
#define MOFEM_LOG_TAG(channel, tag)
Tag channel.
#define MOFEM_LOG_CHANNEL(channel)
Set and reset channel.
FTensor::Index< 'i', SPACE_DIM > i
PetscBool testing
const double c
speed of light (cm/ns)
const double v
phase velocity of light in medium (cm/ns)
FTensor::Index< 'l', 3 > l
FTensor::Index< 'k', 3 > k
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
implementation of Data Operators for Forces and Sources
Definition Common.hpp:10
double q
bool accumulated
Does not decrease in time.
std::map< int, fs::path > files
Label to file.
std::string option
Option giving the file name prefix.
std::vector< std::vector< double > > values
By step, then by node.
bool percent
Given in percent.
MoFEMErrorCode checkHistories() const
MoFEMErrorCode checkResults()
MoFEMErrorCode getOptions()
MoFEMErrorCode findFiles()
AgeingFieldTags(MoFEM::Interface &m_field)
double labelTime
Time of label 1, full-power years.
std::array< Quantity, 3 > quantities
MoFEMErrorCode readFile(const fs::path &file, std::vector< double > &values, int &skipped) const
MoFEMErrorCode runProblem()
MoFEMErrorCode writeHistory() const
std::unordered_set< int > otherIds
GLOBAL_IDs of other vertices.
MoFEMErrorCode checkOneHex() const
MoFEM::Interface & mField
std::vector< int > nodeIds
GLOBAL_ID of each node.
MoFEMErrorCode writeTags()
Range nodes
Corner nodes of 3D elements.
MoFEMErrorCode readFiles()
std::unordered_map< int, int > nodeIndex
GLOBAL_ID to index in nodes.
MoFEMErrorCode selectNodes()
virtual int get_comm_size() const =0
virtual moab::Interface & get_moab()=0
virtual MPI_Comm & get_comm() const =0
Core (interface) class.
Definition Core.hpp:83
static MoFEMErrorCode Initialize(int *argc, char ***args, const char file[], const char help[])
Initializes the MoFEM database PETSc, MOAB and MPI.
Definition Core.cpp:68
static MoFEMErrorCode Finalize()
Checks for options to be called at the conclusion of the program.
Definition Core.cpp:123
Deprecated interface functions.
virtual MoFEMErrorCode addTestCommandLine(const std::string &prefix, int number, const std::string &name, TestHook hook)=0
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.