openCARP
Doxygen code documentation for the open cardiac electrophysiology simulator openCARP
electrics_eikonal.cc
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: Copyright (c) NumeriCor GmbH
2 // SPDX-License-Identifier: Apache-2.0
3 
12 #include "electrics_eikonal.h"
13 #include "electric_integrators.h"
14 #include <cstdlib>
15 #include "SF_globals.h"
16 #include "basics.h"
17 #include "petsc_utils.h"
18 #include "timers.h"
19 #include "stimulate.h"
20 
21 #include "SF_init.h"
22 
23 namespace opencarp
24 {
25 
27 {
28  if (get_size() > 1) {
29  log_msg(NULL, 5, 0, "DREAM/Eikonal physics currently do not support MPI parallelization. Use openMP instead. Aborting!");
30  EXIT(EXIT_FAILURE);
31  }
32 
33  double t1, t2;
34  get_time(t1);
35 
36  set_dir(OUTPUT);
37 
38  // open logger
39  logger = f_open("eikonal.log", param_globals::experiment != 4 ? "w" : "r");
40 
41  // setup mappings between extra and intra grids, algebraic and nodal,
42  // and between PETSc and canonical orderings
43  setup_mappings();
44 
45  eik_tech = static_cast<Eikonal::eikonal_t>(param_globals::dream.solve);
46 
47  // the ionic physics is currently triggered from inside the Electrics to have tighter
48  // control over it. The standalone eikonal solver does not require it.
49  switch (eik_tech) {
50  case EIKONAL: break;
51  default:
52  ion.logger = logger;
53  ion.initialize();
54  }
55 
56  // set up Intracellular tissue
57  set_elec_tissue_properties(mtype, intra_grid, logger);
58  region_mask(intra_elec_msh, mtype[intra_grid].regions, mtype[intra_grid].regionIDs, true, "gregion_i");
59 
60  // add electrics timer for time stepping, add to time stepper tool (TS)
61  double global_time = user_globals::tm_manager->time;
62  timer_idx = user_globals::tm_manager->add_eq_timer(global_time, param_globals::tend, 0,
63  param_globals::dt, 0, "elec::ref_dt", "TS");
64 
65  // electrics stimuli setup
66  setup_stimuli();
67 
68  // set up the linear equation systems. this needs to happen after the stimuli have been
69  // set up, since we need boundary condition info
70  setup_solvers();
71 
72  // the next setup steps require the solvers to be set up, since they use the matrices
73  // generated by those
74 
75  // initialize the LATs detector
76  switch (eik_tech) {
77  case EIKONAL: break; // not available for pure eikonal solve
78  default:
80  }
81 
82  // prepare the electrics output. we skip it if we do post-processing
83  if (param_globals::experiment != EXP_POSTPROCESS)
84  setup_output();
85 
86  this->initialize_time += timing(t2, t1);
87  log_msg(NULL, 0, 0, "All done in %f sec.", float(t2 - t1));
88 }
89 
90 void Eikonal::set_elec_tissue_properties(MaterialType* mtype, Eikonal::grid_t g, FILE_SPEC logger)
91 {
92  MaterialType* m = mtype + g;
93 
94  // initialize random conductivity fluctuation structure with PrM values
95  m->regions.resize(param_globals::num_gregions);
96 
97  const char* grid_name = g == Eikonal::intra_grid ? "intracellular" : "extracellular";
98  log_msg(logger, 0, 0, "Setting up %s tissue poperties for %d regions ..", grid_name,
99  param_globals::num_gregions);
100 
101  char buf[64];
102  RegionSpecs* reg = m->regions.data();
103 
104  for (size_t i = 0; i < m->regions.size(); i++, reg++) {
105  if (!strcmp(param_globals::gregion[i].name, "")) {
106  snprintf(buf, sizeof buf, ", gregion_%d", int(i));
107  param_globals::gregion[i].name = dupstr(buf);
108  }
109 
110  reg->regname = strdup(param_globals::gregion[i].name);
111  reg->regID = i;
112  reg->nsubregs = param_globals::gregion[i].num_IDs;
113  if (!reg->nsubregs)
114  reg->subregtags = NULL;
115  else {
116  reg->subregtags = new int[reg->nsubregs];
117 
118  for (int j = 0; j < reg->nsubregs; j++)
119  reg->subregtags[j] = param_globals::gregion[i].ID[j];
120  }
121 
122  // describe material in given region
123  elecMaterial* emat = new elecMaterial();
124  emat->material_type = ElecMat;
125 
126  emat->InVal[0] = param_globals::gregion[i].g_il;
127  emat->InVal[1] = param_globals::gregion[i].g_it;
128  emat->InVal[2] = param_globals::gregion[i].g_in;
129 
130  emat->ExVal[0] = param_globals::gregion[i].g_el;
131  emat->ExVal[1] = param_globals::gregion[i].g_et;
132  emat->ExVal[2] = param_globals::gregion[i].g_en;
133 
134  emat->BathVal[0] = param_globals::gregion[i].g_bath;
135  emat->BathVal[1] = param_globals::gregion[i].g_bath;
136  emat->BathVal[2] = param_globals::gregion[i].g_bath;
137 
138  // convert units from S/m -> mS/um
139  for (int j = 0; j < 3; j++) {
140  emat->InVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
141  emat->ExVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
142  emat->BathVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
143  }
144  reg->material = emat;
145  }
146 
147  {
149  const char* file = g == Eikonal::intra_grid ? param_globals::gi_scale_vec : param_globals::ge_scale_vec;
150  if (strlen(file))
151  read_el_scale_vec(file, mt, m->el_scale, m->el_scale_dpn);
152  }
153 }
154 
155 void Eikonal::setup_mappings()
156 {
157  bool intra_exits = mesh_is_registered(intra_elec_msh), extra_exists = mesh_is_registered(extra_elec_msh);
158  assert(intra_exits);
159  const int dpn = 1;
160 
161  // It may be that another physic (e.g. ionic models) has already computed the intracellular mappings,
162  // thus we first test their existence
163  if (get_scattering(intra_elec_msh, ALG_TO_NODAL, dpn) == NULL) {
164  log_msg(logger, 0, 0, "%s: Setting up intracellular algebraic-to-nodal scattering.", __func__);
166  }
168  log_msg(logger, 0, 0, "%s: Setting up intracellular PETSc to canonical permutation.", __func__);
170  }
171 }
172 
174 {
175  double t1, t2;
176  get_time(t1);
177 
178  switch (eik_tech) {
179  case EIKONAL: solve_EIKONAL(); break;
180  case DREAM: solve_DREAM(); break;
181  default: solve_RE(); break;
182  }
183 
185  // output lin solver stats
187  }
188  this->compute_time += timing(t2, t1);
189 
190  // since the traces have their own timing, we check for trace dumps in the compute step loop
193 }
194 
196 {
197  double t1, t2;
198  get_time(t1);
199 
200  switch (eik_tech) {
201  case EIKONAL: break;
202  default:
204  output_manager_time.write_data(); // does not exist in EIKONAL
205  }
206 
207  if (do_output_eikonal) {
209  do_output_eikonal = false;
210  }
211 
212  double curtime = timing(t2, t1);
213  this->output_time += curtime;
214 
215  IO_stats.calls++;
216  IO_stats.tot_time += curtime;
217 
220 }
221 
226 {
227  switch (eik_tech) {
228  case EIKONAL:
230  break;
231  default:
232  // output LAT data
236  // destroy ionics before closing the logger: the ionic interface holds an alias of it
237  ion.destroy();
238  }
239 
240  // close logger
241  f_close(logger);
242 }
243 
244 void Eikonal::setup_stimuli()
245 {
246  // initialize basic stim info data (used units, supported types, etc)
247  init_stim_info();
248 
249  stimuli.resize(param_globals::num_stim);
250  for (int i = 0; i < param_globals::num_stim; i++) {
251  // construct new stimulus
252  stimulus& s = stimuli[i];
253 
254  if (param_globals::stim[i].crct.type != 0 && param_globals::stim[i].crct.type != 9) {
255  // In the Eikonal class, only the intracellular domain is registered.
256  // Therefore, only I_tm and Vm_clmp are compatible.
257  log_msg(NULL, 5, 0, "%s error: stimulus of type %i is incompatible with the eikonal model! Use I_tm or Vm_clmp instead. Aborting!", __func__, s.phys.type);
258  EXIT(EXIT_FAILURE);
259  }
260 
262  s.translate(i);
263 
264  s.setup(i);
265 
266  if (s.electrode.dump_vtx)
267  s.dump_vtx_file(i);
268 
269  log_msg(NULL, 2, 0, "Only geometry, start time, npls, and bcl of stim[%i] are used", i);
270 
271  if (param_globals::stim[i].pulse.dumpTrace && get_rank() == 0) {
272  set_dir(OUTPUT);
273  s.pulse.wave.write_trace(s.name + ".trc");
274  }
275  }
276 
278 }
279 
280 void Eikonal::stimulate_intracellular()
281 {
282  parabolic_solver& ps = parab_solver;
283 
284  // iterate over stimuli
285  for (stimulus& s : stimuli) {
286  if (s.is_active()) {
287  // for active stimuli, deal with the stimuli-type specific stimulus application
288  switch (s.phys.type) {
289  case I_tm: {
290  if (param_globals::operator_splitting) {
291  apply_stim_to_vector(s, *ps.Vmv, true);
292  } else {
293  SF_real Cm = 1.0;
294  timer_manager& tm = *user_globals::tm_manager;
295  SF_real sc = tm.time_step / Cm;
296 
297  ps.Irhs->set(0.0);
298  apply_stim_to_vector(s, *ps.Irhs, true);
299 
300  *ps.tmp_i1 = *ps.IIon;
301  *ps.tmp_i1 -= *ps.Irhs;
302  *ps.tmp_i1 *= sc; // tmp_i1 = sc * (IIon - Irhs)
303 
304  // add ionic, transmembrane and intracellular currents to rhs
305  if (param_globals::parab_solve != parabolic_solver::EXPLICIT)
306  ps.mass_i->mult(*ps.tmp_i1, *ps.Irhs);
307  else
308  *ps.Irhs = *ps.tmp_i1;
309  }
310  break;
311  }
312 
313  case Illum: {
314  sf_vec* illum_vec = ion.miif->gdata[limpet::illum];
315 
316  if (illum_vec == NULL) {
317  log_msg(0, 5, 0, "Cannot apply illumination stim: global vector not present!");
318  EXIT(EXIT_FAILURE);
319  } else {
320  apply_stim_to_vector(s, *illum_vec, false);
321  }
322 
323  break;
324  }
325 
326  default: break;
327  }
328  }
329  }
330 }
331 
332 void Eikonal::clamp_Vm()
333 {
334  for (stimulus& s : stimuli) {
335  if (s.phys.type == Vm_clmp && s.is_active())
337  }
338 }
339 
340 void Eikonal::setup_output()
341 {
342  int rank = get_rank();
343  SF::vector<mesh_int_t>* restr_i = NULL;
344  SF::vector<mesh_int_t>* restr_e = NULL;
345  set_dir(OUTPUT);
346 
347  setup_dataout(param_globals::dataout_i, param_globals::dataout_i_vtx, intra_elec_msh,
348  restr_i, param_globals::num_io_nodes > 0);
349 
350  if (param_globals::dataout_i) {
351  switch (eik_tech) {
352  case EIKONAL:
353  output_manager_cycle.register_output(eik_solver.AT, intra_elec_msh, 1, param_globals::dream.output.atfile, "ms", restr_i);
354  break;
355  case DREAM:
356  output_manager_time.register_output(parab_solver.Vmv, intra_elec_msh, 1, param_globals::vofile, "mV", restr_i);
357  output_manager_cycle.register_output(eik_solver.AT, intra_elec_msh, 1, param_globals::dream.output.atfile, "ms", restr_i);
358  output_manager_cycle.register_output(eik_solver.RT, intra_elec_msh, 1, param_globals::dream.output.rtfile, "ms", restr_i);
359  if (strcmp(param_globals::dream.output.idifffile, "") != 0) {
360  output_manager_time.register_output(eik_solver.Idiff, intra_elec_msh, 1, param_globals::dream.output.idifffile, "muA/cm2", restr_i);
361  }
362  break;
363  default:
364  output_manager_time.register_output(parab_solver.Vmv, intra_elec_msh, 1, param_globals::vofile, "mV", restr_i);
365  output_manager_cycle.register_output(eik_solver.AT, intra_elec_msh, 1, param_globals::dream.output.atfile, "ms", restr_i);
366  if (strcmp(param_globals::dream.output.idifffile, "") != 0) {
367  output_manager_time.register_output(eik_solver.Idiff, intra_elec_msh, 1, param_globals::dream.output.idifffile, "muA/cm2", restr_i);
368  }
369  }
370  }
371 
373 
374  if (param_globals::num_trace) {
375  sf_mesh& imesh = get_mesh(intra_elec_msh);
376  open_trace(ion.miif, param_globals::num_trace, param_globals::trace_node, NULL, &imesh);
377  }
378 
379  // initialize generic logger for IO timings per time_dt
380  IO_stats.init_logger("IO_stats.dat");
381 }
382 
383 void Eikonal::dump_matrices()
384 {
385  std::string bsname = param_globals::dump_basename;
386  std::string fn;
387 
388  set_dir(OUTPUT);
389 
390  // dump monodomain matrices
391  if (param_globals::parab_solve == 1) {
392  // using Crank-Nicolson
393  fn = bsname + "_Ki_CN.bin";
394  parab_solver.lhs_parab->write(fn.c_str());
395  }
396  fn = bsname + "_Ki.bin";
397  parab_solver.rhs_parab->write(fn.c_str());
398 
399  fn = bsname + "_Mi.bin";
400  parab_solver.mass_i->write(fn.c_str());
401 }
402 
405 double Eikonal::timer_val(const int timer_id)
406 {
407  // determine
408  int sidx = stimidx_from_timeridx(stimuli, timer_id);
409  double val = 0.0;
410  if (sidx != -1) {
411  stimuli[sidx].value(val);
412  } else
413  val = std::nan("NaN");
414 
415  return val;
416 }
417 
420 std::string Eikonal::timer_unit(const int timer_id)
421 {
422  int sidx = stimidx_from_timeridx(stimuli, timer_id);
423  std::string s_unit;
424 
425  if (sidx != -1)
426  // found a timer-linked stimulus
427  s_unit = stimuli[sidx].pulse.wave.f_unit;
428 
429  return s_unit;
430 }
431 
432 void Eikonal::setup_solvers()
433 {
434  set_dir(OUTPUT);
435 
436  switch (eik_tech) {
437  case EIKONAL:
438  eik_solver.init();
439  break;
440  default:
441  parab_solver.init();
443  eik_solver.init();
445  if (param_globals::dump2MatLab) dump_matrices();
446  }
447 }
448 
449 void Eikonal::checkpointing()
450 {
451  const timer_manager& tm = *user_globals::tm_manager;
452 
453  // regular user selected state save
454  if (tm.trigger(iotm_chkpt_list)) {
455  char save_fnm[1024];
456  const char* tsav_ext = get_tsav_ext(tm.time);
457 
458  snprintf(save_fnm, sizeof save_fnm, "%s.%s.roe", param_globals::write_statef, tsav_ext);
459 
460  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
461  eik_solver.save_eikonal_state(tsav_ext);
462  }
463 
464  // checkpointing based on interval
465  if (tm.trigger(iotm_chkpt_intv)) {
466  char save_fnm[1024];
467  snprintf(save_fnm, sizeof save_fnm, "checkpoint.%.1f.roe", tm.time);
468  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
469  }
470 }
471 
472 void Eikonal::solve_EIKONAL()
473 {
474  if (user_globals::tm_manager->time == 0) {
475  eik_solver.FIM();
478  do_output_eikonal = true;
479  }
480 }
481 
482 void Eikonal::solve_RE()
483 {
484  if (user_globals::tm_manager->time == 0) {
485  eik_solver.FIM();
488  do_output_eikonal = true;
489  }
490  solve_RD();
491 }
492 
493 void Eikonal::solve_DREAM()
494 {
496  solve_RD();
497  } else {
498  if (user_globals::tm_manager->time != 0) {
500  }
501 
502  eik_solver.cycFIM();
504 
507  do_output_eikonal = true;
508  }
509 }
510 
511 void Eikonal::solve_RD()
512 {
513  // if requested, we checkpoint the current state
514  checkpointing();
515 
516  // activation checking
517  const double time = user_globals::tm_manager->time,
518  time_step = user_globals::tm_manager->time_step;
519 
520  lat.check_acts(time);
521  lat.check_quiescence(time, time_step);
522 
523  clamp_Vm();
524 
525  *parab_solver.old_vm = *parab_solver.Vmv; // needed in step D of DREAM
526 
527  // compute ionics update
528  ion.compute_step();
529 
530  // Compute the I diff current
531  *eik_solver.Idiff *= 0;
534 
535  if (eik_tech == REp) {
537  }
538 
539  switch (eik_tech) {
541  default: break;
542  }
543 
544  clamp_Vm();
545 }
546 
548 {
549  if (param_globals::output_level > 1) log_msg(0, 0, 0, "\n *** Initializing Eikonal Solver ***\n");
550  stats.init_logger("eik_stats.dat");
551 
552  if (param_globals::dream.output.debugNode >= 0) {
553  nodeData.idX = param_globals::dream.output.debugNode;
554  char buf[256];
555  snprintf(buf, sizeof buf, "node_%lld.dat", static_cast<long long>(nodeData.idX));
556  nodeData.init_logger(buf);
557  }
558 
559  // currently only used for output
560  const sf_mesh& mesh = get_mesh(intra_elec_msh);
561  twoFib = mesh.she.size() > 0;
565 
566  num_pts = mesh.l_numpts;
567 
568  e2n_con = mesh.con; // Connectivity vector with nodes that belong to each element
569  // The 4 nodes from index 4j to 4j+3 belong to the same element for 0<=j<num elements
570  elem_start = mesh.dsp; // For the i_th element elem_start[j] stores its starting position in the "connect" vector
571 
575 
576  List.assign(num_pts, 0); // List of active nodes
577  T_A.assign(num_pts, inf); // Activation times
578  D_I.assign(num_pts, 0); // Diastolic Intervals
579  T_R.assign(num_pts, -400); // Recovery times
580  TA_old.assign(num_pts, inf); // Activation Time is the previous cycle
581  num_changes.assign(num_pts, 0); // Number of Times entered in the List per current LAT
582  nReadded2List.assign(num_pts, 0); // Number of Times entered in the List per current LAT
583  stim_status.assign(num_pts, 0); // Status of nodes
584 
585  switch (mesh.type[0]) {
586  case 0:
587  MESH_SIZE = 4;
588  break;
589 
590  case 6:
591  MESH_SIZE = 3;
592  break;
593 
594  case 7:
595  MESH_SIZE = 2;
596  break;
597 
598  default:
599  log_msg(0, 5, 0, "Error: Type of element is not compatible with this version of the eikonal model. Use tetrahedra or triangles");
600  EXIT(EXIT_FAILURE);
601  break;
602  }
603 
604  if (strlen(param_globals::start_statef) > 0) load_state_file();
605 
606  create_node_to_node_graph();
607 
608  translate_stim_to_eikonal();
609 
610  precompute_squared_anisotropy_metric();
611 }
612 
614 {
615  double t1, t2;
616  get_time(t1);
617 
618  const sf_mesh& mesh = get_mesh(intra_elec_msh);
619 
620  diff_cur.resize(mesh.l_numpts);
621  rho_cvrest.resize(mesh.l_numpts);
625 
626  // --- Precompute resolved region IDs for each point ---
627  // Use the same region delegation as the ionics class
628  SF::vector<int> regionIDs;
629  SF::vector<RegionSpecs> rs(param_globals::num_imp_regions);
630  for (size_t i = 0; i < rs.size(); i++) {
631  rs[i].nsubregs = param_globals::imp_region[i].num_IDs;
632  rs[i].subregtags = param_globals::imp_region[i].ID;
633  for (int j = 0; j < rs[i].nsubregs; j++) {
634  if (rs[i].subregtags[j] == -1 && get_rank() == 0)
635  log_msg(NULL, 3, ECHO, "Warning: not all %u IDs provided for imp_region[%u]!\n", rs[i].nsubregs, i);
636  }
637  }
638  if (rs.size() == 1) {
639  regionIDs.assign(mesh.l_numpts, 0);
640  } else {
641  region_mask(intra_elec_msh, rs, regionIDs, false, "imp_regions");
642  }
643 
644  // --- Parallel initialization, one write per vertex ---
645  // region_mask returns the IDs in algebraic (PETSc) order, the per-vertex arrays are nodal
646  const SF::vector<mesh_int_t>& alg_nod = mesh.pl.algebraic_nodes();
647  #pragma omp parallel for schedule(dynamic)
648  for (size_t i = 0; i < alg_nod.size(); i++) {
649  mesh_int_t v = alg_nod[i];
650  int reg = regionIDs[i];
651 
652  const auto& region_diff = param_globals::imp_region[reg].dream.Idiff;
653  const auto& region_rest = param_globals::imp_region[reg].dream.CVrest;
654 
655  auto model = static_cast<eikonal_solver::Idiff_t>(region_diff.model);
656  diff_cur[v].model = model;
657 
658  if (model == GAUSS) {
659  diff_cur[v].alpha_1 = region_diff.alpha_i[0];
660  diff_cur[v].alpha_2 = region_diff.alpha_i[1];
661  diff_cur[v].alpha_3 = region_diff.alpha_i[2];
662  diff_cur[v].beta_1 = region_diff.beta_i[0];
663  diff_cur[v].beta_2 = region_diff.beta_i[1];
664  diff_cur[v].beta_3 = region_diff.beta_i[2];
665  diff_cur[v].gamma_1 = region_diff.gamma_i[0];
666  diff_cur[v].gamma_2 = region_diff.gamma_i[1];
667  diff_cur[v].gamma_3 = region_diff.gamma_i[2];
668  } else {
669  diff_cur[v].A_F = region_diff.A_F;
670  diff_cur[v].tau_F = region_diff.tau_F;
671  diff_cur[v].V_th = region_diff.V_th;
672  }
673 
674  rho_cvrest[v] = region_rest.rho;
675  kappa_cvrest[v] = region_rest.kappa;
676  theta_cvrest[v] = region_rest.theta;
677  denom_cvrest[v] = log(region_rest.rho) / region_rest.psi;
678  }
679  if (param_globals::output_level) log_msg(NULL, 0, 0, "Diffusion current and CV restitution initialized in %f sec.", timing(t2, t1));
680 }
681 
682 void eikonal_solver::translate_stim_to_eikonal()
683 {
684  double t1, t2;
685  get_time(t1);
686  Index_currStim = 0;
687 
688  // Collect all pulses as (start_time, stimulus_index)
689  std::vector<std::pair<SF_real, int>> stim_events;
690  stim_events.reserve(param_globals::num_stim * 8); // rough guess
691 
692  for (int stim_idx = 0; stim_idx < stimuliRef->size(); ++stim_idx) {
693  const stimulus& s = (*stimuliRef)[stim_idx];
694  for (int idx_pls = 0; idx_pls < s.ptcl.npls; ++idx_pls) {
695  SF_real start_time = s.ptcl.start + s.ptcl.pcl * idx_pls;
696  stim_events.emplace_back(start_time, stim_idx);
697  }
698  }
699 
700  // Sort events by start_time
701  std::sort(stim_events.begin(), stim_events.end(),
702  [](auto& a, auto& b) { return a.first < b.first; });
703 
704  // Reserve enough space for output
705  size_t total_nodes = 0;
706  for (auto& ev : stim_events)
707  total_nodes += (*stimuliRef)[ev.second].electrode.vertices.size();
708  StimulusPoints.resize(total_nodes + 1, -1);
709  StimulusTimes.resize(total_nodes + 1, -1);
710 
711  // Fill outputs
712  size_t count = 0;
713  for (auto& ev : stim_events) {
714  const stimulus& s = (*stimuliRef)[ev.second];
715  for (mesh_int_t v : s.electrode.vertices) {
716  StimulusPoints[count] = v;
717  StimulusTimes[count] = ev.first;
718  ++count;
719  }
720  }
721 
722  if (param_globals::output_level)
723  log_msg(NULL, 0, 0, "Translating stimuli for eikonal model done in %f sec.", timing(t2, t1));
724 }
725 
726 void eikonal_solver::create_node_to_node_graph()
727 {
728  double t1, t2;
729  get_time(t1);
730 
731  n2n_dsp.resize(num_pts + 1, 0);
732  const sf_mesh& mesh = get_mesh(intra_elec_msh);
733 
734  // Thread-local storage for neighbors
735  std::vector<std::vector<mesh_int_t>> thread_neighbors(num_pts);
736 
737  // Preallocate thread-local marker arrays for O(n) duplicate removal
738  #pragma omp parallel
739  {
740  std::vector<char> mark(num_pts, 0); // one per thread
741 
742  #pragma omp for schedule(dynamic)
743  for (int point_idx = 0; point_idx < num_pts; point_idx++) {
744  int numNBElem = n2e_dsp[point_idx + 1] - n2e_dsp[point_idx];
745  std::vector<mesh_int_t> neighbors;
746  neighbors.reserve(numNBElem * MESH_SIZE); // rough estimate
747 
748  // Loop over all elements containing this node
749  for (int eedsp = 0; eedsp < numNBElem; eedsp++) {
750  int currElem = n2e_con[n2e_dsp[point_idx] + eedsp];
751 
752  // Loop over all nodes of the current element
753  for (int nndsp = 0; nndsp < MESH_SIZE; nndsp++) {
754  int nb = e2n_con[elem_start[currElem] + nndsp];
755 
756  if (nb == point_idx) continue; // skip self
757  if (!mark[nb]) {
758  mark[nb] = 1;
759  neighbors.push_back(nb);
760  }
761  }
762  }
763 
764  // Reset marks for the next iteration
765  for (int nb : neighbors) mark[nb] = 0;
766 
767  // Move neighbor list into the final container
768  thread_neighbors[point_idx] = std::move(neighbors);
769  }
770  }
771 
772  // Build prefix sums (serial, cheap compared to above)
773  for (int i = 0; i < num_pts; i++) {
774  n2n_dsp[i + 1] = n2n_dsp[i] + thread_neighbors[i].size();
775  }
776 
777  // Allocate once, then fill in parallel
778  n2n_connect.resize(n2n_dsp[num_pts]);
779 
780  #pragma omp parallel for schedule(static)
781  for (int i = 0; i < num_pts; i++) {
782  std::copy(thread_neighbors[i].begin(),
783  thread_neighbors[i].end(),
784  n2n_connect.begin() + n2n_dsp[i]);
785  }
786 
787  if (param_globals::output_level) {
788  log_msg(NULL, 0, 0, "Node-to-node graph done in %f sec.", timing(t2, t1));
789  }
790 }
791 
792 void eikonal_solver::precompute_squared_anisotropy_metric()
793 {
794  double t1, t2;
795  get_time(t1);
796 
797  const sf_mesh& mesh = get_mesh(intra_elec_msh);
798 
799  S.resize(mesh.l_numelem); // store anisotropy matrices (dimensionless)
800  CV_L.resize(mesh.l_numelem); // store CV_L per element for later use
801 
802  // temporary variables
803  SF::dmat<double> I(3, 3);
804  I.assign(0.0);
805  I.diag(1.0);
806 
807  #pragma omp parallel
808  {
809  SF::dmat<double> Saniso(3, 3);
810  SF::dmat<double> Ff(3, 3);
811  SF::dmat<double> diff(3, 3);
812  SF::Point f, s, n;
813 
814  #pragma omp for schedule(static)
815  for (int eidx = 0; eidx < mesh.l_numelem; eidx++) {
816  double vl = 0.0, vt = 0.0, vn = 0.0;
817 
818  // Find region match (break early when found)
819  for (int g = 0; g < param_globals::num_gregions; g++) {
820  const auto& reg = param_globals::gregion[g];
821  const auto& dream = reg.dream;
822  for (int j = 0; j < reg.num_IDs; j++) {
823  if (mesh.tag[eidx] == reg.ID[j]) {
824  vl = dream.vel_l;
825  vt = dream.vel_t;
826  vn = dream.vel_n;
827  goto region_found; // break out of both loops
828  }
829  }
830  }
831  region_found:;
832 
833  // Store CV_L directly (for later rescaling)
834  CV_L[eidx] = vl;
835 
836  // Compute anisotropy ratios relative to CV_L
837  double AR_T2 = (vl / vt) * (vl / vt);
838  double AR_N2 = (vl / vn) * (vl / vn);
839 
840  f.x = mesh.fib[3 * eidx + 0];
841  f.y = mesh.fib[3 * eidx + 1];
842  f.z = mesh.fib[3 * eidx + 2];
843 
844  if (twoFib) {
845  s.x = mesh.she[3 * eidx + 0];
846  s.y = mesh.she[3 * eidx + 1];
847  s.z = mesh.she[3 * eidx + 2];
848  n = cross(f, s);
849 
850  SF::outer_prod(f, f, 1.0, Saniso[0], false);
851  SF::outer_prod(s, s, AR_T2, Saniso[0], true);
852  SF::outer_prod(n, n, AR_N2, Saniso[0], true);
853  } else {
854  SF::outer_prod(f, f, 1.0, Ff[0], false);
855  diff = I - Ff;
856  diff *= AR_T2;
857 
858  Saniso = Ff + diff;
859  }
860 
861  S[eidx] = Saniso;
862  }
863  }
864 
865  if (param_globals::output_level)
866  log_msg(NULL, 0, 0, "Anisotropy tensors precomputed in %f sec.", timing(t2, t1));
867 }
868 
870 {
871  double t0, t1;
872  get_time(t0);
873 
874  // --- 0) Reset all activation times to infinity
875  std::fill(T_A.begin(), T_A.end(), inf);
876 
877  // --- 1) Build initial active list = neighbors of stimuli
878  std::vector<mesh_int_t> activeList;
879  activeList.reserve(num_pts / 10); // heuristic reserve to avoid frequent reallocs
880  std::vector<char> in_active(num_pts, 0);
881 
882  // Mark stimuli
883  for (size_t si = 0; si < StimulusTimes.size() - 1; ++si) { // skip last entry, since its a -1 placeholder currently still used in DREAM
884  mesh_int_t s = StimulusPoints[si];
885  T_A[s] = StimulusTimes[si];
886  }
887  // Seed neighbors; separate loop to avoid adding stim nodes into the list if they are a neighbor
888  for (size_t si = 0; si < StimulusTimes.size() - 1; ++si) { // skip last entry, since its a -1 placeholder currently still used in DREAM
889  mesh_int_t s = StimulusPoints[si];
890  for (int off = n2n_dsp[s]; off < n2n_dsp[s + 1]; ++off) {
891  mesh_int_t nb = n2n_connect[off];
892  if (T_A[nb] == inf) {
893  add_to_active(activeList, in_active, nb);
894  }
895  }
896  }
897 
898  // --- 2) Iterative solve of activeList
899  int niter = 0;
900  while (!activeList.empty() && niter <= param_globals::dream.fim.max_iter) {
901  const std::vector<mesh_int_t> activeVec = std::move(activeList);
902  activeList.clear();
903 
904  #pragma omp parallel
905  {
906  std::vector<mesh_int_t> local_active;
907  local_active.reserve(64); // small local buffer
908 
909  #pragma omp for schedule(dynamic)
910  for (size_t i = 0; i < activeVec.size(); ++i) {
911  mesh_int_t id = activeVec[i];
912  remove_from_active(in_active, id);
913 
914  SF_real p = T_A[id];
915  SF_real q = update(id);
916 
917  #pragma omp atomic write
918  T_A[id] = q;
919 
920  if (std::fabs(p - q) < param_globals::dream.fim.tol) {
921  for (int off = n2n_dsp[id]; off < n2n_dsp[id + 1]; ++off) {
922  mesh_int_t nb = n2n_connect[off];
923  p = T_A[nb];
924  q = update(nb);
925  if (p > q) {
926  #pragma omp atomic write
927  T_A[nb] = q;
928  local_active.push_back(nb);
929  }
930  }
931  } else {
932  local_active.push_back(id); // non-converged -> add back
933  }
934  }
935 
936  // Merge local results
937  #pragma omp critical
938  {
939  for (mesh_int_t nb : local_active) {
940  add_to_active(activeList, in_active, nb);
941  }
942  }
943  }
944  ++niter;
945  }
946 
947  // collect iteration stats
948  stats.update_iter(niter);
949  auto [minIt, maxIt] = std::minmax_element(T_A.begin(), T_A.end());
950  actMIN = *minIt;
951  actMAX = *maxIt;
952 
953  // --- 3) Copy into AT for output; AT is in PETSc order, T_A in nodal order
954  const SF::vector<mesh_int_t>& alg_nod = get_mesh(intra_elec_msh).pl.algebraic_nodes();
955  double* atc = AT->ptr();
956  #pragma omp parallel for
957  for (size_t i = 0; i < alg_nod.size(); ++i) {
958  SF_real ta = T_A[alg_nod[i]];
959  atc[i] = (ta == inf ? -1.0 : ta);
960  }
961  AT->release_ptr(atc);
962 
963  // --- 4) Timing & list‐size stats
964  auto dur = timing(t1, t0);
965  stats.slvtime_A += dur;
966  stats.minAT = actMIN;
967  stats.maxAT = actMAX;
968  stats.activeList = activeList.size();
969  stats.bc_status = true;
971 }
972 
974 {
975  int niter = 0;
976  double t1, t0;
977  get_time(t0);
978 
979  if (sum(List) == 0) {
980  compute_bc();
981  }
982 
983  double time2stop_eikonal = param_globals::dream.tau_inc;
984  float maxadvance = user_globals::tm_manager->time + param_globals::dream.tau_s + param_globals::dream.tau_inc + param_globals::dream.tau_max;
985 
986  do {
987  if (StimulusTimes[Index_currStim] <= maxadvance) {
988  compute_bc();
989  }
990 
991  for (mesh_int_t indX = 0; indX < List.size(); indX++) {
992  SF_real p = T_A[indX];
993  SF_real q;
994 
995  if (List[indX] == 0) continue;
996 
997  q = compute_coherence(indX);
998 
999  T_A[indX] = q;
1000  num_changes[indX] = num_changes[indX] + 1;
1001 
1002  if (q > maxadvance) continue;
1003 
1004  if (abs(p - q) < param_globals::dream.fim.tol || (num_changes[indX] > param_globals::dream.fim.max_iter) || (q == inf || p == inf)) {
1005  for (int ii = n2n_dsp[indX]; ii < n2n_dsp[indX + 1]; ii++) {
1006  mesh_int_t indXNB = n2n_connect[ii];
1007 
1008  if (List[indXNB] == 1) {
1009  continue;
1010  }
1011 
1012  SF_real pNB = T_A[indXNB];
1013  SF_real qNB;
1014 
1015  qNB = compute_coherence(indXNB);
1016 
1017  bool node_is_valid = add_node_neighbor_to_list(T_R[indXNB], pNB, qNB) && qNB != inf && qNB > user_globals::tm_manager->time;
1018  // This second condition is there to be able to add a node to the list when a new valid activation time
1019  // is found but a reentry would be blocked by the L2 parameter. Normally this condition does not make or brake the
1020  // simulation but would leave individual nodes inactivated, which is not ideal.
1021  bool ignore_L2_if_valid = node_is_valid && qNB > pNB && nReadded2List[indXNB] >= param_globals::dream.fim.max_addpt;
1022 
1023  if (node_is_valid && (nReadded2List[indXNB] < param_globals::dream.fim.max_addpt) || ignore_L2_if_valid) {
1024  if (qNB > pNB) {
1025  nReadded2List[indXNB] = 0;
1026  }
1027  T_A[indXNB] = qNB;
1028  nReadded2List[indXNB]++;
1029  num_changes[indXNB] = 0;
1030  List[indXNB] = 1;
1031  if (param_globals::dream.output.debugNode == indXNB) {
1033  nodeData.idXNB = indX;
1034  nodeData.nbn_T_A = q;
1035  }
1036  }
1037  }
1038 
1039  List[indX] = 0;
1040  if (param_globals::dream.output.debugNode == indX) {
1042  }
1043  }
1044  }
1045 
1046  SF_real actMIN_old = actMIN;
1047  SF_real progress_time;
1048 
1049  update_Ta_in_active_list();
1050 
1051  if (actMIN > actMIN_old) {
1052  progress_time = actMIN - actMIN_old;
1053  } else {
1054  progress_time = 0;
1055  }
1056 
1057  time2stop_eikonal -= progress_time;
1058  niter++;
1059 
1060  } while (time2stop_eikonal > 0 && sum(List) > 0);
1061 
1062  if (sum(List) == 0) {
1064  }
1065 
1066  // copy for igb output; AT/RT are in PETSc order, T_A/T_R in nodal order
1067  const SF::vector<mesh_int_t>& alg_nod = get_mesh(intra_elec_msh).pl.algebraic_nodes();
1068  double* atc = AT->ptr();
1069  double* rpt = RT->ptr();
1070  for (size_t i = 0; i < alg_nod.size(); i++) {
1071  mesh_int_t n = alg_nod[i];
1072  if (T_A[n] == inf) {
1073  // for better visualization in meshalyzer
1074  atc[i] = -1;
1075  } else {
1076  atc[i] = T_A[n];
1077  }
1078  rpt[i] = T_R[n];
1079  }
1080  AT->release_ptr(atc);
1081  RT->release_ptr(rpt);
1082 
1083  // treat solver statistics
1084  auto dur = timing(t1, t0);
1085  stats.slvtime_A += dur;
1086  stats.update_iter(niter);
1087  stats.minAT = actMIN;
1088  stats.maxAT = actMAX;
1089  stats.activeList = sum(List);
1091 
1092  // treat node stats
1093  if (param_globals::dream.output.debugNode >= 0) {
1097  }
1098 
1099 } // close iterate list
1100 
1101 SF_real eikonal_solver::update(mesh_int_t& indX, SF_real CVrest_factor, bool isDREAM)
1102 {
1103  switch (MESH_SIZE) {
1104  case 4: return update_impl<4>(indX, CVrest_factor, isDREAM);
1105  case 3: return update_impl<3>(indX, CVrest_factor, isDREAM);
1106  case 2: return update_impl<2>(indX, CVrest_factor, isDREAM);
1107  default:
1108  return T_A[indX]; // fallback
1109  }
1110 }
1111 
1112 template <int N>
1113 SF_real eikonal_solver::update_impl(mesh_int_t& indX, SF_real CVrest_factor, bool CheckValidity)
1114 {
1115  double min = inf;
1116  const double time = user_globals::tm_manager->time;
1117  const sf_mesh& mesh = get_mesh(intra_elec_msh);
1118 
1119  // element-wise update
1120  for (int e_i = n2e_dsp[indX]; e_i < n2e_dsp[indX + 1]; e_i++) { // gather all elements the node belongs to
1121  int Elem_i = n2e_con[e_i];
1122  mesh_int_t indEle = elem_start[Elem_i];
1123  std::array<SF::Point, N> base; // points
1124  std::array<double, N> values; // activation times
1125  std::array<int, N> nodeIDs;
1126 
1127  std::size_t k = 0;
1128  for (std::size_t j = 0; j < N; j++) { // loop over nodes of element e_i
1129  int n_i = e2n_con[indEle + j];
1130  if (n_i != indX) {
1131  base[k].x = mesh.xyz[3 * n_i + 0]; base[k].y = mesh.xyz[3 * n_i + 1]; base[k].z = mesh.xyz[3 * n_i + 2];
1132  values[k] = T_A[n_i];
1133  nodeIDs[k] = n_i;
1134  k++;
1135  } else { // last slot is reserved for the current vertex we are solving for
1136  base[N - 1].x = mesh.xyz[3 * indX + 0]; base[N - 1].y = mesh.xyz[3 * indX + 1]; base[N - 1].z = mesh.xyz[3 * indX + 2];
1137  values[N - 1] = T_A[indX];
1138  nodeIDs[N - 1] = indX;
1139  }
1140  }
1141  // scale slowness metric by CV
1142  double cv = CV_L[Elem_i] * CVrest_factor;
1143  if (cv == 0.0) continue; // avoid 1/(cv*cv)
1144  SF::dmat<double> D = 1.0 / (cv * cv) * S[Elem_i];
1145 
1146  // 1) solve full N-simplex (eikonal run OR if valid for DREAM)
1147  if (!CheckValidity || !is_not_valid_update<N>(nodeIDs, time)) {
1148  LocalSolver<N> solver(D, base, values);
1149  SF_real tmp = solver.solve();
1150  if (min > tmp && tmp > T_R[indX] && compute_H(indX, tmp) > 0.0) {
1151  min = tmp;
1152  }
1153  continue;
1154  }
1155 
1156  // If the full N-simplex was not valid, we have to do additional checks for the DREAM,
1157  // since a subsimplex could be valid if e.g. only one node of a tet/triangle is invalid
1158  // 2) triangles that include the target (only done if MESH_SIZE is 4)
1159  if constexpr (N - 1 == 3) {
1160  // neighbor indices are 0..(N-2); choose pairs (i,j) and add target (N-1)
1161  for (int i = 0; i < (N - 1); ++i) {
1162  for (int j = i + 1; j < (N - 1); ++j) {
1163  // build nodeIDs/points/values for face {i, j, target}
1164  std::array<int, 3> tri_ids{nodeIDs[i], nodeIDs[j], nodeIDs[N - 1]};
1165  if (is_not_valid_update<3>(tri_ids, time)) continue;
1166 
1167  std::array<SF::Point, 3> tri_pts{base[i], base[j], base[N - 1]};
1168  std::array<double, 3> tri_vals{values[i], values[j], values[N - 1]};
1169 
1170  LocalSolver<3> solver(D, tri_pts, tri_vals);
1171  // min = std::min(min, solver.solve());
1172  SF_real tmp = solver.solve();
1173  if (min > tmp && tmp > T_R[indX] && compute_H(indX, tmp) > 0.0) {
1174  min = tmp;
1175  }
1176  }
1177  }
1178  }
1179 
1180  // 3) edges that include the target
1181  for (int i = 0; i < N - 1; i++) {
1182  std::array<int, 2> edge_ids{nodeIDs[i], nodeIDs[N - 1]};
1183  if (is_not_valid_update<2>(edge_ids, time)) continue;
1184 
1185  std::array<SF::Point, 2> edge_pts{base[i], base[N - 1]};
1186  std::array<double, 2> edge_vals{values[i], values[N - 1]};
1187 
1188  LocalSolver<2> solver(D, edge_pts, edge_vals);
1189  SF_real tmp = solver.solve();
1190  if (min > tmp && tmp > T_R[indX] && compute_H(indX, tmp) > 0.0) {
1191  min = tmp;
1192  }
1193  }
1194  }
1195 
1196  return min;
1197 }
1198 
1199 template <int N>
1200 bool eikonal_solver::is_not_valid_update(const std::array<int, N>& nodeIDs, double time)
1201 {
1202  const int target = nodeIDs[N - 1];
1203  const bool failedStim = (stim_status[target] == 2);
1204 
1205  for (int i = 0; i < N - 1; i++) {
1206  const int nb = nodeIDs[i];
1207 
1208  if (T_A[nb] < time) return true;
1209  if (T_A[nb] < T_R[nb]) return true;
1210  if (failedStim && stim_status[nb] == 1) return true;
1211  }
1212 
1213  return false;
1214 }
1215 
1216 SF_real eikonal_solver::compute_H(mesh_int_t& indX, SF_real& tmpTA)
1217 {
1218  // Apply a refractory delay if stimulus previously failed
1219  const double delay = (stim_status[indX] == 2) ? 5.0 : 0.0;
1220 
1221  // Early exit conditions
1222  if (tmpTA == inf ||
1223  (T_R[indX] + delay) == -400.0 ||
1224  std::fabs(tmpTA - TA_old[indX]) < param_globals::dream.fim.tol ||
1225  T_R[indX] > tmpTA) {
1226  return 1.0;
1227  }
1228 
1229  // Compute diastolic interval
1230  const double DI = tmpTA - (T_R[indX] + delay);
1231  D_I[indX] = DI;
1232 
1233  // CV restitution factor
1234  const double exponent = -(DI + kappa_cvrest[indX]) * denom_cvrest[indX];
1235  const double Factor_DI = 1.0 - rho_cvrest[indX] * std::exp(exponent);
1236 
1237  if (Factor_DI <= 0.0) {
1238  return 0.0;
1239  }
1240 
1241  // Apply restitution curve behavior
1242  return (DI <= theta_cvrest[indX]) ? -Factor_DI : Factor_DI;
1243 }
1244 
1245 SF_real eikonal_solver::compute_coherence(mesh_int_t& indX)
1246 {
1247  SF_real scaling = 1.0;
1248  SF_real p = T_A[indX]; // starting guess (previous arrival time)
1249  SF_real q = update(indX, scaling, true); // candidate new arrival time
1250 
1251  for (int niter = 0; niter < param_globals::dream.fim.max_coh; ++niter) {
1252  scaling = compute_H(indX, p); // restitution-based scaling for CV (can be negative mid-iteration)
1253  q = update(indX, std::fabs(scaling), true); // new candidate arrival time; use fabs() to allow intermediate negative scaling
1254 
1255  if (std::fabs(p - q) < param_globals::dream.fim.tol)
1256  break; // converged
1257 
1258  p = q; // continue iterating
1259  }
1260 
1261  // Only accept q if final state is physiologically valid
1262  return (compute_H(indX, q) < 0.0) ? T_A[indX] : q;
1263 }
1264 
1265 void eikonal_solver::compute_bc()
1266 {
1267  bool EmpList = sum(List) == 0;
1268 
1269  if (EmpList) {
1270  for (size_t j = Index_currStim; j < StimulusTimes.size(); j++) {
1271  if ((StimulusPoints[j] == -1) || (StimulusTimes[j] > StimulusTimes[Index_currStim])) {
1272  Index_currStim = j;
1273  break;
1274  }
1275 
1276  mesh_int_t indNode = StimulusPoints[j];
1277  SF_real TimeSt = StimulusTimes[j];
1278 
1279  bool cond2add = add_node_neighbor_to_list(T_R[indNode], T_A[indNode], TimeSt);
1280  if (cond2add && compute_H(indNode, TimeSt) > 0) {
1281  T_A[indNode] = TimeSt;
1282  stim_status[indNode] = 1;
1283  stats.bc_status = true;
1284 
1285  if (param_globals::dream.output.debugNode == indNode) {
1286  nodeData.T_A = TimeSt;
1288  }
1289 
1290  for (int ii = n2n_dsp[indNode]; ii < n2n_dsp[indNode + 1]; ii++) {
1291  mesh_int_t indXNB = n2n_connect[ii];
1292  if (List[indXNB] == 0) {
1293  List[indXNB] = 1;
1294  if (param_globals::dream.output.debugNode == indXNB) {
1296  nodeData.idXNB = indNode;
1297  nodeData.nbn_T_A = TimeSt;
1298  }
1299  }
1300  }
1301  }
1302 
1303  if (cond2add && compute_H(indNode, TimeSt) <= 0) {
1304  stim_status[indNode] = 2;
1305  }
1306  }
1307 
1308  // After NB of initial points are assigned remove initial points from the list if they were added in the previous loop.
1309  for (size_t j = 0; j < StimulusPoints.size(); j++) {
1310  if ((StimulusPoints[j] == -1) && (StimulusTimes[j] > StimulusTimes[Index_currStim])) continue;
1311  if (List[StimulusPoints[j]] == 1) {
1312  List[StimulusPoints[j]] = 0;
1313  if (param_globals::dream.output.debugNode == StimulusPoints[j]) nodeData.update_status(node_stats::out, node_stats::stim);
1314  }
1315  }
1316 
1318  } else {
1319  for (size_t i = Index_currStim; i < StimulusTimes.size(); i++) {
1320  mesh_int_t indNode = StimulusPoints[i];
1321  SF_real TimeSt = StimulusTimes[i];
1322 
1323  if (indNode == -1) continue;
1324 
1325  if (TimeSt <= actMAX) {
1326  bool cond2add = add_node_neighbor_to_list(T_R[indNode], T_A[indNode], TimeSt);
1327  if (cond2add && compute_H(indNode, TimeSt) > 0) {
1328  T_A[indNode] = TimeSt;
1329  stim_status[indNode] = 1;
1330  stats.bc_status = true;
1331 
1332  if (param_globals::dream.output.debugNode == indNode) {
1333  nodeData.T_A = TimeSt;
1335  }
1336 
1337  for (int ii = n2n_dsp[indNode]; ii < n2n_dsp[indNode + 1]; ii++) {
1338  mesh_int_t indXNB = n2n_connect[ii];
1339  if (List[indXNB] == 0) {
1340  List[indXNB] = 1;
1341  if (param_globals::dream.output.debugNode == indXNB) {
1343  nodeData.idXNB = indNode;
1344  nodeData.nbn_T_A = TimeSt;
1345  }
1346  }
1347  }
1348 
1349  for (size_t j = 0; j < StimulusPoints.size(); j++) {
1350  if ((StimulusPoints[j] == -1) && (StimulusTimes[j] > StimulusTimes[Index_currStim])) continue;
1351  if (List[StimulusPoints[j]] == 1) {
1352  List[StimulusPoints[j]] = 0;
1353  if (param_globals::dream.output.debugNode == StimulusPoints[j]) nodeData.update_status(node_stats::out, node_stats::stim);
1354  }
1355  }
1356  }
1357  if (cond2add && compute_H(indNode, TimeSt) <= 0) {
1358  stim_status[indNode] = 2;
1359  }
1360 
1361  } else {
1362  Index_currStim = i;
1363 
1364  break;
1365  }
1366  }
1367  }
1368 
1369 } // end compute stimulus
1370 
1372 {
1373  bool act_is_in_safety_window, empty_list_and_illegal_stimulus, empty_stimulus, stimulus_is_in_safety_window;
1374 
1375  act_is_in_safety_window = (actMIN > param_globals::dream.tau_s) && (actMIN - time > param_globals::dream.tau_s);
1376  empty_stimulus = (StimulusPoints[Index_currStim] == -1);
1377  stimulus_is_in_safety_window = (StimulusTimes[Index_currStim] - time > param_globals::dream.tau_s);
1378  empty_list_and_illegal_stimulus = (sum(List) == 0) && (empty_stimulus || stimulus_is_in_safety_window);
1379 
1380  return act_is_in_safety_window || empty_list_and_illegal_stimulus;
1381 }
1382 
1383 void eikonal_solver::update_Ta_in_active_list()
1384 {
1385  bool First_in_List = 1;
1386 
1387  for (size_t j = 0; j < List.size(); j++) {
1388  if (T_A[j] < 0) continue;
1389  if (List[j] == 1 && First_in_List) {
1390  actMIN = T_A[j];
1391  actMAX = T_A[j];
1392  First_in_List = 0;
1393  continue;
1394  }
1395  if (List[j] == 1) {
1396  if (T_A[j] < actMIN) actMIN = T_A[j];
1397  if (T_A[j] > actMAX) actMAX = T_A[j];
1398  }
1399  }
1400 }
1401 
1403 {
1404  for (size_t j = 0; j < List.size(); j++) {
1405  if (T_A[j] < user_globals::tm_manager->time) {
1406  TA_old[j] = T_A[j];
1407  stim_status[j] = 0;
1408  nReadded2List[j] = 0;
1409 
1410  if (List[j] == 1) List[j] = 0;
1411  }
1412  }
1413 }
1414 
1415 bool eikonal_solver::add_node_neighbor_to_list(SF_real& RT, SF_real& oldTA, SF_real& newTA)
1416 {
1417  // Condition (A): RT < newTA < oldTA
1418  // Condition (B): oldTA < RT < newTA
1419  return ((RT < newTA) && (newTA < oldTA)) ||
1420  ((oldTA < RT) && (RT < newTA));
1421 }
1422 
1424 {
1425  SF_real* old_ptr = Vmv_old.ptr();
1426  SF_real* new_ptr = Vmv.ptr();
1427 
1428  const double thresh = param_globals::dream.repol_time_thresh;
1429 
1430  // Vm is in PETSc order, T_R in nodal order
1431  const SF::vector<mesh_int_t>& alg_nod = get_mesh(intra_elec_msh).pl.algebraic_nodes();
1432  for (size_t i = 0; i < alg_nod.size(); i++) {
1433  if (old_ptr[i] >= thresh && new_ptr[i] < thresh) {
1434  T_R[alg_nod[i]] = time;
1435  }
1436  }
1437 
1438  Vmv_old.release_ptr(old_ptr);
1439  Vmv.release_ptr(new_ptr);
1440 }
1441 
1443 {
1444  double t1, t0;
1445  get_time(t0);
1446 
1447  #ifdef _OPENMP
1448  int max_threads = omp_get_max_threads();
1449  omp_set_num_threads(1); // with the current setup of this function, it is better to run it in serial.
1450  #endif
1451 
1452  limpet::MULTI_IF* miif = ion.miif;
1453  const SF::vector<mesh_int_t>& alg_nod = get_mesh(intra_elec_msh).pl.algebraic_nodes();
1454 
1455  const double time = user_globals::tm_manager->time,
1457 
1458  for (int i = 0; i < miif->N_IIF; i++) {
1459  if (!miif->N_Nodes[i]) continue;
1460  limpet::IonIfBase* pIF = ion.miif->IIF[i];
1461  limpet::IonIfBase* IIF_old = pIF->get_type().make_ion_if(pIF->get_target(),
1462  pIF->get_num_node(),
1463  ion.miif->plugtypes[i]);
1464  IIF_old->copy_SVs_from(*pIF, false);
1465 
1466  int current = 0;
1467  do {
1468  // NodeLists holds PETSc indices, T_A/T_R are nodal
1469  mesh_int_t loc_nodal_idx = alg_nod[miif->NodeLists[i][current]];
1470  // save states at the moment
1471  double Vm_old = miif->ldata[i][limpet::Vm][current];
1472  double Iion_old = miif->ldata[i][limpet::Iion][current];
1473  double prev_R = T_R[loc_nodal_idx];
1474 
1475  bool cond_2upd = T_R[loc_nodal_idx] <= T_A[loc_nodal_idx] && T_A[loc_nodal_idx] != inf && Vm_old > param_globals::dream.repol_time_thresh;
1476 
1477  if (cond_2upd) {
1478  double elapsed_time = 0;
1479  double prev_Vm = miif->ldata[i][limpet::Vm][current];
1480 
1481  do {
1482  elapsed_time += dt;
1483  pIF->compute(current, current + 1, miif->ldata[i]);
1484  miif->ldata[i][limpet::Vm][current] -= miif->ldata[i][limpet::Iion][current] * param_globals::dt;
1485  if (miif->ldata[i][limpet::Vm][current] < param_globals::dream.repol_time_thresh) {
1486  T_R[loc_nodal_idx] = time + elapsed_time;
1487  break;
1488  }
1489  } while (elapsed_time < 600);
1490 
1491  // Restore old states
1492  miif->ldata[i][limpet::Vm][current] = Vm_old;
1493  miif->ldata[i][limpet::Iion][current] = Iion_old;
1494  }
1495  current++;
1496  } while (current < miif->N_Nodes[i]);
1497  pIF->copy_SVs_from(*IIF_old, false);
1498  }
1499 
1500  #ifdef _OPENMP
1501  omp_set_num_threads(max_threads); // restore max threads for parabolic solver
1502  #endif
1503 
1504  // treat solver statistics
1505  auto dur = timing(t1, t0);
1506  stats.slvtime_D += dur;
1507 }
1508 
1510 {
1511  double t0, t1;
1512  get_time(t0);
1513 
1514  SF_real* c = Idiff->ptr();
1515  SF_real* v = vm.ptr();
1516 
1517  const sf_mesh& mesh = get_mesh(intra_elec_msh);
1518  const SF::vector<mesh_int_t>& alg_nod = mesh.pl.algebraic_nodes();
1519  int rank = get_rank();
1520 
1521  for (size_t j = 0; j < alg_nod.size(); j++) {
1522  mesh_int_t loc_nodal_idx = alg_nod[j];
1523  mesh_int_t loc_petsc_idx = local_nodal_to_local_petsc(mesh, rank, loc_nodal_idx);
1524 
1525  double TA = T_A[loc_nodal_idx];
1526  if (!(time >= TA && (TA + 5) >= time && List[loc_nodal_idx] == 0))
1527  continue;
1528 
1529  double dT = time - TA;
1530  auto& node = diff_cur[loc_nodal_idx];
1531 
1532  switch (node.model) {
1533  case GAUSS: {
1534  double term1 = (dT - node.beta_1) / node.gamma_1;
1535  double term2 = (dT - node.beta_2) / node.gamma_2;
1536  double term3 = (dT - node.beta_3) / node.gamma_3;
1537  c[loc_petsc_idx] = node.alpha_1 * exp(-term1 * term1) + node.alpha_2 * exp(-term2 * term2) + node.alpha_3 * exp(-term3 * term3);
1538  break;
1539  }
1540  default: {
1541  double e_on = (dT >= 0.0) ? 1.0 : 0.0;
1542  double e_off = (v[loc_petsc_idx] < node.V_th) ? 1.0 : 0.0;
1543  c[loc_petsc_idx] = node.A_F / node.tau_F * exp(dT / node.tau_F) * e_on * e_off;
1544  break;
1545  }
1546  }
1547  }
1548 
1549  Idiff->release_ptr(c);
1550  vm.release_ptr(v);
1551 
1552  stats.slvtime_B += timing(t1, t0);
1553 }
1554 
1555 void eikonal_solver::save_eikonal_state(const char* tsav_ext)
1556 {
1557  if (get_rank() == 0) {
1558  FILE* file_writestate;
1559  char buffer_writestate[1024];
1560  snprintf(buffer_writestate, sizeof buffer_writestate, "%s.%s.roe.dat", param_globals::write_statef, tsav_ext);
1561  file_writestate = fopen(buffer_writestate, "w");
1562  for (size_t jjj = 0; jjj < List.size(); jjj++) {
1563  fprintf(file_writestate, "%lld %lld %lld %f %f %f %f \n",
1564  static_cast<long long>(List[jjj]),
1565  static_cast<long long>(num_changes[jjj]),
1566  static_cast<long long>(nReadded2List[jjj]),
1567  T_A[jjj], T_R[jjj], TA_old[jjj], D_I[jjj]);
1568  }
1569 
1570  fclose(file_writestate);
1571  }
1572 }
1573 
1574 void eikonal_solver::load_state_file()
1575 {
1576  set_dir(INPUT);
1577  FILE* file_startstate;
1578  char buffer_startstate[strlen(param_globals::start_statef) + 10];
1579 
1580  snprintf(buffer_startstate, sizeof buffer_startstate, "%s.dat", param_globals::start_statef);
1581  file_startstate = fopen(buffer_startstate, "r");
1582 
1583  if (file_startstate == NULL) {
1584  log_msg(NULL, 5, 0, "Not able to open state file: %s", buffer_startstate);
1585  } else if (param_globals::output_level) {
1586  log_msg(NULL, 0, 0, "Open state file for eikonal model: %s", buffer_startstate);
1587  }
1588 
1589  int ListVal, numChangesVal, numChanges2Val;
1590  float T_AVal, T_RVal, TA_oldVal, D_IVal, PCLVal;
1591  int index = 0;
1592 
1593  while (fscanf(file_startstate, "%d %d %d %f %f %f %f", &ListVal, &numChangesVal, &numChanges2Val, &T_AVal, &T_RVal, &TA_oldVal, &D_IVal) == 7) {
1594  List[index] = ListVal;
1595  num_changes[index] = numChangesVal;
1596  nReadded2List[index] = numChanges2Val;
1597  T_A[index] = T_AVal;
1598  T_R[index] = T_RVal;
1599  TA_old[index] = TA_oldVal;
1600  D_I[index] = D_IVal;
1601  ++index;
1602  }
1603  if (param_globals::output_level) log_msg(NULL, 0, 0, "Number of nodes in active list: %i", sum(List));
1604 
1605  fclose(file_startstate);
1606 }
1607 
1609 {
1610  logger = f_open(filename, "w");
1611 
1612  const char* h1 = " ------ ---------- ---------- ------- ------- | List logic ----- -------- | Neighbor node ---- |";
1613  const char* h2 = " cycle AT old AT RT DI | Status Entry Exit | ID AT |";
1614 
1615  if (logger == NULL)
1616  log_msg(NULL, 3, 0, "%s error: Could not open file %s in %s. Turning off logging.\n",
1617  __func__, filename);
1618  else {
1619  log_msg(logger, 0, 0, "%s", h1);
1620  log_msg(logger, 0, 0, "%s", h2);
1621  }
1622 }
1623 
1624 void node_stats::log_stats(double time, bool cflg)
1625 {
1626  if (!this->logger) return;
1627 
1628  char abuf[256];
1629  char bbuf[256];
1630  char cbuf[256];
1631 
1632  // create nicer output in logger for inf, -inf, nan
1633  std::ostringstream oss_TA, oss_TA_, oss_TR, oss_DI, oss_nbnTA;
1634  oss_TA << this->T_A;
1635  oss_TA_ << this->T_A_;
1636  oss_TR << this->T_R;
1637  oss_DI << this->D_I;
1638  oss_nbnTA << this->nbn_T_A;
1639 
1640  if (this->idXNB == std::numeric_limits<Int>::min()) {
1641  snprintf(cbuf, sizeof cbuf, "%7s %10s", "-", "-");
1642  } else {
1643  snprintf(cbuf, sizeof cbuf, "%7lld %10s", static_cast<long long>(this->idXNB), oss_nbnTA.str().c_str());
1644  }
1645 
1646  snprintf(abuf, sizeof abuf, "%6lld %10s %10s %7s %7s",
1647  static_cast<long long>(this->cycle),
1648  oss_TA.str().c_str(), oss_TA_.str().c_str(), oss_TR.str().c_str(), oss_DI.str().c_str());
1649  snprintf(bbuf, sizeof bbuf, "%7s %8s %8s", this->status, this->reasonIn, this->reasonOut);
1650 
1651  unsigned char flag = cflg ? ECHO : 0;
1652  log_msg(this->logger, 0, flag | FLUSH | NONL, "%9.3f %s | %s | %s |\n", time, abuf, bbuf, cbuf);
1653 
1654  this->reasonIn = "-";
1655  this->reasonOut = "-";
1656  this->T_A_ = this->T_A;
1657  this->T_A = std::numeric_limits<double>::quiet_NaN();
1658  this->T_R = std::numeric_limits<double>::quiet_NaN();
1659  this->D_I = std::numeric_limits<double>::quiet_NaN();
1661  this->nbn_T_A = std::numeric_limits<double>::quiet_NaN();
1662  this->cycle++;
1663 }
1664 
1666 {
1667  // directly convert enums to strings for logging
1668  const char* stat_str;
1669  const char* reas_str;
1670  switch (s) {
1671  case node_stats::in: stat_str = "in"; break;
1672  case node_stats::out: stat_str = "out"; break;
1673  }
1674 
1675  switch (r) {
1676  case node_stats::none: reas_str = "-"; break;
1677  case node_stats::nbn: reas_str = "nbn"; break;
1678  case node_stats::conv: reas_str = "conv"; break;
1679  case node_stats::stim: reas_str = "stim"; break;
1680  }
1681 
1682  this->status = stat_str;
1683  if (s == in) {
1684  this->reasonIn = reas_str;
1685  } else {
1686  this->reasonOut = reas_str;
1687  }
1688 }
1689 
1690 template<int MESH_SIZE>
1692  const SF::Point& x1 = points[0];
1693  const SF::Point& x2 = points[1];
1694 
1695  const double& u1 = values[0];
1696 
1697  if constexpr (MESH_SIZE == 2) {
1698  return tsitsiklis_update_line({x1,x2}, D, u1);
1699 
1700  } else if constexpr (MESH_SIZE == 3) {
1701  const SF::Point& x3 = points[2];
1702  const double& u2 = values[1];
1703  return tsitsiklis_update_triangle({x1,x2,x3}, D, {u1,u2});
1704 
1705  } else if constexpr (MESH_SIZE == 4) {
1706  const SF::Point& x3 = points[2];
1707  const SF::Point& x4 = points[3];
1708  const double& u2 = values[1];
1709  const double& u3 = values[2];
1710 
1711  double u_tet = tsitsiklis_update_tetra({x1,x2,x3,x4}, D, {u1,u2,u3});
1712  if (isnan(u_tet)) {
1713  u_tet = std::numeric_limits<double>::infinity();
1714  }
1715  // face calculations (contains edge update as fallback)
1716  double u_face1 = tsitsiklis_update_triangle({x1, x2, x4}, D, {u1, u2});
1717  double u_face2 = tsitsiklis_update_triangle({x1, x3, x4}, D, {u1, u3});
1718  double u_face3 = tsitsiklis_update_triangle({x2, x3, x4}, D, {u2, u3});
1719 
1720  double u_tri = std::min({u_face1, u_face2, u_face3});
1721  return std::min(u_tet, u_tri);
1722  }
1723 }
1724 
1725 template <int MESH_SIZE>
1726 double LocalSolver<MESH_SIZE>::tsitsiklis_update_line(const std::array<SF::Point, 2>& base,
1727  const SF::dmat<double>& D,
1728  const double& value)
1729 {
1730  // Compute the difference vector: a1 = x2 - x1
1731  SF::Point a1 = base[1] - base[0];
1732  // Return updated value at x2: u1 + norm
1733  return value + std::sqrt(SF::inner_prod(a1, D * a1));
1734 }
1735 
1736 template <int MESH_SIZE>
1737 double LocalSolver<MESH_SIZE>::tsitsiklis_update_triangle(const std::array<SF::Point, 3>& base,
1738  const SF::dmat<double>& D,
1739  const std::array<double, 2>& values)
1740 {
1741  const SF::Point& x1 = base[0];
1742  const SF::Point& x2 = base[1];
1743  const SF::Point& x3 = base[2];
1744  const double& u1 = values[0];
1745  const double& u2 = values[1];
1746  double result = std::numeric_limits<double>::infinity();
1747 
1748  SF::Point z1 = x1 - x2;
1749  SF::Point z2 = x2 - x3;
1750  double k = u1 - u2;
1751 
1752  // Squared Mahalanobis norms
1753  const SF::Point Dz1 = D * z1;
1754  const SF::Point Dz2 = D * z2;
1755  double p11 = SF::inner_prod(z1, Dz1);
1756  double p12 = SF::inner_prod(z1, Dz2);
1757  double p22 = SF::inner_prod(z2, Dz2);
1758 
1759  double denominator = p11 - k * k;
1760  double sqrt_val = (p11 * p22 - p12 * p12) / denominator;
1761 
1762  if (denominator > 1e-12) { // avoid dividing by zero or near zero -> k very small, likely due to collapsed triangle/coinciding points
1763  const double sqrt_val = (p11 * p22 - p12 * p12) / denominator;
1764  if (sqrt_val >= 0.0) { // only real solutions are considered
1765  const double rhs = k * std::sqrt(sqrt_val);
1766  double alpha1 = -(p12 + rhs) / p11;
1767  double alpha2 = -(p12 - rhs) / p11;
1768 
1769  alpha1 = std::clamp(alpha1, 0.0, 1.0);
1770  alpha2 = std::clamp(alpha2, 0.0, 1.0);
1771 
1772  for (double alpha : {alpha1, alpha2}) {
1773  SF::Point x_interp = x1 * alpha + x2 * (1.0 - alpha);
1774  SF::Point dist = x3 - x_interp;
1775  double norm_D = std::sqrt(SF::inner_prod(dist, D * dist));
1776  double u3 = alpha * u1 + (1.0 - alpha) * u2 + norm_D;
1777  result = std::min(result, u3);
1778  }
1779  }
1780  }
1781 
1782  // Fallback: point-based update if square root was invalid or denominator is too small
1783  double u_edge1 = tsitsiklis_update_line({x1,x3}, D, u1);
1784  double u_edge2 = tsitsiklis_update_line({x2,x3}, D, u2);
1785 
1786  return std::min({result, u_edge1, u_edge2});
1787 }
1788 
1789 template <int MESH_SIZE>
1790 double LocalSolver<MESH_SIZE>::tsitsiklis_update_tetra(const std::array<SF::Point, 4>& base,
1791  const SF::dmat<double>& D,
1792  const std::array<double, 3>& values)
1793 {
1794  const SF::Point& x1 = base[0];
1795  const SF::Point& x2 = base[1];
1796  const SF::Point& x3 = base[2];
1797  const SF::Point& x4 = base[3];
1798 
1799  const double& u1 = values[0];
1800  const double& u2 = values[1];
1801  const double& u3 = values[2];
1802 
1803  // edge vectors
1804  const SF::Point y1 = x3 - x1;
1805  const SF::Point y2 = x3 - x2;
1806  const SF::Point y3 = x4 - x3;
1807 
1808  const double k1 = u1 - u3;
1809  const double k2 = u2 - u3;
1810 
1811  // Matrix products (squared norms and dot products under metric D)
1812  const SF::Point Dy1 = D * y1;
1813  const SF::Point Dy2 = D * y2;
1814  const SF::Point Dy3 = D * y3;
1815  const double r11 = SF::inner_prod(y1, Dy1);
1816  const double r12 = SF::inner_prod(y1, Dy2);
1817  const double r13 = SF::inner_prod(y1, Dy3);
1818  const double r21 = r12;
1819  const double r22 = SF::inner_prod(y2, Dy2);
1820  const double r23 = SF::inner_prod(y2, Dy3);
1821  const double r31 = r13;
1822  const double r32 = r23;
1823 
1824  const double A1 = k2 * r11 - k1 * r12;
1825  const double A2 = k2 * r21 - k1 * r22;
1826  const double B = k2 * r31 - k1 * r32;
1827  const double k = k1 - (A1 / A2) * k2;
1828  const SF::Point z1 = y1 - (A1 / A2) * y2;
1829  const SF::Point z2 = y3 - (B / A2) * y2;
1830 
1831  // compute quadratic equation
1832  const SF::Point Dz1 = D * z1;
1833  const SF::Point Dz2 = D * z2;
1834  const double p11 = SF::inner_prod(z1, Dz1);
1835  const double p12 = SF::inner_prod(z1, Dz2);
1836  const double p22 = SF::inner_prod(z2, Dz2);
1837  const double denominator = p11 - k*k;
1838  const double sqrt_val = (p11 * p22 - (p12 * p12)) / denominator;
1839  const double rhs = k * std::sqrt(sqrt_val);
1840 
1841  double alpha1 = -(p12 + rhs) / p11;
1842  double alpha2 = -(B + alpha1 * A1) / A2;
1843 
1844  // handle degenerate cases
1845  const double EPS = 1e-16;
1846  if ((std::abs(A1) < EPS) && (std::abs(A2) < EPS)) {
1847  alpha1 = (r12 * r23 - r13 * r22) / (r11 * r22 - (r12 * r12));
1848  alpha2 = (r12 * r13 - r11 * r23) / (r11 * r22 - (r12 * r12));
1849  } else if ((std::abs(A1) < EPS) && (std::abs(A2) > EPS)) {
1850  alpha1 = 0;
1851  alpha2 = -B / A2;
1852  } else if ((std::abs(A1) > EPS) && (std::abs(A2) < EPS)) {
1853  alpha1 = -B / A1;
1854  alpha2 = 0;
1855  }
1856 
1857  double alpha3 = 1 - alpha1 - alpha2;
1858  const SF::Point dist = x4 - (alpha1 * x1 + alpha2 * x2 + alpha3 * x3);
1859  // barycentric coordinate should be inside the tetrahedron
1860  if (alpha1 < -EPS || alpha2 < -EPS || alpha3 < -EPS ||
1861  alpha1 > 1.0+EPS || alpha2 > 1.0+EPS || alpha3 > 1.0+EPS) {
1862  return std::numeric_limits<double>::infinity();
1863  } else {
1864  return alpha1 * u1 + alpha2 * u2 + alpha3 * u3 + std::sqrt(SF::inner_prod(dist, D * dist));
1865  }
1866 }
1867 
1868 } // namespace opencarp
void output(vector< int > nodes, IGBheader *h, char *ofname, enum_format of, int t0, int t1, int stride, bool explode, float scale)
Definition: IGBextract.cc:210
opencarp::local_index_t mesh_int_t
Definition: SF_container.h:31
opencarp::real_t SF_real
Global scalar type.
Definition: SF_globals.h:18
Basic utility structs and functions, mostly IO related.
#define FLUSH
Definition: basics.h:304
#define ECHO
Definition: basics.h:301
#define NONL
Definition: basics.h:305
virtual void write(const char *filename) const =0
virtual S * ptr()=0
virtual void release_ptr(S *&p)=0
virtual void add_scaled(const abstract_vector< T, S > &vec, S k)=0
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< elem_t > type
element type
Definition: SF_container.h:403
vector< T > con
Definition: SF_container.h:397
size_t l_numpts
local number of points
Definition: SF_container.h:386
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
const T * end() const
Pointer to the vector's end.
Definition: SF_vector.h:113
void assign(InputIterator s, InputIterator e)
Assign a memory range.
Definition: SF_vector.h:146
void reserve(size_t n)
Definition: SF_vector.h:226
const T * begin() const
Pointer to the vector's start.
Definition: SF_vector.h:101
T & push_back(T val)
Definition: SF_vector.h:268
Represents the ionic model and plug-in (IMP) data structure.
Definition: ION_IF.h:168
const IonType & get_type() const
Gets this IMP's model type.
Definition: ION_IF.cc:134
virtual void copy_SVs_from(IonIfBase &other, bool alloc)=0
Copies the state variables of an IMP.
void compute(node_index_t start, node_index_t end, GlobalData_t **data)
Perform ionic model computation for 1 time step.
Definition: ION_IF.cc:258
Target get_target() const
Definition: ION_IF.h:381
node_count_t get_num_node() const
Gets the number of nodes handled by this IMP.
Definition: ION_IF.cc:138
virtual IonIfBase * make_ion_if(Target target, node_count_t num_node, const std::vector< std::reference_wrapper< IonType >> &plugins) const =0
Generate an IonIf object from this type.
std::vector< IonIfBase * > IIF
array of IIF's
Definition: MULTI_ION_IF.h:198
opencarp::sf_vec * gdata[NUM_IMP_DATA_TYPES]
data used by all IMPs
Definition: MULTI_ION_IF.h:212
std::vector< IonTypeList > plugtypes
plugins types for each region
Definition: MULTI_ION_IF.h:211
void dump_state(char *, float, opencarp::mesh_t gid, bool, unsigned int)
GlobalData_t *** ldata
data local to each IMP
Definition: MULTI_ION_IF.h:201
int N_IIF
how many different IIF's
Definition: MULTI_ION_IF.h:207
node_count_t * N_Nodes
#nodes for each IMP
Definition: MULTI_ION_IF.h:196
node_index_t ** NodeLists
local partitioned node lists for each IMP stored
Definition: MULTI_ION_IF.h:197
int timer_idx
the timer index received from the timer manager
Definition: physics_types.h:51
FILE_SPEC logger
The logger of the physic, each physic should have one.
Definition: physics_types.h:49
const char * name
The name of the physic, each physic should have one.
Definition: physics_types.h:47
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
SF::vector< stimulus > stimuli
the electrical stimuli
parabolic_solver parab_solver
Solver for the parabolic bidomain equation.
MaterialType mtype[2]
the material types of intra_grid and extra_grid grids.
void destroy()
Currently we only need to close the file logger.
double timer_val(const int timer_id)
figure out current value of a signal linked to a given timer
sf_vec * phie_dummy
no elliptic solver needed, but we need a dummy for phie to use parabolic solver
eikonal_solver eik_solver
Solver for the eikonal equation.
LAT_detector lat
the activation time detector
gvec_data gvec
datastruct holding global IMP state variable output
generic_timing_stats IO_stats
grid_t
An electrics grid identifier to distinguish between intra and extra grids.
igb_output_manager output_manager_cycle
void initialize()
Initialize the Eikonal class.
igb_output_manager output_manager_time
class handling the igb output
limpet::MULTI_IF * miif
Definition: ionics.h:52
void compute_step()
Definition: ionics.cc:18
void initialize()
Definition: ionics.cc:43
void destroy()
Definition: ionics.cc:35
int check_quiescence(double tm, double dt)
check for quiescence
Definition: electrics.cc:1796
void output_initial_activations()
output one nodal vector of initial activation time
Definition: electrics.cc:1911
void init(sf_vec &vm, sf_vec &phie, int offset, enum physic_t=elec_phys)
initializes all datastructs after electric solver setup
Definition: electrics.cc:1605
int check_acts(double tm)
check activations at sim time tm
Definition: electrics.cc:1728
void FIM()
Standard fast iterative method to solve eikonal equation with active list approach.
void update_repolarization_times_from_rd(sf_vec &Vmv, sf_vec &Vmv_old, double time)
Updates node repolarization times based on transmembrane voltage crossing.
SF::vector< SF_real > T_R
void init_imp_region_properties()
Initializes diffusion current models and CV restitution parameters per mesh node.
SF::vector< mesh_int_t > n2e_dsp
SF::vector< SF_real > T_A
SF::vector< SF_real > TA_old
SF::vector< diffusion_current > diff_cur
void init()
Initialize vectors and variables in the eikonal_solver class.
SF::vector< mesh_int_t > e2n_con
bool determine_model_to_run(double &time)
Determine the next model to run in the alternation between RD and Eikonal.
SF::vector< mesh_int_t > stim_status
SF::vector< mesh_int_t > elem_start
SF::vector< mesh_int_t > StimulusPoints
SF::vector< SF_real > rho_cvrest
std::vector< double > CV_L
void save_eikonal_state(const char *tsav_ext)
Save the current state of variables related to the Eikonal simulation to a file to initialize a futur...
SF::vector< SF_real > denom_cvrest
void compute_diffusion_current(const double &time, sf_vec &vm)
Computes the stimulus-driven diffusion current at mesh nodes.
std::vector< mesh_int_t > n2n_connect
void set_stimuli(SF::vector< stimulus > &stimuli)
Simple setter for stimulus vector.
SF::vector< mesh_int_t > e2n_cnt
SF::vector< mesh_int_t > n2e_con
void clean_list()
Clean the list of nodes by resetting their status and tracking changes based on the time step of the ...
SF::vector< SF_real > D_I
SF::vector< mesh_int_t > nReadded2List
SF::vector< SF_real > theta_cvrest
SF::vector< mesh_int_t > num_changes
std::vector< mesh_int_t > n2n_dsp
SF::vector< SF_real > StimulusTimes
SF::vector< SF_real > kappa_cvrest
SF::vector< mesh_int_t > n2e_cnt
void cycFIM()
Implementation of the cyclical fast iterative method used in step A of the DREAM model.
void update_repolarization_times(const Ionics &ion)
Estimates initial repolarization times (T_R) in Step D of DREAM.
eikonal_solver_stats stats
std::vector< SF::dmat< double > > S
void write_data()
write registered data to disk
Definition: sim_utils.cc:2883
void close_files_and_cleanup()
close file descriptors
Definition: sim_utils.cc:2939
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:2850
sf_mat * rhs_parab
rhs matrix to solve parabolic
Definition: electrics.h:104
lin_solver_stats stats
Definition: electrics.h:114
void rebuild_matrices(MaterialType *mtype, limpet::MULTI_IF &miif, FILE_SPEC logger)
Definition: electrics.cc:1246
void solve(sf_vec &phie_i)
Definition: electrics.cc:1360
sf_mat * mass_i
lumped for parabolic problem
Definition: electrics.h:103
sf_mat * lhs_parab
lhs matrix (CN) to solve parabolic
Definition: electrics.h:105
sf_vec * Vmv
global Vm vector
Definition: electrics.h:89
sf_vec * old_vm
older Vm needed for 2nd order dT
Definition: electrics.h:95
int write_trace()
write traces to file
Definition: signals.h:686
stim_t type
type of stimulus
Definition: stimulate.h:123
int npls
number of stimulus pulses
Definition: stimulate.h:106
double pcl
pacing cycle length
Definition: stimulate.h:107
double start
start time of protocol
Definition: stimulate.h:105
sig::time_trace wave
wave form of stimulus pulse
Definition: stimulate.h:83
stim_protocol ptcl
applied stimulation protocol used
Definition: stimulate.h:154
stim_electrode electrode
electrode geometry
Definition: stimulate.h:156
stim_pulse pulse
stimulus wave form
Definition: stimulate.h:153
void translate(int id)
convert legacy definitions to new format
Definition: stimulate.cc:92
bool is_active() const
Return whether stim is active.
Definition: stimulate.cc:185
void setup(int idx)
Setup from a param stimulus index.
Definition: stimulate.cc:153
void dump_vtx_file(int idx)
Export the vertices to vtx file.
Definition: stimulate.cc:457
stim_physics phys
physics of stimulus
Definition: stimulate.h:155
std::string name
label stimulus
Definition: stimulate.h:151
double time_step
global reference time step
Definition: timer_utils.h:64
int add_eq_timer(double istart, double iend, int ntrig, double iintv, double idur, const char *iname, const char *poolname=nullptr)
Add a equidistant step timer to the array of timers.
Definition: timer_utils.cc:63
double time
current time
Definition: timer_utils.h:62
Diffusion Reaction Eikonal Alternant Model (DREAM) based on the electrics physics class.
void transpose_connectivity(const vector< T > &a_cnt, const vector< T > &a_con, vector< T > &b_cnt, vector< T > &b_con)
Transpose CRS matrix graph A into B.
double inner_prod(const Point &a, const Point &b)
Definition: SF_container.h:75
T sum(const vector< T > &vec)
Compute sum of a vector's entries.
Definition: SF_vector.h:325
void count(const vector< T > &data, vector< S > &cnt)
Count number of occurrences of indices.
Definition: SF_vector.h:317
void outer_prod(const Point &a, const Point &b, const double s, double *buff, const bool add=false)
Definition: SF_container.h:80
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:110
V clamp(const V val, const W start, const W end)
Clamp a value into an interval [start, end].
Definition: kdpart.hpp:117
void cnt_from_dsp(const std::vector< T > &dsp, std::vector< T > &cnt)
Compute counts from displacements.
Definition: kdpart.hpp:134
void dsp_from_cnt(const std::vector< T > &cnt, std::vector< T > &dsp)
Compute displacements from counts.
Definition: kdpart.hpp:125
constexpr T min(T a, T b)
Definition: ion_type.h:18
void dump_trace(MULTI_IF *MIIF, limpet::Real time)
void open_trace(MULTI_IF *MIIF, int n_traceNodes, int *traceNodes, int *label, opencarp::sf_mesh *imesh)
Set up ionic model traces at some global node numbers.
timer_manager * tm_manager
a manager for the various physics timers
Definition: main.cc:40
bool using_legacy_stimuli
flag storing whether legacy stimuli are used
Definition: main.cc:46
int stimidx_from_timeridx(const SF::vector< stimulus > &stimuli, const int timer_id)
determine link between timer and stimulus
Definition: electrics.cc:842
@ iotm_chkpt_list
Definition: timer_utils.h:29
@ iotm_console
Definition: timer_utils.h:29
@ iotm_trace
Definition: timer_utils.h:29
@ iotm_chkpt_intv
Definition: timer_utils.h:29
SF::scattering * get_scattering(const int from, const int to, const SF::SF_nbr nbr, const int dpn)
Get a scattering from the global scatter registry.
void read_el_scale_vec(const char *file, mesh_t mt, SF::vector< double > &el_scale, int &el_scale_dpn)
sf_mesh & get_mesh(const mesh_t gt)
Get a mesh by specifying the gridID.
Definition: sf_interface.cc:18
SF::scattering * register_scattering(const int from, const int to, const SF::SF_nbr nbr, const int dpn)
Register a scattering between to grids, or between algebraic and nodal representation of data on the ...
Definition: sf_interface.cc:54
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.
void region_mask(mesh_t meshspec, SF::vector< RegionSpecs > &regspec, SF::vector< int > &regionIDs, bool mask_elem, const char *reglist, bool warn_on_default_tags)
classify elements/points as belonging to a region
Definition: ionics.cc:342
SF::meshdata< mesh_int_t, mesh_real_t > sf_mesh
Definition: sf_interface.h:33
void apply_stim_to_vector(const stimulus &s, sf_vec &vec, bool add)
Definition: electrics.cc:438
int set_dir(IO_t dest)
Definition: sim_utils.cc:1615
vec3< V > cross(const vec3< V > &a, const vec3< V > &b)
Definition: vect.h:129
int get_rank(MPI_Comm comm=PETSC_COMM_WORLD)
Definition: basics.h:269
V dist(const vec3< V > &p1, const vec3< V > &p2)
Definition: vect.h:99
@ Vm_clmp
Definition: stimulate.h:64
void init_stim_info(void)
uses potential for stimulation
Definition: stimulate.cc:34
FILE_SPEC f_open(const char *fname, const char *mode)
Open a FILE_SPEC.
Definition: basics.cc:123
SF::scattering * register_permutation(const int mesh_id, const int perm_id, const int dpn)
Register a permutation between two orderings for a mesh.
@ OUTPUT
Definition: sim_utils.h:39
void init_sv_gvec(gvec_data &GVs, limpet::MULTI_IF *miif, sf_vec &tmpl, igb_output_manager &output_manager)
Definition: ionics.cc:552
void assemble_sv_gvec(gvec_data &gvecs, limpet::MULTI_IF *miif)
Definition: ionics.cc:623
char * dupstr(const char *old_str)
Definition: basics.cc:29
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
Definition: basics.cc:57
mesh_t
The enum identifying the different meshes we might want to load.
Definition: sf_interface.h:44
@ extra_elec_msh
Definition: sf_interface.h:46
@ intra_elec_msh
Definition: sf_interface.h:45
void get_time(double &tm)
Definition: basics.h:429
bool mesh_is_registered(const mesh_t gt)
check wheter a SF mesh is set
Definition: sf_interface.cc:48
SF::abstract_vector< SF_int, SF_real > sf_vec
Definition: sf_interface.h:35
int get_size(MPI_Comm comm=PETSC_COMM_WORLD)
Definition: basics.h:283
void setup_dataout(const int dataout, std::string dataout_vtx, mesh_t grid, SF::vector< mesh_int_t > *&restr, bool async, const hashmap::unordered_set< int > *output_tags)
Definition: electrics.cc:598
const char * get_tsav_ext(double time)
Definition: electrics.cc:928
V timing(V &t2, const V &t1)
Definition: basics.h:441
void f_close(FILE_SPEC &f)
Close a FILE_SPEC.
Definition: basics.cc:150
@ ElecMat
Definition: fem_types.h:24
#define PETSC_TO_CANONICAL
Permute algebraic data from PETSC to canonical ordering.
Definition: sf_interface.h:64
#define ALG_TO_NODAL
Scatter algebraic to nodal.
Definition: sf_interface.h:62
#define EXP_POSTPROCESS
Definition: sim_utils.h:192
Electrical stimulation functions.
Point and vector struct.
Definition: SF_container.h:50
double y
Definition: SF_container.h:52
double z
Definition: SF_container.h:53
double x
Definition: SF_container.h:51
description of materal properties in a mesh
Definition: fem_types.h:106
SF::vector< RegionSpecs > regions
array with region params
Definition: fem_types.h:111
SF::vector< double > el_scale
optionally provided per-element params scale
Definition: fem_types.h:112
int el_scale_dpn
0=disabled, 1=isotropic scalar, 3=anisotropic (sl, st, sn) per element
Definition: fem_types.h:113
region based variations of arbitrary material parameters
Definition: fem_types.h:78
physMaterial * material
material parameter description
Definition: fem_types.h:83
int nsubregs
#subregions forming this region
Definition: fem_types.h:81
int * subregtags
FEM tags forming this region.
Definition: fem_types.h:82
char * regname
name of region
Definition: fem_types.h:79
int regID
region ID
Definition: fem_types.h:80
double slvtime_A
total time in Step A
Definition: timers.h:48
void log_stats(double time, bool cflg)
Definition: timers.cc:133
double minAT
minimum activation time in current solve
Definition: timers.h:43
double maxAT
maximum activation time in current solve
Definition: timers.h:45
void init_logger(const char *filename)
Definition: timers.cc:117
int activeList
number of nodes currently in list
Definition: timers.h:41
void update_iter(const int curiter)
Definition: timers.cc:165
double slvtime_B
total time in Step B
Definition: timers.h:50
double slvtime_D
total time in Step D
Definition: timers.h:52
bool bc_status
boundary conditions were applied?
Definition: timers.h:56
void update_cli(double time, bool cflg)
Definition: timers.cc:171
File descriptor struct.
Definition: basics.h:120
void log_stats(double tm, bool cflg)
Definition: timers.cc:96
void init_logger(const char *filename)
Definition: timers.cc:80
int calls
# calls for this interval, this is incremented externally
Definition: timers.h:73
double tot_time
total time, this is incremented externally
Definition: timers.h:75
void log_stats(double tm, bool cflg)
Definition: timers.cc:30
const char * reasonOut
reason for list entry
SF_real T_R
repolarization time
void init_logger(const char *filename)
void log_stats(double tm, bool cflg)
SF_real D_I
diastolic interval
mesh_int_t idXNB
neighboring node index responsible for list entry
const char * reasonIn
reason for list entry
SF_real T_A_
previous activation time
SF_real T_A
current activation time
SF_real nbn_T_A
activation time of neighboring node
mesh_int_t cycle
DREAM cycle.
mesh_int_t idX
node index
void update_status(enum status s, enum reason r)