openCARP
Doxygen code documentation for the open cardiac electrophysiology simulator openCARP
sim_utils.cc
Go to the documentation of this file.
1 // ----------------------------------------------------------------------------
2 // openCARP is an open cardiac electrophysiology simulator.
3 //
4 // Copyright (C) 2020 openCARP project
5 //
6 // This program is licensed under the openCARP Academic Public License (APL)
7 // v1.0: You can use and redistribute it and/or modify it in non-commercial
8 // academic environments under the terms of APL as published by the openCARP
9 // project v1.0, or (at your option) any later version. Commercial use requires
10 // a commercial license (info@opencarp.org).
11 //
12 // This program is distributed without any warranty; see the openCARP APL for
13 // more details.
14 //
15 // You should have received a copy of the openCARP APL along with this program
16 // and can find it online: http://www.opencarp.org/license
17 // ----------------------------------------------------------------------------
18 
27 #include "basics.h"
28 #include "sim_utils.h"
29 #include "fem.h"
30 #include "physics.h"
31 #include "async_io.h"
32 #include "SF_init.h"
33 
34 #include <libgen.h>
35 #include <fstream>
36 #include <iomanip>
37 
38 
39 namespace opencarp {
40 
41 static char input_dir[1024], // directory from which to read input
42  output_dir[1024], // directory to which to write results
43  postproc_dir[1024], // postprocessing directory
44  current_dir[1024]; // current directory
45 
46 void parse_params_cpy(int argc, char** argv)
47 {
48  // copy the command line parameters that are for carp (i.e. before the first "+")
49  int cpy_argc = argc;
50  SF::vector<char*> cpy_argv(cpy_argc, NULL);
51 
52  for(int i=0; i < cpy_argc; i++) {
53  if(strcmp(argv[i], "+") != 0) {
54  cpy_argv[i] = dupstr(argv[i]);
55  }
56  else {
57  cpy_argc = i;
58  break;
59  }
60  }
61 
62  // launch param on the carp command line parameters
63  int param_argc = cpy_argc;
64  int status;
65 
66  do {
67  status = param(PARAMETERS, &param_argc, cpy_argv.data());
68  if ( status==PrMERROR||status==PrMFATAL )
69  fprintf( stderr, "\n*** Error reading parameters\n\n");
70  else if ( status == PrMQUIT )
71  fprintf( stderr, "\n*** Quitting by user's request\n\n");
72  } while (status == PrMERROR);
73 
74  // if --output-setup then loop over PARAMETERS
75  // output value of each PARAMETER
76  if (param_globals::output_setup)
77  param_output(PARAMETERS, 1);
78 
79  // free the parameters
80  for(int i=0; i<param_argc; i++)
81  free(cpy_argv[i]);
82 
83  // exit on error
84  if (status & PrMERROR) exit(status);
85 
86 }
87 
88 
90 {
91  // here all the physics can be registered to the physics registry
92  // then they should be processed automatically
96 #if WITH_EMI_MODEL
98 #else
99  log_msg(NULL, 5, ECHO, "The EMI model was not compiled for this binary.\n");
100  exit(EXIT_FAILURE);
101 #endif
102 
105 
108 }
109 
111 {
112  log_msg(0,0,0, "\n *** Initializing physics ***\n");
113 
114  //load in the external imp modules
115 #ifdef HAVE_DLOPEN
116  for (int ii = 0; ii < param_globals::num_external_imp; ii++) {
117  int loading_succeeded = limpet::load_ionic_module(param_globals::external_imp[ii]);
118  assert(loading_succeeded);
119  }
120 #else
121  if(param_globals::num_external_imp)
122  log_msg(NULL, 4, ECHO,"Loading of external LIMPET modules not enabled.\n"
123  "Recompile with DLOPEN set.\n" );
124 #endif
125 
126  // init physics via Basic_physic interface
127  for(auto it : user_globals::physics_reg) {
128  Basic_physic* p = it.second;
129  log_msg(NULL, 0, 0, "Initializing %s ..", p->name);
130  p->initialize();
131  }
132 }
133 
135 {
136  log_msg(0,0,0, "\n *** Destroying physics ***\n");
137 
138  for(auto it : user_globals::physics_reg) {
139  Basic_physic* p = it.second;
140  log_msg(NULL, 0, 0, "Destroying %s ..", p->name);
141  p->destroy();
142  }
143 }
144 
145 // ignore_extracellular stim must be moved to stimulate.cc to be able
146 // to use all defined set operations instead of defines
147 
161 void ignore_extracellular_stim(Stimulus *st, int ns, int ignore)
162 {
163  // needs to be switch to stim enum types defined in stimulate.h
164  for ( int i=0; i<ns; i++ ) {
165  int turn_off = 0;
166  turn_off += (st[i].stimtype == Extracellular_Ground) && (ignore & NO_EXTRA_GND);
167  turn_off += (IsExtraV(st[i])) && (ignore & NO_EXTRA_V);
168  turn_off += (st[i].stimtype==Extracellular_I) && (ignore & NO_EXTRA_I);
169 
170  if (turn_off) {
171  st[i].stimtype = Ignore_Stim;
172  log_msg( NULL, 1, 0, "Extracellular stimulus %d ignored for monodomain", i );
173  } else if ( st[i].stimtype==Intracellular_I ) {
174  st[i].stimtype = Transmembrane_I;
175  log_msg( NULL, 1, 0, "Intracellular stimulus %d converted to transmembrane", i );
176  }
177  }
178 }
179 
187 int set_ignore_flags( int mode )
188 {
189  if(mode==MONODOMAIN)
190  return STM_IGNORE_MONODOMAIN;
191  if(mode==BIDOMAIN)
192  return STM_IGNORE_BIDOMAIN;
193  if(mode==PSEUDO_BIDM)
194  return STM_IGNORE_PSEUDO_BIDM;
195 
196  return IGNORE_NONE;
197 }
198 
199 
210 {
211  if(param_globals::floating_ground)
212  return;
213 
214  Stimulus* s = param_globals::stimulus;
215 
216  for(int i=0; i < param_globals::num_stim; i++) {
217  if(s[i].stimtype == Extracellular_Ground ||
218  s[i].stimtype == Extracellular_V ||
219  s[i].stimtype == Extracellular_V_OL)
220  return;
221  }
222 
223  // for now we only warn, although we should actually stop the run
224  log_msg( NULL, 4, 0,"Elliptic system is singular!\n"
225  "Either set floating_ground=1 or use an explicit ground:voltage (stimulus[X].stimtype=3)\n"
226  "Do not trust the elliptic solution of this simulation run!\n");
227 }
228 
230 {
231  printf("\n""*** GIT tag: %s\n", GIT_COMMIT_TAG);
232  printf( "*** GIT hash: %s\n", GIT_COMMIT_HASH);
233  printf( "*** GIT repo: %s\n", GIT_PATH);
234  printf( "*** dependency commits: %s\n\n", SUBREPO_COMMITS);
235 }
236 
238 {
239  // convert time steps to milliseconds
240  param_globals::dt /= 1000.;
241 
242  // check parab-solve solution method
243  if(param_globals::mass_lumping == 0 && param_globals::parab_solve==0) {
244  log_msg(NULL, 2, ECHO,
245  "Warning: explicit solve not possible without mass lumping. \n"
246  "Switching to Crank-Nicolson!\n\n");
247 
248  param_globals::parab_solve = 1;
249  }
250 
251  // check if we have to modify stimuli based on used bidomain setting
252  if(!param_globals::extracell_monodomain_stim)
253  ignore_extracellular_stim(param_globals::stimulus, param_globals::num_stim,
254  set_ignore_flags(param_globals::bidomain));
255 
256  // check nullspace if necessary
257  // if((param_globals::bidomain==BIDOMAIN && !param_globals::ellip_use_pt) ||
258  // (param_globals::bidomain==PSEUDO_BIDM && !param_globals::parab_use_pt))
259  // check_nullspace_ok();
260 
261  if(param_globals::t_sentinel > 0 && param_globals::sentinel_ID < 0 ) {
262  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");
263  }
264 
265  if(param_globals::num_external_imp > 0 ) {
266  for(int ext_imp_i = 0; ext_imp_i < param_globals::num_external_imp; ext_imp_i++) {
267  if(param_globals::external_imp[ext_imp_i][0] != '/') {
268  log_msg(0,5,0, "external_imp[%d] error: absolute paths must be used for .so file loading (\'%s\')",
269  ext_imp_i, param_globals::external_imp[ext_imp_i]);
270  EXIT(1);
271  }
272  }
273  }
274 
275  if(param_globals::experiment == EXP_LAPLACE && param_globals::bidomain != 1) {
276  log_msg(0,4,0, "Warning: Laplace experiment mode requires bidomain = 1. Setting bidomain = 1.");
277  param_globals::bidomain = 1;
278  }
279 
280  if(param_globals::num_phys_regions == 0) {
281  log_msg(0,4,0, "Warning: No physics region defined! Please set phys_region parameters to correctly define physics.");
282 
283  if(param_globals::experiment != EXP_LAPLACE) {
284  log_msg(0,4,0, "Intra-elec and Extra-elec domains will be derived from fibers.\n");
285  param_globals::num_phys_regions = param_globals::bidomain ? 2 : 1;
286  param_globals::phys_region = (p_region*) malloc(param_globals::num_phys_regions * sizeof(p_region));
287  param_globals::phys_region[0].ptype = PHYSREG_INTRA_ELEC;
288  param_globals::phys_region[0].name = strdup("Autogenerated intracellular Electrics");
289  param_globals::phys_region[0].num_IDs = 0;
290 
291  if(param_globals::bidomain) {
292  param_globals::phys_region[1].ptype = PHYSREG_EXTRA_ELEC;
293  param_globals::phys_region[1].name = strdup("Autogenerated extracellular Electrics");
294  param_globals::phys_region[1].num_IDs = 0;
295  }
296  } else {
297  log_msg(0,4,0, "Laplace domain will be derived from fibers.\n");
298  param_globals::num_phys_regions = 1;
299  param_globals::phys_region = (p_region*) malloc(param_globals::num_phys_regions * sizeof(p_region));
300  param_globals::phys_region[0].ptype = PHYSREG_LAPLACE;
301  param_globals::phys_region[0].name = strdup("Autogenerated Laplace");
302  param_globals::phys_region[0].num_IDs = 0;
303  }
304  }
305 
306  if(param_globals::experiment == EXP_LAPLACE && !phys_defined(PHYSREG_LAPLACE)) {
307  log_msg(0,4,0, "Warning: Laplace experiment mode requires a laplace physics regions defined.");
308 
309  int idx = -1;
310  if((idx = get_phys_index(PHYSREG_EXTRA_ELEC)) > -1) {
311  log_msg(0,4,0, "Converting the defined extracellular-electrics-region to laplace-region.");
312  param_globals::phys_region[idx].ptype = PHYSREG_LAPLACE;
313  } else if ((idx = get_phys_index(PHYSREG_INTRA_ELEC)) > -1) {
314  log_msg(0,4,0, "Converting the defined intracellular-electrics-region to laplace-region.");
315  param_globals::phys_region[idx].ptype = PHYSREG_LAPLACE;
316  } else {
317  param_globals::num_phys_regions += 1;
318  param_globals::phys_region = (p_region*) realloc(param_globals::phys_region, param_globals::num_phys_regions * sizeof(p_region));
319 
320  param_globals::phys_region[param_globals::num_phys_regions - 1].ptype = PHYSREG_LAPLACE;
321  param_globals::phys_region[param_globals::num_phys_regions - 1].name = strdup("Autogenerated Laplace");
322  param_globals::phys_region[param_globals::num_phys_regions - 1].num_IDs = 0;
323  }
324  }
325 
326 #ifndef WITH_PARMETIS
327  if(param_globals::pstrat == 1) {
328  log_msg(0,3,0, "openCARP was built without Parmetis support. Swithing to KDtree.");
329  param_globals::pstrat = 2;
330  }
331 #endif
332 
333  // check if we have the legacy stimuli or the new stimuli defined by the user
334  bool legacy_stim_set = false, new_stim_set = false;
335 
336  for(int i=0; i<param_globals::num_stim; i++) {
337  Stimulus & legacy_stim = param_globals::stimulus[i];
338  Stim & new_stim = param_globals::stim[i];
339 
340  if(legacy_stim.stimtype || legacy_stim.strength)
341  legacy_stim_set = true;
342 
343  if(new_stim.crct.type || new_stim.pulse.strength)
344  new_stim_set = true;
345  }
346 
347  if(legacy_stim_set || new_stim_set) {
348  if(legacy_stim_set && new_stim_set) {
349  log_msg(0,4,0, "Warning: Legacy stimuli and default stimuli are defined. Only default stimuli will be used!");
350  }
351  else if (legacy_stim_set) {
352  log_msg(0,1,0, "Warning: Legacy stimuli defined. Please consider switching to stimulus definition \"stim[]\"!");
354  }
355  }
356  else {
357  log_msg(0,4,0, "Warning: No potential or current stimuli found!");
358  }
359 }
360 
361 void set_io_dirs(char *sim_ID, char *pp_ID, IO_t init)
362 {
363  int flg = 0, err = 0, rank = get_rank();
364 
365  char *ptr = getcwd(current_dir, 1024);
366  if (ptr == NULL) err++;
367  ptr = getcwd(input_dir, 1024);
368  if (ptr == NULL) err++;
369  //if (param_globals::experiment == 4 && post_processing_opts == MECHANIC_POSTPROCESS)
370  // { sim_ID = param_globals::ppID; param_globals::ppID = "POSTPROC_DIR"; }
371 
372  // output directory
373  if (rank == 0) {
374  if (strcmp(sim_ID, "OUTPUT_DIR")) {
375  if (mkdir(sim_ID, 0775)) { // rwxrwxr-x
376  if (errno == EEXIST ) {
377  log_msg(NULL, 2, 0, "Output directory exists: %s\n", sim_ID);
378  } else {
379  log_msg(NULL, 5, 0, "Unable to make output directory\n");
380  flg = 1;
381  }
382  }
383  } else if (mkdir(sim_ID, 0775) && errno != EEXIST) {
384  log_msg(NULL, 5, 0, "Unable to make output directory\n");
385  flg = 1;
386  }
387  }
388 
389  // terminate?
390  if(get_global(flg, MPI_SUM)) { EXIT(-1); }
391 
392  err += chdir(sim_ID);
393  ptr = getcwd(output_dir, 1024);
394  if (ptr == NULL) err++;
395 
396  // terminate?
397  if(get_global(err, MPI_SUM)) { EXIT(-1); }
398 
399  err += chdir(output_dir);
400 
401  // postprocessing directory
402  if (rank == 0 && (param_globals::experiment==EXP_POSTPROCESS)) {
403 
404  if (strcmp(param_globals::ppID, "POSTPROC_DIR")) {
405  if (mkdir(param_globals::ppID, 0775)) { // rwxrwxr-x
406  if (errno == EEXIST ) {
407  log_msg(NULL, 2, ECHO, "Postprocessing directory exists: %s\n\n", param_globals::ppID);
408  } else {
409  log_msg(NULL, 5, ECHO, "Unable to make postprocessing directory\n\n");
410  flg = 1;
411  }
412  }
413  } else if (mkdir(param_globals::ppID, 0775) && errno != EEXIST) {
414  log_msg(NULL, 5, ECHO, "Unable to make postprocessing directory\n\n");
415  flg = 1;
416  }
417 
418  }
419 
420  if(get_global(flg, MPI_SUM)) { EXIT(-1); }
421 
422  err += chdir(param_globals::ppID);
423  ptr = getcwd(postproc_dir, 1024);
424  if (ptr == NULL) err++;
425  err = chdir(output_dir);
426  if(get_global(err, MPI_SUM)) { EXIT(-1); }
427 
428  err = set_dir(init);
429  if(get_global(err, MPI_SUM)) { EXIT(-1); }
430 }
431 
432 bool setup_IO(int argc, char **argv)
433 {
434  bool io_node = false;
435  int psize = get_size(), prank = get_rank();
436 
437  if (param_globals::num_io_nodes > 0) {
438  // Can't do async IO with only one core
439  if (get_size() == 1) {
440  log_msg(NULL, 5, 0, "You cannot run with async IO on only one core.\n");
441  EXIT(EXIT_FAILURE);
442  }
443  // Can't do async IO with more IO cores than compute cores
444  if (2 * param_globals::num_io_nodes >= psize) {
445  log_msg(NULL, 5, 0, "The number of IO cores be less " "than the number of compute cores.");
446  EXIT(EXIT_FAILURE);
447  }
448 #if 0
449  if (param_globals::num_PS_nodes && param_globals::num_io_nodes > param_globals::num_PS_nodes) {
450  LOG_MSG(NULL, 5, 0,
451  "The number of IO cores (%d) should not "
452  "exceed the number of PS compute cores (%d).\n",
453  param_globals::num_io_nodes, param_globals::num_PS_nodes);
454  EXIT(-1);
455  }
456 #endif
457  // root IO node is global node 0
458  io_node = prank < param_globals::num_io_nodes;
459 
460  MPI_Comm comm;
461  MPI_Comm_split(PETSC_COMM_WORLD, io_node, get_rank(), &comm);
462  MPI_Comm_set_name(comm, io_node ? "IO" : "compute");
463 
464  PETSC_COMM_WORLD = comm; // either the compute world or IO world
465 
466  prank = get_rank();
467 
468  MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, io_node ? param_globals::num_io_nodes : 0,
470 
472  log_msg(NULL, 4, 0, "Global node %d, Comm rank %d != Intercomm rank %d\n",
473  get_rank(MPI_COMM_WORLD), get_rank(PETSC_COMM_WORLD),
475  } else
476  MPI_Comm_set_name(PETSC_COMM_WORLD, "compute");
477 
478  set_io_dirs(param_globals::simID, param_globals::ppID, OUTPUT);
479 
480  if((io_node || !param_globals::num_io_nodes) && !prank)
481  output_parameter_file("parameters.par", argc, argv);
482 
483  return io_node;
484 }
486 {
487  getcwd(current_dir, 1024);
488 }
489 
490 int set_dir(IO_t dest)
491 {
492  int err;
493 
494  if (dest==OUTPUT) err = chdir(output_dir);
495  else if (dest==POSTPROC) err = chdir(postproc_dir);
496  else if (dest==CURDIR) err = chdir(current_dir);
497  else err = chdir(input_dir);
498 
499  return err;
500 }
501 
503 {
504  // if we restart from a checkpoint, the timer_manager will be notified at a later stage
505  double start_time = 0.0;
506  user_globals::tm_manager = new timer_manager(param_globals::dt, start_time, param_globals::tend);
507 
508  double end_time = param_globals::tend;
510 
511  if(param_globals::experiment == EXP_LAPLACE) {
512  tm.initialize_singlestep_timer(tm.time, 0, iotm_console, "IO (console)", nullptr);
513  tm.initialize_singlestep_timer(tm.time, 0, iotm_state_var, "IO (state vars)", nullptr);
514  tm.initialize_singlestep_timer(tm.time, 0, iotm_spacedt, "IO (spacedt)", nullptr);
515  }
516  else {
517  tm.initialize_eq_timer(tm.time, end_time, 0, param_globals::timedt, 0, iotm_console, "IO (console)");
518  tm.initialize_eq_timer(tm.time, end_time, 0, param_globals::spacedt, 0, iotm_state_var, "IO (state vars)");
519  tm.initialize_eq_timer(tm.time, end_time, 0, param_globals::spacedt, 0, iotm_spacedt, "IO (spacedt)");
520  }
521 
522  if(param_globals::num_tsav) {
523  std::vector<double> trig(param_globals::num_tsav);
524  for(size_t i=0; i<trig.size(); i++) trig[i] = param_globals::tsav[i];
525 
526  tm.initialize_neq_timer(trig, 0, iotm_chkpt_list, "instance checkpointing");
527  }
528 
529  if(param_globals::chkpt_intv)
530  tm.initialize_eq_timer(param_globals::chkpt_start, param_globals::chkpt_stop, 0,
531  param_globals::chkpt_intv, 0, iotm_chkpt_intv, "interval checkpointing");
532 
533  if(param_globals::num_trace)
534  tm.initialize_eq_timer(tm.time, end_time, 0, param_globals::tracedt, 0, iotm_trace, "IO (node trace)");
535 }
536 
537 void get_protocol_column_widths(std::vector<int> & col_width, std::vector<int> & used_timer_ids)
538 {
539  char buff[256];
540  const short padding = 4;
541  Electrics* elec = (Electrics*) get_physics(elec_phys, false);
542 
543  do {
544  snprintf(buff, sizeof buff, "%.3lf", user_globals::tm_manager->time);
545  if(col_width[0] < int(strlen(buff)+padding))
546  col_width[0] = strlen(buff)+padding;
547 
548  snprintf(buff, sizeof buff, "%.3d", user_globals::tm_manager->d_time);
549  if(col_width[1] < int(strlen(buff)+padding))
550  col_width[1] = strlen(buff)+padding;
551 
552  int col = 2;
553  for (size_t tid = 0; tid < used_timer_ids.size(); tid++)
554  {
555  int timer_id = used_timer_ids[tid];
557 
558  if(t->d_trigger_dur && elec) {
559  // figure out value of signal linked to this timer
560  double val = 0.;
561 
562  // determine timer linked to which physics, for now we deal with electrics only
563  val = elec->timer_val(timer_id);
564 
565  snprintf(buff, sizeof buff, "%.3lf", val);
566  if(col_width[col] < int(strlen(buff)+padding))
567  col_width[col] = strlen(buff)+padding;
568  }
569  col++;
570  }
571 
572  // advance time
574  } while (!user_globals::tm_manager->elapsed());
575 
577 }
580 int plot_protocols(const char *fname)
581 {
582  int err = {0};
583  std::ofstream fh;
584  const char* smpl_endl = "\n";
585 
586  if(!get_rank()) {
587  fh.open(fname);
588 
589  // If we couldn't open the output file stream for writing
590  if (!fh) {
591  // Print an error and exit
592  log_msg(0,5,0,"Protocol file %s could not be opened for writing!\n", fname);
593  err = -1;
594  }
595  }
596 
597  // broadcast and return if err
598  if(get_global(err, MPI_SUM))
599  return err;
600 
601  // only rank 0 writes
602  if(!get_rank()) {
603 
604  // collect timer information, label, short label, unit
605  std::vector<std::string> col_labels = {"time", "tick"};
606  std::vector<std::string> col_short_labels = {"A", "B"};
607  std::vector<std::string> col_unit_labels = {"ms", "--" };
608  std::vector<int> col_width = {4, 4};
609 
610  char c_label = {'C'};
611  std::string label = {""};
612  std::string unit = {""};
613 
614  // here we store the IDs of the timers that we care about. currently this are the IO and TS timers
615  // and the electricts timers
616  std::vector<int> used_timer_ids;
617  std::vector<int> used_stim_ids;
618 
619  Electrics* elec = (Electrics*) get_physics(elec_phys, false);
620  if(elec) {
621  int sidx = 0;
622  for(const stimulus & s : elec->stimuli) {
623  if(s.ptcl.timer_id > -1) {
625  if(t) {
626  used_timer_ids.push_back(s.ptcl.timer_id);
627  used_stim_ids.push_back(sidx);
628  }
629  }
630 
631  sidx++;
632  }
633  }
634 
635  // determine longest timer label
636  int mx_llen = 0;
637  for (size_t tid = 0; tid < used_timer_ids.size(); tid++)
638  {
639  int timer_id = used_timer_ids[tid];
641 
642  int llen = strlen(t->name);
643  mx_llen = llen > mx_llen ? llen : mx_llen;
644  }
645 
646  for (size_t tid = 0; tid < used_timer_ids.size(); tid++)
647  {
648  int timer_id = used_timer_ids[tid];
650 
651  col_labels.push_back(t->name);
652  label = c_label;
653  col_short_labels.push_back(label);
654 
655  if(elec) {
656  // search physics for signals linked to timer
657  unit = elec->timer_unit(timer_id);
658  if(unit.empty()) unit = "--";
659  col_unit_labels.push_back(unit);
660  col_width.push_back(4);
661  }
662  c_label++;
663  }
664 
665  get_protocol_column_widths(col_width, used_timer_ids);
666 
667  // print header + legend first
668  fh << "# Protocol header\n#\n" << "# Legend:\n";
669  for(size_t i = 0; i<col_short_labels.size(); i++)
670  {
671  fh << "#" << std::setw(2) << col_short_labels[i] << " = " << std::setw(mx_llen) << col_labels[i];
672  fh << " [" << std::setw(10) << col_unit_labels[i] << "]";
673 
674  if(i >= 2 && used_stim_ids[i-2] > -1) {
675  stimulus & s = elec->stimuli[used_stim_ids[i-2]];
676 
677  if (is_potential(s.phys.type)) {
678  if(s.phys.type == GND_ex)
679  fh << " ground stim" << smpl_endl;
680  else
681  fh << " applied: " << std::to_string(s.pulse.strength) << smpl_endl;
682  } else {
683  fh << smpl_endl;
684  }
685  } else {
686  fh << smpl_endl;
687  }
688  }
689 
690  // plot column short labels
691  fh << "#";
692  for(size_t i = 0; i<col_short_labels.size(); i++)
693  fh << std::setw(col_width[i] - 3) << col_short_labels[i].c_str() << std::setw(3) << " ";
694 
695  // plot column units
696  fh << smpl_endl << "#";
697  for(size_t i = 0; i<col_unit_labels.size(); i++)
698  fh << "[" << std::setw(col_width[i]-2) << col_unit_labels[i].c_str() << "]";
699 
700  // step through simulated time period
701  fh << smpl_endl << std::fixed;
702  do {
703  // time and discrete time
704  fh << std::setw(col_width[0]) << std::setprecision(3) << user_globals::tm_manager->time;
705  fh << std::setw(col_width[1]) << user_globals::tm_manager->d_time;
706 
707  // iterate over all timers
708  int col = 2;
709  for (size_t tid = 0; tid < used_timer_ids.size(); tid++)
710  {
711  int timer_id = used_timer_ids[tid];
713 
714  // type of timer: plain trigger or trigger linked to signal
715  if(!t->d_trigger_dur) {
716  int On = t->triggered ? 1 : 0;
717  fh << std::setw(col_width[col]) << On;
718  } else if(elec) {
719  // figure out value of signal linked to this timer
720  double val = 0.;
721 
722  // determine timer linked to which physics, for now we deal with electrics only
723  val = elec->timer_val(timer_id);
724 
725  fh << std::setw(col_width[col]) << std::setprecision(3) << val;
726  }
727  col++;
728  }
729 
730  fh << smpl_endl;
731 
732  // advance time
734  } while (!user_globals::tm_manager->elapsed());
735 
736  fh.close();
737 
738  // reset timer to start before actual simulation
740  }
741 
742  return err;
743 }
744 
746 {
747  const char* h1_prog = "PROG\t----- \t----\t-------\t-------|";
748  const char* h2_prog = "time\t%%comp\ttime\t ctime \t ETA |";
749  const char* h1_wc = "\tELAPS |";
750  const char* h2_wc = "\twc |";
751 
752  p.start = get_time();
753  p.last = p.start;
754 
755  log_msg(NULL, 0, 0, "%s", h1_prog );
756  log_msg(NULL, 0, NONL, "%s", h2_prog );
757  log_msg(NULL, 0, 0, "" );
758 }
759 
760 
761 void time_to_string(float time, char* str, short str_size)
762 {
763  int req_hours = ((int)(time)) / 3600;
764  int req_min = (((int)(time)) % 3600) / 60;
765  int req_sec = (((int)(time)) % 3600) % 60;
766 
767  snprintf(str, str_size, "%d:%02d:%02d", req_hours, req_min, req_sec);
768 }
769 
771 {
772 
773  float progress = 100.*(tm.time - tm.start) / (tm.end - tm.start);
774  float elapsed_time = timing(p.curr, p.start);
775  float req_time = (elapsed_time / progress) * (100.0f - progress);
776 
777  if(progress == 0.0f)
778  req_time = 0.0f;
779 
780  char elapsed_time_str[256];
781  char req_time_str[256];
782  time_to_string(elapsed_time, elapsed_time_str, 255);
783  time_to_string(req_time, req_time_str, 255);
784 
785  log_msg( NULL, 0, NONL, "%.2f\t%.1f\t%.1f\t%s\t%s",
786  tm.time,
787  progress,
788  (float)(p.curr - p.last),
789  elapsed_time_str,
790  req_time_str);
791 
792  p.last = p.curr;
793 
794  // we add an empty string for newline and flush
795  log_msg( NULL, 0, ECHO | FLUSH, "");
796 }
797 
798 void simulate()
799 {
800  // here we want to include all time dependent physics, to check if we have any of those
801  bool have_timedependent_phys = (phys_defined(PHYSREG_INTRA_ELEC) || phys_defined(PHYSREG_EIKONAL) || phys_defined(PHYSREG_EMI));
802 
803  if(!have_timedependent_phys) {
804  log_msg(0,0,0, "\n no time-dependent physics region registered, skipping simulate loop..\n");
805  return;
806  }
807 
808  log_msg(0,0,0, "\n *** Launching simulation ***\n");
809 
810  set_dir(OUTPUT);
811 
812  if(param_globals::dump_protocol)
813  plot_protocols("protocol.trc");
814 
815  prog_stats prog;
817  init_console_output(tm, prog);
818 
819  // main loop
820  do {
821  // console output
822  if(tm.trigger(iotm_console)) {
823  // print console
824  update_console_output(tm, prog);
825  }
826 
827  // in order to be closer to carpentry we first do output and then compute the solution
828  // for the next time slice ..
829  if (tm.trigger(iotm_spacedt)) {
830  for(const auto & it : user_globals::physics_reg) {
831  it.second->output_step();
832  }
833  }
834  // compute step
835  for(const auto & it : user_globals::physics_reg) {
836  Basic_physic* p = it.second;
837  if (tm.trigger(p->timer_idx))
838  p->compute_step();
839  }
840 
841  // advance time
842  tm.update_timers();
843  } while (!tm.elapsed());
844 
845  log_msg(0,0,0, "\n\nTimings of individual physics:");
846  log_msg(0,0,0, "------------------------------\n");
847 
848  for(const auto & it : user_globals::physics_reg) {
849  Basic_physic* p = it.second;
850  p->output_timings();
851  }
852 
853 }
854 
856 {
857  if(param_globals::post_processing_opts & RECOVER_PHIE) {
858  log_msg(NULL,0,ECHO,"\nPOSTPROCESSOR: Recovering Phie ...");
859  log_msg(NULL,0,ECHO, "----------------------------------\n");
860 
861  // do postprocessing
862  int err = postproc_recover_phie();
863 
864  if(!err) {
865  log_msg(NULL,0,ECHO,"\n-----------------------------------------");
866  log_msg(NULL,0,ECHO, "POSTPROCESSOR: Successfully recoverd Phie.\n");
867  }
868  }
869 }
870 
871 Basic_physic* get_physics(physic_t p, bool error_if_missing)
872 {
873  auto it = user_globals::physics_reg.find(p);
874 
875  if(it != user_globals::physics_reg.end()) {
876  return it->second;
877  } else {
878  if(error_if_missing) {
879  log_msg(0,5,0, "%s error: required physic is not active! Usually this is due to an inconsistent experiment configuration. Aborting!", __func__);
880  EXIT(EXIT_FAILURE);
881  }
882 
883  return NULL;
884  }
885 }
886 
888 {
889  sf_vec* ret = NULL;
890 
892  ret = user_globals::datavec_reg[d];
893 
894  return ret;
895 }
896 
898 {
899  if(user_globals::datavec_reg.count(d) == 0) {
900  user_globals::datavec_reg[d] = dat;
901  }
902  else {
903  log_msg(0,5,0, "%s warning: trying to register already registered data vector.", __func__);
904  }
905 }
906 
908 {
909  std::map<mesh_t, sf_mesh> & mesh_registry = user_globals::mesh_reg;
910 
911  // This is the initial grid we read the hard-disk data into
912  mesh_registry[reference_msh] = sf_mesh();
913  // we specify the MPI communicator for the reference mesh,
914  // all derived meshes will get this comminicator automatically
915  mesh_registry[reference_msh].comm = PETSC_COMM_WORLD;
916 
917  auto register_new_mesh = [&] (mesh_t mt, int pidx) {
918  if(!mesh_registry.count(mt)) {
919  mesh_registry[mt] = sf_mesh();
920  mesh_registry[mt].name = param_globals::phys_region[pidx].name;
921  }
922  return &mesh_registry[mt];
923  };
924 
925  // based on cli parameters we determine which grids need to be defined
926  for(int i=0; i<param_globals::num_phys_regions; i++)
927  {
928  sf_mesh* curmesh = NULL;
929  // register mesh type
930  switch(param_globals::phys_region[i].ptype) {
931  case PHYSREG_EIKONAL:
932  case PHYSREG_INTRA_ELEC:
933  curmesh = register_new_mesh(intra_elec_msh, i);
934  break;
935 
936  case PHYSREG_LAPLACE:
937  case PHYSREG_EXTRA_ELEC:
938  curmesh = register_new_mesh(extra_elec_msh, i);
939  break;
940 #if WITH_EMI_MODEL
941  case PHYSREG_EMI:
942  curmesh = register_new_mesh(emi_msh, i);
943  break;
944 #endif
945 
946  default:
947  log_msg(0,5,0, "Unsupported mesh type %d! Aborting!", param_globals::phys_region[i].ptype);
948  EXIT(EXIT_FAILURE);
949  }
950 
951  if(curmesh) {
952  // set mesh unique tags
953  for(int j=0; j<param_globals::phys_region[i].num_IDs; j++)
954  curmesh->extr_tag.insert(param_globals::phys_region[i].ID[j]);
955  }
956  }
957 }
958 
969 void retag_elements(sf_mesh & mesh, TagRegion *tagRegs, int ntr)
970 {
971  if(ntr == 0) return;
972  // checkTagRegDefs(ntr, tagRegs);
973 
975 
976  for (int i=0; i<ntr; i++) {
977  tagreg_t type = tagreg_t(tagRegs[i].type);
978  SF::vector<mesh_int_t> elem_indices;
979 
980  if (type == tagreg_list)
981  read_indices(elem_indices, tagRegs[i].elemfile, ref_eidx, mesh.comm);
982  else {
983  geom_shape shape;
984  shape.type = geom_shape::shape_t(tagRegs[i].type);
985  shape.p0.x = tagRegs[i].p0[0];
986  shape.p0.y = tagRegs[i].p0[1];
987  shape.p0.z = tagRegs[i].p0[2];
988  shape.p1.x = tagRegs[i].p1[0];
989  shape.p1.y = tagRegs[i].p1[1];
990  shape.p1.z = tagRegs[i].p1[2];
991  shape.radius = tagRegs[i].radius;
992 
993  bool nodal = false;
994  indices_from_geom_shape(elem_indices, mesh, shape, nodal);
995  }
996 
997  if(get_global((long int)elem_indices.size(), MPI_SUM, mesh.comm) == 0)
998  log_msg(0,3,0,"Tag region %d is empty", i);
999 
1000  for(size_t j=0; j<elem_indices.size(); j++)
1001  mesh.tag[elem_indices[j]] = tagRegs[i].tag;
1002  }
1003 
1004  // output the vector?
1005  if(strlen(param_globals::retagfile))
1006  {
1007  update_cwd();
1008  set_dir(OUTPUT);
1009 
1010  int dpn = 1;
1011  SF::write_data_ascii(mesh.comm, ref_eidx, mesh.tag, param_globals::retagfile, dpn);
1012 
1013  // Set dir back to what is was prior to retagfile output
1014  set_dir(CURDIR);
1015  }
1016 }
1017 
1018 size_t renormalise_fibres(SF::vector<mesh_real_t> &fib, size_t l_numelem)
1019 {
1020  size_t renormalised_count = 0;
1021 
1022  // using pragma omp without global OMP control can lead to massive compute stalls,
1023  // as all cores may be already occupied by MPI, thus they become oversubscribed. Once
1024  // there is a global OMP control in place, we can activate this parallel for again. -Aurel, 20.01.2022
1025  // #pragma omp parallel for schedule(static) reduction(+ : renormalised_count)
1026  for (size_t i = 0; i < l_numelem; i++)
1027  {
1028  const mesh_real_t f0 = fib[3*i+0], f1 = fib[3*i+1], f2 = fib[3*i+2];
1029  mesh_real_t fibre_len = sqrt(f0*f0 + f1*f1 + f2*f2);
1030 
1031  if (fibre_len && fabs(fibre_len - 1) > 1e-3) {
1032  fib[3 * i + 0] /= fibre_len;
1033  fib[3 * i + 1] /= fibre_len;
1034  fib[3 * i + 2] /= fibre_len;
1035  renormalised_count++;
1036  }
1037  }
1038 
1039  return renormalised_count;
1040 }
1041 
1042 void setup_meshes(bool require_fibers=true)
1043 {
1044  log_msg(0,0,0, "\n *** Processing meshes ***\n");
1045 
1046  const std::string basename = param_globals::meshname;
1047  const int verb = param_globals::output_level;
1048  std::map<mesh_t, sf_mesh> & mesh_registry = user_globals::mesh_reg;
1049  assert(mesh_registry.count(reference_msh) == 1); // There must be a reference mesh
1050 
1051  set_dir(INPUT);
1052 
1053  // we always read into the reference mesh
1054  sf_mesh & ref_mesh = mesh_registry[reference_msh];
1055  MPI_Comm comm = ref_mesh.comm;
1056 
1057  int size, rank;
1058  double t1, t2, s1, s2;
1059  MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank);
1060 
1062  SF::vector<mesh_int_t> ptsidx;
1063 
1064  // we add pointers to the meshes that need vertex cooridnates to this list
1065  std::list< sf_mesh* > ptsread_list;
1066 
1067  // read element mesh data
1068  t1 = MPI_Wtime(); s1 = t1;
1069  if(verb) log_msg(NULL, 0, 0,"Reading reference mesh: %s.*", basename.c_str());
1070 
1071  SF::read_elements(ref_mesh, basename, require_fibers);
1072  SF::read_points(basename, comm, pts, ptsidx);
1073 
1074  t2 = MPI_Wtime();
1075  if(verb) log_msg(NULL, 0, 0, "Done in %f sec.", float(t2 - t1));
1076 
1077  bool check_fibre_normality = true;
1078  if (check_fibre_normality and ref_mesh.fib.size()>0) {
1079  t1 = MPI_Wtime();
1080 
1081  // make sure that all fibre vectors have unit length
1082  size_t l_num_fixed_fib = renormalise_fibres(ref_mesh.fib, ref_mesh.l_numelem);
1083 
1084  size_t l_num_fixed_she = 0;
1085  if (ref_mesh.she.size() > 0)
1086  l_num_fixed_she = renormalise_fibres(ref_mesh.she, ref_mesh.l_numelem);
1087 
1088  unsigned long fixed[2] = {(unsigned long) l_num_fixed_fib, (unsigned long) l_num_fixed_she};
1089  MPI_Allreduce(MPI_IN_PLACE, fixed, 2, MPI_UNSIGNED_LONG, MPI_SUM, comm);
1090 
1091  if (fixed[0] + fixed[1] > 0)
1092  log_msg(NULL, 0, 0, "Renormalised %ld longitudinal and %ld sheet-transverse fibre vectors.", fixed[0], fixed[1]);
1093 
1094  t2 = MPI_Wtime();
1095  if(verb) log_msg(NULL, 0, 0, "Done in %f sec.", float(t2 - t1));
1096  }
1097 
1098  if(param_globals::numtagreg > 0) {
1099  log_msg(0, 0, 0, "Re-tagging reference mesh");
1100 
1101  // the retagging requires vertex coordinates, as such we need to read them into
1102  // the reference mesh
1103  ptsread_list.push_back(&ref_mesh);
1104  SF::insert_points(pts, ptsidx, ptsread_list);
1105 
1106  retag_elements(ref_mesh, param_globals::tagreg, param_globals::numtagreg);
1107 
1108  // we clear the list of meshet to receive vertices
1109  ptsread_list.clear();
1110  }
1111 
1112  if(verb) log_msg(NULL, 0, 0, "Processing submeshes");
1113 
1114  for(auto it = mesh_registry.begin(); it != mesh_registry.end(); ++it) {
1115  mesh_t grid_type = it->first;
1116  sf_mesh & submesh = it->second;
1117 
1118  if(grid_type != reference_msh) {
1119  if(verb > 1) log_msg(NULL, 0, 0, "\nSubmesh name: %s", submesh.name.c_str());
1120  t1 = MPI_Wtime();
1121 
1122  if(submesh.extr_tag.size() && grid_type != emi_msh)
1123  extract_tagbased(ref_mesh, submesh);
1124  else {
1125  // all submeshes should be defined on sets of tags, for backwards compatibility
1126  // we do a fiber based intra_elec_msh extraction if no tags are provided. Also, we
1127  // could do special treatments of any other physics type here. It would defeat
1128  // the purpose of the tag-based design, though. -Aurel
1129  switch(grid_type) {
1130  case emi_msh:
1131  case intra_elec_msh: extract_myocardium(ref_mesh, submesh, require_fibers); break;
1132  default: extract_tagbased(ref_mesh, submesh); break;
1133  }
1134  }
1135  t2 = MPI_Wtime();
1136  if(verb > 1) log_msg(NULL, 0, 0, "Extraction done in %f sec.", float(t2 - t1));
1137 
1138  ptsread_list.push_back(&submesh);
1139  }
1140  }
1141 
1142  // KDtree partitioning requires the coordinates to be present in the mesh data
1143  if(param_globals::pstrat == 2)
1144  SF::insert_points(pts, ptsidx, ptsread_list);
1145 
1146  for(auto it = mesh_registry.begin(); it != mesh_registry.end(); ++it)
1147  {
1148  mesh_t grid_type = it->first;
1149  sf_mesh & submesh = it->second;
1150  if(grid_type != reference_msh && grid_type!=emi_msh) {
1151  if(verb > 2) log_msg(NULL, 0, 0, "\nSubmesh name: %s", submesh.name.c_str());
1153 
1154  // generate partitioning vector
1155  t1 = MPI_Wtime();
1156  switch(param_globals::pstrat) {
1157  case 0:
1158  if(verb > 2) log_msg(NULL, 0, 0, "Using linear partitioning ..");
1159  break;
1160 
1161 #ifdef WITH_PARMETIS
1162  case 1:
1163  {
1164  if(verb > 2) log_msg(NULL, 0, 0, "Using Parmetis partitioner ..");
1165  SF::parmetis_partitioner<mesh_int_t, mesh_real_t> partitioner(param_globals::pstrat_imbalance, 2);
1166  partitioner(submesh, part);
1167  break;
1168  }
1169 #endif
1170  default:
1171  case 2: {
1172  if(verb > 2) log_msg(NULL, 0, 0, "Using KDtree partitioner ..");
1174  partitioner(submesh, part);
1175  break;
1176  }
1177  }
1178  t2 = MPI_Wtime();
1179  if(verb > 2) log_msg(NULL, 0, 0, "Partitioning done in %f sec.", float(t2 - t1));
1180 
1181  if(param_globals::pstrat > 0) {
1182  if(param_globals::gridout_p) {
1183  std::string out_name = get_basename(param_globals::meshname);
1184  if(grid_type == intra_elec_msh) out_name += "_i.part.dat";
1185  else if(grid_type == extra_elec_msh) out_name += "_e.part.dat";
1186 
1187  set_dir(OUTPUT);
1188  log_msg(0,0,0, "Writing \"%s\" partitioning to: %s", submesh.name.c_str(), out_name.c_str());
1189  write_data_ascii(submesh.comm, submesh.get_numbering(SF::NBR_ELEM_REF), part, out_name);
1190  }
1191 
1192  t1 = MPI_Wtime();
1193  SF::redistribute_elements(submesh, part);
1194  t2 = MPI_Wtime();
1195  if(verb > 2) log_msg(NULL, 0, 0, "Redistributing done in %f sec.", float(t2 - t1));
1196  }
1197 
1198  t1 = MPI_Wtime();
1200  sm_numbering(submesh);
1201  t2 = MPI_Wtime();
1202  if(verb > 2) log_msg(NULL, 0, 0, "Canonical numbering done in %f sec.", float(t2 - t1));
1203 
1204  t1 = MPI_Wtime();
1205  submesh.generate_par_layout();
1206  SF::petsc_numbering<mesh_int_t, mesh_real_t> p_numbering(submesh.pl);
1207  p_numbering(submesh);
1208  t2 = MPI_Wtime();
1209  if(verb > 2) log_msg(NULL, 0, 0, "PETSc numbering done in %f sec.", float(t2 - t1));
1210  if(verb > 2) print_DD_info(submesh);
1211  }
1212  }
1213 
1214  SF::insert_points(pts, ptsidx, ptsread_list);
1215  ref_mesh.clear_data();
1216 
1217  s2 = MPI_Wtime();
1218  if(verb) log_msg(NULL, 0, 0, "All done in %f sec.", float(s2 - s1));
1219 }
1220 
1221 
1223 {
1224  bool write_intra_elec = mesh_is_registered(intra_elec_msh) && param_globals::gridout_i;
1225  bool write_extra_elec = mesh_is_registered(extra_elec_msh) && param_globals::gridout_e;
1226 
1227  set_dir(OUTPUT);
1228  std::string output_base = get_basename(param_globals::meshname);
1229 
1230  if(write_intra_elec) {
1231  sf_mesh & mesh = get_mesh(intra_elec_msh);
1232 
1233  if(param_globals::gridout_i & 1) {
1234  sf_mesh surfmesh;
1235  if(param_globals::output_level > 1)
1236  log_msg(0,0,0, "Computing \"%s\" surface ..", mesh.name.c_str());
1237  compute_surface_mesh(mesh, SF::NBR_SUBMESH, surfmesh);
1238 
1239  std::string output_file = output_base + "_i.surf";
1240  log_msg(0,0,0, "Writing \"%s\" surface: %s", mesh.name.c_str(), output_file.c_str());
1241  write_surface(surfmesh, output_file);
1242  }
1243  if(param_globals::gridout_i & 2) {
1244  bool write_binary = false;
1245 
1246  std::string output_file = output_base + "_i";
1247  log_msg(0,0,0, "Writing \"%s\" mesh: %s", mesh.name.c_str(), output_file.c_str());
1248  write_mesh_parallel(mesh, write_binary, output_file.c_str());
1249  }
1250  }
1251 
1252  if(write_extra_elec) {
1253  sf_mesh & mesh = get_mesh(extra_elec_msh);
1254 
1255  if(param_globals::gridout_e & 1) {
1256  sf_mesh surfmesh;
1257  if(param_globals::output_level > 1)
1258  log_msg(0,0,0, "Computing \"%s\" surface ..", mesh.name.c_str());
1259 
1260  compute_surface_mesh(mesh, SF::NBR_SUBMESH, surfmesh);
1261  std::string output_file = output_base + "_e.surf";
1262  log_msg(0,0,0, "Writing \"%s\" surface: %s", mesh.name.c_str(), output_file.c_str());
1263  write_surface(surfmesh, output_file);
1264  }
1265  if(param_globals::gridout_e & 2) {
1266  bool write_binary = false;
1267  std::string output_file = output_base + "_e";
1268  log_msg(0,0,0, "Writing \"%s\" mesh: %s", mesh.name.c_str(), output_file.c_str());
1269  write_mesh_parallel(mesh, write_binary, output_file.c_str());
1270  }
1271  }
1272 }
1273 
1274 [[noreturn]] void cleanup_and_exit()
1275 {
1276  destroy_physics();
1278 
1279  param_clean();
1280  PetscFinalize();
1281 
1282  // close petsc error FD
1285 
1286  exit(EXIT_SUCCESS);
1287 }
1288 
1289 char* get_file_dir(const char* file)
1290 {
1291  char* filecopy = dupstr(file);
1292  char* dir = dupstr(dirname(filecopy));
1293 
1294  free(filecopy);
1295  return dir;
1296 }
1297 
1299 {
1300  int rank = get_rank();
1301  set_dir(OUTPUT);
1302 
1303  if(rank == 0) {
1304  // we open a error log file handle and set it as petsc stderr
1305  user_globals::petsc_error_fd = fopen("petsc_err_log.txt", "w");
1306  PETSC_STDERR = user_globals::petsc_error_fd;
1307  }
1308  else {
1309  PetscErrorPrintf = PetscErrorPrintfNone;
1310  }
1311 }
1312 
1314 {
1315  const sf_mesh & mesh = get_mesh(id);
1317  short mindim = 3;
1318 
1319  for(size_t eidx = 0; eidx < mesh.l_numelem; eidx++) {
1320  view.set_elem(eidx);
1321  short cdim = view.dimension();
1322  if(mindim < cdim) mindim = cdim;
1323  }
1324 
1325  mindim = get_global(mindim, MPI_MIN, mesh.comm);
1326 
1327  return mindim;
1328 }
1329 
1331  const mesh_t inp_meshid,
1332  const int dpn,
1333  const char* name,
1334  const char* units,
1335  const SF::vector<mesh_int_t>* idx,
1336  bool elem_data)
1337 {
1338  sync_io_item IO;
1339 
1340  IO.data = inp_data;
1341  IO.elem_flag = elem_data;
1342  IO.restr_idx = idx;
1343 
1344  IGBheader regigb;
1346  const int num_io = tm.timers[iotm_spacedt]->numIOs;
1347  int err = 0;
1348 
1349  int gsize = inp_data->gsize();
1350 
1351  // if we are restricting, we have to compute the restricted global size
1352  if(idx != NULL)
1353  gsize = get_global(int(idx->size()), MPI_SUM);
1354 
1355  regigb.x(gsize / dpn);
1356  regigb.dim_x(regigb.x()-1);
1357  regigb.inc_x(1);
1358 
1359  regigb.y(1); regigb.z(1);
1360  regigb.t(num_io);
1361  regigb.dim_t(tm.end-tm.start);
1362 
1363  switch(dpn) {
1364  default:
1365  case 1: regigb.type(IGB_FLOAT); break;
1366  case 3: regigb.type(IGB_VEC3_f); break;
1367  case 4: regigb.type(IGB_VEC4_f); break;
1368  case 9: regigb.type(IGB_VEC9_f); break;
1369  }
1370 
1371  regigb.unites_x("um"); regigb.unites_y("um"); regigb.unites_z("um");
1372  regigb.unites_t("ms");
1373  regigb.unites(units);
1374 
1375  regigb.inc_t(param_globals::spacedt);
1376 
1377  if(get_rank() == 0) {
1378  FILE_SPEC file = f_open(name, "w");
1379  if(file != NULL) {
1380  regigb.fileptr(file->fd);
1381  regigb.write();
1382  delete file;
1383  }
1384  else err++;
1385  }
1386 
1387  err = get_global(err, MPI_SUM);
1388  if(err) {
1389  log_msg(0,5,0, "%s error: Could not set up data output! Aborting!", __func__);
1390  EXIT(1);
1391  }
1392 
1393  IO.igb = regigb;
1394 
1395  SF::mixed_tuple<mesh_t, int> mesh_spec = {inp_meshid, dpn};
1396  IO.spec = mesh_spec;
1397 
1398  if(elem_data) {
1399  if(buffmap_elem.find(mesh_spec) == buffmap_elem.end()) {
1400  sf_vec *inp_copy; SF::init_vector(&inp_copy, inp_data);
1401  buffmap_elem[mesh_spec] = inp_copy;
1402  }
1403  } else {
1404  if(buffmap.find(mesh_spec) == buffmap.end()) {
1405  sf_vec *inp_copy; SF::init_vector(&inp_copy, inp_data);
1406  buffmap[mesh_spec] = inp_copy;
1407  }
1408  }
1409 
1410  this->sync_IOs.push_back(IO);
1411 }
1412 
1413 void igb_output_manager::register_output_async(sf_vec* inp_data,
1414  const mesh_t inp_meshid,
1415  const int dpn,
1416  const char* name,
1417  const char* units,
1418  const SF::vector<mesh_int_t>* idx,
1419  bool elem_data)
1420 {
1421  sf_mesh & mesh = get_mesh(inp_meshid);
1422  SF::vector<mesh_int_t> ioidx;
1423  int rank = get_rank();
1424 
1425  async_io_item IO;
1426  IO.data = inp_data;
1427  IO.restr_idx = idx;
1428 
1429  if(elem_data) {
1431  ioidx.resize(mesh.l_numelem);
1432  for(size_t i=0; i<mesh.l_numelem; i++)
1433  ioidx[i] = nbr[i];
1434  } else {
1435  const SF::vector<mesh_int_t> & alg_nod = mesh.pl.algebraic_nodes();
1437 
1438  if(idx == NULL) {
1439  ioidx.resize(alg_nod.size());
1440 
1441  for(size_t i=0; i<alg_nod.size(); i++)
1442  ioidx[i] = nbr[alg_nod[i]];
1443  } else {
1444  ioidx.resize(idx->size());
1445  IO.restr_petsc_idx.resize(idx->size());
1446 
1447  for(size_t i=0; i<idx->size(); i++) {
1448  mesh_int_t loc_nodal = (*idx)[i];
1449  ioidx[i] = nbr[loc_nodal];
1450  IO.restr_petsc_idx[i] = local_nodal_to_local_petsc(mesh, rank, loc_nodal);
1451  }
1452  }
1453  }
1454 
1455  int id = async::COMPUTE_register_output(ioidx, dpn, name, units);
1456  IO.IO_id = id;
1457 
1458  this->async_IOs.push_back(IO);
1459 }
1460 
1462  const mesh_t inp_meshid,
1463  const int dpn,
1464  const char* name,
1465  const char* units,
1466  const SF::vector<mesh_int_t>* idx,
1467  bool elem_data)
1468 {
1469  if(param_globals::num_io_nodes == 0)
1470  register_output_sync(inp_data, inp_meshid, dpn, name, units, idx, elem_data);
1471  else
1472  register_output_async(inp_data, inp_meshid, dpn, name, units, idx, elem_data);
1473 }
1474 
1475 sf_vec* igb_output_manager::fill_output_buffer(const sync_io_item & it)
1476 {
1477  const SF::mixed_tuple<mesh_t, int> & cspec = it.spec;
1478  sf_vec* data_vec = it.data;
1479 
1480  bool have_perm = it.elem_flag ? have_permutation(cspec.v1, ELEM_PETSC_TO_CANONICAL, cspec.v2):
1481  have_permutation(cspec.v1, PETSC_TO_CANONICAL, cspec.v2);
1482 
1483  if(have_perm) {
1484  sf_vec* perm_vec = it.elem_flag ? this->buffmap_elem[cspec] : this->buffmap[cspec];
1486  get_permutation(cspec.v1, PETSC_TO_CANONICAL, cspec.v2);
1487  sc->forward(*data_vec, *perm_vec);
1488  return perm_vec;
1489  } else {
1490  return data_vec;
1491  }
1492 }
1493 
1495 {
1496  SF::vector<float> restr_buff;
1497  int rank = get_rank();
1498  // loop over registered datasets and root-write one by one
1499  //
1500  for (sync_io_item & it : sync_IOs) {
1501  // write to associated file descriptor
1502  FILE* fd = static_cast<FILE*>(it.igb.fileptr());
1503 
1504  // fill the output buffer
1505  sf_vec* buff = fill_output_buffer(it);
1506 
1507  if(it.restr_idx == NULL) {
1508  buff->write_binary<float>(fd);
1509  } else {
1510  const SF::vector<mesh_int_t> & idx = *it.restr_idx;
1511  SF_real* p = buff->ptr();
1512 
1513  restr_buff.resize(idx.size()); restr_buff.resize(0);
1514 
1515  for(mesh_int_t ii : idx)
1516  restr_buff.push_back(p[ii]);
1517 
1518  root_write(fd, restr_buff, PETSC_COMM_WORLD);
1519  buff->release_ptr(p);
1520  }
1521  }
1522 
1523  // do all A-synchronous output:
1524  // loop over IDs received from the IO nodes and trigger async output
1525  //
1526  for (async_io_item & it : async_IOs) {
1527  SF_real* p = it.data->ptr();
1528  int ls = it.data->lsize();
1529  int id = it.IO_id;
1530 
1531  if(it.restr_idx == NULL)
1532  async::COMPUTE_do_output(p, ls, id);
1533  else {
1534  async::COMPUTE_do_output(p, it.restr_petsc_idx, id);
1535  }
1536 
1537  it.data->release_ptr(p);
1538  }
1539 }
1540 
1542 {
1543  if(get_rank() == 0) {
1544  // loop over registered datasets and close fd
1545  for(sync_io_item & it : sync_IOs) {
1546  FILE* fd = static_cast<FILE*>(it.igb.fileptr());
1547  fclose(fd);
1548  }
1549  }
1550 
1551  for(auto it = buffmap.begin(); it != buffmap.end(); ++it)
1552  delete it->second;
1553 
1554  for(auto it = buffmap_elem.begin(); it != buffmap_elem.end(); ++it)
1555  delete it->second;
1556 
1557  // we resize the arrays and clear the maps so that we are safe when calling
1558  // close_files_and_cleanup multiple times.
1559  sync_IOs.resize(0);
1560  async_IOs.resize(0);
1561  buffmap.clear();
1562  buffmap_elem.clear();
1563 }
1564 
1566 {
1567  for(sync_io_item & it : sync_IOs) {
1568  if(it.data == vec)
1569  return &it.igb;
1570  }
1571 
1572  return NULL;
1573 }
1574 
1575 void output_parameter_file(const char *fname, int argc, char **argv)
1576 {
1577  const int max_line_len = 128;
1578  const char* file_sep = "#=======================================================";
1579 
1580  // make sure only root executes this function
1581  if(get_rank() != 0)
1582  return;
1583 
1584  FILE_SPEC out = f_open(fname, "w");
1585  fprintf(out->fd, "# CARP GIT commit hash: %s\n", GIT_COMMIT_HASH);
1586  fprintf(out->fd, "# dependency hashes: %s\n", SUBREPO_COMMITS);
1587  fprintf(out->fd, "\n");
1588 
1589  // output the command line
1590  char line[8196] = "# ";
1591 
1592  for (int j=0; j<argc; j++) {
1593  strcat(line, argv[j]);
1594  if(strlen(line) > max_line_len) {
1595  fprintf(out->fd, "%s\n", line);
1596  strcpy(line, "# ");
1597  } else
1598  strcat(line, " ");
1599  }
1600 
1601  fprintf(out->fd, "%s\n\n", line);
1602  set_dir(INPUT);
1603 
1604  // convert command line to a par file
1605  for (int i=1; i<argc; i++) {
1606  std::string argument(argv[i]);
1607  if (argument == "+F" || argument.find("_options_file")!= std::string::npos) {
1608 
1609  std::string init = "";
1610  if (argument.find("_options_file")!= std::string::npos) {
1611  fprintf(out->fd, "%s = %s\n", argument.substr(1).c_str(), argv[i+1]);
1612  init = "#";
1613  }
1614  fprintf(out->fd, "%s>>\n", file_sep);
1615  // import par files
1616  i++;
1617  fprintf(out->fd, "## %s ##\n", argv[i]);
1618  FILE *in = fopen(argv[i], "r");
1619  while (fgets(line, 8196, in))
1620  fprintf(out->fd, "%s%s", init.c_str(), line);
1621  fclose(in);
1622  fprintf(out->fd, "\n##END of %s\n", argv[i]);
1623  fprintf(out->fd, "%s<<\n\n", file_sep);
1624  }
1625  else if(argv[i][0] == '-')
1626  {
1627  bool prelast = (i==argc-1);
1628  bool paramFollows = !prelast && ((argv[i+1][0] != '-') ||
1629  ((argv[i+1][1] >= '0') && (argv[i+1][1] <= '9')));
1630 
1631  // strip leading hyphens from command line opts
1632  // assume options do not start with numbers
1633  if(paramFollows) {
1634  // nonflag option
1635  char *optcpy = strdup(argv[i+1]);
1636  char *front = optcpy;
1637  // strip {} if present for arrays of values
1638  while(*front==' ' && *front) front++;
1639  if(*front=='{') {
1640  while(*++front == ' ');
1641  char *back = optcpy+strlen(optcpy)-1;
1642  while(*back==' ' && back>front) back--;
1643  if(*back == '}')
1644  *back = '\0';
1645  }
1646  if (strstr(front, "=") != nullptr) // if "=" is find then we need ""
1647  fprintf(out->fd, "%-40s= \"%s\"\n", argv[i]+1, front);
1648  else
1649  fprintf(out->fd, "%-40s= %s\n", argv[i]+1, front);
1650  free(optcpy);
1651  i++;
1652  }
1653  else // a flag was specified
1654  fprintf(out->fd, "%-40s= 1\n", argv[i]);
1655  }
1656  }
1657  f_close(out);
1658 }
1659 
1660 void savequit()
1661 {
1662  if(!get_physics(elec_phys)) return;
1663 
1664  set_dir(OUTPUT);
1665 
1666  double time = user_globals::tm_manager->time;
1667  char save_fn[512];
1668 
1669  snprintf(save_fn, sizeof save_fn, "exit.save.%.3f.roe", time);
1670  log_msg(NULL, 0, 0, "savequit called at time %g\n", time);
1671 
1673  elec->ion.miif->dump_state(save_fn, time, intra_elec_msh, false, GIT_COMMIT_COUNT);
1674 
1675  cleanup_and_exit();
1676 }
1677 
1678 } // namespace opencarp
1679 
int mesh_int_t
Definition: SF_container.h:46
float mesh_real_t
Definition: SF_container.h:47
double SF_real
Use the general double as real type.
Definition: SF_globals.h:38
Async IO functions.
Basic utility structs and functions, mostly IO related.
#define FLUSH
Definition: basics.h:311
#define ECHO
Definition: basics.h:308
#define NONL
Definition: basics.h:312
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:704
void set_elem(size_t eidx)
Set the view to a new element.
Definition: SF_fem_utils.h:731
short dimension() const
Definition: SF_fem_utils.h:922
void clear_data()
Clear the mesh data from memory.
Definition: SF_container.h:552
overlapping_layout< T > pl
nodal parallel layout
Definition: SF_container.h:429
vector< S > she
sheet direction
Definition: SF_container.h:421
vector< S > fib
fiber direction
Definition: SF_container.h:420
size_t l_numelem
local number of elements
Definition: SF_container.h:399
std::string name
the mesh name
Definition: SF_container.h:407
void generate_par_layout()
Set up the parallel layout.
Definition: SF_container.h:538
MPI_Comm comm
the parallel mesh is defined on a MPI world
Definition: SF_container.h:404
vector< T > & get_numbering(SF_nbr nbr_type)
Get the vector defining a certain numbering.
Definition: SF_container.h:464
vector< T > tag
element tag
Definition: SF_container.h:417
hashmap::unordered_set< int > extr_tag
the element tags based on which the mesh has been extracted
Definition: SF_container.h:424
Functor class generating a numbering optimized for PETSc.
Definition: SF_numbering.h:231
void free_scatterings()
Free the registered scatterings.
Container for a PETSc VecScatter.
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:68
A vector storing arbitrary data.
Definition: SF_vector.h:43
size_t size() const
The current size of the vector.
Definition: SF_vector.h:104
void resize(size_t n)
Resize a vector.
Definition: SF_vector.h:209
T * data()
Pointer to the vector's start.
Definition: SF_vector.h:91
T & push_back(T val)
Definition: SF_vector.h:283
size_t size() const
Definition: hashmap.hpp:1066
void insert(InputIterator first, InputIterator last)
Definition: hashmap.hpp:962
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:59
virtual void destroy()=0
int timer_idx
the timer index received from the timer manager
Definition: physics_types.h:66
virtual void output_timings()
Definition: physics_types.h:76
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:62
SF::vector< stimulus > stimuli
the electrical stimuli
Definition: electrics.h:263
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
Definition: electrics.cc:786
double timer_val(const int timer_id)
figure out current value of a signal linked to a given timer
Definition: electrics.cc:770
void dim_t(float a)
Definition: IGBheader.h:333
void unites_x(const char *a)
Definition: IGBheader.h:345
void unites_z(const char *a)
Definition: IGBheader.h:351
void unites(const char *a)
Definition: IGBheader.h:357
void unites_y(const char *a)
Definition: IGBheader.h:348
void unites_t(const char *a)
Definition: IGBheader.h:354
void fileptr(gzFile f)
Definition: IGBheader.cc:336
void dim_x(float a)
Definition: IGBheader.h:324
void inc_t(float a)
Definition: IGBheader.h:321
void inc_x(float a)
Definition: IGBheader.h:312
limpet::MULTI_IF * miif
Definition: ionics.h:66
class to store shape definitions
Definition: basics.h:381
std::map< SF::mixed_tuple< mesh_t, int >, sf_vec * > buffmap_elem
Definition: sim_utils.h:309
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:1565
void write_data()
write registered data to disk
Definition: sim_utils.cc:1494
SF::vector< async_io_item > async_IOs
Definition: sim_utils.h:306
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:1330
std::map< SF::mixed_tuple< mesh_t, int >, sf_vec * > buffmap
map data spec -> PETSc vector buffer
Definition: sim_utils.h:308
void close_files_and_cleanup()
close file descriptors
Definition: sim_utils.cc:1541
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:1461
SF::vector< sync_io_item > sync_IOs
Definition: sim_utils.h:305
stim_t type
type of stimulus
Definition: stimulate.h:137
int timer_id
timer for stimulus
Definition: stimulate.h:122
double strength
strength of stimulus
Definition: stimulate.h:93
stim_protocol ptcl
applied stimulation protocol used
Definition: stimulate.h:168
stim_pulse pulse
stimulus wave form
Definition: stimulate.h:167
stim_physics phys
physics of stimulus
Definition: stimulate.h:169
centralize time managment and output triggering
Definition: timer_utils.h:73
void initialize_neq_timer(const std::vector< double > &itrig, double idur, int ID, const char *iname, const char *poolname=nullptr)
Definition: timer_utils.cc:63
double end
final time
Definition: timer_utils.h:81
long d_time
current time instance index
Definition: timer_utils.h:77
bool trigger(int ID) const
Definition: timer_utils.h:166
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:48
void reset_timers()
Reset time in timer_manager and then reset registered timers.
Definition: timer_utils.h:115
double start
initial time (nonzero when restarting)
Definition: timer_utils.h:79
void initialize_singlestep_timer(double tg, double idur, int ID, const char *iname, const char *poolname=nullptr)
Definition: timer_utils.h:156
std::vector< base_timer * > timers
vector containing individual timers
Definition: timer_utils.h:84
double time
current time
Definition: timer_utils.h:76
Base class for tracking progress.
Definition: progress.hpp:39
Top-level header of FEM module.
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:824
void write_surface(const meshdata< T, S > &surfmesh, std::string surffile)
Definition: SF_mesh_io.h:712
void count(const vector< T > &data, vector< S > &cnt)
Count number of occurrences of indices.
Definition: SF_vector.h:332
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:894
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.
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:99
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)
Write a parallel mesh to harddisk without gathering it on one rank.
size_t root_write(FILE *fd, const vector< V > &vec, MPI_Comm comm)
Write vector data binary to disk.
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:518
@ NBR_PETSC
PETSc numbering of nodes.
Definition: SF_container.h:203
@ NBR_ELEM_REF
The element numbering of the reference mesh (the one stored on HD).
Definition: SF_container.h:204
@ NBR_SUBMESH
Submesh nodal numbering: The globally ascending sorted reference indices are reindexed.
Definition: SF_container.h:202
@ NBR_ELEM_SUBMESH
Submesh element numbering: The globally ascending sorted reference indices are reindexed.
Definition: SF_container.h:205
int load_ionic_module(const char *)
void COMPUTE_do_output(SF_real *dat, const int lsize, const int IO_id)
Definition: async_io.cc:396
int COMPUTE_register_output(const SF::vector< mesh_int_t > &idx, const int dpn, const char *name, const char *units)
Definition: async_io.cc:104
std::map< int, std::string > units
Definition: stimulate.cc:41
MPI_Comm IO_Intercomm
Communicator between IO and compute worlds.
Definition: main.cc:66
FILE * petsc_error_fd
file descriptor for petsc error output
Definition: main.cc:62
timer_manager * tm_manager
a manager for the various physics timers
Definition: main.cc:58
std::map< datavec_t, sf_vec * > datavec_reg
important solution vectors from different physics
Definition: main.cc:60
bool using_legacy_stimuli
flag storing whether legacy stimuli are used
Definition: main.cc:64
SF::scatter_registry scatter_reg
Registry for the different scatter objects.
Definition: main.cc:50
std::map< mesh_t, sf_mesh > mesh_reg
Registry for the different meshes used in a multi-physics simulation.
Definition: main.cc:52
std::map< physic_t, Basic_physic * > physics_reg
the physics
Definition: main.cc:56
void time_to_string(float time, char *str, short str_size)
Definition: sim_utils.cc:761
physic_t
Identifier for the different physics we want to set up.
Definition: physics_types.h:51
@ iotm_chkpt_list
Definition: timer_utils.h:44
@ iotm_console
Definition: timer_utils.h:44
@ iotm_spacedt
Definition: timer_utils.h:44
@ iotm_trace
Definition: timer_utils.h:44
@ iotm_chkpt_intv
Definition: timer_utils.h:44
@ iotm_state_var
Definition: timer_utils.h:44
sf_vec * get_data(datavec_t d)
Retrieve a petsc data vector from the data registry.
Definition: sim_utils.cc:887
void output_parameter_file(const char *fname, int argc, char **argv)
Definition: sim_utils.cc:1575
void initialize_physics()
Initialize all physics in the registry.
Definition: sim_utils.cc:110
bool setup_IO(int argc, char **argv)
Definition: sim_utils.cc:432
void retag_elements(sf_mesh &mesh, TagRegion *tagRegs, int ntr)
Definition: sim_utils.cc:969
void parse_params_cpy(int argc, char **argv)
Initialize input parameters on a copy of the real command line parameters.
Definition: sim_utils.cc:46
sf_mesh & get_mesh(const mesh_t gt)
Get a mesh by specifying the gridID.
Definition: sf_interface.cc:33
int set_ignore_flags(int mode)
Definition: sim_utils.cc:187
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:48
datavec_t
Enum used to adress the different data vectors stored in the data registry.
Definition: physics_types.h:99
int set_dir(IO_t dest)
Definition: sim_utils.cc:490
void cleanup_and_exit()
Definition: sim_utils.cc:1274
void register_physics()
Register physics to the physics registry.
Definition: sim_utils.cc:89
void post_process()
do postprocessing
Definition: sim_utils.cc:855
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:237
int get_rank(MPI_Comm comm=PETSC_COMM_WORLD)
Definition: basics.h:276
short get_mesh_dim(mesh_t id)
get (lowest) dimension of the mesh used in the experiment
Definition: sim_utils.cc:1313
T get_global(T in, MPI_Op OP, MPI_Comm comm=PETSC_COMM_WORLD)
Do a global reduction on a variable.
Definition: basics.h:233
@ GND_ex
Definition: stimulate.h:78
bool is_potential(stim_t type)
uses current for stimulation
Definition: stimulate.cc:66
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:770
void show_build_info()
show the build info, exit if -buildinfo was provided. This code runs before MPI_Init().
Definition: sim_utils.cc:229
FILE_SPEC f_open(const char *fname, const char *mode)
Open a FILE_SPEC.
Definition: basics.cc:135
void savequit()
save state and quit simulator
Definition: sim_utils.cc:1660
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:361
void register_data(sf_vec *dat, datavec_t d)
Register a data vector in the global registry.
Definition: sim_utils.cc:897
void basic_timer_setup()
Here we set up the timers that we always want to have, independent of physics.
Definition: sim_utils.cc:502
char * get_file_dir(const char *file)
Definition: sim_utils.cc:1289
IO_t
The different output (directory) types.
Definition: sim_utils.h:53
@ POSTPROC
Definition: sim_utils.h:53
@ CURDIR
Definition: sim_utils.h:53
@ OUTPUT
Definition: sim_utils.h:53
void get_protocol_column_widths(std::vector< int > &col_width, std::vector< int > &used_timer_ids)
Definition: sim_utils.cc:537
int get_phys_index(int physreg)
get index in param_globals::phys_region array for a certain phys region
void check_nullspace_ok()
Definition: sim_utils.cc:209
int postproc_recover_phie()
Definition: electrics.cc:2016
char * dupstr(const char *old_str)
Definition: basics.cc:44
int plot_protocols(const char *fname)
plot simulation protocols (I/O timers, stimuli, boundary conditions, etc)
Definition: sim_utils.cc:580
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:184
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
Definition: basics.cc:72
mesh_t
The enum identifying the different meshes we might want to load.
Definition: sf_interface.h:59
@ reference_msh
Definition: sf_interface.h:69
@ extra_elec_msh
Definition: sf_interface.h:61
@ intra_elec_msh
Definition: sf_interface.h:60
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:1042
void get_time(double &tm)
Definition: basics.h:436
bool mesh_is_registered(const mesh_t gt)
check wheter a SF mesh is set
Definition: sf_interface.cc:63
void output_meshes()
Definition: sim_utils.cc:1222
int get_size(MPI_Comm comm=PETSC_COMM_WORLD)
Definition: basics.h:290
Basic_physic * get_physics(physic_t p, bool error_if_missing)
Convinience function to get a physics.
Definition: sim_utils.cc:871
size_t renormalise_fibres(SF::vector< mesh_real_t > &fib, size_t l_numelem)
Definition: sim_utils.cc:1018
void destroy_physics()
Destroy all physics in the registry.
Definition: sim_utils.cc:134
void ignore_extracellular_stim(Stimulus *st, int ns, int ignore)
Definition: sim_utils.cc:161
void init_console_output(const timer_manager &tm, prog_stats &p)
Definition: sim_utils.cc:745
tagreg_t
tag regions types. must be in line with carp.prm
Definition: sim_utils.h:56
@ tagreg_list
Definition: sim_utils.h:56
V timing(V &t2, const V &t1)
Definition: basics.h:448
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:120
std::string get_basename(const std::string &path)
Definition: basics.cc:61
void update_cwd()
save the current working directory to curdir so that we can switch back to it if needed.
Definition: sim_utils.cc:485
void f_close(FILE_SPEC &f)
Close a FILE_SPEC.
Definition: basics.cc:162
void setup_petsc_err_log()
set up error logs for PETSc, so that it doesnt print errors to stderr.
Definition: sim_utils.cc:1298
void simulate()
Main simulate loop.
Definition: sim_utils.cc:798
void parse_mesh_types()
Parse the phys_type CLI parameters and set up (empty) SF::meshdata meshes.
Definition: sim_utils.cc:907
#define IGB_VEC9_f
Definition: IGBheader.h:76
#define IGB_VEC3_f
Definition: IGBheader.h:71
#define IGB_FLOAT
Definition: IGBheader.h:60
#define IGB_VEC4_f
Definition: IGBheader.h:73
Top-level header of physics module.
#define PHYSREG_INTRA_ELEC
Definition: sf_interface.h:84
#define PHYSREG_LAPLACE
Definition: sf_interface.h:89
#define PETSC_TO_CANONICAL
Permute algebraic data from PETSC to canonical ordering.
Definition: sf_interface.h:79
#define PHYSREG_EIKONAL
Definition: sf_interface.h:86
#define PHYSREG_EMI
Definition: sf_interface.h:90
#define ELEM_PETSC_TO_CANONICAL
Permute algebraic element data from PETSC to canonical ordering.
Definition: sf_interface.h:81
#define PHYSREG_EXTRA_ELEC
Definition: sf_interface.h:85
Simulator-level utility execution control functions.
#define BIDOMAIN
Definition: sim_utils.h:145
#define RECOVER_PHIE
Definition: sim_utils.h:150
#define MONODOMAIN
Definition: sim_utils.h:144
#define EXP_POSTPROCESS
Definition: sim_utils.h:162
#define PSEUDO_BIDM
Definition: sim_utils.h:146
#define EXP_LAPLACE
Definition: sim_utils.h:160
#define Extracellular_I
Definition: stimulate.h:38
#define Extracellular_V
Definition: stimulate.h:39
#define STM_IGNORE_PSEUDO_BIDM
Definition: stimulate.h:62
#define NO_EXTRA_GND
Definition: stimulate.h:56
#define NO_EXTRA_I
Definition: stimulate.h:58
#define Intracellular_I
Definition: stimulate.h:41
#define Ignore_Stim
Definition: stimulate.h:49
#define STM_IGNORE_MONODOMAIN
Definition: stimulate.h:61
#define IsExtraV(A)
Definition: stimulate.h:51
#define IGNORE_NONE
Definition: stimulate.h:55
#define STM_IGNORE_BIDOMAIN
Definition: stimulate.h:60
#define Extracellular_Ground
Definition: stimulate.h:40
#define Extracellular_V_OL
Definition: stimulate.h:42
#define Transmembrane_I
Definition: stimulate.h:37
#define NO_EXTRA_V
Definition: stimulate.h:57
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:283
SF::vector< mesh_int_t > restr_petsc_idx
pointer to index vector with nodal indices we restrict to.
Definition: sim_utils.h:284
int IO_id
pointer to data registered for output
Definition: sim_utils.h:282
long d_trigger_dur
discrete duration
Definition: timer_utils.h:58
const char * name
timer name
Definition: timer_utils.h:53
bool triggered
flag indicating trigger at current time step
Definition: timer_utils.h:54
File descriptor struct.
Definition: basics.h:133
for display execution progress and statistical data of electrical solve
Definition: sim_utils.h:265
double curr
current output wallclock time
Definition: sim_utils.h:269
double start
output start wallclock time
Definition: sim_utils.h:267
double last
last output wallclock time
Definition: sim_utils.h:268
bool elem_flag
igb header we use for output
Definition: sim_utils.h:276
IGBheader igb
pointer to index vector used for restricting output.
Definition: sim_utils.h:275
const SF::vector< mesh_int_t > * restr_idx
pointer to data registered for output
Definition: sim_utils.h:274
SF::mixed_tuple< mesh_t, int > spec
flag whether the data is elements-wise
Definition: sim_utils.h:277