openCARP
Doxygen code documentation for the open cardiac electrophysiology simulator openCARP
sim_utils.cc
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: Copyright (c) NumeriCor GmbH
2 // SPDX-License-Identifier: LicenseRef-APL-1.1
3 
12 #include "backend.h"
13 #include "basics.h"
14 #include "sim_utils.h"
15 #include "fem.h"
16 #include "physics.h"
17 #include "async_io.h"
18 #include "SF_init.h"
19 #include "opencarp_types.h"
20 #ifdef WITH_LEADFIELD
21 #include "leadfield.h"
22 #endif
23 #ifdef WITH_POWERCAPPING
24 #include <vector>
25 #include "powercapping.h"
26 #endif
27 
28 #include <cstdlib>
29 #include <libgen.h>
30 #include <iomanip>
31 #include <map>
32 #include <string>
33 #include <unistd.h>
34 #include <vector>
35 
36 #include "openCARP_schema.hpp"
37 #include "runtime.hpp"
38 
39 namespace opencarp {
40 
41 namespace {
42 
43 std::vector<paramschema::CitationSuggestion> active_citation_suggestions;
44 
45 bool match_long_option(const std::string& token, const char* option, std::string* attached_value)
46 {
47  *attached_value = std::string();
48  if (token == option) {
49  return true;
50  }
51 
52  const std::string prefix = std::string(option) + "=";
53  if (token.size() > prefix.size() && token.compare(0, prefix.size(), prefix) == 0) {
54  *attached_value = token.substr(prefix.size());
55  return true;
56  }
57 
58  return false;
59 }
60 
61 bool is_help_topic_candidate(const char* token)
62 {
63  return token != NULL && token[0] != '\0' && token[0] != '-' && token[0] != '+';
64 }
65 
66 bool is_long_option_argument_error(const std::string& token,
67  const char* option,
68  const std::string& attached_value,
69  std::string* error)
70 {
71  if (attached_value.empty()) {
72  return false;
73  }
74 
75  *error = "Unexpected argument for " + std::string(option) + " in '" + token + "'";
76  return true;
77 }
78 
79 bool normalize_runtime_args(int argc,
80  char** argv,
81  std::vector<std::string>* normalized,
82  std::string* error)
83 {
84  normalized->clear();
85 
86  if (argc <= 0 || argv == NULL || argv[0] == NULL) {
87  *error = "Missing program name";
88  return false;
89  }
90 
91  normalized->push_back(argv[0]);
92 
93  for (int i = 1; i < argc; ++i) {
94  const std::string token = argv[i];
95  if (token == "+") {
96  break;
97  }
98 
99  std::string attached_value;
100 
101  if (token == "+Help" || match_long_option(token, "--help", &attached_value)) {
102  std::string topic = "PrM";
103  if (!attached_value.empty()) {
104  topic = attached_value;
105  } else if (i + 1 < argc && is_help_topic_candidate(argv[i + 1])) {
106  topic = argv[++i];
107  }
108  normalized->push_back("+Help");
109  normalized->push_back(topic);
110  break;
111  }
112 
113  if (token == "+Doc" || match_long_option(token, "--doc", &attached_value)) {
114  std::string topic = "ALL";
115  if (!attached_value.empty()) {
116  topic = attached_value;
117  } else if (i + 1 < argc && is_help_topic_candidate(argv[i + 1])) {
118  topic = argv[++i];
119  }
120  normalized->push_back("+Doc");
121  normalized->push_back(topic);
122  break;
123  }
124 
125  if (token == "+Default" || match_long_option(token, "--default", &attached_value)) {
126  if (token != "+Default" && is_long_option_argument_error(token, "--default", attached_value, error)) {
127  return false;
128  }
129  normalized->push_back("+Default");
130  break;
131  }
132 
133  if (token == "+Run" || match_long_option(token, "--run", &attached_value)) {
134  if (token != "+Run" && is_long_option_argument_error(token, "--run", attached_value, error)) {
135  return false;
136  }
137  normalized->push_back("+Run");
138  continue;
139  }
140 
141  if (token == "+I" || match_long_option(token, "--interactive", &attached_value)) {
142  if (!attached_value.empty()) {
143  *error = "Unexpected argument for --interactive in '" + token + "'";
144  } else {
145  *error = "Unsupported option " + token + " (interactive mode is not available)";
146  }
147  return false;
148  }
149 
150  if (token == "+F" || match_long_option(token, "--file", &attached_value)) {
151  std::string filename = attached_value;
152  if (filename.empty()) {
153  if (i + 1 >= argc) {
154  *error = "Missing filename after " + token;
155  return false;
156  }
157  filename = argv[++i];
158  }
159  normalized->push_back("+F");
160  normalized->push_back(filename);
161  continue;
162  }
163 
164  if (token == "+Save" || match_long_option(token, "--save", &attached_value)) {
165  std::string filename = attached_value;
166  if (filename.empty()) {
167  if (i + 1 >= argc) {
168  *error = "Missing argument after " + token;
169  return false;
170  }
171  filename = argv[++i];
172  }
173  normalized->push_back("+Save");
174  normalized->push_back(filename);
175  continue;
176  }
177 
178  normalized->push_back(token);
179  }
180 
181  return true;
182 }
183 
184 void populate_arg_pointers(const std::vector<std::string>& values, std::vector<char*>* argv)
185 {
186  argv->assign(values.size(), NULL);
187  for (std::size_t i = 0; i < values.size(); ++i) {
188  (*argv)[i] = const_cast<char*>(values[i].c_str());
189  }
190 }
191 
192 void print_lines(FILE* stream, const char* label, const std::vector<std::string>& lines)
193 {
194  for (std::size_t i = 0; i < lines.size(); ++i) {
195  fprintf(stream, "%s%s\n", label, lines[i].c_str());
196  }
197 }
198 
199 void clear_active_citation_suggestions()
200 {
201  active_citation_suggestions.clear();
202 }
203 
204 void store_active_citation_suggestions(const std::vector<paramschema::CitationSuggestion>& suggestions)
205 {
206  active_citation_suggestions = suggestions;
207 }
208 
209 void print_active_citation_suggestions()
210 {
211  if (active_citation_suggestions.empty() || get_rank() != 0) {
212  return;
213  }
214 
215  const std::vector<std::string> lines =
216  paramschema::format_citation_suggestions(active_citation_suggestions);
217  if (lines.empty()) {
218  return;
219  }
220 
221  std::fprintf(stdout, "\nIf you publish studies based on this simulation, the following references are likely relevant:\n");
222  for (std::size_t i = 0; i < lines.size(); ++i) {
223  std::fprintf(stdout, " %s\n", lines[i].c_str());
224  }
225  std::fprintf(stdout, " You can use https://citation.doi.org to format references in your preferred format or https://www.doi2bib.org to turn the DOIs into BibTeX format.\n");
226  std::fprintf(stdout, "\nWe'd be happy to also see your experiment published to boost its impact and foster reproducibility.\nSee https://opencarp.org/community/upload-experiment for details.\n\n");
227 
228  std::fflush(stdout);
229 }
230 
231 void print_parser_runtime_state(const std::vector<std::string>& runtime_args)
232 {
233  const auto& schema = paramschema::openCARP_schema();
234  const std::string program_name =
235  runtime_args.empty() || runtime_args[0].empty() ? "openCARP" : runtime_args[0];
236 
237  std::string rendered;
238  std::vector<std::string> errors;
239  if (!paramschema::render_save_text(schema, program_name, &rendered, &errors)) {
240  print_lines(stderr, "parameter parser warning: ", errors);
241  return;
242  }
243 
244  fputs(rendered.c_str(), stderr);
245 }
246 
247 paramschema::ExecutionResult execute_parser_runtime_args(const std::vector<std::string>& runtime_args)
248 {
249  std::vector<char*> argv;
250  populate_arg_pointers(runtime_args, &argv);
251 
252  const auto& schema = paramschema::openCARP_schema();
253 
254  return paramschema::execute_legacy_cli(schema, static_cast<int>(argv.size()), argv.data());
255 }
256 
257 bool apply_parser_runtime_args(const std::vector<std::string>& runtime_args)
258 {
259  clear_active_citation_suggestions();
260  const paramschema::ExecutionResult executed = execute_parser_runtime_args(runtime_args);
261  print_lines(stderr, "parameter parser warning: ", executed.warnings);
262  if (!executed.rendered_output.empty()) {
263  fputs(executed.rendered_output.c_str(), stdout);
264  }
265  if (!executed.errors.empty() || executed.status == paramschema::ExecutionStatus::Fatal) {
266  print_lines(stderr, "parameter parser error: ", executed.errors);
267  return false;
268  }
269 
270  if (param_globals::output_setup) {
271  print_parser_runtime_state(runtime_args);
272  }
273 
274  if (executed.status == paramschema::ExecutionStatus::Help) {
275  exit(EXIT_SUCCESS);
276  }
277 
278  store_active_citation_suggestions(executed.citations);
279  return true;
280 }
281 
282 } // namespace
283 
284 static char input_dir[1024], // directory from which to read input
285  output_dir[1024], // directory to which to write results
286  postproc_dir[1024], // postprocessing directory
287  current_dir[1024]; // current directory
288 
289 namespace {
290 
291 void localize_gridout_nodes(sf_mesh& mesh,
292  SF::vector<mesh_int_t>& selected_nodes,
293  SF::vector<mesh_int_t>& output_idx,
294  bool async)
295 {
296  const int mpi_rank = get_rank();
297  const int mpi_size = get_size();
298  const SF::vector<mesh_int_t>& nbr = mesh.get_numbering(SF::NBR_SUBMESH);
299 
300  for(mesh_int_t& node : selected_nodes)
301  node = nbr[node];
302 
303  binary_sort(selected_nodes);
304  unique_resize(selected_nodes);
305 
306  output_idx.resize(0);
307 
308  if(async) {
309  const SF::vector<mesh_int_t>& alg_nod = mesh.pl.algebraic_nodes();
311  alg_map.reserve(alg_nod.size());
312 
313  for(mesh_int_t local_node : alg_nod)
314  alg_map[nbr[local_node]] = local_node;
315 
316  SF::vector<mesh_int_t> recv_nodes;
317  size_t buffsize = 0;
318  for(int pid = 0; pid < mpi_size; pid++) {
319  if(mpi_rank == pid) {
320  recv_nodes = selected_nodes;
321  buffsize = recv_nodes.size();
322  }
323 
324  MPI_Bcast(&buffsize, sizeof(size_t), MPI_BYTE, pid, mesh.comm);
325  recv_nodes.resize(buffsize);
326  MPI_Bcast(recv_nodes.data(), buffsize * sizeof(mesh_int_t), MPI_BYTE, pid, mesh.comm);
327 
328  for(mesh_int_t node : recv_nodes) {
329  auto it = alg_map.find(node);
330  if(it != alg_map.end())
331  output_idx.push_back(it->second);
332  }
333  }
334  } else {
335  const SF::vector<mesh_int_t>& layout = mesh.pl.algebraic_layout();
336  const mesh_int_t start = layout[mpi_rank];
337  const mesh_int_t stop = layout[mpi_rank + 1];
338 
339  SF::vector<mesh_int_t> recv_nodes;
340  size_t buffsize = 0;
341  for(int pid = 0; pid < mpi_size; pid++) {
342  if(mpi_rank == pid) {
343  recv_nodes = selected_nodes;
344  buffsize = recv_nodes.size();
345  }
346 
347  MPI_Bcast(&buffsize, sizeof(size_t), MPI_BYTE, pid, mesh.comm);
348  recv_nodes.resize(buffsize);
349  MPI_Bcast(recv_nodes.data(), buffsize * sizeof(mesh_int_t), MPI_BYTE, pid, mesh.comm);
350 
351  for(mesh_int_t node : recv_nodes) {
352  if(node >= start && node < stop)
353  output_idx.push_back(node - start);
354  }
355  }
356  }
357 
358  binary_sort(output_idx);
359  unique_resize(output_idx);
360 }
361 
362 bool mesh_has_gridout_tags(const sf_mesh& mesh,
363  const hashmap::unordered_set<int>& output_tags)
364 {
365  bool local_has_tag = false;
366  for(size_t eidx = 0; eidx < mesh.l_numelem; eidx++) {
367  if(output_tags.count(mesh.tag[eidx]) != 0) {
368  local_has_tag = true;
369  break;
370  }
371  }
372 
373  int local = local_has_tag ? 1 : 0;
374  int global = 0;
375  MPI_Allreduce(&local, &global, 1, MPI_INT, MPI_MAX, mesh.comm);
376  return global != 0;
377 }
378 
379 void extract_gridout_tag_mesh(const sf_mesh& mesh,
380  const hashmap::unordered_set<int>& output_tags,
381  sf_mesh& out_mesh)
382 {
383  SF::vector<bool> keep_elem(mesh.l_numelem, false);
384  for(size_t eidx = 0; eidx < mesh.l_numelem; eidx++)
385  keep_elem[eidx] = output_tags.count(mesh.tag[eidx]) != 0;
386 
387  out_mesh.name = mesh.name;
388  extract_mesh(keep_elem, mesh, out_mesh);
389  if(out_mesh.g_numelem == 0) {
390  log_msg(0, 5, ECHO, "gridout_tags selected no elements in \"%s\".", mesh.name.c_str());
391  EXIT(EXIT_FAILURE);
392  }
393 
394  rebalance_mesh(out_mesh);
395 
396  SF::vector<mesh_real_t> pts(mesh.xyz);
397  SF::vector<mesh_int_t> ptsidx(mesh.get_numbering(SF::NBR_REF));
398  std::list<sf_mesh*> meshlist;
399  meshlist.push_back(&out_mesh);
400  insert_points(pts, ptsidx, meshlist);
401 
403  numbering(out_mesh);
404  out_mesh.generate_par_layout();
405 }
406 
410 void extract_gridout_surface_mesh(const sf_mesh& mesh, sf_mesh& out_mesh)
411 {
412  compute_surface_mesh(mesh, SF::NBR_REF, out_mesh);
413  out_mesh.name = mesh.name;
414 
415  // the surface connectivity refers to the nodes of the parent mesh. Turn it into a
416  // node numbering of its own, so that the surface has points independent of the parent.
417  out_mesh.localize(SF::NBR_REF);
418 
419  // surface elements are created here and carry no reference numbering of their own
420  SF::vector<mesh_int_t>& ref_eidx = out_mesh.register_numbering(SF::NBR_ELEM_REF);
421  ref_eidx.resize(out_mesh.l_numelem);
422 
423  long int num_local = out_mesh.l_numelem, offset = 0;
424  MPI_Exscan(&num_local, &offset, 1, MPI_LONG, MPI_SUM, out_mesh.comm);
425  if(get_rank() == 0) offset = 0;
426  for(size_t eidx = 0; eidx < out_mesh.l_numelem; eidx++)
427  ref_eidx[eidx] = offset + eidx;
428 
429  SF::vector<mesh_real_t> pts(mesh.xyz);
430  SF::vector<mesh_int_t> ptsidx(mesh.get_numbering(SF::NBR_REF));
431  std::list<sf_mesh*> meshlist;
432  meshlist.push_back(&out_mesh);
433  insert_points(pts, ptsidx, meshlist);
434 
436  numbering(out_mesh);
437  out_mesh.generate_par_layout();
438 }
439 
443 void write_gridout_surface(const sf_mesh& mesh, const std::string& basename)
444 {
445  sf_mesh surf;
446  extract_gridout_surface_mesh(mesh, surf);
447 
448  write_points_parallel(surf, false, basename);
449 
450  sf_mesh surf_global = surf;
451  const SF::vector<mesh_int_t>& nbr = surf.get_numbering(SF::NBR_SUBMESH);
452  for(size_t i = 0; i < surf_global.con.size(); i++)
453  surf_global.con[i] = nbr[surf_global.con[i]];
454 
455  write_surface(surf_global, basename + ".surf");
456 }
457 
458 } // namespace
459 
460 void parse_params_cpy(int argc, char** argv)
461 {
462  std::vector<std::string> normalized_args;
463  std::string normalize_error;
464  if (!normalize_runtime_args(argc, argv, &normalized_args, &normalize_error)) {
465  fprintf(stderr, "\n*** %s\n\n", normalize_error.c_str());
466  exit(EXIT_FAILURE);
467  }
468 
469  if (!apply_parser_runtime_args(normalized_args)) {
470  exit(EXIT_FAILURE);
471  }
472 }
473 
474 
476 {
477  // here all the physics can be registered to the physics registry
478  // then they should be processed automatically
482 #if WITH_EMI_MODEL
483  user_globals::physics_reg[emi_phys] = new EMI();
484 #else
485  log_msg(NULL, 5, ECHO, "The EMI model was not compiled for this binary.\n");
486  exit(EXIT_FAILURE);
487 #endif
488  }
489 
492 
495 }
496 
498 {
499  log_msg(0,0,0, "\n *** Initializing physics ***\n");
500 
501  //load in the external imp modules
502 #ifdef HAVE_DLOPEN
503  for (int ii = 0; ii < param_globals::num_external_imp; ii++) {
504  int loading_succeeded = limpet::load_ionic_module(param_globals::external_imp[ii]);
505  assert(loading_succeeded);
506  }
507 #else
508  if(param_globals::num_external_imp)
509  log_msg(NULL, 4, ECHO,"Loading of external LIMPET modules not enabled.\n"
510  "Recompile with DLOPEN set.\n" );
511 #endif
512 
513  // init physics via Basic_physic interface
514  for(auto it : user_globals::physics_reg) {
515  Basic_physic* p = it.second;
516  log_msg(NULL, 0, 0, "Initializing %s ..", p->name);
517  p->initialize();
518  }
519 }
520 
522 {
523  log_msg(0,0,0, "\n *** Destroying physics ***\n");
524 
525  for(auto it : user_globals::physics_reg) {
526  Basic_physic* p = it.second;
527  log_msg(NULL, 0, 0, "Destroying %s ..", p->name);
528  p->destroy();
529  }
530 }
531 
532 // ignore_extracellular stim must be moved to stimulate.cc to be able
533 // to use all defined set operations instead of defines
534 
548 void ignore_extracellular_stim(Stimulus *st, int ns, int ignore)
549 {
550  // needs to be switch to stim enum types defined in stimulate.h
551  for ( int i=0; i<ns; i++ ) {
552  int turn_off = 0;
553  turn_off += (st[i].stimtype == Extracellular_Ground) && (ignore & NO_EXTRA_GND);
554  turn_off += (IsExtraV(st[i])) && (ignore & NO_EXTRA_V);
555  turn_off += (st[i].stimtype==Extracellular_I) && (ignore & NO_EXTRA_I);
556 
557  if (turn_off) {
558  st[i].stimtype = Ignore_Stim;
559  log_msg( NULL, 1, 0, "Extracellular stimulus %d ignored for monodomain", i );
560  } else if ( st[i].stimtype==Intracellular_I ) {
561  st[i].stimtype = Transmembrane_I;
562  log_msg( NULL, 1, 0, "Intracellular stimulus %d converted to transmembrane", i );
563  }
564  }
565 }
566 
574 int set_ignore_flags( int mode )
575 {
576  if(mode==MONODOMAIN)
577  return STM_IGNORE_MONODOMAIN;
578  if(mode==BIDOMAIN)
579  return STM_IGNORE_BIDOMAIN;
580  if(mode==PSEUDO_BIDM)
581  return STM_IGNORE_PSEUDO_BIDM;
582 
583  return IGNORE_NONE;
584 }
585 
586 
596 {
597  Stimulus* s = param_globals::stimulus;
598 
599  for(int i=0; i < param_globals::num_stim; i++) {
600  if(s[i].stimtype == Extracellular_Ground ||
601  s[i].stimtype == Extracellular_V ||
602  s[i].stimtype == Extracellular_V_OL)
603  return;
604  }
605 
606  // for now we only warn, although we should actually stop the run
607  log_msg( NULL, 4, 0,"Elliptic system is singular!\n"
608  "Use an explicit ground:voltage (stimulus[X].stimtype=3)\n"
609  "Do not trust the elliptic solution of this simulation run!\n");
610 }
611 
613 {
614  const char* real_precision = OPENCARP_REAL_BITS == 32 ? "single" : "double";
615  printf("\n""*** GIT tag: %s\n", GIT_COMMIT_TAG);
616  printf( "*** GIT hash: %s\n", GIT_COMMIT_HASH);
617  printf( "*** GIT repo: %s\n", GIT_PATH);
618  printf( "*** local index bits: %d\n", OPENCARP_LOCAL_INDEX_BITS);
619  printf( "*** global index bits: %d\n", OPENCARP_GLOBAL_INDEX_BITS);
620  printf( "*** real precision: %s (%d-bit)\n", real_precision, OPENCARP_REAL_BITS);
621  printf( "*** dependency commits: %s\n\n", SUBREPO_COMMITS);
622 }
623 
625 {
626  // convert time steps to milliseconds
627  param_globals::dt /= 1000.;
628 
629  // check parab-solve solution method
630  // explicit integration inverts the mass matrix directly, which is only feasible if it is lumped
631  if(param_globals::mass_lumping == 0 && param_globals::parab_solve==0) {
632  log_msg(0,5,0, "parab_solve = 0 (explicit) requires mass_lumping = 1. "
633  "Either enable mass lumping or choose an implicit parab_solve method.");
634  EXIT(1);
635  }
636 
637  // check if we have to modify stimuli based on used bidomain setting
638  if(!param_globals::extracell_monodomain_stim)
639  ignore_extracellular_stim(param_globals::stimulus, param_globals::num_stim,
640  set_ignore_flags(param_globals::bidomain));
641 
642  // check nullspace if necessary
643  // if((param_globals::bidomain==BIDOMAIN) ||
644  // (param_globals::bidomain==PSEUDO_BIDM))
645  // check_nullspace_ok();
646 
647  if(param_globals::t_sentinel > 0 && param_globals::sentinel_ID < 0 ) {
648  log_msg(0,4,0, "Warning: t_sentinel is set but no sentinel_ID has been specified; check_quiescence() behavior may not be as expected");
649  }
650 
651  if(param_globals::num_external_imp > 0 ) {
652  for(int ext_imp_i = 0; ext_imp_i < param_globals::num_external_imp; ext_imp_i++) {
653  if(param_globals::external_imp[ext_imp_i][0] != '/') {
654  log_msg(0,5,0, "external_imp[%d] error: absolute paths must be used for .so file loading (\'%s\')",
655  ext_imp_i, param_globals::external_imp[ext_imp_i]);
656  EXIT(1);
657  }
658  }
659  }
660 
661  if(param_globals::experiment == EXP_LAPLACE && param_globals::bidomain != 1) {
662  log_msg(0,4,0, "Warning: Laplace experiment mode requires bidomain = 1. Setting bidomain = 1.");
663  param_globals::bidomain = 1;
664  }
665 
666  if(param_globals::num_phys_regions == 0) {
667  log_msg(0,4,0, "Warning: No physics region defined! Please set phys_region parameters to correctly define physics.");
668 
669  if(param_globals::experiment != EXP_LAPLACE) {
670  log_msg(0,4,0, "Intra-elec and Extra-elec domains will be derived from fibers.\n");
671  param_globals::num_phys_regions = param_globals::bidomain ? 2 : 1;
672  param_globals::phys_region = (p_region*) calloc(param_globals::num_phys_regions, sizeof(p_region));
673  param_globals::phys_region[0].ptype = PHYSREG_INTRA_ELEC;
674  param_globals::phys_region[0].name = strdup("Autogenerated intracellular Electrics");
675  param_globals::phys_region[0].num_IDs = 0;
676 
677  if(param_globals::bidomain) {
678  param_globals::phys_region[1].ptype = PHYSREG_EXTRA_ELEC;
679  param_globals::phys_region[1].name = strdup("Autogenerated extracellular Electrics");
680  param_globals::phys_region[1].num_IDs = 0;
681  }
682  } else {
683  log_msg(0,4,0, "Laplace domain will be derived from fibers.\n");
684  param_globals::num_phys_regions = 1;
685  param_globals::phys_region = (p_region*) calloc(param_globals::num_phys_regions, sizeof(p_region));
686  param_globals::phys_region[0].ptype = PHYSREG_LAPLACE;
687  param_globals::phys_region[0].name = strdup("Autogenerated Laplace");
688  param_globals::phys_region[0].num_IDs = 0;
689  }
690  }
691 
692  if(param_globals::experiment == EXP_LAPLACE && !phys_defined(PHYSREG_LAPLACE)) {
693  log_msg(0,4,0, "Warning: Laplace experiment mode requires a laplace physics regions defined.");
694 
695  int idx = -1;
696  if((idx = get_phys_index(PHYSREG_EXTRA_ELEC)) > -1) {
697  log_msg(0,4,0, "Converting the defined extracellular-electrics-region to laplace-region.");
698  param_globals::phys_region[idx].ptype = PHYSREG_LAPLACE;
699  } else if ((idx = get_phys_index(PHYSREG_INTRA_ELEC)) > -1) {
700  log_msg(0,4,0, "Converting the defined intracellular-electrics-region to laplace-region.");
701  param_globals::phys_region[idx].ptype = PHYSREG_LAPLACE;
702  } else {
703  param_globals::num_phys_regions += 1;
704  param_globals::phys_region = (p_region*) realloc(param_globals::phys_region, param_globals::num_phys_regions * sizeof(p_region));
705 
706  param_globals::phys_region[param_globals::num_phys_regions - 1].ptype = PHYSREG_LAPLACE;
707  param_globals::phys_region[param_globals::num_phys_regions - 1].name = strdup("Autogenerated Laplace");
708  param_globals::phys_region[param_globals::num_phys_regions - 1].num_IDs = 0;
709  }
710  }
711 
712 #ifndef WITH_PARMETIS
713  if(param_globals::pstrat == 1) {
714  log_msg(0,3,0, "openCARP was built without Parmetis support. Swithing to KDtree.");
715  param_globals::pstrat = 2;
716  }
717 #endif
718 
719  // check if we have the legacy stimuli or the new stimuli defined by the user
720  bool legacy_stim_set = false, new_stim_set = false;
721 
722  for(int i=0; i<param_globals::num_stim; i++) {
723  Stimulus & legacy_stim = param_globals::stimulus[i];
724  Stim & new_stim = param_globals::stim[i];
725 
726  if(legacy_stim.stimtype || legacy_stim.strength)
727  legacy_stim_set = true;
728 
729  if(new_stim.crct.type || new_stim.pulse.strength)
730  new_stim_set = true;
731  }
732 
733  if(legacy_stim_set || new_stim_set) {
734  if(legacy_stim_set && new_stim_set) {
735  log_msg(0,4,0, "Warning: Legacy stimuli and default stimuli are defined. Only default stimuli will be used!");
736  }
737  else if (legacy_stim_set) {
738  log_msg(0,1,0, "Warning: Legacy stimuli defined. Please consider switching to stimulus definition \"stim[]\"!");
740  }
741  }
742  else {
743  log_msg(0,4,0, "Warning: No potential or current stimuli found!");
744  }
745 }
746 
748 {
749  if(mpi_runtime_ready() && get_rank() != 0)
750  return;
751 
752  log_msg(0, 0, 0, "");
753  log_msg(0, 0, 0, "LICENSE NOTICE:");
754  log_msg(0, 0, 0,
755  "This run uses openCARP components licensed under the Academic Public License v1.1.");
756  log_msg(0, 0, 0,
757  "That includes code from simulator/** and APL-licensed parts of physics/**.");
758  log_msg(0, 0, FLUSH,
759  "Commercial use is not allowed without a separate commercial license.");
760 }
761 
762 void set_io_dirs(char *sim_ID, char *pp_ID, IO_t init)
763 {
764  int flg = 0, err = 0, rank = get_rank();
765 
766  char *ptr = getcwd(current_dir, 1024);
767  if (ptr == NULL) err++;
768  ptr = getcwd(input_dir, 1024);
769  if (ptr == NULL) err++;
770  //if (param_globals::experiment == 4 && post_processing_opts == MECHANIC_POSTPROCESS)
771  // { sim_ID = param_globals::ppID; param_globals::ppID = "POSTPROC_DIR"; }
772 
773  // output directory
774  if (rank == 0) {
775  if (strcmp(sim_ID, "OUTPUT_DIR")) {
776  if (mkdir(sim_ID, 0775)) { // rwxrwxr-x
777  if (errno == EEXIST ) {
778  log_msg(NULL, 2, 0, "Output directory exists: %s\n", sim_ID);
779  } else {
780  log_msg(NULL, 5, 0, "Unable to make output directory\n");
781  flg = 1;
782  }
783  }
784  } else if (mkdir(sim_ID, 0775) && errno != EEXIST) {
785  log_msg(NULL, 5, 0, "Unable to make output directory\n");
786  flg = 1;
787  }
788  }
789 
790  // terminate?
791  if(get_global(flg, MPI_SUM)) { EXIT(-1); }
792 
793  err += chdir(sim_ID);
794  ptr = getcwd(output_dir, 1024);
795  if (ptr == NULL) err++;
796 
797  // terminate?
798  if(get_global(err, MPI_SUM)) { EXIT(-1); }
799 
800  err += chdir(output_dir);
801 
802  // postprocessing directory
803  if (rank == 0 && ((param_globals::experiment==EXP_POSTPROCESS) || (param_globals::post_processing_opts & LEADFIELD))) {
804 
805  if (strcmp(param_globals::ppID, "POSTPROC_DIR")) {
806  if (mkdir(param_globals::ppID, 0775)) { // rwxrwxr-x
807  if (errno == EEXIST ) {
808  log_msg(NULL, 2, ECHO, "Postprocessing directory exists: %s\n\n", param_globals::ppID);
809  } else {
810  log_msg(NULL, 5, ECHO, "Unable to make postprocessing directory\n\n");
811  flg = 1;
812  }
813  }
814  } else if (mkdir(param_globals::ppID, 0775) && errno != EEXIST) {
815  log_msg(NULL, 5, ECHO, "Unable to make postprocessing directory\n\n");
816  flg = 1;
817  }
818 
819  }
820 
821  if(get_global(flg, MPI_SUM)) { EXIT(-1); }
822 
823  err += chdir(param_globals::ppID);
824  ptr = getcwd(postproc_dir, 1024);
825  if (ptr == NULL) err++;
826  err = chdir(output_dir);
827  if(get_global(err, MPI_SUM)) { EXIT(-1); }
828 
829  err = set_dir(init);
830  if(get_global(err, MPI_SUM)) { EXIT(-1); }
831 }
832 
833 bool setup_IO(int argc, char **argv)
834 {
835  bool io_node = false;
836  int psize = get_size(), prank = get_rank();
837 
838  if (param_globals::num_io_nodes > 0) {
839  // Can't do async IO with only one core
840  if (get_size() == 1) {
841  log_msg(NULL, 5, 0, "You cannot run with async IO on only one core.\n");
842  EXIT(EXIT_FAILURE);
843  }
844  // Can't do async IO with more IO cores than compute cores
845  if (2 * param_globals::num_io_nodes >= psize) {
846  log_msg(NULL, 5, 0, "The number of IO cores be less " "than the number of compute cores.");
847  EXIT(EXIT_FAILURE);
848  }
849 #if 0
850  if (param_globals::num_PS_nodes && param_globals::num_io_nodes > param_globals::num_PS_nodes) {
851  LOG_MSG(NULL, 5, 0,
852  "The number of IO cores (%d) should not "
853  "exceed the number of PS compute cores (%d).\n",
854  param_globals::num_io_nodes, param_globals::num_PS_nodes);
855  EXIT(-1);
856  }
857 #endif
858  // root IO node is global node 0
859  io_node = prank < param_globals::num_io_nodes;
860 
861  MPI_Comm comm;
862  MPI_Comm_split(SF_COMM, io_node, get_rank(), &comm);
863  MPI_Comm_set_name(comm, io_node ? "IO" : "compute");
864 
865  SF_COMM = comm; // either the compute world or IO world
866 #ifdef WITH_PETSC
867  if(petsc_active()) petsc_set_comm_world(comm);
868 #endif
869 
870  prank = get_rank();
871 
872  MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, io_node ? param_globals::num_io_nodes : 0,
874 
876  log_msg(NULL, 4, 0, "Global node %d, Comm rank %d != Intercomm rank %d\n",
877  get_rank(MPI_COMM_WORLD), get_rank(SF_COMM),
879  } else
880  MPI_Comm_set_name(SF_COMM, "compute");
881 
882  set_io_dirs(param_globals::simID, param_globals::ppID, OUTPUT);
883 
884  int flg = 0;
885  if((io_node || !param_globals::num_io_nodes) && !prank)
886  flg = !output_parameter_file("parameters.par", argc, argv);
887  if(get_global(flg, MPI_SUM)) EXIT(EXIT_FAILURE);
888 
889  return io_node;
890 }
892 {
893  getcwd(current_dir, 1024);
894 }
895 
896 int set_dir(IO_t dest)
897 {
898  int err;
899 
900  if (dest==OUTPUT) err = chdir(output_dir);
901  else if (dest==POSTPROC) err = chdir(postproc_dir);
902  else if (dest==CURDIR) err = chdir(current_dir);
903  else err = chdir(input_dir);
904 
905  return err;
906 }
907 
909 {
910  // if we restart from a checkpoint, the timer_manager will be notified at a later stage
911  double start_time = 0.0;
912  user_globals::tm_manager = new timer_manager(param_globals::dt, start_time, param_globals::tend);
913 
914  double end_time = param_globals::tend;
916 
917  if(param_globals::experiment == EXP_LAPLACE) {
918  tm.initialize_singlestep_timer(tm.time, 0, iotm_console, "IO (console)", nullptr);
919  tm.initialize_singlestep_timer(tm.time, 0, iotm_state_var, "IO (state vars)", nullptr);
920  tm.initialize_singlestep_timer(tm.time, 0, iotm_spacedt, "IO (spacedt)", nullptr);
921  }
922  else {
923  tm.initialize_eq_timer(tm.time, end_time, 0, param_globals::timedt, 0, iotm_console, "IO (console)");
924  tm.initialize_eq_timer(tm.time, end_time, 0, param_globals::spacedt, 0, iotm_state_var, "IO (state vars)");
925  tm.initialize_eq_timer(tm.time, end_time, 0, param_globals::spacedt, 0, iotm_spacedt, "IO (spacedt)");
926  }
927 
928  if(param_globals::num_tsav) {
929  std::vector<double> trig(param_globals::num_tsav);
930  for(size_t i=0; i<trig.size(); i++) trig[i] = param_globals::tsav[i];
931 
932  tm.initialize_neq_timer(trig, 0, iotm_chkpt_list, "instance checkpointing");
933  }
934 
935  if(param_globals::chkpt_intv)
936  tm.initialize_eq_timer(param_globals::chkpt_start, param_globals::chkpt_stop, 0,
937  param_globals::chkpt_intv, 0, iotm_chkpt_intv, "interval checkpointing");
938 
939  if(param_globals::num_trace)
940  tm.initialize_eq_timer(tm.time, end_time, 0, param_globals::tracedt, 0, iotm_trace, "IO (node trace)");
941 }
942 
943 #ifdef WITH_POWERCAPPING
944 void basic_powercapping_setup()
945 {
946  user_globals::pc_manager = new powercapping_manager();
947 }
948 
949 void basic_powercapping_cleanup()
950 {
951  /* Must be called explicitly to ensure the orderly termination of potential
952  * background daemons */
953  delete user_globals::pc_manager; user_globals::pc_manager = nullptr;
954 }
955 #endif
956 
957 void get_protocol_column_widths(std::vector<int> & col_width, std::vector<int> & used_timer_ids)
958 {
959  char buff[256];
960  const short padding = 4;
961  Electrics* elec = (Electrics*) get_physics(elec_phys, false);
962 
963  do {
964  snprintf(buff, sizeof buff, "%.3lf", user_globals::tm_manager->time);
965  if(col_width[0] < int(strlen(buff)+padding))
966  col_width[0] = strlen(buff)+padding;
967 
968  snprintf(buff, sizeof buff, "%.3ld", user_globals::tm_manager->d_time);
969  if(col_width[1] < int(strlen(buff)+padding))
970  col_width[1] = strlen(buff)+padding;
971 
972  int col = 2;
973  for (size_t tid = 0; tid < used_timer_ids.size(); tid++)
974  {
975  int timer_id = used_timer_ids[tid];
977 
978  if(t->d_trigger_dur && elec) {
979  // figure out value of signal linked to this timer
980  double val = 0.;
981 
982  // determine timer linked to which physics, for now we deal with electrics only
983  val = elec->timer_val(timer_id);
984 
985  snprintf(buff, sizeof buff, "%.3lf", val);
986  if(col_width[col] < int(strlen(buff)+padding))
987  col_width[col] = strlen(buff)+padding;
988  }
989  col++;
990  }
991 
992  // advance time
994  } while (!user_globals::tm_manager->elapsed());
995 
997 }
1000 int plot_protocols(const char *fname)
1001 {
1002  int err = {0};
1003  std::ofstream fh;
1004  const char* smpl_endl = "\n";
1005 
1006  if(!get_rank()) {
1007  fh.open(fname);
1008 
1009  // If we couldn't open the output file stream for writing
1010  if (!fh) {
1011  // Print an error and exit
1012  log_msg(0,5,0,"Protocol file %s could not be opened for writing!\n", fname);
1013  err = -1;
1014  }
1015  }
1016 
1017  // broadcast and return if err
1018  if(get_global(err, MPI_SUM))
1019  return err;
1020 
1021  // only rank 0 writes
1022  if(!get_rank()) {
1023 
1024  // collect timer information, label, short label, unit
1025  std::vector<std::string> col_labels = {"time", "tick"};
1026  std::vector<std::string> col_short_labels = {"A", "B"};
1027  std::vector<std::string> col_unit_labels = {"ms", "--" };
1028  std::vector<int> col_width = {4, 4};
1029 
1030  char c_label = {'C'};
1031  std::string label = {""};
1032  std::string unit = {""};
1033 
1034  // here we store the IDs of the timers that we care about. currently this are the IO and TS timers
1035  // and the electricts timers
1036  std::vector<int> used_timer_ids;
1037  std::vector<int> used_stim_ids;
1038 
1039  Electrics* elec = (Electrics*) get_physics(elec_phys, false);
1040  if(elec) {
1041  int sidx = 0;
1042  for(const stimulus & s : elec->stimuli) {
1043  if(s.ptcl.timer_id > -1) {
1045  if(t) {
1046  used_timer_ids.push_back(s.ptcl.timer_id);
1047  used_stim_ids.push_back(sidx);
1048  }
1049  }
1050 
1051  sidx++;
1052  }
1053  }
1054 
1055  // determine longest timer label
1056  int mx_llen = 0;
1057  for (size_t tid = 0; tid < used_timer_ids.size(); tid++)
1058  {
1059  int timer_id = used_timer_ids[tid];
1060  base_timer* t = user_globals::tm_manager->timers[timer_id];
1061 
1062  int llen = strlen(t->name);
1063  mx_llen = llen > mx_llen ? llen : mx_llen;
1064  }
1065 
1066  for (size_t tid = 0; tid < used_timer_ids.size(); tid++)
1067  {
1068  int timer_id = used_timer_ids[tid];
1069  base_timer* t = user_globals::tm_manager->timers[timer_id];
1070 
1071  col_labels.push_back(t->name);
1072  label = c_label;
1073  col_short_labels.push_back(label);
1074 
1075  if(elec) {
1076  // search physics for signals linked to timer
1077  unit = elec->timer_unit(timer_id);
1078  if(unit.empty()) unit = "--";
1079  col_unit_labels.push_back(unit);
1080  col_width.push_back(4);
1081  }
1082  c_label++;
1083  }
1084 
1085  get_protocol_column_widths(col_width, used_timer_ids);
1086 
1087  // print header + legend first
1088  fh << "# Protocol header\n#\n" << "# Legend:\n";
1089  for(size_t i = 0; i<col_short_labels.size(); i++)
1090  {
1091  fh << "#" << std::setw(2) << col_short_labels[i] << " = " << std::setw(mx_llen) << col_labels[i];
1092  fh << " [" << std::setw(10) << col_unit_labels[i] << "]";
1093 
1094  if(i >= 2 && used_stim_ids[i-2] > -1) {
1095  stimulus & s = elec->stimuli[used_stim_ids[i-2]];
1096 
1097  if (is_potential(s.phys.type)) {
1098  if(s.phys.type == GND_ex)
1099  fh << " ground stim" << smpl_endl;
1100  else
1101  fh << " applied: " << std::to_string(s.pulse.strength) << smpl_endl;
1102  } else {
1103  fh << smpl_endl;
1104  }
1105  } else {
1106  fh << smpl_endl;
1107  }
1108  }
1109 
1110  // plot column short labels
1111  fh << "#";
1112  for(size_t i = 0; i<col_short_labels.size(); i++)
1113  fh << std::setw(col_width[i] - 3) << col_short_labels[i].c_str() << std::setw(3) << " ";
1114 
1115  // plot column units
1116  fh << smpl_endl << "#";
1117  for(size_t i = 0; i<col_unit_labels.size(); i++)
1118  fh << "[" << std::setw(col_width[i]-2) << col_unit_labels[i].c_str() << "]";
1119 
1120  // step through simulated time period
1121  fh << smpl_endl << std::fixed;
1122  do {
1123  // time and discrete time
1124  fh << std::setw(col_width[0]) << std::setprecision(3) << user_globals::tm_manager->time;
1125  fh << std::setw(col_width[1]) << user_globals::tm_manager->d_time;
1126 
1127  // iterate over all timers
1128  int col = 2;
1129  for (size_t tid = 0; tid < used_timer_ids.size(); tid++)
1130  {
1131  int timer_id = used_timer_ids[tid];
1132  base_timer* t = user_globals::tm_manager->timers[timer_id];
1133 
1134  // type of timer: plain trigger or trigger linked to signal
1135  if(!t->d_trigger_dur) {
1136  int On = t->triggered ? 1 : 0;
1137  fh << std::setw(col_width[col]) << On;
1138  } else if(elec) {
1139  // figure out value of signal linked to this timer
1140  double val = 0.;
1141 
1142  // determine timer linked to which physics, for now we deal with electrics only
1143  val = elec->timer_val(timer_id);
1144 
1145  fh << std::setw(col_width[col]) << std::setprecision(3) << val;
1146  }
1147  col++;
1148  }
1149 
1150  fh << smpl_endl;
1151 
1152  // advance time
1154  } while (!user_globals::tm_manager->elapsed());
1155 
1156  fh.close();
1157 
1158  // reset timer to start before actual simulation
1160  }
1161 
1162  return err;
1163 }
1164 
1166 {
1167  const char* h1_prog = "PROG\t----- \t----\t-------\t-------|";
1168  const char* h2_prog = "time\t%%comp\ttime\t ctime \t ETA |";
1169  const char* h1_wc = "\tELAPS |";
1170  const char* h2_wc = "\twc |";
1171 
1172  p.start = get_time();
1173  p.last = p.start;
1174 
1175  log_msg(NULL, 0, 0, "%s", h1_prog );
1176  log_msg(NULL, 0, NONL, "%s", h2_prog );
1177  log_msg(NULL, 0, 0, "" );
1178 }
1179 
1180 
1181 void time_to_string(float time, char* str, short str_size)
1182 {
1183  int req_hours = ((int)(time)) / 3600;
1184  int req_min = (((int)(time)) % 3600) / 60;
1185  int req_sec = (((int)(time)) % 3600) % 60;
1186 
1187  snprintf(str, str_size, "%d:%02d:%02d", req_hours, req_min, req_sec);
1188 }
1189 
1191 {
1192 
1193  float progress = 100.*(tm.time - tm.start) / (tm.end - tm.start);
1194  float elapsed_time = timing(p.curr, p.start);
1195  float req_time = (elapsed_time / progress) * (100.0f - progress);
1196 
1197  if(progress == 0.0f)
1198  req_time = 0.0f;
1199 
1200  char elapsed_time_str[256];
1201  char req_time_str[256];
1202  time_to_string(elapsed_time, elapsed_time_str, 255);
1203  time_to_string(req_time, req_time_str, 255);
1204 
1205  log_msg( NULL, 0, NONL, "%.2f\t%.1f\t%.1f\t%s\t%s",
1206  tm.time,
1207  progress,
1208  (float)(p.curr - p.last),
1209  elapsed_time_str,
1210  req_time_str);
1211 
1212  p.last = p.curr;
1213 
1214  // we add an empty string for newline and flush
1215  log_msg( NULL, 0, ECHO | FLUSH, "");
1216 }
1217 
1218 void simulate()
1219 {
1220  // here we want to include all time dependent physics, to check if we have any of those
1221  bool have_timedependent_phys = (phys_defined(PHYSREG_INTRA_ELEC) || phys_defined(PHYSREG_EIKONAL) || phys_defined(PHYSREG_EMI));
1222 
1223  if(!have_timedependent_phys) {
1224  log_msg(0,0,0, "\n no time-dependent physics region registered, skipping simulate loop..\n");
1225  return;
1226  }
1227 
1228  log_msg(0,0,0, "\n *** Launching simulation ***\n");
1229 
1230  set_dir(OUTPUT);
1231 
1232  if(param_globals::dump_protocol)
1233  plot_protocols("protocol.trc");
1234 
1235  prog_stats prog;
1237  init_console_output(tm, prog);
1238 
1239 #ifdef WITH_POWERCAPPING
1240  basic_powercapping_setup();
1241  powercapping_manager *pc = user_globals::pc_manager;
1242 #endif
1243 
1244  // main loop
1245  do {
1246  // console output
1247  if(tm.trigger(iotm_console)) {
1248  // print console
1249  update_console_output(tm, prog);
1250  }
1251 
1252 #ifdef WITH_POWERCAPPING
1253  std::vector<int> flops_per_rank;
1254 
1255  // TODO: fill vector with expected flops per MPI rank for upcoming iteration
1256 #endif
1257 
1258 #ifdef WITH_POWERCAPPING
1259  pc->iteration_begin(flops_per_rank);
1260 #endif
1261 
1262  // in order to be closer to carpentry we first do output and then compute the solution
1263  // for the next time slice ..
1264  if (tm.trigger(iotm_spacedt)) {
1265  for(const auto & it : user_globals::physics_reg) {
1266  it.second->output_step();
1267  }
1268  }
1269 #ifdef WITH_POWERCAPPING
1270  pc->sample("output step");
1271 #endif
1272 
1273  // compute step
1274  for(const auto & it : user_globals::physics_reg) {
1275  Basic_physic* p = it.second;
1276  if (tm.trigger(p->timer_idx))
1277  p->compute_step();
1278 #ifdef WITH_POWERCAPPING
1279  pc->sample(p->name);
1280 #endif
1281  }
1282 
1283 #ifdef WITH_POWERCAPPING
1284  pc->iteration_end(flops_per_rank);
1285 #endif
1286 
1287  // advance time
1288  tm.update_timers();
1289  } while (!tm.elapsed());
1290 
1292  log_msg(0,0,0, "\n\nTimings of individual physics:");
1293  log_msg(0,0,0, "------------------------------\n");
1294 
1295  for(const auto & it : user_globals::physics_reg) {
1296  Basic_physic* p = it.second;
1297  p->output_timings();
1298  }
1299 
1300 #ifdef WITH_POWERCAPPING
1301  pc = nullptr;
1302  basic_powercapping_cleanup();
1303 #endif
1304 }
1305 
1307 {
1308  if(param_globals::post_processing_opts & RECOVER_PHIE) {
1309  log_msg(NULL,0,ECHO,"\nPOSTPROCESSOR: Recovering Phie ...");
1310  log_msg(NULL,0,ECHO, "----------------------------------\n");
1311 
1312  // do postprocessing
1313  int err = postproc_recover_phie();
1314 
1315  if(!err) {
1316  log_msg(NULL,0,ECHO,"\n-----------------------------------------");
1317  log_msg(NULL,0,ECHO, "POSTPROCESSOR: Successfully recoverd Phie.\n");
1318  }
1319  }
1320 
1321  if(param_globals::post_processing_opts & LEADFIELD) {
1322 #ifdef WITH_LEADFIELD
1323  log_msg(NULL,0,ECHO,"\nPOSTPROCESSOR: Computing leadfields ...");
1324  log_msg(NULL,0,ECHO, "-------------------------------------\n");
1325 
1326  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
1327  if(!elec) {
1328  log_msg(NULL, 5, 0, "Error: Leadfield requires active EP physics. Aborting.");
1329  EXIT(1);
1330  }
1331  Leadfield leadfield;
1332  int err = leadfield.run(*elec);
1333 
1334  if(!err) {
1335  log_msg(NULL,0,ECHO,"\n------------------------------------------");
1336  log_msg(NULL,0,ECHO, "POSTPROCESSOR: Successfully computed leadfields.\n");
1337  }
1338 #else
1339  log_msg(NULL, 5, 0, "Error: leadfield support not compiled in. Rebuild with -DENABLE_LEADFIELD=ON.");
1340  EXIT(1);
1341 #endif
1342  }
1343 }
1344 
1345 Basic_physic* get_physics(physic_t p, bool error_if_missing)
1346 {
1347  auto it = user_globals::physics_reg.find(p);
1348 
1349  if(it != user_globals::physics_reg.end()) {
1350  return it->second;
1351  } else {
1352  if(error_if_missing) {
1353  log_msg(0,5,0, "%s error: required physic is not active! Usually this is due to an inconsistent experiment configuration. Aborting!", __func__);
1354  EXIT(EXIT_FAILURE);
1355  }
1356 
1357  return NULL;
1358  }
1359 }
1360 
1362 {
1363  sf_vec* ret = NULL;
1364 
1366  ret = user_globals::datavec_reg[d];
1367 
1368  return ret;
1369 }
1370 
1372 {
1373  if(user_globals::datavec_reg.count(d) == 0) {
1374  user_globals::datavec_reg[d] = dat;
1375  }
1376  else {
1377  log_msg(0,5,0, "%s warning: trying to register already registered data vector.", __func__);
1378  }
1379 }
1380 
1382 {
1383  std::map<mesh_t, sf_mesh> & mesh_registry = user_globals::mesh_reg;
1384 
1385  // This is the initial grid we read the hard-disk data into
1386  mesh_registry[reference_msh] = sf_mesh();
1387  // we specify the MPI communicator for the reference mesh,
1388  // all derived meshes will get this comminicator automatically
1389  mesh_registry[reference_msh].comm = SF_COMM;
1390 
1391  auto register_new_mesh = [&] (mesh_t mt, int pidx) {
1392  if(!mesh_registry.count(mt)) {
1393  mesh_registry[mt] = sf_mesh();
1394  mesh_registry[mt].name = param_globals::phys_region[pidx].name;
1395  }
1396  return &mesh_registry[mt];
1397  };
1398 
1399  // based on cli parameters we determine which grids need to be defined
1400  for(int i=0; i<param_globals::num_phys_regions; i++)
1401  {
1402  sf_mesh* curmesh = NULL;
1403  // register mesh type
1404  switch(param_globals::phys_region[i].ptype) {
1405  case PHYSREG_EIKONAL:
1406  case PHYSREG_INTRA_ELEC:
1407  curmesh = register_new_mesh(intra_elec_msh, i);
1408  break;
1409 
1410  case PHYSREG_LAPLACE:
1411  case PHYSREG_EXTRA_ELEC:
1412  curmesh = register_new_mesh(extra_elec_msh, i);
1413  break;
1414 #if WITH_EMI_MODEL
1415  case PHYSREG_EMI:
1416  curmesh = register_new_mesh(emi_msh, i);
1417  break;
1418 #endif
1419 
1420  default:
1421  log_msg(0,5,0, "Unsupported mesh type %d! Aborting!", param_globals::phys_region[i].ptype);
1422  EXIT(EXIT_FAILURE);
1423  }
1424 
1425  if(curmesh) {
1426  // set mesh unique tags
1427  for(int j=0; j<param_globals::phys_region[i].num_IDs; j++)
1428  curmesh->extr_tag.insert(param_globals::phys_region[i].ID[j]);
1429  }
1430  }
1431 }
1432 
1443 void retag_elements(sf_mesh & mesh, TagRegion *tagRegs, int ntr)
1444 {
1445  if(ntr == 0) return;
1446  // checkTagRegDefs(ntr, tagRegs);
1447 
1449 
1450  for (int i=0; i<ntr; i++) {
1451  tagreg_t type = tagreg_t(tagRegs[i].type);
1452  SF::vector<mesh_int_t> elem_indices;
1453 
1454  if (type == tagreg_list)
1455  read_indices(elem_indices, tagRegs[i].elemfile, ref_eidx, mesh.comm);
1456  else {
1457  geom_shape shape;
1458  shape.type = geom_shape::shape_t(tagRegs[i].type);
1459  shape.p0.x = tagRegs[i].p0[0];
1460  shape.p0.y = tagRegs[i].p0[1];
1461  shape.p0.z = tagRegs[i].p0[2];
1462  shape.p1.x = tagRegs[i].p1[0];
1463  shape.p1.y = tagRegs[i].p1[1];
1464  shape.p1.z = tagRegs[i].p1[2];
1465  shape.radius = tagRegs[i].radius;
1466 
1467  bool nodal = false;
1468  indices_from_geom_shape(elem_indices, mesh, shape, nodal);
1469  }
1470 
1471  if(get_global((long int)elem_indices.size(), MPI_SUM, mesh.comm) == 0)
1472  log_msg(0,3,0,"Tag region %d is empty", i);
1473 
1474  for(size_t j=0; j<elem_indices.size(); j++)
1475  mesh.tag[elem_indices[j]] = tagRegs[i].tag;
1476  }
1477 
1478  // output the vector?
1479  if(strlen(param_globals::retagfile))
1480  {
1481  update_cwd();
1482  set_dir(OUTPUT);
1483 
1484  int dpn = 1;
1485  SF::write_data_ascii(mesh.comm, ref_eidx, mesh.tag, param_globals::retagfile, dpn);
1486 
1487  // Set dir back to what is was prior to retagfile output
1488  set_dir(CURDIR);
1489  }
1490 }
1491 
1492 size_t renormalise_fibres(SF::vector<mesh_real_t> &fib, size_t l_numelem)
1493 {
1494  size_t renormalised_count = 0;
1495 
1496  // using pragma omp without global OMP control can lead to massive compute stalls,
1497  // as all cores may be already occupied by MPI, thus they become oversubscribed. Once
1498  // there is a global OMP control in place, we can activate this parallel for again. -Aurel, 20.01.2022
1499  // #pragma omp parallel for schedule(static) reduction(+ : renormalised_count)
1500  for (size_t i = 0; i < l_numelem; i++)
1501  {
1502  const mesh_real_t f0 = fib[3*i+0], f1 = fib[3*i+1], f2 = fib[3*i+2];
1503  mesh_real_t fibre_len = sqrt(f0*f0 + f1*f1 + f2*f2);
1504 
1505  if (fibre_len && fabs(fibre_len - 1) > 1e-3) {
1506  fib[3 * i + 0] /= fibre_len;
1507  fib[3 * i + 1] /= fibre_len;
1508  fib[3 * i + 2] /= fibre_len;
1509  renormalised_count++;
1510  }
1511  }
1512 
1513  return renormalised_count;
1514 }
1515 
1516 void setup_meshes(bool require_fibers=true)
1517 {
1518  log_msg(0,0,0, "\n *** Processing meshes ***\n");
1519 
1520  const std::string basename = param_globals::meshname;
1521  const int verb = param_globals::output_level;
1522  std::map<mesh_t, sf_mesh> & mesh_registry = user_globals::mesh_reg;
1523  assert(mesh_registry.count(reference_msh) == 1); // There must be a reference mesh
1524 
1525  set_dir(INPUT);
1526 
1527  // we always read into the reference mesh
1528  sf_mesh & ref_mesh = mesh_registry[reference_msh];
1529  MPI_Comm comm = ref_mesh.comm;
1530 
1531  int size, rank;
1532  double t1, t2, s1, s2;
1533  MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank);
1534 
1536  SF::vector<mesh_int_t> ptsidx;
1537 
1538  // we add pointers to the meshes that need vertex cooridnates to this list
1539  std::list< sf_mesh* > ptsread_list;
1540 
1541  // read element mesh data
1542  t1 = MPI_Wtime(); s1 = t1;
1543  if(verb) log_msg(NULL, 0, 0,"Reading reference mesh: %s.*", basename.c_str());
1544 
1545  SF::read_elements(ref_mesh, basename, require_fibers);
1546  SF::read_points(basename, comm, pts, ptsidx);
1547 
1548  if (strlen(param_globals::tagfile)) {
1549  if(verb) log_msg(NULL, 0, 0, "Overriding element tags from: %s", param_globals::tagfile);
1550  SF::read_element_tags(ref_mesh, param_globals::tagfile);
1551  }
1552 
1553  t2 = MPI_Wtime();
1554  if(verb) log_msg(NULL, 0, 0, "Done in %f sec.", float(t2 - t1));
1555 
1556  bool check_fibre_normality = true;
1557  if (check_fibre_normality and ref_mesh.fib.size()>0) {
1558  t1 = MPI_Wtime();
1559 
1560  // make sure that all fibre vectors have unit length
1561  size_t l_num_fixed_fib = renormalise_fibres(ref_mesh.fib, ref_mesh.l_numelem);
1562 
1563  size_t l_num_fixed_she = 0;
1564  if (ref_mesh.she.size() > 0)
1565  l_num_fixed_she = renormalise_fibres(ref_mesh.she, ref_mesh.l_numelem);
1566 
1567  unsigned long fixed[2] = {(unsigned long) l_num_fixed_fib, (unsigned long) l_num_fixed_she};
1568  MPI_Allreduce(MPI_IN_PLACE, fixed, 2, MPI_UNSIGNED_LONG, MPI_SUM, comm);
1569 
1570  if (fixed[0] + fixed[1] > 0)
1571  log_msg(NULL, 0, 0, "Renormalised %ld longitudinal and %ld sheet-transverse fibre vectors.", fixed[0], fixed[1]);
1572 
1573  t2 = MPI_Wtime();
1574  if(verb) log_msg(NULL, 0, 0, "Done in %f sec.", float(t2 - t1));
1575  }
1576 
1577  if(param_globals::numtagreg > 0) {
1578  log_msg(0, 0, 0, "Re-tagging reference mesh");
1579 
1580  // the retagging requires vertex coordinates, as such we need to read them into
1581  // the reference mesh
1582  ptsread_list.push_back(&ref_mesh);
1583  SF::insert_points(pts, ptsidx, ptsread_list);
1584 
1585  retag_elements(ref_mesh, param_globals::tagreg, param_globals::numtagreg);
1586 
1587  // we clear the list of meshet to receive vertices
1588  ptsread_list.clear();
1589  }
1590 
1591  if(verb) log_msg(NULL, 0, 0, "Processing submeshes");
1592 
1593  bool have_emi_mesh = false;
1594  bool have_non_emi_mesh = false;
1595 
1596  for(auto it = mesh_registry.begin(); it != mesh_registry.end(); ++it) {
1597  mesh_t grid_type = it->first;
1598  sf_mesh & submesh = it->second;
1599 
1600  if(grid_type != reference_msh) {
1601  if(grid_type == emi_msh)
1602  have_emi_mesh = true;
1603  else
1604  have_non_emi_mesh = true;
1605 
1606  if(verb > 1) log_msg(NULL, 0, 0, "\nSubmesh name: %s", submesh.name.c_str());
1607  t1 = MPI_Wtime();
1608 
1609  if(submesh.extr_tag.size() && grid_type != emi_msh)
1610  extract_tagbased(ref_mesh, submesh);
1611  else {
1612  // all submeshes should be defined on sets of tags, for backwards compatibility
1613  // we do a fiber based intra_elec_msh extraction if no tags are provided. Also, we
1614  // could do special treatments of any other physics type here. It would defeat
1615  // the purpose of the tag-based design, though. -Aurel
1616  switch(grid_type) {
1617  case emi_msh:
1618  case intra_elec_msh: extract_myocardium(ref_mesh, submesh, require_fibers); break;
1619  default: extract_tagbased(ref_mesh, submesh); break;
1620  }
1621  }
1622  t2 = MPI_Wtime();
1623  if(verb > 1) log_msg(NULL, 0, 0, "Extraction done in %f sec.", float(t2 - t1));
1624 
1625  ptsread_list.push_back(&submesh);
1626  }
1627  }
1628 
1629  if(have_emi_mesh && have_non_emi_mesh) {
1630  log_msg(NULL, 5, ECHO, "EMI and non-EMI submeshes cannot be mixed during mesh setup.");
1631  EXIT(EXIT_FAILURE);
1632  }
1633 
1634  // KDtree partitioning requires the coordinates to be present in the mesh data
1635  if(param_globals::pstrat == 2 && have_non_emi_mesh)
1636  SF::insert_points(pts, ptsidx, ptsread_list);
1637 
1638  for(auto it = mesh_registry.begin(); it != mesh_registry.end(); ++it)
1639  {
1640  mesh_t grid_type = it->first;
1641  sf_mesh & submesh = it->second;
1642  if(grid_type != reference_msh && grid_type!=emi_msh) {
1643  if(verb > 2) log_msg(NULL, 0, 0, "\nSubmesh name: %s", submesh.name.c_str());
1645 
1646  // generate partitioning vector
1647  t1 = MPI_Wtime();
1648  switch(param_globals::pstrat) {
1649  case 0:
1650  if(verb > 2) log_msg(NULL, 0, 0, "Using linear partitioning ..");
1651  break;
1652 
1653 #ifdef WITH_PARMETIS
1654  case 1:
1655  {
1656  if(verb > 2) log_msg(NULL, 0, 0, "Using Parmetis partitioner ..");
1657  SF::parmetis_partitioner<mesh_int_t, mesh_real_t> partitioner(param_globals::pstrat_imbalance, 2);
1658  partitioner(submesh, part);
1659  break;
1660  }
1661 #endif
1662  default:
1663  case 2: {
1664  if(verb > 2) log_msg(NULL, 0, 0, "Using KDtree partitioner ..");
1666  partitioner(submesh, part);
1667  break;
1668  }
1669  }
1670  t2 = MPI_Wtime();
1671  if(verb > 2) log_msg(NULL, 0, 0, "Partitioning done in %f sec.", float(t2 - t1));
1672 
1673  if(param_globals::pstrat > 0) {
1674  if(param_globals::gridout_p) {
1675  std::string out_name = get_basename(param_globals::meshname);
1676  if(grid_type == intra_elec_msh) out_name += "_i.part.dat";
1677  else if(grid_type == extra_elec_msh) out_name += "_e.part.dat";
1678 
1679  set_dir(OUTPUT);
1680  log_msg(0,0,0, "Writing \"%s\" partitioning to: %s", submesh.name.c_str(), out_name.c_str());
1681  write_data_ascii(submesh.comm, submesh.get_numbering(SF::NBR_ELEM_REF), part, out_name);
1682  }
1683 
1684  t1 = MPI_Wtime();
1685  SF::redistribute_elements(submesh, part);
1686  t2 = MPI_Wtime();
1687  if(verb > 2) log_msg(NULL, 0, 0, "Redistributing done in %f sec.", float(t2 - t1));
1688  }
1689 
1690  t1 = MPI_Wtime();
1692  sm_numbering(submesh);
1693  t2 = MPI_Wtime();
1694  if(verb > 2) log_msg(NULL, 0, 0, "Canonical numbering done in %f sec.", float(t2 - t1));
1695 
1696  t1 = MPI_Wtime();
1697  submesh.generate_par_layout();
1698  SF::petsc_numbering<mesh_int_t, mesh_real_t> p_numbering(submesh.pl, param_globals::renumbering);
1699  p_numbering(submesh);
1700  t2 = MPI_Wtime();
1701  if(verb > 2) log_msg(NULL, 0, 0, "PETSc numbering done in %f sec.", float(t2 - t1));
1702  if(verb > 2) print_DD_info(submesh);
1703  }
1704  }
1705 
1706  if(have_non_emi_mesh)
1707  SF::insert_points(pts, ptsidx, ptsread_list);
1708 
1709  ref_mesh.clear_data();
1710 
1711  s2 = MPI_Wtime();
1712  if(verb) log_msg(NULL, 0, 0, "All done in %f sec.", float(s2 - s1));
1713 }
1714 
1716 {
1717  static const char* parameter_name = "gridout_tags";
1718  const std::string spec = param_globals::gridout_tags ? param_globals::gridout_tags : "";
1719 
1720  std::vector<int> tags;
1721  std::string error;
1722  if(!paramschema::parse_idset_spec(spec, &tags, &error)) {
1723  log_msg(0, 5, ECHO, "Could not parse %s: %s.", parameter_name, error.c_str());
1724  EXIT(EXIT_FAILURE);
1725  }
1726 
1727  output_tags.clear();
1728  output_tags.insert(tags.begin(), tags.end());
1729 
1730  if(output_tags.size() == 0) return false;
1731 
1732  log_msg(0, 0, 0, "Restricting grid output to %zu tag(s) from %s.",
1733  output_tags.size(), parameter_name);
1734  return true;
1735 }
1736 
1738  const hashmap::unordered_set<int>& output_tags,
1739  SF::vector<mesh_int_t>& output_idx,
1740  bool async)
1741 {
1742  SF::vector<mesh_int_t> selected_nodes;
1743 
1744  for(size_t eidx = 0; eidx < mesh.l_numelem; eidx++) {
1745  if(output_tags.count(mesh.tag[eidx]) == 0) continue;
1746 
1747  for(mesh_int_t j = mesh.dsp[eidx]; j < mesh.dsp[eidx + 1]; j++)
1748  selected_nodes.push_back(mesh.con[j]);
1749  }
1750 
1751  localize_gridout_nodes(mesh, selected_nodes, output_idx, async);
1752 }
1753 
1755  const SF::vector<mesh_t>& mesh_ids)
1756 {
1757  hashmap::unordered_set<int> local_seen;
1758 
1759  for(mesh_t mesh_id : mesh_ids) {
1760  if(!mesh_is_registered(mesh_id)) continue;
1761 
1762  const sf_mesh& mesh = get_mesh(mesh_id);
1763  for(size_t eidx = 0; eidx < mesh.l_numelem; eidx++) {
1764  if(output_tags.count(mesh.tag[eidx]) != 0)
1765  local_seen.insert(mesh.tag[eidx]);
1766  }
1767  }
1768 
1769  SF::vector<int> sorted_tags;
1770  sorted_tags.assign(output_tags.begin(), output_tags.end());
1771  binary_sort(sorted_tags);
1772 
1773  SF::vector<int> missing_tags;
1774  for(int tag : sorted_tags) {
1775  int local_found = local_seen.count(tag) ? 1 : 0;
1776  int global_found = 0;
1777  MPI_Allreduce(&local_found, &global_found, 1, MPI_INT, MPI_MAX, SF_COMM);
1778  if(global_found == 0)
1779  missing_tags.push_back(tag);
1780  }
1781 
1782  if(missing_tags.size()) {
1783  binary_sort(missing_tags);
1784 
1785  std::stringstream msg;
1786  for(size_t i = 0; i < missing_tags.size(); i++) {
1787  if(i) msg << ", ";
1788  msg << missing_tags[i];
1789  }
1790 
1791  log_msg(0, 3, ECHO, "Warning: ignoring gridout_tags not present in the selected output mesh(es): %s.",
1792  msg.str().c_str());
1793 
1794  for(int tag : missing_tags)
1795  output_tags.erase(tag);
1796 
1797  if(output_tags.size() == 0) {
1798  log_msg(0, 5, ECHO, "gridout_tags did not match any tag in the selected output mesh(es).");
1799  EXIT(EXIT_FAILURE);
1800  }
1801  }
1802 }
1803 
1805  const SF::vector<mesh_int_t>& selected_idx)
1806 {
1807  if(restr == NULL) {
1808  restr = new SF::vector<mesh_int_t>(selected_idx);
1809  return;
1810  }
1811 
1812  binary_sort(*restr);
1813  SF::vector<mesh_int_t> selected(selected_idx);
1814  binary_sort(selected);
1815 
1816  SF::vector<mesh_int_t> intersection;
1817  size_t lhs = 0, rhs = 0;
1818  while(lhs < restr->size() && rhs < selected.size()) {
1819  if((*restr)[lhs] == selected[rhs]) {
1820  intersection.push_back((*restr)[lhs]);
1821  lhs++;
1822  rhs++;
1823  } else if((*restr)[lhs] < selected[rhs]) {
1824  lhs++;
1825  } else {
1826  rhs++;
1827  }
1828  }
1829 
1830  *restr = intersection;
1831 }
1832 
1833 
1835 {
1836  bool write_intra_elec = mesh_is_registered(intra_elec_msh) && param_globals::gridout_i;
1837  bool write_extra_elec = mesh_is_registered(extra_elec_msh) && param_globals::gridout_e;
1838 
1839  set_dir(OUTPUT);
1840  std::string output_base = get_basename(param_globals::meshname);
1841  hashmap::unordered_set<int> output_tags;
1842  const bool restrict_gridout =
1843  (write_intra_elec || write_extra_elec) && parse_gridout_tags(output_tags);
1844  if(restrict_gridout) {
1845  SF::vector<mesh_t> mesh_ids;
1846  if(write_intra_elec) mesh_ids.push_back(intra_elec_msh);
1847  if(write_extra_elec) mesh_ids.push_back(extra_elec_msh);
1848  validate_gridout_tags(output_tags, mesh_ids);
1849  }
1850 
1851  if(write_intra_elec) {
1852  sf_mesh & mesh = get_mesh(intra_elec_msh);
1853  sf_mesh restricted_mesh;
1854  sf_mesh* output_mesh = &mesh;
1855  if(restrict_gridout) {
1856  if(!mesh_has_gridout_tags(mesh, output_tags)) {
1857  log_msg(0, 5, ECHO, "gridout_tags selected no intracellular grid elements.");
1858  EXIT(EXIT_FAILURE);
1859  }
1860  extract_gridout_tag_mesh(mesh, output_tags, restricted_mesh);
1861  output_mesh = &restricted_mesh;
1862  }
1863 
1864  if(param_globals::gridout_i & 1) {
1865  if(param_globals::output_level > 1)
1866  log_msg(0,0,0, "Computing \"%s\" surface ..", output_mesh->name.c_str());
1867 
1868  std::string output_file = output_base + "_i.surf";
1869  log_msg(0,0,0, "Writing \"%s\" surface: %s", output_mesh->name.c_str(), output_file.c_str());
1870 
1871  if(param_globals::gridout_i & 2) {
1872  // the surface indexes into the points of the volume mesh written below
1873  sf_mesh surfmesh;
1874  compute_surface_mesh(*output_mesh, SF::NBR_SUBMESH, surfmesh);
1875  write_surface(surfmesh, output_file);
1876  }
1877  else {
1878  // no volume mesh is written, so the surface needs points of its own
1879  write_gridout_surface(*output_mesh, output_base + "_i");
1880  }
1881  }
1882  if(param_globals::gridout_i & 2) {
1883  bool write_binary = false;
1884 
1885  std::string output_file = output_base + "_i";
1886  log_msg(0,0,0, "Writing \"%s\" mesh: %s", output_mesh->name.c_str(), output_file.c_str());
1887  write_mesh_parallel(*output_mesh, write_binary, output_file.c_str());
1888  }
1889  }
1890 
1891  if(write_extra_elec) {
1892  sf_mesh & mesh = get_mesh(extra_elec_msh);
1893  sf_mesh restricted_mesh;
1894  sf_mesh* output_mesh = &mesh;
1895  if(restrict_gridout) {
1896  if(!mesh_has_gridout_tags(mesh, output_tags)) {
1897  log_msg(0, 5, ECHO, "gridout_tags selected no extracellular grid elements.");
1898  EXIT(EXIT_FAILURE);
1899  }
1900  extract_gridout_tag_mesh(mesh, output_tags, restricted_mesh);
1901  output_mesh = &restricted_mesh;
1902  }
1903 
1904  if(param_globals::gridout_e & 1) {
1905  if(param_globals::output_level > 1)
1906  log_msg(0,0,0, "Computing \"%s\" surface ..", output_mesh->name.c_str());
1907 
1908  std::string output_file = output_base + "_e.surf";
1909  log_msg(0,0,0, "Writing \"%s\" surface: %s", output_mesh->name.c_str(), output_file.c_str());
1910 
1911  if(param_globals::gridout_e & 2) {
1912  // the surface indexes into the points of the volume mesh written below
1913  sf_mesh surfmesh;
1914  compute_surface_mesh(*output_mesh, SF::NBR_SUBMESH, surfmesh);
1915  write_surface(surfmesh, output_file);
1916  }
1917  else {
1918  // no volume mesh is written, so the surface needs points of its own
1919  write_gridout_surface(*output_mesh, output_base + "_e");
1920  }
1921  }
1922  if(param_globals::gridout_e & 2) {
1923  bool write_binary = false;
1924  std::string output_file = output_base + "_e";
1925  log_msg(0,0,0, "Writing \"%s\" mesh: %s", output_mesh->name.c_str(), output_file.c_str());
1926  write_mesh_parallel(*output_mesh, write_binary, output_file.c_str());
1927  }
1928  }
1929 }
1930 
1931 [[noreturn]] void cleanup_and_exit()
1932 {
1933  destroy_physics();
1935  print_active_citation_suggestions();
1936 
1937  const paramschema::ResetResult reset = paramschema::reset_schema_state(paramschema::openCARP_schema());
1938  print_lines(stderr, "parameter cleanup warning: ", reset.warnings);
1939  print_lines(stderr, "parameter cleanup error: ", reset.errors);
1940  finalize_backend();
1941 
1942  // close petsc error FD
1945 
1946  exit(EXIT_SUCCESS);
1947 }
1948 
1949 char* get_file_dir(const char* file)
1950 {
1951  char* filecopy = dupstr(file);
1952  char* dir = dupstr(dirname(filecopy));
1953 
1954  free(filecopy);
1955  return dir;
1956 }
1957 
1959 {
1960  set_dir(OUTPUT);
1961 
1962 #ifdef WITH_PETSC
1963  if(!petsc_active()) return;
1964 
1965  if(get_rank() == 0) {
1966  // we open a error log file handle and set it as petsc stderr
1967  user_globals::petsc_error_fd = fopen("petsc_err_log.txt", "w");
1968  petsc_redirect_errors(user_globals::petsc_error_fd);
1969  }
1970  else {
1971  petsc_redirect_errors(NULL);
1972  }
1973 #endif
1974 }
1975 
1977 {
1978  const sf_mesh & mesh = get_mesh(id);
1980  short mindim = 3;
1981 
1982  for(size_t eidx = 0; eidx < mesh.l_numelem; eidx++) {
1983  view.set_elem(eidx);
1984  short cdim = view.dimension();
1985  if(mindim < cdim) mindim = cdim;
1986  }
1987 
1988  mindim = get_global(mindim, MPI_MIN, mesh.comm);
1989 
1990  return mindim;
1991 }
1992 
1994  const mesh_t inp_meshid,
1995  const int dpn,
1996  const char* name,
1997  const char* units,
1998  const SF::vector<mesh_int_t>* idx,
1999  bool elem_data)
2000 {
2001  sync_io_item IO;
2002 
2003  IO.data = inp_data;
2004  IO.elem_flag = elem_data;
2005  IO.restr_idx = idx;
2006  if(idx != NULL) {
2007  const sf_mesh& mesh = get_mesh(inp_meshid);
2008  const SF::vector<mesh_int_t>& layout = elem_data ? mesh.epl.algebraic_layout() :
2009  mesh.pl.algebraic_layout();
2010  const mesh_int_t start = layout[get_rank()];
2011 
2012  IO.restr_global_idx.resize(idx->size());
2013  for(size_t i = 0; i < idx->size(); i++)
2014  IO.restr_global_idx[i] = start + (*idx)[i];
2015  }
2016 
2017  IGBheader regigb;
2019  const int num_io = tm.timers[iotm_spacedt]->numIOs;
2020  int err = 0;
2021 
2022  int gsize = inp_data->gsize();
2023 
2024  // if we are restricting, we have to compute the restricted global size
2025  if(idx != NULL)
2026  gsize = get_global(int(idx->size()), MPI_SUM) * dpn;
2027 
2028  regigb.x(gsize / dpn);
2029  regigb.dim_x(regigb.x()-1);
2030  regigb.inc_x(1);
2031 
2032  regigb.y(1); regigb.z(1);
2033  regigb.t(num_io);
2034  regigb.dim_t(tm.end-tm.start);
2035 
2036  switch(dpn) {
2037  default:
2038  case 1: regigb.type(IGB_FLOAT); break;
2039  case 3: regigb.type(IGB_VEC3_f); break;
2040  case 4: regigb.type(IGB_VEC4_f); break;
2041  case 9: regigb.type(IGB_VEC9_f); break;
2042  }
2043 
2044  regigb.unites_x("um"); regigb.unites_y("um"); regigb.unites_z("um");
2045  regigb.unites_t("ms");
2046  regigb.unites(units);
2047  regigb.org_t(tm.time);
2048  regigb.inc_t(param_globals::spacedt);
2049 
2050  if(get_rank() == 0) {
2051  FILE_SPEC file = f_open(name, "w");
2052  if(file != NULL) {
2053  regigb.fileptr(file->fd);
2054  regigb.write();
2055  delete file;
2056  }
2057  else err++;
2058  }
2059 
2060  err = get_global(err, MPI_SUM);
2061  if(err) {
2062  log_msg(0,5,0, "%s error: Could not set up data output! Aborting!", __func__);
2063  EXIT(1);
2064  }
2065 
2066  IO.igb = regigb;
2067 
2068  SF::mixed_tuple<mesh_t, int> mesh_spec = {inp_meshid, dpn};
2069  IO.spec = mesh_spec;
2070 
2071  if(elem_data) {
2072  if(buffmap_elem.find(mesh_spec) == buffmap_elem.end()) {
2073  sf_vec *inp_copy; SF::init_vector(&inp_copy, inp_data);
2074  buffmap_elem[mesh_spec] = inp_copy;
2075  }
2076  } else {
2077  if(buffmap.find(mesh_spec) == buffmap.end()) {
2078  sf_vec *inp_copy; SF::init_vector(&inp_copy, inp_data);
2079  buffmap[mesh_spec] = inp_copy;
2080  }
2081  }
2082 
2083  this->sync_IOs.push_back(IO);
2084 }
2085 
2086 void igb_output_manager::register_output_async(sf_vec* inp_data,
2087  const mesh_t inp_meshid,
2088  const int dpn,
2089  const char* name,
2090  const char* units,
2091  const SF::vector<mesh_int_t>* idx,
2092  bool elem_data)
2093 {
2094  sf_mesh & mesh = get_mesh(inp_meshid);
2095  SF::vector<mesh_int_t> ioidx;
2096  int rank = get_rank();
2097 
2098  async_io_item IO;
2099  IO.data = inp_data;
2100  IO.restr_idx = idx;
2101 
2102  if(elem_data) {
2104  ioidx.resize(mesh.l_numelem);
2105  for(size_t i=0; i<mesh.l_numelem; i++)
2106  ioidx[i] = nbr[i];
2107  } else {
2108  const SF::vector<mesh_int_t> & alg_nod = mesh.pl.algebraic_nodes();
2110 
2111  if(idx == NULL) {
2112  ioidx.resize(alg_nod.size());
2113 
2114  for(size_t i=0; i<alg_nod.size(); i++)
2115  ioidx[i] = nbr[alg_nod[i]];
2116  } else {
2117  ioidx.resize(idx->size());
2118  IO.restr_petsc_idx.resize(idx->size());
2119 
2120  for(size_t i=0; i<idx->size(); i++) {
2121  mesh_int_t loc_nodal = (*idx)[i];
2122  ioidx[i] = nbr[loc_nodal];
2123  IO.restr_petsc_idx[i] = local_nodal_to_local_petsc(mesh, rank, loc_nodal);
2124  }
2125  }
2126  }
2127 
2128  int id = async::COMPUTE_register_output(ioidx, dpn, name, units);
2129  IO.IO_id = id;
2130 
2131  this->async_IOs.push_back(IO);
2132 }
2133 
2135  const mesh_t inp_meshid,
2136  const int dpn,
2137  const char* name,
2138  const char* units,
2139  const SF::vector<mesh_int_t>* idx,
2140  bool elem_data)
2141 {
2142  if(param_globals::num_io_nodes == 0)
2143  register_output_sync(inp_data, inp_meshid, dpn, name, units, idx, elem_data);
2144  else
2145  register_output_async(inp_data, inp_meshid, dpn, name, units, idx, elem_data);
2146 }
2147 
2148 sf_vec* igb_output_manager::fill_output_buffer(const sync_io_item & it)
2149 {
2150  const SF::mixed_tuple<mesh_t, int> & cspec = it.spec;
2151  sf_vec* data_vec = it.data;
2152 
2153  bool have_perm = it.elem_flag ? have_permutation(cspec.v1, ELEM_PETSC_TO_CANONICAL, cspec.v2):
2154  have_permutation(cspec.v1, PETSC_TO_CANONICAL, cspec.v2);
2155 
2156  if(have_perm) {
2157  sf_vec* perm_vec = it.elem_flag ? this->buffmap_elem[cspec] : this->buffmap[cspec];
2159  get_permutation(cspec.v1, PETSC_TO_CANONICAL, cspec.v2);
2160  sc->forward(*data_vec, *perm_vec);
2161  return perm_vec;
2162  } else {
2163  return data_vec;
2164  }
2165 }
2166 
2168 {
2169  SF::vector<float> restr_buff;
2170  int rank = get_rank();
2171  // loop over registered datasets and root-write one by one
2172  //
2173  for (sync_io_item & it : sync_IOs) {
2174  // write to associated file descriptor
2175  FILE* fd = static_cast<FILE*>(it.igb.fileptr());
2176 
2177  // fill the output buffer
2178  sf_vec* buff = fill_output_buffer(it);
2179 
2180  if(it.restr_idx == NULL) {
2181  buff->write_binary<float>(fd);
2182  } else {
2183  const SF::vector<mesh_int_t> & idx = *it.restr_idx;
2184  const int dpn = it.spec.v2;
2185  SF_real* p = buff->ptr();
2186 
2187  restr_buff.resize(idx.size()); restr_buff.resize(0);
2188 
2189  for(mesh_int_t ii : idx) {
2190  const mesh_int_t offset = ii * dpn;
2191  for(int j = 0; j < dpn; j++)
2192  restr_buff.push_back(p[offset + j]);
2193  }
2194 
2195  if(dpn == 1) {
2196  root_write_ordered(fd, it.restr_global_idx, restr_buff, SF_COMM);
2197  } else {
2199  root_write_ordered(fd, it.restr_global_idx, cnt, restr_buff, SF_COMM);
2200  }
2201  buff->release_ptr(p);
2202  }
2203  }
2204 
2205  // do all A-synchronous output:
2206  // loop over IDs received from the IO nodes and trigger async output
2207  //
2208  for (async_io_item & it : async_IOs) {
2209  SF_real* p = it.data->ptr();
2210  int ls = it.data->lsize();
2211  int id = it.IO_id;
2212 
2213  if(it.restr_idx == NULL)
2214  async::COMPUTE_do_output(p, ls, id);
2215  else {
2216  async::COMPUTE_do_output(p, it.restr_petsc_idx, id);
2217  }
2218 
2219  it.data->release_ptr(p);
2220  }
2221 }
2222 
2224 {
2225  if(get_rank() == 0) {
2226  // loop over registered datasets and close fd
2227  for(sync_io_item & it : sync_IOs) {
2228  FILE* fd = static_cast<FILE*>(it.igb.fileptr());
2229  fclose(fd);
2230  }
2231  }
2232 
2233  for(auto it = buffmap.begin(); it != buffmap.end(); ++it)
2234  delete it->second;
2235 
2236  for(auto it = buffmap_elem.begin(); it != buffmap_elem.end(); ++it)
2237  delete it->second;
2238 
2239  // we resize the arrays and clear the maps so that we are safe when calling
2240  // close_files_and_cleanup multiple times.
2241  sync_IOs.resize(0);
2242  async_IOs.resize(0);
2243  buffmap.clear();
2244  buffmap_elem.clear();
2245 }
2246 
2248 {
2249  for(sync_io_item & it : sync_IOs) {
2250  if(it.data == vec)
2251  return &it.igb;
2252  }
2253 
2254  return NULL;
2255 }
2256 
2257 namespace {
2258 
2259 bool render_output_parameter_arguments(int argc,
2260  char** argv,
2261  std::vector<std::string>* rendered_values)
2262 {
2263  rendered_values->assign(static_cast<std::size_t>(argc), std::string());
2264 
2265  for (int i = 1; i < argc; ++i) {
2266  const std::string argument(argv[i]);
2267  if (argument == "+F" || argument.find("_options_file") != std::string::npos) {
2268  if (i + 1 >= argc) {
2269  std::fprintf(stderr, "parameter file error: missing value for '%s'\n", argument.c_str());
2270  return false;
2271  }
2272  if (argument.find("_options_file") != std::string::npos) {
2273  std::string render_error;
2274  if (!render_parameter_file_value(argv[i + 1], false, &(*rendered_values)[i], &render_error)) {
2275  std::fprintf(stderr, "parameter file error: cannot render '%s': %s\n",
2276  argument.substr(1).c_str(), render_error.c_str());
2277  return false;
2278  }
2279  }
2280  ++i;
2281  continue;
2282  }
2283 
2284  if (argument.empty() || argument[0] != '-') {
2285  continue;
2286  }
2287 
2288  const bool prelast = (i == argc - 1);
2289  const bool parameter_follows = !prelast &&
2290  ((argv[i + 1][0] != '-') ||
2291  ((argv[i + 1][1] >= '0') && (argv[i + 1][1] <= '9')));
2292  if (!parameter_follows) {
2293  continue;
2294  }
2295 
2296  const std::string raw_value(argv[i + 1]);
2297  std::string::size_type front = 0;
2298  while (front < raw_value.size() && raw_value[front] == ' ') {
2299  ++front;
2300  }
2301 
2302  bool aggregate_value = false;
2303  std::string value = raw_value.substr(front);
2304  if (front < raw_value.size() && raw_value[front] == '{') {
2305  aggregate_value = true;
2306  ++front;
2307  while (front < raw_value.size() && raw_value[front] == ' ') {
2308  ++front;
2309  }
2310 
2311  std::string::size_type back = raw_value.size();
2312  while (back > front && raw_value[back - 1] == ' ') {
2313  --back;
2314  }
2315  if (back > front && raw_value[back - 1] == '}') {
2316  --back;
2317  value = raw_value.substr(front, back - front);
2318  } else {
2319  value = raw_value.substr(front);
2320  }
2321  }
2322 
2323  std::string render_error;
2324  if (!render_parameter_file_value(value, aggregate_value, &(*rendered_values)[i], &render_error)) {
2325  std::fprintf(stderr, "parameter file error: cannot render '%s': %s\n",
2326  argv[i] + 1, render_error.c_str());
2327  return false;
2328  }
2329  ++i;
2330  }
2331 
2332  return true;
2333 }
2334 
2335 } // namespace
2336 
2337 bool output_parameter_file(const char *fname, int argc, char **argv)
2338 {
2339  const int max_line_len = 128;
2340  const char* file_sep = "#=======================================================";
2341 
2342  // make sure only root executes this function
2343  if(mpi_runtime_ready() && get_rank() != 0)
2344  return true;
2345 
2346  std::vector<std::string> rendered_values;
2347  if (!render_output_parameter_arguments(argc, argv, &rendered_values)) {
2348  return false;
2349  }
2350 
2351  FILE_SPEC out = f_open(fname, "w");
2352  fprintf(out->fd, "# CARP GIT commit hash: %s\n", GIT_COMMIT_HASH);
2353  fprintf(out->fd, "# dependency hashes: %s\n", SUBREPO_COMMITS);
2354  fprintf(out->fd, "\n");
2355 
2356  // output the command line
2357  char line[8196] = "# ";
2358 
2359  for (int j=0; j<argc; j++) {
2360  strcat(line, argv[j]);
2361  if(strlen(line) > max_line_len) {
2362  fprintf(out->fd, "%s\n", line);
2363  strcpy(line, "# ");
2364  } else
2365  strcat(line, " ");
2366  }
2367 
2368  fprintf(out->fd, "%s\n\n", line);
2369  set_dir(INPUT);
2370 
2371  // convert command line to a par file
2372  for (int i=1; i<argc; i++) {
2373  std::string argument(argv[i]);
2374  if (argument == "+F" || argument.find("_options_file")!= std::string::npos) {
2375 
2376  std::string init = "";
2377  if (argument.find("_options_file")!= std::string::npos) {
2378  fprintf(out->fd, "%s = %s\n", argument.substr(1).c_str(), rendered_values[i].c_str());
2379  init = "#";
2380  }
2381  fprintf(out->fd, "%s>>\n", file_sep);
2382  // import par files
2383  i++;
2384  fprintf(out->fd, "## %s ##\n", argv[i]);
2385  FILE *in = fopen(argv[i], "r");
2386  while (fgets(line, 8196, in))
2387  fprintf(out->fd, "%s%s", init.c_str(), line);
2388  fclose(in);
2389  fprintf(out->fd, "\n##END of %s\n", argv[i]);
2390  fprintf(out->fd, "%s<<\n\n", file_sep);
2391  }
2392  else if(argv[i][0] == '-')
2393  {
2394  bool prelast = (i==argc-1);
2395  bool paramFollows = !prelast && ((argv[i+1][0] != '-') ||
2396  ((argv[i+1][1] >= '0') && (argv[i+1][1] <= '9')));
2397 
2398  // strip leading hyphens from command line opts
2399  // assume options do not start with numbers
2400  if(paramFollows) {
2401  fprintf(out->fd, "%-40s= %s\n", argv[i]+1, rendered_values[i].c_str());
2402  i++;
2403  }
2404  else // a flag was specified
2405  fprintf(out->fd, "%-40s= 1\n", argv[i]);
2406  }
2407  }
2408  f_close(out);
2409  return true;
2410 }
2411 
2412 bool render_parameter_file_value(const std::string& value,
2413  bool aggregate_value,
2414  std::string* rendered,
2415  std::string* error)
2416 {
2417  if (aggregate_value) {
2418  *rendered = value;
2419  if (error != NULL) {
2420  error->clear();
2421  }
2422  return true;
2423  }
2424  return paramschema::quote_legacy_par_value(value, rendered, error);
2425 }
2426 
2427 void savequit()
2428 {
2429  if(!get_physics(elec_phys)) return;
2430 
2431  set_dir(OUTPUT);
2432 
2433  double time = user_globals::tm_manager->time;
2434  char save_fn[512];
2435 
2436  snprintf(save_fn, sizeof save_fn, "exit.save.%.3f.roe", time);
2437  log_msg(NULL, 0, 0, "savequit called at time %g\n", time);
2438 
2440  elec->ion.miif->dump_state(save_fn, time, intra_elec_msh, false, GIT_COMMIT_COUNT);
2441 
2442  cleanup_and_exit();
2443 }
2444 
2445 } // namespace opencarp
opencarp::local_index_t mesh_int_t
Definition: SF_container.h:31
float mesh_real_t
Definition: SF_container.h:32
#define SF_COMM
the default SlimFem MPI communicator
Definition: SF_globals.h:25
opencarp::real_t SF_real
Global scalar type.
Definition: SF_globals.h:30
Async IO functions.
Starts and stops the linear algebra backend the flavor parameter selects.
#define EXIT(A)
finalize the backend, if it runs, and exit
Definition: backend.h:23
Basic utility structs and functions, mostly IO related.
#define FLUSH
Definition: basics.h:305
#define ECHO
Definition: basics.h:302
#define NONL
Definition: basics.h:306
virtual S * ptr()=0
virtual void release_ptr(S *&p)=0
virtual T gsize() const =0
size_t write_binary(FILE *fd)
Write a vector to HD in binary. File descriptor is already set up.
virtual T lsize() const =0
Comfort class. Provides getter functions to access the mesh member variables more comfortably.
Definition: SF_fem_utils.h:689
void set_elem(size_t eidx)
Set the view to a new element.
Definition: SF_fem_utils.h:716
short dimension() const
Definition: SF_fem_utils.h:907
void clear_data()
Clear the mesh data from memory.
Definition: SF_container.h:537
overlapping_layout< T > pl
nodal parallel layout
Definition: SF_container.h:414
vector< T > dsp
connectivity starting index of each element
Definition: SF_container.h:401
vector< S > she
sheet direction
Definition: SF_container.h:406
vector< S > fib
fiber direction
Definition: SF_container.h:405
size_t l_numelem
local number of elements
Definition: SF_container.h:384
std::string name
the mesh name
Definition: SF_container.h:392
void generate_par_layout()
Set up the parallel layout.
Definition: SF_container.h:523
vector< T > con
Definition: SF_container.h:397
MPI_Comm comm
the parallel mesh is defined on a MPI world
Definition: SF_container.h:389
vector< T > & get_numbering(SF_nbr nbr_type)
Get the vector defining a certain numbering.
Definition: SF_container.h:449
vector< T > tag
element tag
Definition: SF_container.h:402
hashmap::unordered_set< int > extr_tag
the element tags based on which the mesh has been extracted
Definition: SF_container.h:409
non_overlapping_layout< T > epl
element parallel layout
Definition: SF_container.h:415
Functor class generating a numbering optimized for PETSc.
Definition: SF_numbering.h:238
void free_scatterings()
Free the registered scatterings.
Redistributes vector data from indexing "a" to indexing "b".
void forward(abstract_vector< T, S > &in, abstract_vector< T, S > &out, bool add=false)
Forward scattering.
Functor class applying a submesh renumbering.
Definition: SF_numbering.h:55
size_t size() const
The current size of the vector.
Definition: SF_vector.h:89
void resize(size_t n)
Resize a vector.
Definition: SF_vector.h:194
void assign(InputIterator s, InputIterator e)
Assign a memory range.
Definition: SF_vector.h:146
T * data()
Pointer to the vector's start.
Definition: SF_vector.h:76
T & push_back(T val)
Definition: SF_vector.h:268
iterator find(const K &key)
Search for key. Return iterator.
Definition: hashmap.hpp:626
void reserve(size_t n)
Definition: hashmap.hpp:719
size_t size() const
Definition: hashmap.hpp:1141
hm_int erase(const K &key)
Definition: hashmap.hpp:1053
hm_int count(const K &key) const
Definition: hashmap.hpp:1067
void insert(InputIterator first, InputIterator last)
Definition: hashmap.hpp:1037
void dump_state(char *, float, opencarp::mesh_t gid, bool, unsigned int)
The abstract physics interface we can use to trigger all physics.
Definition: physics_types.h:44
virtual void destroy()=0
int timer_idx
the timer index received from the timer manager
Definition: physics_types.h:51
virtual void output_timings()
Definition: physics_types.h:61
virtual void compute_step()=0
virtual void initialize()=0
const char * name
The name of the physic, each physic should have one.
Definition: physics_types.h:47
SF::vector< stimulus > stimuli
the electrical stimuli
Definition: electrics.h:250
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
Definition: electrics.cc:825
double timer_val(const int timer_id)
figure out current value of a signal linked to a given timer
Definition: electrics.cc:809
void dim_t(float a)
Definition: IGBheader.h:314
void unites_x(const char *a)
Definition: IGBheader.h:326
void unites_z(const char *a)
Definition: IGBheader.h:332
void unites(const char *a)
Definition: IGBheader.h:338
void unites_y(const char *a)
Definition: IGBheader.h:329
void unites_t(const char *a)
Definition: IGBheader.h:335
float org_t(void)
Definition: IGBheader.h:290
void dim_x(float a)
Definition: IGBheader.h:305
void fileptr(FILE *f)
Definition: IGBheader.cc:312
void inc_t(float a)
Definition: IGBheader.h:302
void inc_x(float a)
Definition: IGBheader.h:293
limpet::MULTI_IF * miif
Definition: ionics.h:82
int run(Electrics &elec)
Full pipeline: construct or load Z, stream vm.igb, write ECG_*.dat.
Definition: leadfield.cc:264
class to store shape definitions
Definition: basics.h:375
std::map< SF::mixed_tuple< mesh_t, int >, sf_vec * > buffmap_elem
Definition: sim_utils.h:351
IGBheader * get_igb_header(const sf_vec *vec)
Get the pointer to the igb header for a vector that was registered for output.
Definition: sim_utils.cc:2247
void write_data()
write registered data to disk
Definition: sim_utils.cc:2167
SF::vector< async_io_item > async_IOs
Definition: sim_utils.h:348
void register_output_sync(sf_vec *inp_data, const mesh_t inp_meshid, const int dpn, const char *name, const char *units, const SF::vector< mesh_int_t > *idx=NULL, bool elem_data=false)
Definition: sim_utils.cc:1993
std::map< SF::mixed_tuple< mesh_t, int >, sf_vec * > buffmap
map data spec -> PETSc vector buffer
Definition: sim_utils.h:350
void close_files_and_cleanup()
close file descriptors
Definition: sim_utils.cc:2223
void register_output(sf_vec *inp_data, const mesh_t inp_meshid, const int dpn, const char *name, const char *units, const SF::vector< mesh_int_t > *idx=NULL, bool elem_data=false)
Register a data vector for output.
Definition: sim_utils.cc:2134
SF::vector< sync_io_item > sync_IOs
Definition: sim_utils.h:347
stim_t type
type of stimulus
Definition: stimulate.h:123
int timer_id
timer for stimulus
Definition: stimulate.h:108
double strength
strength of stimulus
Definition: stimulate.h:79
stim_protocol ptcl
applied stimulation protocol used
Definition: stimulate.h:154
stim_pulse pulse
stimulus wave form
Definition: stimulate.h:153
stim_physics phys
physics of stimulus
Definition: stimulate.h:155
centralize time managment and output triggering
Definition: timer_utils.h:59
void initialize_neq_timer(const std::vector< double > &itrig, double idur, int ID, const char *iname, const char *poolname=nullptr)
Definition: timer_utils.cc:48
double end
final time
Definition: timer_utils.h:67
long d_time
current time instance index
Definition: timer_utils.h:63
bool trigger(int ID) const
Definition: timer_utils.h:152
void initialize_eq_timer(double istart, double iend, int ntrig, double iintv, double idur, int ID, const char *iname, const char *poolname=nullptr)
Definition: timer_utils.cc:33
void reset_timers()
Reset time in timer_manager and then reset registered timers.
Definition: timer_utils.h:101
double start
initial time (nonzero when restarting)
Definition: timer_utils.h:65
void initialize_singlestep_timer(double tg, double idur, int ID, const char *iname, const char *poolname=nullptr)
Definition: timer_utils.h:142
std::vector< base_timer * > timers
vector containing individual timers
Definition: timer_utils.h:70
double time
current time
Definition: timer_utils.h:62
Base class for tracking progress.
Definition: progress.hpp:24
Top-level header of FEM module.
Lead field ECG computation.
void extract_tagbased(const meshdata< T, S > &mesh, meshdata< T, S > &submesh)
Extract a submesh based on element tags.
void write_data_ascii(const MPI_Comm comm, const vector< T > &idx, const vector< S > &data, std::string file, short dpn=1)
void compute_surface_mesh(const meshdata< T, S > &mesh, const SF_nbr numbering, const hashmap::unordered_set< T > &tags, meshdata< T, S > &surfmesh)
Compute the surface of a given mesh.
void print_DD_info(const meshdata< T, S > &mesh)
Print some basic information on the domain decomposition of a mesh.
void read_points(const std::string basename, const MPI_Comm comm, vector< S > &pts, vector< T > &ptsidx)
Read the points and insert them into a list of meshes.
Definition: SF_mesh_io.h:948
void rebalance_mesh(meshdata< T, S > &mesh)
Rebalance the parallel distribution of a mesh, if a local size is 0.
void write_surface(const meshdata< T, S > &surfmesh, std::string surffile)
Definition: SF_mesh_io.h:826
void extract_mesh(const vector< bool > &keep, const meshdata< T, S > &mesh, meshdata< T, S > &submesh)
Extract a submesh from a given mesh.
void unique_resize(vector< T > &_P)
Definition: SF_sort.h:338
void count(const vector< T > &data, vector< S > &cnt)
Count number of occurrences of indices.
Definition: SF_vector.h:317
size_t root_write_ordered(FILE *fd, const vector< T > &idx, const vector< V > &vec, MPI_Comm comm)
Write index value pairs to disk in ordered permutation.
void insert_points(const vector< S > &pts, const vector< T > &ptsidx, std::list< meshdata< T, S > * > &meshlist)
Insert the points from the read-in buffers into a list of distributed meshes.
Definition: SF_mesh_io.h:1046
void read_element_tags(meshdata< T, S > &mesh, std::string filename)
Override element tags from an ASCII file (one int per element, global element order).
Definition: SF_mesh_io.h:541
void redistribute_elements(meshdata< T, S > &mesh, meshdata< T, S > &sendbuff, vector< T > &part)
Redistribute the element data of a parallel mesh among the ranks based on a partitioning.
void write_points_parallel(const meshdata< T, S > &mesh, bool binary, std::string basename)
Write a parallel mesh to harddisk without gathering it on one rank.
T local_nodal_to_local_petsc(const meshdata< T, S > &mesh, int rank, T local_nodal)
void init_vector(SF::abstract_vector< T, S > **vec)
Definition: SF_init.h:127
void binary_sort(vector< T > &_V)
Definition: SF_sort.h:274
void extract_myocardium(const meshdata< T, S > &mesh, meshdata< T, S > &submesh, bool require_fibers=true)
Extract the myocardium submesh.
void write_mesh_parallel(const meshdata< T, S > &mesh, bool binary, std::string basename)
void read_elements(meshdata< T, S > &mesh, std::string basename, bool require_fibers=true)
Read the element data (elements and fibers) of a CARP mesh.
Definition: SF_mesh_io.h:632
@ NBR_PETSC
PETSc numbering of nodes.
Definition: SF_container.h:188
@ NBR_ELEM_REF
The element numbering of the reference mesh (the one stored on HD).
Definition: SF_container.h:189
@ NBR_REF
The nodal numbering of the reference mesh (the one stored on HD).
Definition: SF_container.h:186
@ NBR_SUBMESH
Submesh nodal numbering: The globally ascending sorted reference indices are reindexed.
Definition: SF_container.h:187
@ NBR_ELEM_SUBMESH
Submesh element numbering: The globally ascending sorted reference indices are reindexed.
Definition: SF_container.h:190
int load_ionic_module(const char *)
void COMPUTE_do_output(SF_real *dat, const int lsize, const int IO_id)
Definition: async_io.cc:381
int COMPUTE_register_output(const SF::vector< mesh_int_t > &idx, const int dpn, const char *name, const char *units)
Definition: async_io.cc:89
std::map< int, std::string > units
Definition: stimulate.cc:26
MPI_Comm IO_Intercomm
Communicator between IO and compute worlds.
Definition: main.cc:48
FILE * petsc_error_fd
file descriptor for petsc error output
Definition: main.cc:44
timer_manager * tm_manager
a manager for the various physics timers
Definition: main.cc:40
std::map< datavec_t, sf_vec * > datavec_reg
important solution vectors from different physics
Definition: main.cc:42
bool using_legacy_stimuli
flag storing whether legacy stimuli are used
Definition: main.cc:46
SF::scatter_registry scatter_reg
Registry for the different scatter objects.
Definition: main.cc:32
std::map< mesh_t, sf_mesh > mesh_reg
Registry for the different meshes used in a multi-physics simulation.
Definition: main.cc:34
std::map< physic_t, Basic_physic * > physics_reg
the physics
Definition: main.cc:38
void time_to_string(float time, char *str, short str_size)
Definition: sim_utils.cc:1181
physic_t
Identifier for the different physics we want to set up.
Definition: physics_types.h:36
@ iotm_chkpt_list
Definition: timer_utils.h:29
@ iotm_console
Definition: timer_utils.h:29
@ iotm_spacedt
Definition: timer_utils.h:29
@ iotm_trace
Definition: timer_utils.h:29
@ iotm_chkpt_intv
Definition: timer_utils.h:29
@ iotm_state_var
Definition: timer_utils.h:29
sf_vec * get_data(datavec_t d)
Retrieve a petsc data vector from the data registry.
Definition: sim_utils.cc:1361
bool petsc_active()
Definition: backend.cc:53
void initialize_physics()
Initialize all physics in the registry.
Definition: sim_utils.cc:497
bool setup_IO(int argc, char **argv)
Definition: sim_utils.cc:833
void retag_elements(sf_mesh &mesh, TagRegion *tagRegs, int ntr)
Definition: sim_utils.cc:1443
void parse_params_cpy(int argc, char **argv)
Initialize input parameters on a copy of the real command line parameters.
Definition: sim_utils.cc:460
sf_mesh & get_mesh(const mesh_t gt)
Get a mesh by specifying the gridID.
Definition: sf_interface.cc:18
int set_ignore_flags(int mode)
Definition: sim_utils.cc:574
int get_size(MPI_Comm comm=SF_COMM)
Definition: basics.h:284
SF::scattering * get_permutation(const int mesh_id, const int perm_id, const int dpn)
Get the PETSC to canonical permutation scattering for a given mesh and number of dpn.
SF::meshdata< mesh_int_t, mesh_real_t > sf_mesh
Definition: sf_interface.h:33
datavec_t
Enum used to adress the different data vectors stored in the data registry.
Definition: physics_types.h:84
int set_dir(IO_t dest)
Definition: sim_utils.cc:896
void cleanup_and_exit()
Definition: sim_utils.cc:1931
void register_physics()
Register physics to the physics registry.
Definition: sim_utils.cc:475
void post_process()
do postprocessing
Definition: sim_utils.cc:1306
void check_and_convert_params()
Here we want to put all parameter checks, conversions and modifications that have been littered throu...
Definition: sim_utils.cc:624
short get_mesh_dim(mesh_t id)
get (lowest) dimension of the mesh used in the experiment
Definition: sim_utils.cc:1976
T get_global(T in, MPI_Op OP, MPI_Comm comm=SF_COMM)
Do a global reduction on a variable.
Definition: basics.h:219
@ GND_ex
Definition: stimulate.h:64
bool is_potential(stim_t type)
uses current for stimulation
Definition: stimulate.cc:52
bool phys_defined(int physreg)
function to check if certain physics are defined
void update_console_output(const timer_manager &tm, prog_stats &p)
Definition: sim_utils.cc:1190
bool output_parameter_file(const char *fname, int argc, char **argv)
Definition: sim_utils.cc:2337
void show_build_info()
show the build info, exit if -buildinfo was provided. This code runs before MPI_Init().
Definition: sim_utils.cc:612
void finalize_backend()
Definition: backend.cc:87
FILE_SPEC f_open(const char *fname, const char *mode)
Open a FILE_SPEC.
Definition: basics.cc:111
void savequit()
save state and quit simulator
Definition: sim_utils.cc:2427
bool have_permutation(const int mesh_id, const int perm_id, const int dpn)
void set_io_dirs(char *sim_ID, char *pp_ID, IO_t init)
Definition: sim_utils.cc:762
void register_data(sf_vec *dat, datavec_t d)
Register a data vector in the global registry.
Definition: sim_utils.cc:1371
bool render_parameter_file_value(const std::string &value, bool aggregate_value, std::string *rendered, std::string *error)
Definition: sim_utils.cc:2412
void basic_timer_setup()
Here we set up the timers that we always want to have, independent of physics.
Definition: sim_utils.cc:908
char * get_file_dir(const char *file)
Definition: sim_utils.cc:1949
IO_t
The different output (directory) types.
Definition: sim_utils.h:39
@ POSTPROC
Definition: sim_utils.h:39
@ CURDIR
Definition: sim_utils.h:39
@ OUTPUT
Definition: sim_utils.h:39
void get_protocol_column_widths(std::vector< int > &col_width, std::vector< int > &used_timer_ids)
Definition: sim_utils.cc:957
int get_phys_index(int physreg)
get index in param_globals::phys_region array for a certain phys region
void intersect_output_restriction(SF::vector< mesh_int_t > *&restr, const SF::vector< mesh_int_t > &selected_idx)
Intersect an existing output restriction with another local index set.
Definition: sim_utils.cc:1804
bool mpi_runtime_ready()
Definition: basics.h:254
void check_nullspace_ok()
Definition: sim_utils.cc:595
int postproc_recover_phie()
Definition: electrics.cc:2102
char * dupstr(const char *old_str)
Definition: basics.cc:27
int plot_protocols(const char *fname)
plot simulation protocols (I/O timers, stimuli, boundary conditions, etc)
Definition: sim_utils.cc:1000
void indices_from_geom_shape(SF::vector< mesh_int_t > &idx, const sf_mesh &mesh, const geom_shape shape, const bool nodal)
Populate vertex data with the vertices inside a defined box shape.
Definition: fem_utils.cc:169
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
Definition: basics.cc:55
mesh_t
The enum identifying the different meshes we might want to load.
Definition: sf_interface.h:44
@ reference_msh
Definition: sf_interface.h:54
@ extra_elec_msh
Definition: sf_interface.h:46
@ intra_elec_msh
Definition: sf_interface.h:45
void setup_meshes(bool require_fibers=true)
Read in the reference mesh and use its data to populate all meshes registered in the mesh registry.
Definition: sim_utils.cc:1516
void get_time(double &tm)
Definition: basics.h:430
bool mesh_is_registered(const mesh_t gt)
check wheter a SF mesh is set
Definition: sf_interface.cc:48
bool parse_gridout_tags(hashmap::unordered_set< int > &output_tags)
Parse the gridout_tags idset into a unique set of region IDs.
Definition: sim_utils.cc:1715
void validate_gridout_tags(hashmap::unordered_set< int > &output_tags, const SF::vector< mesh_t > &mesh_ids)
Warn about selected gridout tags that are absent from the relevant meshes.
Definition: sim_utils.cc:1754
void output_meshes()
Definition: sim_utils.cc:1834
Basic_physic * get_physics(physic_t p, bool error_if_missing)
Convinience function to get a physics.
Definition: sim_utils.cc:1345
int get_rank(MPI_Comm comm=SF_COMM)
Definition: basics.h:270
size_t renormalise_fibres(SF::vector< mesh_real_t > &fib, size_t l_numelem)
Definition: sim_utils.cc:1492
void destroy_physics()
Destroy all physics in the registry.
Definition: sim_utils.cc:521
void ignore_extracellular_stim(Stimulus *st, int ns, int ignore)
Definition: sim_utils.cc:548
void init_console_output(const timer_manager &tm, prog_stats &p)
Definition: sim_utils.cc:1165
tagreg_t
tag regions types. must be in line with carp.prm
Definition: sim_utils.h:42
@ tagreg_list
Definition: sim_utils.h:42
V timing(V &t2, const V &t1)
Definition: basics.h:442
void read_indices(SF::vector< T > &idx, const std::string filename, const hashmap::unordered_map< mesh_int_t, mesh_int_t > &dd_map, MPI_Comm comm)
Read indices from a file.
Definition: fem_utils.h:105
std::string get_basename(const std::string &path)
Definition: basics.cc:44
void build_tagged_nodal_output_restriction(sf_mesh &mesh, const hashmap::unordered_set< int > &output_tags, SF::vector< mesh_int_t > &output_idx, bool async)
Build a local output-vector restriction from mesh element tags.
Definition: sim_utils.cc:1737
void update_cwd()
save the current working directory to curdir so that we can switch back to it if needed.
Definition: sim_utils.cc:891
void f_close(FILE_SPEC &f)
Close a FILE_SPEC.
Definition: basics.cc:138
void setup_petsc_err_log()
set up error logs for PETSc, so that it doesnt print errors to stderr.
Definition: sim_utils.cc:1958
void simulate()
Main simulate loop.
Definition: sim_utils.cc:1218
void log_runtime_apl_notice()
log the runtime APL notice for the simulator binary.
Definition: sim_utils.cc:747
void parse_mesh_types()
Parse the phys_type CLI parameters and set up (empty) SF::meshdata meshes.
Definition: sim_utils.cc:1381
#define IGB_VEC9_f
Definition: IGBheader.h:60
#define IGB_VEC3_f
Definition: IGBheader.h:55
#define IGB_FLOAT
Definition: IGBheader.h:44
#define IGB_VEC4_f
Definition: IGBheader.h:57
Top-level header of physics module.
#define PHYSREG_INTRA_ELEC
Definition: sf_interface.h:69
#define PHYSREG_LAPLACE
Definition: sf_interface.h:74
#define PETSC_TO_CANONICAL
Permute algebraic data from PETSC to canonical ordering.
Definition: sf_interface.h:64
#define PHYSREG_EIKONAL
Definition: sf_interface.h:71
#define PHYSREG_EMI
Definition: sf_interface.h:75
#define ELEM_PETSC_TO_CANONICAL
Permute algebraic element data from PETSC to canonical ordering.
Definition: sf_interface.h:66
#define PHYSREG_EXTRA_ELEC
Definition: sf_interface.h:70
Simulator-level utility execution control functions.
#define BIDOMAIN
Definition: sim_utils.h:174
#define RECOVER_PHIE
Definition: sim_utils.h:179
#define MONODOMAIN
Definition: sim_utils.h:173
#define EXP_POSTPROCESS
Definition: sim_utils.h:192
#define PSEUDO_BIDM
Definition: sim_utils.h:175
#define LEADFIELD
Definition: sim_utils.h:185
#define EXP_LAPLACE
Definition: sim_utils.h:190
#define Extracellular_I
Definition: stimulate.h:23
#define Extracellular_V
Definition: stimulate.h:24
#define STM_IGNORE_PSEUDO_BIDM
Definition: stimulate.h:48
#define NO_EXTRA_GND
Definition: stimulate.h:42
#define NO_EXTRA_I
Definition: stimulate.h:44
#define Intracellular_I
Definition: stimulate.h:26
#define Ignore_Stim
Definition: stimulate.h:34
#define STM_IGNORE_MONODOMAIN
Definition: stimulate.h:47
#define IsExtraV(A)
Definition: stimulate.h:37
#define IGNORE_NONE
Definition: stimulate.h:41
#define STM_IGNORE_BIDOMAIN
Definition: stimulate.h:46
#define Extracellular_Ground
Definition: stimulate.h:25
#define Extracellular_V_OL
Definition: stimulate.h:27
#define Transmembrane_I
Definition: stimulate.h:22
#define NO_EXTRA_V
Definition: stimulate.h:43
const SF::vector< mesh_int_t > * restr_idx
when using asyncIO, here we store the different IDs associated to the vectors we output
Definition: sim_utils.h:325
SF::vector< mesh_int_t > restr_petsc_idx
pointer to index vector with nodal indices we restrict to.
Definition: sim_utils.h:326
int IO_id
pointer to data registered for output
Definition: sim_utils.h:324
long d_trigger_dur
discrete duration
Definition: timer_utils.h:43
const char * name
timer name
Definition: timer_utils.h:38
bool triggered
flag indicating trigger at current time step
Definition: timer_utils.h:39
File descriptor struct.
Definition: basics.h:121
for display execution progress and statistical data of electrical solve
Definition: sim_utils.h:306
double curr
current output wallclock time
Definition: sim_utils.h:310
double start
output start wallclock time
Definition: sim_utils.h:308
double last
last output wallclock time
Definition: sim_utils.h:309
SF::vector< mesh_int_t > restr_global_idx
pointer to index vector used for restricting output.
Definition: sim_utils.h:316
bool elem_flag
igb header we use for output
Definition: sim_utils.h:318
IGBheader igb
global canonical indices matching restr_idx.
Definition: sim_utils.h:317
const SF::vector< mesh_int_t > * restr_idx
pointer to data registered for output
Definition: sim_utils.h:315
SF::mixed_tuple< mesh_t, int > spec
flag whether the data is elements-wise
Definition: sim_utils.h:319