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 <algorithm>
15 #include <cstdlib>
16 #include "SF_globals.h"
17 #include "basics.h"
18 #include "backend.h"
19 #include "timers.h"
20 #include "stimulate.h"
21 
22 #include "SF_init.h"
23 
24 namespace opencarp
25 {
26 
28 {
29  if (get_size() > 1) {
30  log_msg(NULL, 5, 0, "DREAM/Eikonal physics currently do not support MPI parallelization. Use openMP instead. Aborting!");
31  EXIT(EXIT_FAILURE);
32  }
33 
34  // the per-region DREAM parameters are assigned from region_mask() alone, so a point-wise
35  // imp_region override would leave ionic model and DREAM parameters inconsistent
36  if(strlen(param_globals::imp_region_nodefile)) {
37  log_msg(0, 5, 0, "%s error: imp_region_nodefile is not supported with eikonal solvers. Aborting!",
38  __func__);
39  EXIT(1);
40  }
41 
42  double t1, t2;
43  get_time(t1);
44 
45  set_dir(OUTPUT);
46 
47  // open logger
48  logger = f_open("eikonal.log", param_globals::experiment != 4 ? "w" : "r");
49 
50  // setup mappings between extra and intra grids, algebraic and nodal,
51  // and between PETSc and canonical orderings
52  setup_mappings();
53 
54  eik_tech = static_cast<Eikonal::eikonal_t>(param_globals::dream.solve);
55 
56  // DREAM never runs a parabolic solve, so nothing consumes the output of the
57  // non-operator-splitting path.
58  if (eik_tech == DREAM && !param_globals::operator_splitting) {
59  log_msg(NULL, 5, 0,
60  "DREAM requires operator_splitting 1. Without it neither the stimulus current nor the ionic Vm update reaches Vm, "
61  "since DREAM performs no parabolic solve. Aborting!");
62  EXIT(EXIT_FAILURE);
63  }
64 
65  // the ionic physics is currently triggered from inside the Electrics to have tighter
66  // control over it. The standalone eikonal solver does not require it.
67  switch (eik_tech) {
68  case EIKONAL: break;
69  default:
70  ion.logger = logger;
71  ion.initialize();
72  }
73 
74  // set up Intracellular tissue
75  set_elec_tissue_properties(mtype, intra_grid, logger);
76  region_mask(intra_elec_msh, mtype[intra_grid].regions, mtype[intra_grid].regionIDs, true, "gregion_i", logger);
77 
78  // add electrics timer for time stepping, add to time stepper tool (TS)
79  double global_time = user_globals::tm_manager->time;
80  timer_idx = user_globals::tm_manager->add_eq_timer(global_time, param_globals::tend, 0,
81  param_globals::dt, 0, "elec::ref_dt", "TS");
82 
83  // electrics stimuli setup
84  setup_stimuli();
85 
86  // set up the linear equation systems. this needs to happen after the stimuli have been
87  // set up, since we need boundary condition info
88  setup_solvers();
89 
90  // the next setup steps require the solvers to be set up, since they use the matrices
91  // generated by those
92 
93  // initialize the LATs detector
94  switch (eik_tech) {
95  case EIKONAL: break; // not available for pure eikonal solve
96  default:
98  }
99 
100  // prepare the electrics output. we skip it if we do post-processing
101  if (param_globals::experiment != EXP_POSTPROCESS)
102  setup_output();
103 
104  this->initialize_time += timing(t2, t1);
105  log_msg(NULL, 0, 0, "All done in %f sec.", float(t2 - t1));
106 }
107 
108 void Eikonal::set_elec_tissue_properties(MaterialType* mtype, Eikonal::grid_t g, FILE_SPEC logger)
109 {
110  MaterialType* m = mtype + g;
111 
112  // initialize random conductivity fluctuation structure with PrM values
113  m->regions.resize(param_globals::num_gregions);
114 
115  const char* grid_name = g == Eikonal::intra_grid ? "intracellular" : "extracellular";
116  log_msg(logger, 0, 0, "Setting up %s tissue poperties for %d regions ..", grid_name,
117  param_globals::num_gregions);
118 
119  char buf[64];
120  RegionSpecs* reg = m->regions.data();
121 
122  for (size_t i = 0; i < m->regions.size(); i++, reg++) {
123  if (!strcmp(param_globals::gregion[i].name, "")) {
124  snprintf(buf, sizeof buf, ", gregion_%d", int(i));
125  param_globals::gregion[i].name = dupstr(buf);
126  }
127 
128  reg->regname = strdup(param_globals::gregion[i].name);
129  reg->regID = i;
130  reg->nsubregs = param_globals::gregion[i].num_IDs;
131  if (!reg->nsubregs)
132  reg->subregtags = NULL;
133  else {
134  reg->subregtags = new int[reg->nsubregs];
135 
136  for (int j = 0; j < reg->nsubregs; j++)
137  reg->subregtags[j] = param_globals::gregion[i].ID[j];
138  }
139 
140  // describe material in given region
141  elecMaterial* emat = new elecMaterial();
142  emat->material_type = ElecMat;
143 
144  emat->InVal[0] = param_globals::gregion[i].g_il;
145  emat->InVal[1] = param_globals::gregion[i].g_it;
146  emat->InVal[2] = param_globals::gregion[i].g_in;
147 
148  emat->ExVal[0] = param_globals::gregion[i].g_el;
149  emat->ExVal[1] = param_globals::gregion[i].g_et;
150  emat->ExVal[2] = param_globals::gregion[i].g_en;
151 
152  emat->BathVal[0] = param_globals::gregion[i].g_bath;
153  emat->BathVal[1] = param_globals::gregion[i].g_bath;
154  emat->BathVal[2] = param_globals::gregion[i].g_bath;
155 
156  // convert units from S/m -> mS/um
157  for (int j = 0; j < 3; j++) {
158  emat->InVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
159  emat->ExVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
160  emat->BathVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
161  }
162  reg->material = emat;
163  }
164 
165  {
167  const char* file = g == Eikonal::intra_grid ? param_globals::gi_scale_vec : param_globals::ge_scale_vec;
168  if (strlen(file))
169  read_el_scale_vec(file, mt, m->el_scale, m->el_scale_dpn);
170  }
171 }
172 
173 void Eikonal::setup_mappings()
174 {
175  bool intra_exits = mesh_is_registered(intra_elec_msh), extra_exists = mesh_is_registered(extra_elec_msh);
176  assert(intra_exits);
177  const int dpn = 1;
178 
179  // It may be that another physic (e.g. ionic models) has already computed the intracellular mappings,
180  // thus we first test their existence
181  if (get_scattering(intra_elec_msh, ALG_TO_NODAL, dpn) == NULL) {
182  log_msg(logger, 0, 0, "%s: Setting up intracellular algebraic-to-nodal scattering.", __func__);
184  }
186  log_msg(logger, 0, 0, "%s: Setting up intracellular PETSc to canonical permutation.", __func__);
188  }
189 }
190 
192 {
193  double t1, t2;
194  get_time(t1);
195 
196  switch (eik_tech) {
197  case EIKONAL: solve_EIKONAL(); break;
198  case DREAM: solve_DREAM(); break;
199  default: solve_RE(); break;
200  }
201 
203  // output lin solver stats
205  }
206  this->compute_time += timing(t2, t1);
207 
208  // since the traces have their own timing, we check for trace dumps in the compute step loop
211 }
212 
214 {
215  double t1, t2;
216  get_time(t1);
217 
218  switch (eik_tech) {
219  case EIKONAL: break;
220  default:
222  output_manager_time.write_data(); // does not exist in EIKONAL
223  }
224 
225  if (do_output_eikonal) {
227  do_output_eikonal = false;
228  }
229 
230  double curtime = timing(t2, t1);
231  this->output_time += curtime;
232 
233  IO_stats.calls++;
234  IO_stats.tot_time += curtime;
235 
238 }
239 
244 {
245  switch (eik_tech) {
246  case EIKONAL:
248  break;
249  default:
251  log_msg(NULL, 4, 0,
252  "DREAM: %lld activation times were set before the current time; "
253  "those nodes may not have depolarized.",
255  }
256  // output LAT data
260  // destroy ionics before closing the logger: the ionic interface holds an alias of it
261  ion.destroy();
262  }
263 
264  // close logger
265  f_close(logger);
266 }
267 
268 void Eikonal::setup_stimuli()
269 {
270  // initialize basic stim info data (used units, supported types, etc)
271  init_stim_info();
272 
273  stimuli.resize(param_globals::num_stim);
274  for (int i = 0; i < param_globals::num_stim; i++) {
275  // construct new stimulus
276  stimulus& s = stimuli[i];
277 
278  if (param_globals::stim[i].crct.type != 0 && param_globals::stim[i].crct.type != 9) {
279  // In the Eikonal class, only the intracellular domain is registered.
280  // Therefore, only I_tm and Vm_clmp are compatible.
281  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);
282  EXIT(EXIT_FAILURE);
283  }
284 
285  if (strlen(param_globals::stim[i].ptcl.stimlist) > 0) {
286  // translate_stim_to_eikonal() builds its stimulus table from ptcl.start,
287  // ptcl.npls and ptcl.pcl, which stim_protocol::setup() only assigns for
288  // equidistant protocols. With a stimlist those stay at their defaults and
289  // npls == 0 yields no table rows at all, while the stimulus still fires on
290  // the RD side via its timer - current injected, no activation time.
291  log_msg(NULL, 5, 0,
292  "%s error: stim[%i] defines ptcl.stimlist, which the eikonal model does not support. "
293  "Only ptcl.start, ptcl.npls and ptcl.bcl are read. Aborting!",
294  __func__, i);
295  EXIT(EXIT_FAILURE);
296  }
297 
299  s.translate(i);
300 
301  s.setup(i);
302 
303  if (s.electrode.dump_vtx)
304  s.dump_vtx_file(i);
305 
306  log_msg(NULL, 2, 0, "Only geometry, start time, npls, and bcl of stim[%i] are used", i);
307 
308  if (param_globals::stim[i].pulse.dumpTrace && get_rank() == 0) {
309  set_dir(OUTPUT);
310  s.pulse.wave.write_trace(s.name + ".trc");
311  }
312  }
313 
315 }
316 
317 void Eikonal::stimulate_intracellular()
318 {
319  parabolic_solver& ps = parab_solver;
320 
321  // iterate over stimuli
322  for (stimulus& s : stimuli) {
323  if (s.is_active()) {
324  // for active stimuli, deal with the stimuli-type specific stimulus application
325  switch (s.phys.type) {
326  case I_tm: {
327  if (param_globals::operator_splitting) {
328  apply_stim_to_vector(s, *ps.Vmv, true);
329  } else {
330  SF_real Cm = 1.0;
331  timer_manager& tm = *user_globals::tm_manager;
332  SF_real sc = tm.time_step / Cm;
333 
334  ps.Irhs->set(0.0);
335  apply_stim_to_vector(s, *ps.Irhs, true);
336 
337  *ps.tmp_i1 = *ps.IIon;
338  *ps.tmp_i1 -= *ps.Irhs;
339  *ps.tmp_i1 *= sc; // tmp_i1 = sc * (IIon - Irhs)
340 
341  // add ionic, transmembrane and intracellular currents to rhs
342  if (param_globals::parab_solve != parabolic_solver::EXPLICIT)
343  ps.mass_i->mult(*ps.tmp_i1, *ps.Irhs);
344  else
345  *ps.Irhs = *ps.tmp_i1;
346  }
347  break;
348  }
349 
350  case Illum: {
351  sf_vec* illum_vec = ion.miif->gdata[limpet::illum];
352 
353  if (illum_vec == NULL) {
354  log_msg(0, 5, 0, "Cannot apply illumination stim: global vector not present!");
355  EXIT(EXIT_FAILURE);
356  } else {
357  apply_stim_to_vector(s, *illum_vec, false);
358  }
359 
360  break;
361  }
362 
363  default: break;
364  }
365  }
366  }
367 }
368 
369 void Eikonal::clamp_Vm()
370 {
371  for (stimulus& s : stimuli) {
372  if (s.phys.type == Vm_clmp && s.is_active())
374  }
375 }
376 
377 void Eikonal::setup_output()
378 {
379  int rank = get_rank();
380  SF::vector<mesh_int_t>* restr_i = NULL;
381  SF::vector<mesh_int_t>* restr_e = NULL;
382  set_dir(OUTPUT);
383 
384  setup_dataout(param_globals::dataout_i, param_globals::dataout_i_vtx, intra_elec_msh,
385  restr_i, param_globals::num_io_nodes > 0);
386 
387  if (param_globals::dataout_i) {
388  switch (eik_tech) {
389  case EIKONAL:
390  output_manager_cycle.register_output(eik_solver.AT, intra_elec_msh, 1, param_globals::dream.output.atfile, "ms", restr_i);
391  break;
392  case DREAM:
393  output_manager_time.register_output(parab_solver.Vmv, intra_elec_msh, 1, param_globals::vofile, "mV", restr_i);
394  output_manager_cycle.register_output(eik_solver.AT, intra_elec_msh, 1, param_globals::dream.output.atfile, "ms", restr_i);
395  output_manager_cycle.register_output(eik_solver.RT, intra_elec_msh, 1, param_globals::dream.output.rtfile, "ms", restr_i);
396  if (strcmp(param_globals::dream.output.idifffile, "") != 0) {
397  output_manager_time.register_output(eik_solver.Idiff, intra_elec_msh, 1, param_globals::dream.output.idifffile, "muA/cm2", restr_i);
398  }
399  break;
400  default:
401  output_manager_time.register_output(parab_solver.Vmv, intra_elec_msh, 1, param_globals::vofile, "mV", restr_i);
402  output_manager_cycle.register_output(eik_solver.AT, intra_elec_msh, 1, param_globals::dream.output.atfile, "ms", restr_i);
403  if (strcmp(param_globals::dream.output.idifffile, "") != 0) {
404  output_manager_time.register_output(eik_solver.Idiff, intra_elec_msh, 1, param_globals::dream.output.idifffile, "muA/cm2", restr_i);
405  }
406  }
407  }
408 
410 
411  if (param_globals::num_trace) {
412  sf_mesh& imesh = get_mesh(intra_elec_msh);
413  open_trace(ion.miif, param_globals::num_trace, param_globals::trace_node, NULL, &imesh);
414  }
415 
416  // initialize generic logger for IO timings per time_dt
417  IO_stats.init_logger("IO_stats.dat");
418 }
419 
420 void Eikonal::dump_matrices()
421 {
422  std::string bsname = param_globals::dump_basename;
423  std::string fn;
424 
425  set_dir(OUTPUT);
426 
427  // dump monodomain matrices
428  if (param_globals::parab_solve == 1) {
429  // using Crank-Nicolson
430  fn = bsname + "_Ki_CN.bin";
431  parab_solver.lhs_parab->write(fn.c_str());
432  }
433  fn = bsname + "_Ki.bin";
434  parab_solver.rhs_parab->write(fn.c_str());
435 
436  fn = bsname + "_Mi.bin";
437  parab_solver.mass_i->write(fn.c_str());
438 }
439 
442 double Eikonal::timer_val(const int timer_id)
443 {
444  // determine
445  int sidx = stimidx_from_timeridx(stimuli, timer_id);
446  double val = 0.0;
447  if (sidx != -1) {
448  stimuli[sidx].value(val);
449  } else
450  val = std::nan("NaN");
451 
452  return val;
453 }
454 
457 std::string Eikonal::timer_unit(const int timer_id)
458 {
459  int sidx = stimidx_from_timeridx(stimuli, timer_id);
460  std::string s_unit;
461 
462  if (sidx != -1)
463  // found a timer-linked stimulus
464  s_unit = stimuli[sidx].pulse.wave.f_unit;
465 
466  return s_unit;
467 }
468 
469 void Eikonal::setup_solvers()
470 {
471  set_dir(OUTPUT);
472 
473  switch (eik_tech) {
474  case EIKONAL:
475  eik_solver.init();
476  break;
477  default:
478  parab_solver.init();
480  eik_solver.init();
482  if (param_globals::dump2MatLab) dump_matrices();
483  }
484 }
485 
486 void Eikonal::checkpointing()
487 {
488  const timer_manager& tm = *user_globals::tm_manager;
489 
490  // regular user selected state save
491  if (tm.trigger(iotm_chkpt_list)) {
492  char save_fnm[1024];
493  const char* tsav_ext = get_tsav_ext(tm.time);
494 
495  snprintf(save_fnm, sizeof save_fnm, "%s.%s.roe", param_globals::write_statef, tsav_ext);
496 
497  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
498  eik_solver.save_eikonal_state(save_fnm);
499  }
500 
501  // checkpointing based on interval
502  if (tm.trigger(iotm_chkpt_intv)) {
503  char save_fnm[1024];
504  snprintf(save_fnm, sizeof save_fnm, "checkpoint.%.1f.roe", tm.time);
505  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
506  eik_solver.save_eikonal_state(save_fnm);
507  }
508 }
509 
510 void Eikonal::solve_EIKONAL()
511 {
512  if (user_globals::tm_manager->time == 0) {
513  eik_solver.FIM();
516  do_output_eikonal = true;
517  }
518 }
519 
520 void Eikonal::solve_RE()
521 {
522  if (user_globals::tm_manager->time == 0) {
523  eik_solver.FIM();
526  do_output_eikonal = true;
527  }
528  solve_RD();
529 }
530 
531 void Eikonal::solve_DREAM()
532 {
534  solve_RD();
535  } else {
536  // Simulation time is frozen for the whole loop, so the only way out is the
537  // eikonal state itself changing. Count cycles that leave it untouched.
538  int stalled_cycles = 0;
539 
540  // Backstop for a state that keeps changing without ever satisfying the exit condition: the
541  // progress test below compares against the previous cycle only, so a state alternating
542  // between two configurations resets it forever. Legitimate runs tested needed one or two cycles.
543  int cycles = 0;
544  const int cycle_cap = 2 * param_globals::dream.fim.max_iter;
545 
547  const mesh_int_t active_before = eik_solver.num_active_nodes;
548  const SF_real actmin_before = eik_solver.actMIN;
549  const size_t stim_before = eik_solver.Index_currStim;
550 
551  if (user_globals::tm_manager->time != 0) {
553  }
554 
555  eik_solver.cycFIM(this->ion);
557 
561 
562  // should_solve_reaction_diffusion() decides on these three alone, so a cycle
563  // that leaves all of them untouched reaches the same decision again. Tolerate
564  // a few (for now set to 5): cycFIM can refine individual activation times without shifting
565  // actMIN, which is real progress this check cannot see.
566  const bool made_progress = eik_solver.num_active_nodes != active_before ||
567  eik_solver.Index_currStim != stim_before ||
568  !(eik_solver.actMIN == actmin_before);
569 
570  stalled_cycles = made_progress ? 0 : stalled_cycles + 1;
571  cycles++;
572 
573  const bool stalled = stalled_cycles >= 5;
574  const bool at_cap = cycles >= cycle_cap;
575 
576  if (stalled || at_cap) {
579  log_msg(NULL, 4, 0,
580  "%s warning: the eikonal solver %s at t=%.2f ms "
581  "(actMIN %.2f, %lld active nodes, stimulus index %zu). Advancing time instead of "
582  "repeating the cycle. Results from here on may be unreliable.",
583  __func__,
584  stalled ? "made no progress over 5 cycles" : "did not settle within its cycle limit",
586  eik_solver.actMIN, static_cast<long long>(eik_solver.num_active_nodes),
588  }
589  break;
590  }
591  }
592  solve_RD();
593  }
594 }
595 
596 void Eikonal::solve_RD()
597 {
598  // if requested, we checkpoint the current state
599  checkpointing();
600 
601  // activation checking
602  const double time = user_globals::tm_manager->time,
603  time_step = user_globals::tm_manager->time_step;
604 
605  lat.check_acts(time);
606  lat.check_quiescence(time, time_step);
607 
608  if (eik_tech == DREAM) {
609  stimulate_intracellular();
610  }
611  clamp_Vm();
612 
613  *parab_solver.old_vm = *parab_solver.Vmv; // needed in step D of DREAM
614 
615  // compute ionics update
616  ion.compute_step();
617 
618  // Compute the I diff current
619  *eik_solver.Idiff *= 0;
621 
622  // A node captured by its own stimulus is excited by the stimulus current: no Idiff from the
623  // onset until 5 ms (Idiff's window) after its T_A. Other stimulated nodes keep Idiff.
624  if (eik_tech == DREAM) {
625  const sf_mesh& mesh = get_mesh(intra_elec_msh);
626  const int rank = get_rank();
627  SF_real* idiff = eik_solver.Idiff->ptr();
628  for (stimulus& s : stimuli) {
629  if (s.phys.type != I_tm) continue;
630  for (size_t i = 0; i < s.electrode.vertices.size(); i++) {
631  mesh_int_t node = s.electrode.vertices[i];
632  if (time < eik_solver.captured_onset[node] || time > eik_solver.captured_TA[node] + 5.0) continue;
633  mesh_int_t pidx = local_nodal_to_local_petsc(mesh, rank, node);
634  if (pidx >= 0) idiff[pidx] = 0.0;
635  }
636  }
637  eik_solver.Idiff->release_ptr(idiff);
638  }
639 
641 
642  if (eik_tech == REp) {
644  }
645 
646  switch (eik_tech) {
648  default: break;
649  }
650 
651  clamp_Vm();
652 }
653 
655 {
656  if (param_globals::output_level > 1) log_msg(0, 0, 0, "\n *** Initializing Eikonal Solver ***\n");
657  stats.init_logger("eik_stats.dat", param_globals::dream.solve == Eikonal::DREAM);
658 
659  // A captured node must cross repol_time_thresh on its way back, or it never gets a T_R.
660  if (param_globals::dream.solve == Eikonal::DREAM &&
661  param_globals::dream.depol_time_thresh < param_globals::dream.repol_time_thresh) {
662  log_msg(NULL, 5, 0, "%s error: dream.depol_time_thresh (%g mV) must not be below dream.repol_time_thresh (%g mV). Aborting!",
663  __func__, param_globals::dream.depol_time_thresh, param_globals::dream.repol_time_thresh);
664  EXIT(EXIT_FAILURE);
665  }
666 
667  if (param_globals::dream.output.debugNode >= 0) {
668  nodeData.idX = param_globals::dream.output.debugNode;
669  char buf[256];
670  snprintf(buf, sizeof buf, "node_%lld.dat", static_cast<long long>(nodeData.idX));
671  nodeData.init_logger(buf);
672  }
673 
674  // currently only used for output
675  const sf_mesh& mesh = get_mesh(intra_elec_msh);
676  twoFib = mesh.she.size() > 0;
680 
681  num_pts = mesh.l_numpts;
682 
683  e2n_con = mesh.con; // Connectivity vector with nodes that belong to each element
684  // The 4 nodes from index 4j to 4j+3 belong to the same element for 0<=j<num elements
685  elem_start = mesh.dsp; // For the i_th element elem_start[j] stores its starting position in the "connect" vector
686 
690 
691  List.assign(num_pts, 0); // List of active nodes
692  T_A.assign(num_pts, inf); // Activation times
693  D_I.assign(num_pts, 0); // Diastolic Intervals
694  T_R.assign(num_pts, -400); // Recovery times
695  TA_old.assign(num_pts, inf); // Activation Time is the previous cycle
696  num_changes.assign(num_pts, 0); // Number of Times entered in the List per current LAT
697  nReadded2List.assign(num_pts, 0); // Number of Times entered in the List per current LAT
698  stim_status.assign(num_pts, StimStatus::None); // Status of nodes
699  stim_strength.assign(num_pts, 0); // strength of applied stim (only for stim_status[node] = StimStatus::Failed)
700  stim_duration.assign(num_pts, 0); // duration of applied stim (only for stim_status[node] = StimStatus::Failed)
701  stim_start.assign(num_pts, 0); // start of applied stim (only for stim_status[node] = StimStatus::Failed)
702  stim_failed_now.assign(num_pts, false); // reset per compute_bc() call, not per simulation
703  failed_stim_time.assign(num_pts, -inf); // time of the earliest failed stimulus still ahead of the clock
704  T_R_before_failed_stim.assign(num_pts, -400); // T_R before that stimulus rewrote it
705  capture_candidate.assign(num_pts, -1); // per node: index into the stimulus rows whose capture the current compute_bc() call predicts (-1: none)
706  last_noncapturing_stim.assign(num_pts, -inf); // onset of the last stimulus pulse that did not capture the node (-inf: none)
707  last_noncapturing_row.assign(num_pts, NO_PULSE); // and its stimulus table row
708  rejected_TA.assign(num_pts, -inf); // T_A that reject_non_firing_activations() turned down, with the RD time it happened at:
709  rejected_at.assign(num_pts, -inf); // the same cell cannot change its verdict within one RD step, so that T_A is not proposed again
710  captured_onset.assign(num_pts, -inf); // onset and T_A of the stimulus pulse that last captured the node (-inf: none);
711  captured_TA.assign(num_pts, -inf); // Idiff is suppressed there from the onset to T_A + 5 ms (solve_RD)
712 
713  switch (mesh.type[0]) {
714  case 0:
715  MESH_SIZE = 4;
716  break;
717 
718  case 6:
719  MESH_SIZE = 3;
720  break;
721 
722  case 7:
723  MESH_SIZE = 2;
724  break;
725 
726  default:
727  log_msg(0, 5, 0, "Error: Type of element is not compatible with this version of the eikonal model. Use tetrahedra or triangles");
728  EXIT(EXIT_FAILURE);
729  break;
730  }
731 
732  // Header of the detailed debugger.
733  detailed_debug_enabled = (param_globals::dream.output.detailed_debugNode >= 0);
735  const int idx = param_globals::dream.output.detailed_debugNode;
736  char filename[64];
737  snprintf(filename, sizeof filename, "node_%d_debug_details.txt", idx);
738 
739  // Write header
741  if (deepDebugLogger) {
742  FILE* fp = deepDebugLogger->fd;
743  fprintf(fp, "=============================================================\n");
744  fprintf(fp, " DETAILED DEBUG LOG FOR NODE %d\n", idx);
745  fprintf(fp, "=============================================================\n");
746  fprintf(fp, "This file contains high-detail logging for a specific node\n");
747  fprintf(fp, "during simulation. It includes activation/recovery times,\n");
748  fprintf(fp, "list entries, and convergence behavior.\n");
749  fprintf(fp, "Coordinates (X, Y, Z): (%7.3f,%7.3f,%7.3f)\n\n", mesh.xyz[3 * idx + 0], mesh.xyz[3 * idx + 1], mesh.xyz[3 * idx + 2]);
750  fprintf(fp, "Belongs to the following elements:\n\n");
751 
752  int count = 0;
753 
754  for (int e_i = n2e_dsp[idx]; e_i < n2e_dsp[idx + 1]; ++e_i) {
755  int Elem_i = n2e_con[e_i];
756  mesh_int_t indEle = elem_start[Elem_i];
757 
758  if (MESH_SIZE == 4) {
759  fprintf(fp, "Tetrahedron %d: [%d, %d, %d, %d]\n", count,
760  e2n_con[indEle],
761  e2n_con[indEle + 1],
762  e2n_con[indEle + 2],
763  e2n_con[indEle + 3]);
764  } else {
765  fprintf(fp, "Triangle %d: [%d, %d, %d]\n", count,
766  e2n_con[indEle],
767  e2n_con[indEle + 1],
768  e2n_con[indEle + 2]);
769  }
770 
771  ++count;
772  }
773 
774  fflush(fp);
775  }
776  }
777 
778  if (strlen(param_globals::start_statef) > 0) load_state_file();
779 
780  create_node_to_node_graph();
781 
782  translate_stim_to_eikonal();
783 
784  precompute_squared_anisotropy_metric();
785 }
786 
788 {
789  double t1, t2;
790  get_time(t1);
791 
792  const sf_mesh& mesh = get_mesh(intra_elec_msh);
793 
794  diff_cur.resize(mesh.l_numpts);
795  rho_cvrest.resize(mesh.l_numpts);
799 
800  // --- Precompute resolved region IDs for each point ---
801  // Use the same region delegation as the ionics class
802  SF::vector<int> regionIDs;
803  SF::vector<RegionSpecs> rs(param_globals::num_imp_regions);
804  for (size_t i = 0; i < rs.size(); i++) {
805  rs[i].nsubregs = param_globals::imp_region[i].num_IDs;
806  rs[i].subregtags = param_globals::imp_region[i].ID;
807  }
808  if (rs.size() == 1) {
809  regionIDs.assign(mesh.l_numpts, 0);
810  } else {
811  region_mask(intra_elec_msh, rs, regionIDs, false, "imp_regions", logger);
812  dump_region_mask(intra_elec_msh, regionIDs, "imp_regions");
813  }
814 
815  // --- Parallel initialization, one write per vertex ---
816  // region_mask returns the IDs in algebraic (PETSc) order, the per-vertex arrays are nodal
817  const SF::vector<mesh_int_t>& alg_nod = mesh.pl.algebraic_nodes();
818 #pragma omp parallel for schedule(dynamic)
819  for (size_t i = 0; i < alg_nod.size(); i++) {
820  mesh_int_t v = alg_nod[i];
821  int reg = regionIDs[i];
822 
823  const auto& region_diff = param_globals::imp_region[reg].dream.Idiff;
824  const auto& region_rest = param_globals::imp_region[reg].dream.CVrest;
825 
826  auto model = static_cast<eikonal_solver::Idiff_t>(region_diff.model);
827  diff_cur[v].model = model;
828 
829  if (model == GAUSS) {
830  diff_cur[v].alpha_1 = region_diff.alpha_i[0];
831  diff_cur[v].alpha_2 = region_diff.alpha_i[1];
832  diff_cur[v].alpha_3 = region_diff.alpha_i[2];
833  diff_cur[v].beta_1 = region_diff.beta_i[0];
834  diff_cur[v].beta_2 = region_diff.beta_i[1];
835  diff_cur[v].beta_3 = region_diff.beta_i[2];
836  diff_cur[v].gamma_1 = region_diff.gamma_i[0];
837  diff_cur[v].gamma_2 = region_diff.gamma_i[1];
838  diff_cur[v].gamma_3 = region_diff.gamma_i[2];
839  } else {
840  diff_cur[v].A_F = region_diff.A_F;
841  diff_cur[v].tau_F = region_diff.tau_F;
842  diff_cur[v].V_th = region_diff.V_th;
843  }
844 
845  rho_cvrest[v] = region_rest.rho;
846  kappa_cvrest[v] = region_rest.kappa;
847  theta_cvrest[v] = region_rest.theta;
848  denom_cvrest[v] = log(region_rest.rho) / region_rest.psi;
849  }
850  if (param_globals::output_level) log_msg(NULL, 0, 0, "Diffusion current and CV restitution initialized in %f sec.", timing(t2, t1));
851 }
852 
853 void eikonal_solver::translate_stim_to_eikonal()
854 {
855  double t1, t2;
856  get_time(t1);
857  Index_currStim = 0;
858 
859  // Collect all pulses as (start_time, stimulus, original stimulus index)
860  std::vector<std::tuple<SF_real, const stimulus*, int>> stim_events;
861 
862  stim_events.reserve(param_globals::num_stim * 8); // rough guess
863 
864  for (int stim_idx = 0; stim_idx < stimuliRef->size(); ++stim_idx) {
865  const stimulus& s = (*stimuliRef)[stim_idx];
866  for (int idx_pls = 0; idx_pls < s.ptcl.npls; ++idx_pls) {
867  SF_real start_time = s.ptcl.start + s.ptcl.pcl * idx_pls;
868  stim_events.emplace_back(start_time, &s, stim_idx);
869  }
870  }
871 
872  // Sort events by start_time
873  std::sort(stim_events.begin(), stim_events.end(),
874  [](const auto& a, const auto& b) { return std::get<0>(a) < std::get<0>(b); });
875 
876  // A stimulus captures a node only if its recovery time says so, and only the reaction-diffusion
877  // step updates recovery times. Since tau_inc caps how far a cycle runs before that step, a tau_inc
878  // above the gap between two stimuli can judge the later one on times from before the earlier one.
879  if (static_cast<Eikonal::eikonal_t>(param_globals::dream.solve) == Eikonal::DREAM) {
880  SF_real shortest_interval = inf;
881  for (size_t i = 1; i < stim_events.size(); i++) {
882  const SF_real interval = std::get<0>(stim_events[i]) - std::get<0>(stim_events[i - 1]);
883  if (interval > 0.0 && interval < shortest_interval) shortest_interval = interval;
884  }
885  if (std::isfinite(shortest_interval) && param_globals::dream.tau_inc >= shortest_interval) {
886  log_msg(NULL, 4, 0,
887  "%s warning: dream.tau_inc is %.2f ms, which is not shorter than the %.2f ms between "
888  "the closest two stimuli. One eikonal cycle can then run past a whole stimulus "
889  "interval before the reaction-diffusion step refreshes how far the cells have "
890  "recovered, so a stimulus can be judged refractory and capture nothing. therefore, "
891  "keep dream.tau_inc well below %.2f ms. Half that gap is a safe choice.",
892  __func__, param_globals::dream.tau_inc, shortest_interval, shortest_interval);
893  }
894  }
895 
896  // Reserve enough space for output
897  size_t total_nodes = 0;
898  for (auto& ev : stim_events)
899  total_nodes += (*std::get<1>(ev)).electrode.vertices.size();
900  StimulusPoints.resize(total_nodes, -1);
901  StimulusTimes.resize(total_nodes, -1);
902  StimulusDurations.resize(total_nodes, -1);
903  StimulusStrengths.resize(total_nodes, -1);
904  StimulusOrigIndex.resize(total_nodes, -1);
905 
906  // Fill outputs
907  size_t count = 0;
908  for (auto& ev : stim_events) {
909  const stimulus& s = *std::get<1>(ev);
910  const int stim_idx = std::get<2>(ev);
911  for (mesh_int_t v : s.electrode.vertices) {
912  StimulusPoints[count] = v;
913  StimulusTimes[count] = std::get<0>(ev);
914  StimulusStrengths[count] = s.pulse.strength;
915  StimulusDurations[count] = s.pulse.duration;
916  StimulusOrigIndex[count] = stim_idx;
917  ++count;
918  }
919  }
920 
921  // On a restart, the stim protocol before the checkpoint must not be replayed.
922  if (loaded_save_time >= 0) {
923  while (Index_currStim < StimulusTimes.size() &&
924  // Strict <: a stimulus exactly at the save time has not been applied yet.
926  ++Index_currStim;
927 
928  if (param_globals::output_level) {
929  size_t skipped_events = 0;
930  for (const auto& ev : stim_events)
931  if (std::get<0>(ev) < loaded_save_time) ++skipped_events;
932 
934  log_msg(NULL, 0, 0, "Next stimulus at t = %.2f ms; %zu stimulus event(s) scheduled before the save time %.2f ms were skipped",
935  StimulusTimes[Index_currStim], skipped_events, loaded_save_time);
936  else
937  log_msg(NULL, 0, 0, "No stimulus scheduled at or after the save time %.2f ms; %zu event(s) before it were skipped",
938  loaded_save_time, skipped_events);
939  }
940  }
941 
942  // One warning slot per logical stimulus, for the pulse.strength==0 failed-capture warning
943  warned_failed_capture.assign(stimuliRef->size(), false);
944  warned_zero_strength.assign(stimuliRef->size(), false);
945 
946  // Mark every node that is a designated stimulus target anywhere in the table,
947  // so compute_bc can cheaply recognize one among a just-activated node's
948  // neighbors without rescanning the whole table.
949  is_stimulus_target.assign(num_pts, false);
950  for (mesh_int_t v : StimulusPoints) {
951  if (v >= 0) is_stimulus_target[v] = true;
952  }
953 }
954 
955 void eikonal_solver::create_node_to_node_graph()
956 {
957  double t1, t2;
958  get_time(t1);
959 
960  n2n_dsp.resize(num_pts + 1, 0);
961  const sf_mesh& mesh = get_mesh(intra_elec_msh);
962 
963  // Thread-local storage for neighbors
964  std::vector<std::vector<mesh_int_t>> thread_neighbors(num_pts);
965 
966 // Preallocate thread-local marker arrays for O(n) duplicate removal
967 #pragma omp parallel
968  {
969  std::vector<char> mark(num_pts, 0); // one per thread
970 
971 #pragma omp for schedule(dynamic)
972  for (int point_idx = 0; point_idx < num_pts; point_idx++) {
973  int numNBElem = n2e_dsp[point_idx + 1] - n2e_dsp[point_idx];
974  std::vector<mesh_int_t> neighbors;
975  neighbors.reserve(numNBElem * MESH_SIZE); // rough estimate
976 
977  // Loop over all elements containing this node
978  for (int eedsp = 0; eedsp < numNBElem; eedsp++) {
979  int currElem = n2e_con[n2e_dsp[point_idx] + eedsp];
980 
981  // Loop over all nodes of the current element
982  for (int nndsp = 0; nndsp < MESH_SIZE; nndsp++) {
983  int nb = e2n_con[elem_start[currElem] + nndsp];
984 
985  if (nb == point_idx) continue; // skip self
986  if (!mark[nb]) {
987  mark[nb] = 1;
988  neighbors.push_back(nb);
989  }
990  }
991  }
992 
993  // Reset marks for the next iteration
994  for (int nb : neighbors) mark[nb] = 0;
995 
996  // Move neighbor list into the final container
997  thread_neighbors[point_idx] = std::move(neighbors);
998  }
999  }
1000 
1001  // Build prefix sums (serial, cheap compared to above)
1002  for (int i = 0; i < num_pts; i++) {
1003  n2n_dsp[i + 1] = n2n_dsp[i] + thread_neighbors[i].size();
1004  }
1005 
1006  // Allocate once, then fill in parallel
1007  n2n_connect.resize(n2n_dsp[num_pts]);
1008 
1009 #pragma omp parallel for schedule(static)
1010  for (int i = 0; i < num_pts; i++) {
1011  std::copy(thread_neighbors[i].begin(),
1012  thread_neighbors[i].end(),
1013  n2n_connect.begin() + n2n_dsp[i]);
1014  }
1015 
1016  if (param_globals::output_level) {
1017  log_msg(NULL, 0, 0, "Node-to-node graph done in %f sec.", timing(t2, t1));
1018  }
1019 }
1020 
1021 void eikonal_solver::precompute_squared_anisotropy_metric()
1022 {
1023  double t1, t2;
1024  get_time(t1);
1025 
1026  const sf_mesh& mesh = get_mesh(intra_elec_msh);
1027 
1028  S.resize(mesh.l_numelem); // store anisotropy matrices (dimensionless)
1029  CV_L.resize(mesh.l_numelem); // store CV_L per element for later use
1030 
1031  // temporary variables
1032  SF::dmat<double> I(3, 3);
1033  I.assign(0.0);
1034  I.diag(1.0);
1035 
1036 #pragma omp parallel
1037  {
1038  SF::dmat<double> Saniso(3, 3);
1039  SF::dmat<double> Ff(3, 3);
1040  SF::dmat<double> diff(3, 3);
1041  SF::Point f, s, n;
1042 
1043 #pragma omp for schedule(static)
1044  for (int eidx = 0; eidx < mesh.l_numelem; eidx++) {
1045  double vl = 0.0, vt = 0.0, vn = 0.0;
1046 
1047  // Find region match (break early when found)
1048  for (int g = 0; g < param_globals::num_gregions; g++) {
1049  const auto& reg = param_globals::gregion[g];
1050  const auto& dream = reg.dream;
1051  for (int j = 0; j < reg.num_IDs; j++) {
1052  if (mesh.tag[eidx] == reg.ID[j]) {
1053  vl = dream.vel_l;
1054  vt = dream.vel_t;
1055  vn = dream.vel_n;
1056  goto region_found; // break out of both loops
1057  }
1058  }
1059  }
1060  region_found:;
1061 
1062  // Store CV_L directly (for later rescaling)
1063  CV_L[eidx] = vl;
1064 
1065  // Compute anisotropy ratios relative to CV_L
1066  double AR_T2 = (vl / vt) * (vl / vt);
1067  double AR_N2 = (vl / vn) * (vl / vn);
1068 
1069  f.x = mesh.fib[3 * eidx + 0];
1070  f.y = mesh.fib[3 * eidx + 1];
1071  f.z = mesh.fib[3 * eidx + 2];
1072 
1073  if (twoFib) {
1074  s.x = mesh.she[3 * eidx + 0];
1075  s.y = mesh.she[3 * eidx + 1];
1076  s.z = mesh.she[3 * eidx + 2];
1077  n = cross(f, s);
1078 
1079  SF::outer_prod(f, f, 1.0, Saniso[0], false);
1080  SF::outer_prod(s, s, AR_T2, Saniso[0], true);
1081  SF::outer_prod(n, n, AR_N2, Saniso[0], true);
1082  } else {
1083  SF::outer_prod(f, f, 1.0, Ff[0], false);
1084  diff = I - Ff;
1085  diff *= AR_T2;
1086 
1087  Saniso = Ff + diff;
1088  }
1089 
1090  S[eidx] = Saniso;
1091  }
1092  }
1093 
1094  if (param_globals::output_level)
1095  log_msg(NULL, 0, 0, "Anisotropy tensors precomputed in %f sec.", timing(t2, t1));
1096 }
1097 
1099 {
1100  double t0, t1;
1101  get_time(t0);
1102 
1103  // --- 0) Reset all activation times to infinity
1104  std::fill(T_A.begin(), T_A.end(), inf);
1105 
1106  // --- 1) Build initial active list = neighbors of stimuli
1107  std::vector<mesh_int_t> activeList;
1108  activeList.reserve(num_pts / 10); // heuristic reserve to avoid frequent reallocs
1109  std::vector<char> in_active(num_pts, 0);
1110 
1111  // Mark stimuli
1112  for (size_t si = 0; si < StimulusTimes.size(); ++si) {
1113  mesh_int_t s = StimulusPoints[si];
1114  T_A[s] = StimulusTimes[si];
1115  }
1116  // Seed neighbors; separate loop to avoid adding stim nodes into the list if they are a neighbor
1117  for (size_t si = 0; si < StimulusTimes.size(); ++si) {
1118  mesh_int_t s = StimulusPoints[si];
1119  for (int off = n2n_dsp[s]; off < n2n_dsp[s + 1]; ++off) {
1120  mesh_int_t nb = n2n_connect[off];
1121  if (T_A[nb] == inf) {
1122  add_to_active(activeList, in_active, nb);
1123  }
1124  }
1125  }
1126 
1127  // --- 2) Iterative solve of activeList
1128  int niter = 0;
1129  while (!activeList.empty() && niter <= param_globals::dream.fim.max_iter) {
1130  const std::vector<mesh_int_t> activeVec = std::move(activeList);
1131  activeList.clear();
1132 
1133 #pragma omp parallel
1134  {
1135  std::vector<mesh_int_t> local_active;
1136  local_active.reserve(64); // small local buffer
1137 
1138 #pragma omp for schedule(dynamic)
1139  for (size_t i = 0; i < activeVec.size(); ++i) {
1140  mesh_int_t id = activeVec[i];
1141  remove_from_active(in_active, id);
1142 
1143  SF_real p = T_A[id];
1144  SF_real q = update(id);
1145 
1146 #pragma omp atomic write
1147  T_A[id] = q;
1148 
1149  if (std::fabs(p - q) < param_globals::dream.fim.tol) {
1150  for (int off = n2n_dsp[id]; off < n2n_dsp[id + 1]; ++off) {
1151  mesh_int_t nb = n2n_connect[off];
1152  p = T_A[nb];
1153  q = update(nb);
1154  if (p > q) {
1155 #pragma omp atomic write
1156  T_A[nb] = q;
1157  local_active.push_back(nb);
1158  }
1159  }
1160  } else {
1161  local_active.push_back(id); // non-converged -> add back
1162  }
1163  }
1164 
1165 // Merge local results
1166 #pragma omp critical
1167  {
1168  for (mesh_int_t nb : local_active) {
1169  add_to_active(activeList, in_active, nb);
1170  }
1171  }
1172  }
1173  ++niter;
1174  }
1175 
1176  // collect iteration stats
1177  stats.update_iter(niter);
1178  auto [minIt, maxIt] = std::minmax_element(T_A.begin(), T_A.end());
1179  actMIN = *minIt;
1180  actMAX = *maxIt;
1181 
1182  // --- 3) Copy into AT for output; AT is in PETSc order, T_A in nodal order
1183  const SF::vector<mesh_int_t>& alg_nod = get_mesh(intra_elec_msh).pl.algebraic_nodes();
1184  double* atc = AT->ptr();
1185 #pragma omp parallel for
1186  for (size_t i = 0; i < alg_nod.size(); ++i) {
1187  SF_real ta = T_A[alg_nod[i]];
1188  atc[i] = (ta == inf ? -1.0 : ta);
1189  }
1190  AT->release_ptr(atc);
1191 
1192  // --- 4) Timing & list‐size stats
1193  auto dur = timing(t1, t0);
1194  stats.slvtime_A += dur;
1195  stats.minAT = actMIN;
1196  // In FIM() there is no incremental time horizon to report (unlike cycFIM()'s maxadvance),
1197  // so maxAD here is repurposed to report the actual latest activation time reached (== inf
1198  // if some node in the mesh never activated).
1199  stats.maxAD = actMAX;
1200  stats.activeList = activeList.size();
1201  stats.bc_status = true;
1203 }
1204 
1206 {
1207  assert(num_active_nodes == sum(List));
1208 
1209  int niter = 0;
1210  double t1, t0;
1211  get_time(t0);
1212 
1213  if (num_active_nodes == 0) {
1214  size_t Index_currStim_old = Index_currStim;
1215  compute_bc(ion, true, 0);
1216  if (Index_currStim_old < Index_currStim) {
1217  actMIN = StimulusTimes[Index_currStim_old];
1218  actMAX = StimulusTimes[Index_currStim_old];
1220  } else {
1221  actMIN = std::numeric_limits<double>::quiet_NaN();
1222  actMAX = std::numeric_limits<double>::quiet_NaN();
1223  }
1224  }
1225 
1226  double time2stop_eikonal = param_globals::dream.tau_inc;
1227  maxadvance = user_globals::tm_manager->time + param_globals::dream.tau_s + param_globals::dream.tau_inc + param_globals::dream.tau_max;
1228 
1229  int stalled_iterations = 0; // consecutive list iterations that did not advance actMIN
1230 
1231  std::vector<mesh_int_t> freshlyConverged;
1232 
1233  do {
1234  freshlyConverged.clear();
1235 
1237  size_t Index_currStim_old = Index_currStim;
1238  // Use actMAX (current wavefront leading edge) as upper bound, not maxadvance.
1239  // Prevents premature evaluation of future stimuli before the wavefront reaches them.
1240  compute_bc(ion, false, actMAX);
1241  if (Index_currStim_old < Index_currStim && !stim_failed_nodes.empty()) {
1243  }
1244  }
1245 
1246  for (mesh_int_t indX = 0; indX < List.size(); indX++) {
1247  SF_real p = T_A[indX];
1248  SF_real q;
1249 
1250  if (List[indX] == 0) continue;
1251 
1252  // Full FIM iteration: use all available neighbor data (active + converged).
1253  // A post-sweep verification step with convergedOnly=true will catch any
1254  // premature convergences before they propagate to neighbors.
1255  q = compute_coherence(indX);
1256 
1257  // If compute_coherence returns infinity, this node cannot be updated
1258  // (e.g., all neighbors invalid). Remove it from active list and skip.
1259  if (!std::isfinite(q)) {
1260  clear_active(indX);
1262  continue;
1263  }
1264 
1265  T_A[indX] = q;
1266  record_D_I(indX);
1267  check_past_activation(indX);
1268  num_changes[indX] = num_changes[indX] + 1;
1269 
1270  deep_debug_log(DebugCase::ListIter, indX, indX);
1271 
1272  if (q > maxadvance) continue;
1273 
1274  if (abs(p - q) < param_globals::dream.fim.tol || (num_changes[indX] > param_globals::dream.fim.max_iter) || (q == inf || p == inf)) {
1275  // Move neighbor activation to post-sweep verification.
1276  // This prevents premature propagation of over-estimated T_A values
1277  // that result from active neighbors with intermediate results.
1278  clear_active(indX);
1279  freshlyConverged.push_back(indX);
1280 
1281  if (param_globals::dream.output.debugNode == indX) {
1283  }
1284  }
1285  }
1286 
1287  // A node whose cell would not fire is no source: reject its T_A before anything is verified from it
1288  reject_non_firing_activations(ion, freshlyConverged);
1289 
1290  // Post-sweep verification: re-evaluate freshly-converged nodes with convergedOnly=true.
1291  // Phase 1 is read-only on List so all verifications see a consistent state.
1292  std::vector<VerifyEntry> verifyResults;
1293  verifyResults.reserve(freshlyConverged.size());
1294 
1295  for (mesh_int_t indX : freshlyConverged) {
1296  SF_real ta_sweep = T_A[indX];
1297  SF_real ta_verified = compute_coherence(indX, true);
1298 
1299  // One-sided verification: reject only clearly over-estimated sweep times.
1300  // Use fim.tol as the acceptance band — the same threshold the iterative
1301  // solver uses for convergence, so differences below tol are indistinguishable
1302  // from converged agreement.
1303  bool verified = std::isfinite(ta_verified) &&
1304  (ta_sweep <= ta_verified + param_globals::dream.fim.tol);
1305 
1306  // Safety net: if the node hit max_iter, accept the convergence regardless
1307  // of verification to prevent infinite re-entry loops.
1308  bool forceConverge = (num_changes[indX] > param_globals::dream.fim.max_iter);
1309 
1310  VerifyResult vr;
1311  if (verified || forceConverge) {
1313  } else if (std::isfinite(ta_verified)) {
1315  } else {
1316  // ta_verified is infinite. Whether that is a genuine conduction block or
1317  // merely unsettled neighbors cannot be told apart here: compute_coherence
1318  // returns a bare infinity in both cases. Keep the node active either way.
1320  }
1321  verifyResults.push_back({indX, ta_verified, vr});
1322  LogPhaseOneVerify(indX, ta_sweep, ta_verified, vr, forceConverge);
1323  }
1324 
1325  // Phase 2A: compute neighbor activations from a frozen List snapshot (read-only).
1326  // Apply them later to prevent order-dependent local block.
1327  std::vector<char> list_snapshot(List.begin(), List.end());
1328  std::vector<SF_real> pending_q(List.size(), inf);
1329  std::vector<mesh_int_t> pending_src(List.size(), -1);
1330 
1331  // Temporarily mask non-verified freshly-converged nodes from convergedOnly
1332  // stencils. They are not trusted convergence anchors for this sweep.
1333  std::vector<mesh_int_t> masked_untrusted;
1334  for (const auto& vr : verifyResults) {
1335  if (vr.result == VerifyResult::Verified) continue;
1336  if (List[vr.indX] == 0) {
1337  mask_untrusted(vr.indX);
1338  deep_debug_log(DebugCase::MaskedUntrusted, vr.indX, vr.indX);
1339  masked_untrusted.push_back(vr.indX);
1340  }
1341  }
1342 
1343  for (const auto& vr : verifyResults) {
1344  if (vr.result != VerifyResult::Verified) continue;
1345 
1346  mesh_int_t indX = vr.indX;
1347  for (int ii = n2n_dsp[indX]; ii < n2n_dsp[indX + 1]; ii++) {
1348  mesh_int_t indXNB = n2n_connect[ii];
1349 
1350  // Use the frozen snapshot for all checks in this evaluation pass.
1351  if (list_snapshot[indXNB] == 1) continue;
1352 
1353  SF_real pNB = T_A[indXNB];
1354  // convergedOnly: build the candidate only from neighbors that are settled
1355  // AND trusted. The flag rejects nodes still in L; mask_untrusted() above
1356  // extends that to nodes that left L in this sweep but failed verification,
1357  // whose T_A is still the unverified sweep value until Phase 2B rewrites it.
1358  // The two are one mechanism: without the flag, the masking has no effect.
1359  SF_real qNB = compute_coherence(indXNB, true);
1360 
1361  // Already turned down for this T_A at this RD time: the cell state the prediction starts
1362  // from is the same, so it would be turned down again.
1363  if (rejected_at[indXNB] == user_globals::tm_manager->time &&
1364  std::fabs(qNB - rejected_TA[indXNB]) < param_globals::dream.fim.tol) {
1366  continue;
1367  }
1368 
1369  bool node_is_valid = add_node_neighbor_to_list(T_R[indXNB], pNB, qNB) && qNB != inf && qNB > user_globals::tm_manager->time;
1370  // This second condition is there to be able to add a node to the list when a new valid activation time
1371  // is found but a reentry would be blocked by the L2 parameter. Normally this condition does not make or brake the
1372  // simulation but would leave individual nodes inactivated, which is not ideal.
1373  bool ignore_L2_if_valid = node_is_valid && qNB > pNB && nReadded2List[indXNB] >= param_globals::dream.fim.max_addpt;
1374 
1375  if (node_is_valid && ((nReadded2List[indXNB] < param_globals::dream.fim.max_addpt) || ignore_L2_if_valid)) {
1376  // If multiple verified neighbors propose activation, keep the earliest.
1377  if (!std::isfinite(pending_q[indXNB]) || qNB < pending_q[indXNB]) {
1378  pending_q[indXNB] = qNB;
1379  pending_src[indXNB] = indX;
1380  }
1381  } else {
1383  }
1384  }
1385  }
1386 
1387  // Restore temporary mask before applying persistent state changes.
1388  for (mesh_int_t indX : masked_untrusted) {
1389  unmask_untrusted(indX);
1391  }
1392 
1393  // PHASE 2B: Apply verification outcomes and pending activations.
1394  for (const auto& vr : verifyResults) {
1395  mesh_int_t indX = vr.indX;
1396 
1397  if (vr.result == VerifyResult::Overestimated) {
1398  // Premature convergence: converged-only gives a different value.
1399  // Re-enter with the converged-only T_A for further refinement.
1400  // Do not reset num_changes so max_iter can eventually force convergence.
1401  T_A[indX] = vr.ta_verified;
1402  record_D_I(indX);
1403  check_past_activation(indX);
1404  set_active(indX);
1405  } else if (vr.result == VerifyResult::Unresolved) {
1406  // No converged-only activation time this sweep. Do not permanently drop the
1407  // node: if neighbors were simply unsettled it can refine once they converge,
1408  // and if it is genuinely blocked the sweep will keep returning infinity, which
1409  // removes it from L at the top of the next list iteration anyway.
1410  set_active(indX);
1411  }
1412  }
1413 
1414  for (mesh_int_t indXNB = 0; indXNB < static_cast<mesh_int_t>(pending_q.size()); ++indXNB) {
1415  if (!std::isfinite(pending_q[indXNB])) continue;
1416  if (List[indXNB] == 1) continue;
1417 
1418  SF_real pNB = T_A[indXNB];
1419  SF_real qNB = pending_q[indXNB];
1420 
1421  if (qNB > pNB) {
1422  nReadded2List[indXNB] = 0;
1423  TA_old[indXNB] = T_A[indXNB];
1424  }
1425  T_A[indXNB] = qNB;
1426  record_D_I(indXNB);
1427  check_past_activation(indXNB);
1428  nReadded2List[indXNB]++;
1429  num_changes[indXNB] = 0;
1430  set_active(indXNB);
1431 
1432  mesh_int_t src = pending_src[indXNB];
1433  deep_debug_log(DebugCase::ListReenter, src, indXNB);
1434  if (param_globals::dream.output.debugNode == indXNB) {
1436  nodeData.idXNB = src;
1437  nodeData.nbn_T_A = T_A[src];
1438  }
1439  }
1440  // Verified nodes are already List=0 and remain out of the active list.
1441 
1442  SF_real actMIN_old = actMIN;
1443  SF_real progress_time;
1444 
1445  update_Ta_in_active_list();
1446 
1447  if (actMIN > actMIN_old) {
1448  progress_time = actMIN - actMIN_old;
1449  } else {
1450  progress_time = 0;
1451  }
1452 
1453  time2stop_eikonal -= progress_time;
1454  niter++;
1455 
1456  // time2stop_eikonal only shrinks when actMIN advances, so sweeps that make no
1457  // progress do not bring this loop any closer to ending. Force-convergence
1458  // resolves a node after fim.max_iter sweeps, so twice that without actMIN
1459  // moving means the sweep cannot resolve itself and would spin here.
1460  stalled_iterations = (progress_time > 0) ? 0 : stalled_iterations + 1;
1461 
1462  if (stalled_iterations > 2 * param_globals::dream.fim.max_iter) {
1463  if (!warned_sweep_stall) {
1464  warned_sweep_stall = true;
1465  log_msg(NULL, 4, 0,
1466  "%s warning: actMIN did not advance over %d list iterations at t=%.2f ms "
1467  "(actMIN %.2f, %lld active nodes). Ending the cycle early. Results from here on "
1468  "may be unreliable.",
1469  __func__, stalled_iterations, user_globals::tm_manager->time,
1470  actMIN, static_cast<long long>(num_active_nodes));
1471  }
1472  break;
1473  }
1474 
1475  } while (time2stop_eikonal > 0 && num_active_nodes > 0);
1476 
1477  if (num_active_nodes == 0) {
1478  if (Index_currStim == StimulusPoints.size()) actMIN = std::numeric_limits<double>::quiet_NaN();
1479  }
1480 
1481  // copy for igb output; AT/RT are in PETSc order, T_A/T_R in nodal order
1482  const SF::vector<mesh_int_t>& alg_nod = get_mesh(intra_elec_msh).pl.algebraic_nodes();
1483  double* atc = AT->ptr();
1484  double* rpt = RT->ptr();
1485  for (size_t i = 0; i < alg_nod.size(); i++) {
1486  mesh_int_t n = alg_nod[i];
1487  if (T_A[n] == inf) {
1488  // for better visualization in meshalyzer
1489  atc[i] = -1;
1490  } else {
1491  atc[i] = T_A[n];
1492  }
1493  rpt[i] = T_R[n];
1494  }
1495  AT->release_ptr(atc);
1496  RT->release_ptr(rpt);
1497 
1498  // treat solver statistics
1499  auto dur = timing(t1, t0);
1500  stats.slvtime_A += dur;
1501  stats.update_iter(niter);
1502  stats.minAT = actMIN;
1504  stats.bc_status = true;
1507 
1508  // treat node stats
1509  if (param_globals::dream.output.debugNode >= 0) {
1513  }
1514 
1515  assert(num_active_nodes == sum(List));
1516 } // close iterate list
1517 
1518 SF_real eikonal_solver::update(mesh_int_t& indX, SF_real CVrest_factor, bool isDREAM, bool convergedOnly)
1519 {
1520  switch (MESH_SIZE) {
1521  case 4: return update_impl<4>(indX, CVrest_factor, isDREAM, convergedOnly);
1522  case 3: return update_impl<3>(indX, CVrest_factor, isDREAM, convergedOnly);
1523  case 2: return update_impl<2>(indX, CVrest_factor, isDREAM, convergedOnly);
1524  default:
1525  return T_A[indX]; // fallback
1526  }
1527 }
1528 
1529 template <int N>
1530 SF_real eikonal_solver::update_impl(mesh_int_t& indX, SF_real CVrest_factor, bool CheckValidity, bool convergedOnly)
1531 {
1532  double min = inf;
1533  const double time = user_globals::tm_manager->time;
1534  const sf_mesh& mesh = get_mesh(intra_elec_msh);
1535  constexpr ElementCandidate element =
1537  : (N == 2) ? ElementCandidate::EDGE
1539 
1540  // Tracks which element produced the current min, so the debug log can name the winner.
1541  // min carries no provenance, so it has to be captured as it is set.
1542  std::array<int, 4> winning_ids; // read only once winning_count > 0, so left uninitialized
1543  size_t winning_count = 0;
1544  SF_real winning_H = 0.0;
1545 
1546  // element-wise update
1547  for (int e_i = n2e_dsp[indX]; e_i < n2e_dsp[indX + 1]; e_i++) { // gather all elements the node belongs to
1548  int Elem_i = n2e_con[e_i];
1549  mesh_int_t indEle = elem_start[Elem_i];
1550  std::array<SF::Point, N> base; // points
1551  std::array<double, N> values; // activation times
1552  std::array<int, N> nodeIDs;
1553 
1554  std::size_t k = 0;
1555  for (std::size_t j = 0; j < N; j++) { // loop over nodes of element e_i
1556  int n_i = e2n_con[indEle + j];
1557  if (n_i != indX) {
1558  base[k].x = mesh.xyz[3 * n_i + 0];
1559  base[k].y = mesh.xyz[3 * n_i + 1];
1560  base[k].z = mesh.xyz[3 * n_i + 2];
1561  values[k] = T_A[n_i];
1562  nodeIDs[k] = n_i;
1563  k++;
1564  } else { // last slot is reserved for the current vertex we are solving for
1565  base[N - 1].x = mesh.xyz[3 * indX + 0];
1566  base[N - 1].y = mesh.xyz[3 * indX + 1];
1567  base[N - 1].z = mesh.xyz[3 * indX + 2];
1568  values[N - 1] = T_A[indX];
1569  nodeIDs[N - 1] = indX;
1570  }
1571  }
1572 
1573  // scale slowness metric by CV
1574  double cv = CV_L[Elem_i] * CVrest_factor;
1575  if (cv == 0.0) {
1576  is_not_valid_update<N>(nodeIDs, time, e_i, cv, convergedOnly);
1577  continue; // avoid 1/(cv*cv)
1578  }
1579 
1580  SF::dmat<double> D = 1.0 / (cv * cv) * S[Elem_i];
1581 
1582  // 1) solve full N-simplex (eikonal run OR if valid for DREAM)
1583  if (!CheckValidity || !is_not_valid_update<N>(nodeIDs, time, e_i, cv, convergedOnly)) {
1584  LocalSolver<N> solver(D, base, values);
1585  SF_real tmp = solver.solve();
1586  SF_real H = compute_H(indX, tmp);
1587  if (detailed_debug_enabled) {
1588  LogEikonalCandidate(element, indX, nodeIDs.data(), N, tmp, H, e_i - n2e_dsp[indX]);
1589  }
1590 
1591  if (min > tmp && tmp > T_R[indX] && H > 0.0) {
1592  min = tmp;
1593  if (detailed_debug_enabled) {
1594  std::copy_n(nodeIDs.begin(), N, winning_ids.begin());
1595  winning_count = N;
1596  winning_H = H;
1597  }
1598  }
1599 
1600  // A solution at or before the target's repolarization means a neighbor of the previous
1601  // wave (not yet repolarized, so still valid) spoiled the simplex. Only then also try the
1602  // sub-simplices, which may hold a solution from the new wavefront alone.
1603  const bool previous_wave_in_simplex = CheckValidity && std::isfinite(tmp) && tmp <= T_R[indX];
1604  if (!previous_wave_in_simplex) continue;
1605  }
1606 
1607  // If the full N-simplex was not valid or was spoiled (see above), we have to do additional checks for the DREAM,
1608  // since a subsimplex could be valid if e.g. only one node of a tet/triangle is invalid
1609  // 2) triangles that include the target (only done if MESH_SIZE is 4)
1610  if constexpr (N - 1 == 3) {
1611  // neighbor indices are 0..(N-2); choose pairs (i,j) and add target (N-1)
1612  for (int i = 0; i < (N - 1); ++i) {
1613  for (int j = i + 1; j < (N - 1); ++j) {
1614  // build nodeIDs/points/values for face {i, j, target}
1615  std::array<int, 3> tri_ids{nodeIDs[i], nodeIDs[j], nodeIDs[N - 1]};
1616  if (is_not_valid_update<3>(tri_ids, time, e_i, cv, convergedOnly)) continue;
1617 
1618  std::array<SF::Point, 3> tri_pts{base[i], base[j], base[N - 1]};
1619  std::array<double, 3> tri_vals{values[i], values[j], values[N - 1]};
1620 
1621  LocalSolver<3> solver(D, tri_pts, tri_vals);
1622  // min = std::min(min, solver.solve());
1623  SF_real tmp = solver.solve();
1624  SF_real H = compute_H(indX, tmp);
1625  if (detailed_debug_enabled) {
1626  LogEikonalCandidate(ElementCandidate::TRIANGLE, indX, tri_ids.data(), 3, tmp, H, e_i - n2e_dsp[indX]);
1627  }
1628 
1629  if (min > tmp && tmp > T_R[indX] && H > 0.0) {
1630  min = tmp;
1631  if (detailed_debug_enabled) {
1632  std::copy_n(tri_ids.begin(), 3, winning_ids.begin());
1633  winning_count = 3;
1634  winning_H = H;
1635  }
1636  }
1637  }
1638  }
1639  }
1640 
1641  // 3) edges that include the target
1642  for (int i = 0; i < N - 1; i++) {
1643  std::array<int, 2> edge_ids{nodeIDs[i], nodeIDs[N - 1]};
1644  if (is_not_valid_update<2>(edge_ids, time, e_i, cv, convergedOnly)) continue;
1645 
1646  std::array<SF::Point, 2> edge_pts{base[i], base[N - 1]};
1647  std::array<double, 2> edge_vals{values[i], values[N - 1]};
1648 
1649  LocalSolver<2> solver(D, edge_pts, edge_vals);
1650  SF_real tmp = solver.solve();
1651  SF_real H = compute_H(indX, tmp);
1652  if (detailed_debug_enabled) {
1653  LogEikonalCandidate(ElementCandidate::EDGE, indX, edge_ids.data(), 2, tmp, H, e_i - n2e_dsp[indX]);
1654  }
1655 
1656  if (min > tmp && tmp > T_R[indX] && H > 0.0) {
1657  min = tmp;
1658  if (detailed_debug_enabled) {
1659  std::copy_n(edge_ids.begin(), 2, winning_ids.begin());
1660  winning_count = 2;
1661  winning_H = H;
1662  }
1663  }
1664  }
1665  }
1666 
1667  // The local solver's result for this one update() call, not the node's final activation
1668  // time: compute_coherence() calls update() repeatedly and the caller may still reject it.
1669  if (detailed_debug_enabled && winning_count > 0) {
1671  winning_ids.data(), winning_count, min, winning_H, -1);
1672  }
1673 
1674  // D_I is not recorded here. update() is called for every candidate the sweep, the
1675  // verification pass and Phase 2A evaluate, and most of those are never committed to
1676  // T_A. Recording the winner of this call would leave D_I describing an activation
1677  // time the node does not have. It is written at the sites that commit T_A instead.
1678 
1679  return min;
1680 }
1681 
1682 template <int N>
1683 bool eikonal_solver::is_not_valid_update(const std::array<int, N>& nodeIDs, double time, int e_i, double cv, bool convergedOnly)
1684 {
1685  const int target = nodeIDs[N - 1];
1686  const bool failedStim = (stim_status[target] == StimStatus::Failed);
1687 
1688  constexpr ElementCandidate element =
1690  : (N == 2) ? ElementCandidate::EDGE
1692 
1693  for (int i = 0; i < N - 1; i++) {
1694  const int nb = nodeIDs[i];
1695 
1696  bool neighborActivationTimeInvalid = false;
1697  bool neighborTimePrevCycle = false;
1698  bool conductionVelocityZero = false;
1699  bool stimulatedNodeActivatesFailedOne = false;
1700  bool neighborNotYetConverged = false;
1701 
1702  // A neighbor is a valid source until it has repolarized. The eikonal runs ahead of the
1703  // RD time, so a T_A before it only means the front has just passed; rejecting it made
1704  // results depend on when a cycle started and differ between continuous and restarted runs.
1705  if (std::isinf(T_A[nb]))
1706  neighborActivationTimeInvalid = true;
1707 
1708  if (T_A[nb] < T_R[nb] && T_R[nb] < time)
1709  neighborTimePrevCycle = true;
1710 
1711  // When evaluating a neighbor candidate for list entry (convergedOnly=true),
1712  // reject stencil nodes that are still in the active list (not yet converged).
1713  // Their T_A is an intermediate value that may be over-estimated, leading to
1714  // unreasonable activation times and orphan node cascades.
1715  if (convergedOnly && List[nb] == 1)
1716  neighborNotYetConverged = true;
1717 
1718  if (failedStim && stim_status[nb] == StimStatus::Success)
1719  stimulatedNodeActivatesFailedOne = true;
1720 
1721  if (cv == 0.0)
1722  conductionVelocityZero = true;
1723 
1724  if (neighborActivationTimeInvalid ||
1725  neighborTimePrevCycle ||
1726  conductionVelocityZero ||
1727  stimulatedNodeActivatesFailedOne ||
1728  neighborNotYetConverged) {
1729  if (detailed_debug_enabled) {
1730  std::array<int, 5> conditions = {
1731  neighborActivationTimeInvalid,
1732  neighborTimePrevCycle,
1733  conductionVelocityZero,
1734  stimulatedNodeActivatesFailedOne,
1735  neighborNotYetConverged};
1736 
1738  element,
1739  target,
1740  conditions.data(), conditions.size(),
1741  -1, -1,
1742  e_i - n2e_dsp[target]);
1743  }
1744 
1745  return true;
1746  }
1747  }
1748 
1749  return false;
1750 }
1751 
1752 void eikonal_solver::record_D_I(mesh_int_t indX)
1753 {
1754  const SF_real ta = T_A[indX];
1755 
1756  // Same guards compute_H applies before it forms a diastolic interval: a node with no
1757  // activation time, or one that has never repolarized (T_R still at its -400 sentinel),
1758  // or whose recovery lies after the activation, has no interval to report and keeps the
1759  // value it had.
1760  if (!std::isfinite(ta) || T_R[indX] == -400.0 || T_R[indX] > ta) return;
1761 
1762  D_I[indX] = ta - T_R[indX];
1763 }
1764 
1765 SF_real eikonal_solver::compute_H(mesh_int_t& indX, SF_real& tmpTA)
1766 {
1767  // Early exit conditions
1768  if (tmpTA == inf ||
1769  (T_R[indX]) == -400.0 ||
1770  std::fabs(tmpTA - TA_old[indX]) < param_globals::dream.fim.tol ||
1771  T_R[indX] > tmpTA) {
1772  return 1.0;
1773  }
1774 
1775  // Compute diastolic interval. This function does not record it: D_I belongs to the
1776  // committed activation time and is written by record_D_I().
1777  const double DI = tmpTA - (T_R[indX]);
1778 
1779  // CV restitution factor
1780  const double exponent = -(DI + kappa_cvrest[indX]) * denom_cvrest[indX];
1781  const double Factor_DI = 1.0 - rho_cvrest[indX] * std::exp(exponent);
1782 
1783  if (Factor_DI <= 0.0) {
1784  return 0.0;
1785  }
1786 
1787  // Apply restitution curve behavior
1788  return (DI <= theta_cvrest[indX]) ? -Factor_DI : Factor_DI;
1789 }
1790 
1791 SF_real eikonal_solver::compute_coherence(mesh_int_t& indX, bool convergedOnly)
1792 {
1793  SF_real scaling = 1.0;
1794  SF_real p = T_A[indX]; // starting guess (previous arrival time)
1795  SF_real q = update(indX, scaling, true, convergedOnly); // candidate new arrival time
1796 
1797  for (int niter = 0; niter < param_globals::dream.fim.max_coh; ++niter) {
1798  scaling = compute_H(indX, p); // restitution-based scaling for CV (can be negative mid-iteration)
1799  q = update(indX, std::fabs(scaling), true, convergedOnly); // new candidate arrival time; use fabs() to allow intermediate negative scaling
1800 
1801  if (std::fabs(p - q) < param_globals::dream.fim.tol || !std::isfinite(q))
1802  break; // converged
1803 
1804  p = q; // continue iterating
1805  }
1806 
1807  // q is either infinite, or a candidate update() already accepted - and update()
1808  // accepts only candidates whose restitution factor is strictly positive. So a
1809  // finite q is never restitution-blocked or restitution-limited by the time it
1810  // gets here, and an infinite q carries no information about which of the two
1811  // reasons produced it: a genuine block, or neighbors that have not settled yet.
1812  return q;
1813 }
1814 
1815 void eikonal_solver::set_successful_stimulus(mesh_int_t node, SF_real TA)
1816 {
1817  if (TA > T_A[node]) {
1818  TA_old[node] = T_A[node];
1819  }
1820  T_A[node] = TA;
1821  record_D_I(node);
1823 
1825 }
1826 
1827 void eikonal_solver::warn_zero_strength_stimulus(int stim_idx, SF_real stimTime)
1828 {
1829  if (warned_zero_strength[stim_idx]) return;
1830  warned_zero_strength[stim_idx] = true;
1831  log_msg(NULL, 3, ECHO,
1832  "Warning: stimulus '%s' at t=%.2f ms has pulse.strength set to zero, or was not set at all (default: 0),\n"
1833  "so it deposits no charge and cannot depolarize any of its target nodes. It captures nothing and\n"
1834  "no activation propagates from it. Set pulse.strength for DREAM simulations.",
1835  (*stimuliRef)[stim_idx].name.c_str(), stimTime);
1836 }
1837 
1838 void eikonal_solver::set_unsuccessful_stimulus(mesh_int_t node, size_t stimIndex, SF_real stimTime)
1839 {
1841  stim_duration[node] = StimulusDurations[stimIndex];
1842  stim_strength[node] = StimulusStrengths[stimIndex];
1843  stim_start[node] = stimTime;
1844 
1845  // Only the most recent such pulse is kept. Since the look-ahead can fail a stimulus before the
1846  // clock reaches it, a later one can overwrite this while the node is still in L waiting on the
1847  // earlier pulse, which would then be checked against the wrong one in
1848  // reject_non_firing_activations(). That needs two non-capturing pulses within one cycle.
1849  last_noncapturing_stim[node] = stimTime;
1850  last_noncapturing_row[node] = stimIndex;
1851 
1852  // The look-ahead can fail a stimulus before it happens and change T_R already. Remember the
1853  // T_R from before it for save_eikonal_state() (only the first such stimulus per node).
1854  if (failed_stim_time[node] < user_globals::tm_manager->time) {
1855  failed_stim_time[node] = stimTime;
1856  T_R_before_failed_stim[node] = T_R[node];
1857  }
1858 
1859  if (!stim_failed_now[node]) {
1860  stim_failed_now[node] = true;
1861  stim_failed_nodes.push_back(node);
1862  }
1863 
1864  const int stim_idx = StimulusOrigIndex[stimIndex];
1865  if (!warned_failed_capture[stim_idx]) {
1866  warned_failed_capture[stim_idx] = true;
1867  log_msg(NULL, 3, ECHO,
1868  "Warning: stimulus '%s' at t=%.2f ms did not capture all of its target nodes: their\n"
1869  "recovery times did not allow the stimulus to propagate.\n"
1870  "Uncaptured nodes get no activation time and propagate nothing, so they are absent from act.\n"
1871  "%s",
1872  (*stimuliRef)[stim_idx].name.c_str(), stimTime,
1873  std::fabs(stim_strength[node]) < 1e-9
1874  ? "This stimulus has pulse.strength 0, which is the default, so it deposits no charge either\n"
1875  "and leaves the recovery of those nodes unchanged. That can keep a unidirectional block\n"
1876  "from holding, so set pulse.strength for DREAM simulations."
1877  : "The stimulus current is still applied, so they may still fire in vm. This is an expected\n"
1878  "mismatch.");
1879  }
1881 }
1882 
1883 void eikonal_solver::check_past_activation(mesh_int_t indX)
1884 {
1885  const double now = user_globals::tm_manager->time;
1886  if (!(T_A[indX] < now)) return;
1887 
1888  constexpr long long max_reported = 20;
1890  if (num_past_activations <= max_reported) {
1891  log_msg(NULL, 4, 0,
1892  "%s warning: node %d got activation time %.3f ms, before the current time %.3f ms, "
1893  "so it may not depolarize.%s",
1894  __func__, static_cast<int>(indX), T_A[indX], now,
1895  num_past_activations == max_reported ? " Further occurrences are only counted." : "");
1896  }
1897 }
1898 
1899 void eikonal_solver::set_active(mesh_int_t i)
1900 {
1901  if (List[i] == 0) {
1902  List[i] = 1;
1903  num_active_nodes++;
1904  }
1905 }
1906 
1907 void eikonal_solver::clear_active(mesh_int_t i)
1908 {
1909  if (List[i] == 1) {
1910  List[i] = 0;
1911  num_active_nodes--;
1912  }
1913 }
1914 
1915 void eikonal_solver::mask_untrusted(mesh_int_t i)
1916 {
1917  List[i] = 1;
1918 }
1919 
1920 void eikonal_solver::unmask_untrusted(mesh_int_t i)
1921 {
1922  List[i] = 0;
1923 }
1924 
1925 void eikonal_solver::activate_neighbors(mesh_int_t& node)
1926 {
1927  for (int ii = n2n_dsp[node]; ii < n2n_dsp[node + 1]; ++ii) {
1928  mesh_int_t nb = n2n_connect[ii];
1929  if (List[nb] == 0) {
1930  set_active(nb);
1932  }
1933  }
1934 }
1935 
1936 void eikonal_solver::compute_bc(const Ionics& ion, bool EmptyList, SF_real time_upper_bound)
1937 {
1938  // Reset per-call failure record. Callers use this to decide whether the
1939  // failed-stimulus repolarization recovery has anything to do, instead of
1940  // inferring it from Index_currStim having advanced (which is also true when
1941  // every node of the stimulus captured successfully).
1942  // Only the entries set last time need clearing, so this stays proportional to the number
1943  // of failed captures rather than to the mesh size.
1944  for (mesh_int_t n : stim_failed_nodes) stim_failed_now[n] = false;
1945  stim_failed_nodes.clear();
1946 
1947  // Determine the upper bound for stimulus computation.
1948  // Normally it's time_upper_bound, but if the list is empty, use the next scheduled stimulus.
1949  SF_real stimTimeUpperBound = time_upper_bound;
1950  if (EmptyList) {
1951  // The line below does not check Index_currStim itself. It relies on
1952  // should_solve_reaction_diffusion() to stop cycFIM() from running once all
1953  // stimuli are used up, so Index_currStim never goes out of range here.
1954  assert(Index_currStim < StimulusTimes.size());
1955  stimTimeUpperBound = StimulusTimes[Index_currStim];
1956  }
1957 
1958  // Makes the node of stimulus row `row` a wave origin at time TA: sets its T_A and puts its
1959  // neighbors into the active list. The node and neighboring stimulus targets are kept out of
1960  // the list (their T_A comes from their own stimulus row). If the stimulus injects current,
1961  // Idiff is suppressed at the node from the onset to TA + 5 ms (solve_RD()), as the current
1962  // depolarizes it.
1963  auto capture = [&](size_t row, SF_real TA) {
1964  mesh_int_t indNode = StimulusPoints[row];
1965  const stimulus& s = (*stimuliRef)[StimulusOrigIndex[row]];
1966  set_successful_stimulus(indNode, TA);
1967  if (s.phys.type == I_tm && std::fabs(s.pulse.strength) > 1e-9) {
1968  captured_onset[indNode] = StimulusTimes[row];
1969  captured_TA[indNode] = TA;
1970  }
1971  activate_neighbors(indNode);
1972 
1973  // The captured node itself, and any of its neighbors that are themselves
1974  // designated stimulus targets, must not be left sitting in L: their fate
1975  // is decided directly by compute_bc (now, or on a later call once their
1976  // own row is reached), not by the generic iterative refinement L drives.
1977  // activate_neighbors above can incidentally turn on such a neighbor; undo
1978  // that here, scoped to only what this call actually touched.
1979  if (List[indNode] == 1) {
1980  clear_active(indNode);
1982  }
1983  for (int ii = n2n_dsp[indNode]; ii < n2n_dsp[indNode + 1]; ++ii) {
1984  mesh_int_t nb = n2n_connect[ii];
1985  if (is_stimulus_target[nb] && List[nb] == 1) {
1986  clear_active(nb);
1988  }
1989  }
1990  };
1991 
1992  // Loop over stimulus points starting from Index_currStim until the end of the table
1993  // or until the stimulus time exceeds the upper bound. A recovered node of a transmembrane
1994  // stimulus captures only if its cell fires, which is predicted for all of them after the loop.
1995  std::vector<size_t> cand_rows;
1996  std::vector<mesh_int_t> subthreshold; // recovered nodes whose cell does not fire: no T_A, back into L
1997 
1998  size_t j = Index_currStim;
1999  for (; j < StimulusTimes.size(); ++j) {
2000  mesh_int_t indNode = StimulusPoints[j];
2001  SF_real stimTime = StimulusTimes[j];
2002 
2003  if (stimTime > stimTimeUpperBound) {
2004  break;
2005  }
2006 
2007  // Check if the node can be activated (the stimulus time is after the refractory period) and if the stimulus can propagate at that time and that node.
2008  bool can_activate = add_node_neighbor_to_list(T_R[indNode], T_A[indNode], stimTime);
2009  bool can_propagate = compute_H(indNode, stimTime) > 0;
2010 
2011  // Determine if the stimulus on this node is successful or not.
2012  if (!(can_activate && can_propagate)) {
2013  set_unsuccessful_stimulus(indNode, j, stimTime);
2014  continue;
2015  }
2016 
2017  const stimulus& s = (*stimuliRef)[StimulusOrigIndex[j]];
2018  if (s.phys.type != I_tm) {
2019  capture(j, stimTime); // not a transmembrane current: excitation cannot be predicted from it
2020  continue;
2021  }
2022  if (std::fabs(s.pulse.strength) < 1e-9) {
2023  // Deposits no charge, so it cannot depolarize the node and nothing propagates from it.
2024  warn_zero_strength_stimulus(StimulusOrigIndex[j], stimTime);
2026  subthreshold.push_back(indNode);
2027  continue;
2028  }
2029  if (capture_candidate[indNode] >= 0) break; // a second pulse at this node is decided in a later call
2030  capture_candidate[indNode] = static_cast<long>(cand_rows.size());
2031  cand_rows.push_back(j);
2032  }
2033  // Update the current stimulus index: either the first one beyond the upper bound
2034  // or the end of the stimulus table.
2035  Index_currStim = j;
2036 
2037  // Nothing to predict. This path returns before the loop at the end of the function,
2038  // so the zero-strength nodes are put back into L here instead.
2039  if (cand_rows.empty()) {
2040  for (mesh_int_t node : subthreshold) set_active(node);
2041  return;
2042  }
2043 
2044  // Fires: captured, T_A = upstroke. Otherwise subthreshold: no T_A, and the node stays a normal
2045  // node, so it is put back into L if a neighbor's capture took it out.
2046  std::vector<SF_real> t_up;
2047  predict_upstroke(ion, cand_rows, t_up);
2048  for (size_t k = 0; k < cand_rows.size(); k++) {
2049  const mesh_int_t node = StimulusPoints[cand_rows[k]];
2050  capture_candidate[node] = -1;
2051  if (std::isfinite(t_up[k])) {
2052  capture(cand_rows[k], t_up[k]);
2053  } else {
2055  last_noncapturing_stim[node] = StimulusTimes[cand_rows[k]];
2056  last_noncapturing_row[node] = cand_rows[k];
2057  subthreshold.push_back(node);
2058  }
2059  }
2060  for (mesh_int_t node : subthreshold) set_active(node);
2061 } // end compute stimulus
2062 
2063 void eikonal_solver::predict_upstroke(const Ionics& ion, const std::vector<size_t>& rows, std::vector<SF_real>& t_up, const std::vector<SF_real>* idiff_TA, std::vector<SF_real>* vm_end)
2064 {
2065  double t1, t0;
2066  get_time(t0);
2067  t_up.assign(rows.size(), inf);
2068  if (vm_end) vm_end->assign(rows.size(), 0.0);
2069 
2070 #ifdef _OPENMP
2071  int max_threads = omp_get_max_threads();
2072  omp_set_num_threads(1); // one node per compute() call: a parallel region would only cost time
2073 #endif
2074 
2075  limpet::MULTI_IF* miif = ion.miif;
2076  const SF::vector<mesh_int_t>& alg_nod = get_mesh(intra_elec_msh).pl.algebraic_nodes();
2077  const timer_manager& tm = *user_globals::tm_manager;
2078  const double dt = tm.time_step;
2079  const double thresh = param_globals::dream.depol_time_thresh;
2080 
2081  for (int i = 0; i < miif->N_IIF; i++) {
2082  if (!miif->N_Nodes[i]) continue;
2083 
2084  // the model and its plugins, in compute_ionic_current() order; only one node per compute()
2085  std::vector<limpet::IonIfBase*> imps{miif->IIF[i]};
2086  for (limpet::IonIfBase* plug : miif->IIF[i]->plugins()) imps.push_back(plug);
2087  std::vector<std::vector<std::pair<int, int>>> layouts(imps.size());
2088  for (size_t m = 0; m < imps.size(); m++) {
2089  if (imps[m]->get_type().dlo_vector_size() != 1) {
2090  log_msg(NULL, 5, 0, "%s error: the DREAM capture prediction needs ionic models built without vectorized data layout. Aborting!", __func__);
2091  EXIT(EXIT_FAILURE);
2092  }
2093  imps[m]->get_sv_layout(layouts[m]);
2094  }
2095  auto** ldata = miif->ldata[i];
2096  using data_t = std::remove_reference_t<decltype(ldata[0][0])>;
2097 
2098  for (int current = 0; current < static_cast<int>(miif->N_Nodes[i]); current++) {
2099  // NodeLists holds PETSc indices, capture_candidate and the per-node arrays are nodal
2100  const mesh_int_t node = alg_nod[miif->NodeLists[i][current]];
2101  const long k = capture_candidate[node];
2102  if (k < 0) continue;
2103  const size_t row = rows[k];
2104  const bool with_idiff = idiff_TA != nullptr;
2105  const SF_real horizon = with_idiff ? (*idiff_TA)[k] + 5.0 : StimulusTimes[row] + STIM_CAPTURE_WINDOW;
2106 
2107  // pulse steps, computed like the stimulus timer does
2108  const stimulus* s = (row == NO_PULSE) ? nullptr : &(*stimuliRef)[StimulusOrigIndex[row]];
2109  long d_on = 0, d_dur = 0;
2110  if (s) {
2111  const long pulse = (s->ptcl.npls > 1 && s->ptcl.pcl > 0.0) ? lround((StimulusTimes[row] - s->ptcl.start) / s->ptcl.pcl) : 0;
2112  d_on = lround(s->ptcl.start / dt) + pulse * lround(s->ptcl.pcl / dt);
2113  d_dur = lround(tm.timer_duration(s->ptcl.timer_id) / dt);
2114  }
2115 
2116  // save state variables and IMP data of the node
2117  std::vector<char> sv_backup;
2118  std::vector<data_t> data_backup;
2119  for (size_t m = 0; m < imps.size(); m++)
2120  imps[m]->for_each_sv_field(current, layouts[m], [&](char* p, size_t sz) { sv_backup.insert(sv_backup.end(), p, p + sz); });
2121  for (int d = 0; d < NUM_IMP_DATA_TYPES; d++)
2122  if (ldata[d]) data_backup.push_back(ldata[d][current]);
2123 
2124  // one step as in solve_RD(): stimulus (operator splitting), compute_ionic_current(), Idiff
2125  data_t& vm = ldata[limpet::Vm][current];
2126  data_t& iion = ldata[limpet::Iion][current];
2127  for (long d = tm.d_time; d * dt <= horizon + 1e-9; d++) {
2128  const data_t vm_start = vm;
2129  if (s && d >= d_on && d < d_on + d_dur)
2130  vm += s->pulse.strength * s->phys.scale * s->pulse.wave.f[std::min<size_t>(d - d_on, s->pulse.wave.f.size() - 1)];
2131  iion = 0.0;
2132  for (int sub = 0; sub < miif->numSubDt; sub++) {
2133  for (limpet::IonIfBase* imp : imps) imp->compute(current, current + 1, ldata);
2134  vm += iion * (-miif->dt);
2135  }
2136  if (with_idiff) {
2137  const SF_real dT = d * dt - (*idiff_TA)[k];
2138  if (dT >= 0.0 && dT <= 5.0) vm += idiff_template(diff_cur[node], dT, vm) * dt;
2139  }
2140  if (vm_start <= thresh && vm > thresh && !std::isfinite(t_up[k])) {
2141  t_up[k] = d * dt;
2142  if (!with_idiff) break;
2143  }
2144  }
2145  if (vm_end) (*vm_end)[k] = vm;
2146 
2147  // restore
2148  size_t pos = 0;
2149  for (size_t m = 0; m < imps.size(); m++)
2150  imps[m]->for_each_sv_field(current, layouts[m], [&](char* p, size_t sz) { memcpy(p, sv_backup.data() + pos, sz); pos += sz; });
2151  pos = 0;
2152  for (int d = 0; d < NUM_IMP_DATA_TYPES; d++)
2153  if (ldata[d]) ldata[d][current] = data_backup[pos++];
2154  }
2155  }
2156 
2157 #ifdef _OPENMP
2158  omp_set_num_threads(max_threads);
2159 #endif
2160  stats.slvtime_D += timing(t1, t0);
2161 }
2162 
2163 void eikonal_solver::reject_non_firing_activations(const Ionics& ion, std::vector<mesh_int_t>& converged)
2164 {
2165  // The sweep sets T_A from the neighbors alone, without asking whether the cell fires. A
2166  // stimulus pulse that did not capture a node can leave its cell depolarized but unable to
2167  // fire, and its Idiff then does not make it fire either; with that T_A the wave would still
2168  // spread from it. Checked are therefore only nodes that a pulse reached without capturing
2169  // them since their last T_R. The prediction starts at the current time and includes that
2170  // pulse, since the solver may not have applied it yet.
2171  std::vector<mesh_int_t> nodes;
2172  std::vector<size_t> rows;
2173  std::vector<SF_real> idiff_TA;
2174  for (mesh_int_t n : converged) {
2175  const bool at_risk = last_noncapturing_stim[n] > T_R[n] && last_noncapturing_stim[n] < T_A[n];
2176  if (!at_risk || !std::isfinite(T_A[n]) || T_A[n] + 5.0 < user_globals::tm_manager->time) continue;
2177  capture_candidate[n] = static_cast<long>(nodes.size());
2178  nodes.push_back(n);
2179  rows.push_back(last_noncapturing_row[n]);
2180  idiff_TA.push_back(T_A[n]);
2181  }
2182  if (nodes.empty()) return;
2183 
2184  std::vector<SF_real> t_up, vm_end;
2185  predict_upstroke(ion, rows, t_up, &idiff_TA, &vm_end);
2186 
2187  std::vector<mesh_int_t> rejected;
2188  for (size_t k = 0; k < nodes.size(); k++) {
2189  const mesh_int_t n = nodes[k];
2190  capture_candidate[n] = -1;
2191  if (vm_end[k] > param_globals::dream.depol_time_thresh) continue;
2192  rejected_TA[n] = T_A[n];
2194  T_A[n] = (TA_old[n] < T_A[n]) ? TA_old[n] : inf;
2195  record_D_I(n);
2196  rejected.push_back(n);
2198  }
2199 
2200  converged.erase(std::remove_if(converged.begin(), converged.end(),
2201  [&](mesh_int_t n) { return std::find(rejected.begin(), rejected.end(), n) != rejected.end(); }),
2202  converged.end());
2203 }
2204 
2206 {
2207  const double tau_s = param_globals::dream.tau_s; // safety time margin
2208 
2209  const bool active_node_list_is_empty = (num_active_nodes == 0);
2210 
2211  // Case 1: activate nodes exist and its activation times are safely in the future
2212  if (!active_node_list_is_empty) {
2213  if (actMIN > tau_s && actMIN - time > tau_s) {
2214  return true; // → solve RD
2215  }
2216  return false; // → solve Eikonal
2217  }
2218 
2219  // From here on: active node list is empty
2220 
2221  // Case 2a: no activation and no more stimuli
2222  const bool no_more_stimuli = (Index_currStim >= StimulusPoints.size());
2223  if (no_more_stimuli) {
2224  return true; // → solve RD
2225  }
2226 
2227  // Case 2b: stimulus exists but is safely in the future
2228  const double time_to_next_stimulus = StimulusTimes[Index_currStim] - time;
2229  if (time_to_next_stimulus > tau_s) {
2230  return true; // → solve RD
2231  }
2232 
2233  return false; // → solve Eikonal
2234 }
2235 
2236 void eikonal_solver::update_Ta_in_active_list()
2237 {
2238  const SF_real now = user_globals::tm_manager->time;
2239 
2240  // min stays active-only, max also counts departed-but-relevant nodes - this
2241  // asymmetry is intentional: including a departed node here would let its
2242  // frozen value block min from ever advancing, while excluding one there
2243  // would lose a confirmed peak once it leaves the active list.
2244  SF_real min_TA_in_active_list = std::numeric_limits<double>::infinity();
2245  SF_real max_relevant = -std::numeric_limits<double>::infinity();
2246 
2247  for (size_t j = 0; j < List.size(); j++) {
2248  if (T_A[j] < 0 || !std::isfinite(T_A[j])) continue;
2249 
2250  if (List[j] == 1 && T_A[j] < min_TA_in_active_list) {
2251  min_TA_in_active_list = T_A[j];
2252  }
2253 
2254  if ((List[j] == 1 || T_A[j] >= now) && T_A[j] > max_relevant) {
2255  max_relevant = T_A[j];
2256  }
2257  }
2258 
2259  if (std::isfinite(min_TA_in_active_list)) {
2260  actMIN = min_TA_in_active_list;
2261  } else {
2262  // Fallback: active list only has T_A=inf, scan all nodes for wavefront minimum
2263  SF_real min_TA_anywhere = std::numeric_limits<double>::infinity();
2264 
2265  for (size_t j = 0; j < List.size(); j++) {
2266  if (std::isfinite(T_A[j]) &&
2267  T_A[j] >= now &&
2268  T_A[j] < min_TA_anywhere) {
2269  min_TA_anywhere = T_A[j];
2270  }
2271  }
2272  actMIN = std::isfinite(min_TA_anywhere) ? min_TA_anywhere : now;
2273  }
2274 
2275  actMAX = std::isfinite(max_relevant) ? max_relevant : now;
2276 }
2277 
2279 {
2280  for (size_t j = 0; j < List.size(); j++) {
2281  if (T_A[j] < user_globals::tm_manager->time) {
2282  TA_old[j] = T_A[j];
2284  nReadded2List[j] = 0;
2285  stim_duration[j] = -1;
2286  stim_strength[j] = -1;
2287  stim_start[j] = -1;
2288 
2289  if (List[j] == 1) {
2290  clear_active(j);
2291  }
2292  }
2293  }
2294 }
2295 
2296 bool eikonal_solver::add_node_neighbor_to_list(SF_real& RT, SF_real& oldTA, SF_real& newTA)
2297 {
2298  // Condition (A): RT < newTA < oldTA
2299  // Condition (B): oldTA < RT < newTA
2300  return ((RT < newTA) && (newTA < oldTA)) ||
2301  ((oldTA < RT) && (RT < newTA));
2302 }
2303 
2305 {
2306  SF_real* old_ptr = Vmv_old.ptr();
2307  SF_real* new_ptr = Vmv.ptr();
2308 
2309  const double thresh = param_globals::dream.repol_time_thresh;
2310 
2311  // Vm is in PETSc order, T_R in nodal order
2312  const SF::vector<mesh_int_t>& alg_nod = get_mesh(intra_elec_msh).pl.algebraic_nodes();
2313  for (size_t i = 0; i < alg_nod.size(); i++) {
2314  mesh_int_t n = alg_nod[i];
2315  bool crossed_threshold = (old_ptr[i] >= thresh && new_ptr[i] < thresh);
2316 
2317  // T_R only moves forward. update_repolarization_times() predicts it ahead of the clock,
2318  // and the RD trajectory then crosses the threshold slightly earlier, so keeping the
2319  // prediction is what preserves the deficit correction applied after a failed stimulus.
2320  // This cannot be narrowed to those nodes: clean_list() clears stim_status before the
2321  // crossing arrives, so by then they are indistinguishable from any other node.
2322  if (crossed_threshold && time >= T_R[n]) {
2323  T_R[n] = time;
2324  }
2325  }
2326 
2327  Vmv_old.release_ptr(old_ptr);
2328  Vmv.release_ptr(new_ptr);
2329 }
2330 
2332 {
2333  double t1, t0;
2334  get_time(t0);
2335 
2336 #ifdef _OPENMP
2337  int max_threads = omp_get_max_threads();
2338  omp_set_num_threads(1); // with the current setup of this function, it is better to run it in serial.
2339 #endif
2340 
2341  limpet::MULTI_IF* miif = ion.miif;
2342  const SF::vector<mesh_int_t>& alg_nod = get_mesh(intra_elec_msh).pl.algebraic_nodes();
2343 
2344  const double time = user_globals::tm_manager->time,
2346  threshold = param_globals::dream.repol_time_thresh;
2347 
2348  for (int i = 0; i < miif->N_IIF; i++) {
2349  if (!miif->N_Nodes[i]) continue;
2350  limpet::IonIfBase* pIF = ion.miif->IIF[i];
2351  limpet::IonIfBase* IIF_old = pIF->get_type().make_ion_if(pIF->get_target(),
2352  pIF->get_num_node(),
2353  ion.miif->plugtypes[i]);
2354  IIF_old->copy_SVs_from(*pIF, false);
2355 
2356  int current = 0;
2357  do {
2358  // NodeLists holds PETSc indices, T_A/T_R are nodal
2359  mesh_int_t loc_nodal_idx = alg_nod[miif->NodeLists[i][current]];
2360  // save states at the moment
2361  double Vm_old = miif->ldata[i][limpet::Vm][current];
2362  double Iion_old = miif->ldata[i][limpet::Iion][current];
2363  constexpr double MAX_ELAPSED = 600.0;
2364  constexpr double RT_SAFETY_MARGIN = 20.0;
2365 
2366  const double stim_begin = stim_start[loc_nodal_idx];
2367  const double stim_end = stim_begin + stim_duration[loc_nodal_idx];
2368  const bool failed_stim_mode = (mode == RepolMode::FailedStim);
2369 
2370  bool should_check_repolarization = false;
2371  if (mode == RepolMode::Normal) {
2372  should_check_repolarization =
2373  T_R[loc_nodal_idx] <= T_A[loc_nodal_idx] &&
2374  T_A[loc_nodal_idx] != inf &&
2375  Vm_old > threshold;
2376  } else {
2377  // Only the nodes this compute_bc() call failed to capture: stim_start, stim_duration
2378  // and stim_strength below describe that attempt, and an older one has already passed.
2379  should_check_repolarization =
2380  stim_failed_now[loc_nodal_idx] &&
2381  (Vm_old > threshold || std::fabs(stim_strength[loc_nodal_idx]) > 1e-9);
2382  }
2383  if (should_check_repolarization) {
2384  bool activated_node = false;
2385 
2386  for (double elapsed = dt; elapsed < MAX_ELAPSED; elapsed += dt) {
2387  const double t_abs = time + elapsed;
2388  // Update ionic current
2389  pIF->compute(current, current + 1, miif->ldata[i]);
2390 
2391  // Define stimulus current
2392  double I_stim = 0.0;
2393  if (failed_stim_mode &&
2394  t_abs >= stim_begin &&
2395  t_abs <= stim_end) {
2396  I_stim = stim_strength[loc_nodal_idx];
2397  }
2398  // Update Vm
2399  miif->ldata[i][limpet::Vm][current] -=
2400  (miif->ldata[i][limpet::Iion][current] - I_stim) * dt;
2401 
2402  const double Vm = miif->ldata[i][limpet::Vm][current];
2403 
2404  if (failed_stim_mode &&
2405  !activated_node &&
2406  t_abs >= stim_end &&
2407  Vm > threshold) {
2408  activated_node = true;
2409  }
2410 
2411  const bool crossed_repol = Vm < threshold;
2412  const bool repol_allowed =
2413  failed_stim_mode
2414  ? activated_node
2415  : (T_R[loc_nodal_idx] < t_abs + RT_SAFETY_MARGIN);
2416 
2417  if (crossed_repol && repol_allowed) {
2418  T_R[loc_nodal_idx] = t_abs;
2419  break;
2420  }
2421  }
2422 
2423  // Restore old states
2424  miif->ldata[i][limpet::Vm][current] = Vm_old;
2425  miif->ldata[i][limpet::Iion][current] = Iion_old;
2426  }
2427  current++;
2428  } while (current < miif->N_Nodes[i]);
2429  pIF->copy_SVs_from(*IIF_old, false);
2430  }
2431 
2432 #ifdef _OPENMP
2433  omp_set_num_threads(max_threads); // restore max threads for parabolic solver
2434 #endif
2435 
2436  // treat solver statistics
2437  auto dur = timing(t1, t0);
2438  stats.slvtime_D += dur;
2439 }
2440 
2442 {
2443  double t0, t1;
2444  get_time(t0);
2445 
2446  SF_real* c = Idiff->ptr();
2447  SF_real* v = vm.ptr();
2448 
2449  const sf_mesh& mesh = get_mesh(intra_elec_msh);
2450  const SF::vector<mesh_int_t>& alg_nod = mesh.pl.algebraic_nodes();
2451  int rank = get_rank();
2452 
2453  for (size_t j = 0; j < alg_nod.size(); j++) {
2454  mesh_int_t loc_nodal_idx = alg_nod[j];
2455  mesh_int_t loc_petsc_idx = local_nodal_to_local_petsc(mesh, rank, loc_nodal_idx);
2456 
2457  double TA = T_A[loc_nodal_idx];
2458  double TAold = TA_old[loc_nodal_idx];
2459 
2460  bool time_in_TA_window = (time >= TA && (TA + 5) >= time && List[loc_nodal_idx] == 0);
2461  bool time_in_TAold_window = (time >= TAold && (TAold + 5) >= time);
2462 
2463  if (!time_in_TA_window && !time_in_TAold_window)
2464  continue;
2465  double dT;
2466  if (time_in_TA_window)
2467  dT = time - TA;
2468  else
2469  dT = time - TAold;
2470 
2471  c[loc_petsc_idx] = idiff_template(diff_cur[loc_nodal_idx], dT, v[loc_petsc_idx]);
2472  }
2473 
2474  Idiff->release_ptr(c);
2475  vm.release_ptr(v);
2476 
2477  stats.slvtime_B += timing(t1, t0);
2478 }
2479 
2480 SF_real eikonal_solver::idiff_template(const diffusion_current& node, SF_real dT, SF_real vm) const
2481 {
2482  switch (node.model) {
2483  case GAUSS: {
2484  double term1 = (dT - node.beta_1) / node.gamma_1;
2485  double term2 = (dT - node.beta_2) / node.gamma_2;
2486  double term3 = (dT - node.beta_3) / node.gamma_3;
2487  return node.alpha_1 * exp(-term1 * term1) + node.alpha_2 * exp(-term2 * term2) + node.alpha_3 * exp(-term3 * term3);
2488  }
2489  default: {
2490  double e_on = (dT >= 0.0) ? 1.0 : 0.0;
2491  double e_off = (vm < node.V_th) ? 1.0 : 0.0;
2492  return node.A_F / node.tau_F * exp(dT / node.tau_F) * e_on * e_off;
2493  }
2494  }
2495 }
2496 
2497 void eikonal_solver::deep_debug_log(DebugCase debug_case, mesh_int_t index_ref, mesh_int_t ind_target)
2498 {
2499  mesh_int_t idx = param_globals::dream.output.detailed_debugNode;
2500  const double time = user_globals::tm_manager->time;
2501  if (idx < 0 || idx != ind_target) return;
2502  if (!deepDebugLogger) return;
2503 
2504  const char* tag = nullptr;
2505  switch (debug_case) {
2506  case DebugCase::ListIter: tag = "NODE ITERATION INSIDE THE LIST"; break;
2507  case DebugCase::ListReenter: tag = "NEIGHBOR ENTERS LIST"; break;
2508  case DebugCase::FailedReenter: tag = "FAILED TO ENTER LIST"; break;
2509  case DebugCase::Stimulated: tag = "STIMULATED NODE"; break;
2510  case DebugCase::UnsuccessfulStimulated: tag = "STIMULUS FAILED TO CAPTURE NODE"; break;
2511  case DebugCase::RejectedNonFiring: tag = "ACTIVATION REJECTED - CELL WOULD NOT FIRE"; break;
2512  case DebugCase::NBStimulusEnter: tag = "NEIGHBOR OF SUCCESSFULLY STIMULATED NODE ENTERS THE LIST"; break;
2513  case DebugCase::ExitsListStimulated: tag = "EXITS LIST FOR BEING SUCCESSFULLY STIMULATED NODE"; break;
2514  case DebugCase::ExitsListInvalidUpdate: tag = "EXITS LIST - CANNOT COMPUTE VALID UPDATE"; break;
2515  case DebugCase::MaskedUntrusted: tag = "TEMPORARILY MASKED AS UNTRUSTED (PHASE 2A)"; break;
2516  case DebugCase::UnmaskedUntrusted: tag = "UNMASKED - TRUSTED STATE RESTORED (PHASE 2A)"; break;
2517 
2518  default: tag = "UNKNOWN DEBUG CASE"; break;
2519  }
2520 
2521  FILE* fp = deepDebugLogger->fd;
2522  for (int i = 0; i < 5; i++) {
2523  fprintf(fp, "\n ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n");
2524  }
2525  fprintf(fp, "\n================= %s =================\n", tag);
2526  fprintf(fp, "Target Node Index : %d\n", idx);
2527 
2528  if (debug_case == DebugCase::ListReenter) {
2529  fprintf(fp, "Entered List from Neighbor : %d (Converged Node)\n", index_ref);
2530  } else if (debug_case == DebugCase::FailedReenter) {
2531  fprintf(fp, "Failed to Enter from Neighbor : %d (Converged Node)\n", index_ref);
2532  } else if (debug_case == DebugCase::NBStimulusEnter) {
2533  fprintf(fp, "Entered List from Neighbor : %d (Stimulated Node)\n", index_ref);
2534  }
2535 
2536  // Lambda to format time or print "inf"
2537  auto print_time = [&](double value) {
2538  char time_str[16];
2539  if (std::isinf(value))
2540  snprintf(time_str, sizeof time_str, "inf");
2541  else
2542  snprintf(time_str, sizeof time_str, "%6.2f", value);
2543  return std::string(time_str);
2544  };
2545 
2546  // Determine stimulation status string
2547  std::string stim_status_str;
2548 
2549  switch (stim_status[idx]) {
2550  case StimStatus::None:
2551  stim_status_str = "Stimulation Status : Not attempted";
2552  break;
2553 
2554  case StimStatus::Success:
2555  stim_status_str = "Stimulation Status : Successfully stimulated";
2556  break;
2557 
2558  case StimStatus::Failed:
2559  stim_status_str = "Stimulation Status : Attempted, not successful";
2560  break;
2561 
2563  stim_status_str = "Stimulation Status : Attempted, cell predicted not to fire";
2564  break;
2565 
2566  default:
2567  stim_status_str = "Stimulation Status : Unknown";
2568  break;
2569  }
2570 
2571  // Columns with spaced layout
2572  std::string left_col[] = {
2573  "Previous Activation Time : " + print_time(TA_old[idx]),
2574  "Current Activation Time : " + print_time(T_A[idx]),
2575  "Recovery Time : " + print_time(T_R[idx]),
2576  stim_status_str};
2577 
2578  std::string center_col[] = {
2579  "Currently in List : " + std::to_string(List[idx]),
2580  "List Iterations : " + std::to_string(num_changes[idx]),
2581  "Times Re-entered List : " + std::to_string(nReadded2List[idx])};
2582 
2583  std::string right_col[] = {
2584  "Min Activation in List : " + print_time(actMIN),
2585  "Max Advance in List : " + print_time(maxadvance),
2586  "Global RD Model Time : " + print_time(time)};
2587 
2588  // Print headers
2589  fprintf(fp, "\n%-42s%-42s%-40s\n",
2590  "==== Activation & Recovery ====",
2591  "==== List Status ====",
2592  "==== Global & List Metrics ====");
2593 
2594  // Print rows
2595  for (int i = 0; i < 4; ++i) {
2596  fprintf(fp, "%-42s", left_col[i].c_str());
2597  if (i < 3)
2598  fprintf(fp, "%-42s%-40s\n", center_col[i].c_str(), right_col[i].c_str());
2599  else
2600  fprintf(fp, "%-42s%-40s\n", "", "");
2601  }
2602 
2603  fprintf(fp, "--------------------------------------------------------------------------\n");
2604  fflush(fp);
2605 }
2606 
2607 void eikonal_solver::LogPhaseOneVerify(mesh_int_t indX, SF_real ta_sweep, SF_real ta_verified, VerifyResult result, bool forceConverge)
2608 {
2609  mesh_int_t idx = param_globals::dream.output.detailed_debugNode;
2610  if (idx < 0 || idx != indX) return;
2611  if (!deepDebugLogger) return;
2612 
2613  const char* result_str = nullptr;
2614  switch (result) {
2615  case VerifyResult::Verified: result_str = "Verified"; break;
2616  case VerifyResult::Overestimated: result_str = "Overestimated"; break;
2617  case VerifyResult::Unresolved: result_str = "Unresolved"; break;
2618  default: result_str = "Unknown"; break;
2619  }
2620 
2621  // Lambda to format time or print "inf" (matches deep_debug_log's own formatting)
2622  auto print_time = [&](double value) {
2623  char time_str[16];
2624  if (std::isinf(value))
2625  snprintf(time_str, sizeof time_str, "inf");
2626  else
2627  snprintf(time_str, sizeof time_str, "%6.2f", value);
2628  return std::string(time_str);
2629  };
2630 
2631  FILE* fp = deepDebugLogger->fd;
2632  for (int i = 0; i < 5; i++) {
2633  fprintf(fp, "\n ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n");
2634  }
2635  fprintf(fp, "\n================= PHASE 1 VERIFICATION (POST-SWEEP) =================\n");
2636  fprintf(fp, "Target Node Index : %d\n", idx);
2637  fprintf(fp, "%-30s: %s\n", "Sweep Activation Time", print_time(ta_sweep).c_str());
2638  fprintf(fp, "%-30s: %s\n", "Verified Activation Time", print_time(ta_verified).c_str());
2639  fprintf(fp, "%-30s: %s%s\n", "Verification Result", result_str, forceConverge ? " (forced by max_iter)" : "");
2640  fprintf(fp, "--------------------------------------------------------------------------\n");
2641  fflush(fp);
2642 }
2643 
2644 void eikonal_solver::LogEikonalCandidate(ElementCandidate type, mesh_int_t ind_target, const int* contributors, size_t num_contributors, mesh_real_t candidate_TA, mesh_real_t candidate_scaling_CV, int counter)
2645 {
2646  mesh_int_t idx = param_globals::dream.output.detailed_debugNode;
2647 
2648  if (idx < 0 || idx != ind_target) return;
2649  if (!deepDebugLogger) return;
2650 
2651  FILE* fp = deepDebugLogger->fd;
2652 
2653  if (type == ElementCandidate::SELECTED) {
2654  fprintf(fp, "\n----------------- Local Solver Result -----------------\n");
2655  for (int i = 0; i < 5; i++) {
2656  fprintf(fp, "|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|\n");
2657  }
2658  fprintf(fp, "Compute_F (local eikonal solver) result for node %d:\n", ind_target);
2659  fprintf(fp, "→ Activation time: %.2f | Scaled conduction velocity: %.2f | Diastolic interval: %.2f\n", candidate_TA, candidate_scaling_CV, candidate_TA - T_R[ind_target]);
2660 
2661  // contributors[] holds the whole element, the node being solved for included, so the
2662  // counts here are the element's node counts and not the number of neighbors.
2663  int positive_count = std::count_if(contributors, contributors + num_contributors, [](int x) { return x >= 0; });
2664 
2665  const char* element_type = nullptr;
2666  switch (positive_count) {
2667  case 2: element_type = "edge"; break;
2668  case 3: element_type = "triangle"; break;
2669  case 4: element_type = "tetrahedron"; break;
2670  default: element_type = "unknown structure"; break;
2671  }
2672 
2673  fprintf(fp, "→ Based on %s formed with node(s): ", element_type);
2674  for (size_t i = 0; i < num_contributors; ++i) {
2675  if (contributors[i] >= 0) {
2676  fprintf(fp, "%d ", contributors[i]);
2677  }
2678  }
2679  fprintf(fp, "\n");
2680 
2681  if (candidate_scaling_CV < 0.0) {
2682  fprintf(fp, " CV is unfeasible (likely below propagation threshold).\n");
2683  }
2684 
2685  } else {
2686  const char* type_tag = nullptr;
2687 
2688  switch (type) {
2689  case ElementCandidate::SELECTED: type_tag = "SELECTED"; break;
2690  case ElementCandidate::TETRAHEDRON: type_tag = "TETRAHEDRON"; break;
2691  case ElementCandidate::TRIANGLE: type_tag = "TRIANGLE"; break;
2692  case ElementCandidate::EDGE: type_tag = "EDGE"; break;
2693  default: type_tag = "UNKNOWN"; break;
2694  }
2695  if (counter == 0) {
2696  if ((type == ElementCandidate::TETRAHEDRON && MESH_SIZE == 4) ||
2697  (type == ElementCandidate::TRIANGLE && MESH_SIZE == 3)) {
2698  for (int i = 0; i < 5; i++) {
2699  fprintf(fp, "|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|\n");
2700  }
2701  fprintf(fp, "\n====================== Compute_F (local eikonal solver) called ======================\n");
2702  fprintf(fp, "Attempting to update T_A[%d] = %.2f ms (T_R[%d] = %.2f ms):\n\n", ind_target, T_A[ind_target], ind_target, T_R[ind_target]);
2703  }
2704  fprintf(fp, "[%s #%d]\n", type_tag, counter);
2705  } else {
2706  fprintf(fp, "[%s #%d] \n", type_tag, counter);
2707  }
2708  if (candidate_TA >= 0) {
2709  fprintf(fp, " ├─ Contributing Nodes (index : activation time):\n");
2710  for (size_t i = 0; i < num_contributors; ++i) {
2711  fprintf(fp, " │ %d : %.2f ms\n", contributors[i], T_A[contributors[i]]);
2712  }
2713  if (std::isinf(candidate_TA)) {
2714  fprintf(fp, " └─ → No valid activation time found within this %s; a valid solution may lie along its boundary.\n", type_tag);
2715  } else {
2716  fprintf(fp, " └─ → Potential activation time: %.2f ms | sCV: %.2f mm/s | DI: %.2f ms\n", candidate_TA, candidate_scaling_CV, candidate_TA - T_R[ind_target]);
2717 
2718  if (candidate_scaling_CV < 0.0) {
2719  fprintf(fp, " This conduction velocity value is unfeasible (likely below propagation threshold of the given restitution curve)\n");
2720  }
2721  }
2722 
2723  } else {
2724  // contributors[] here is the flag array is_not_valid_update() builds: one entry per
2725  // rejection ground, matched positionally to reasons[], not node indices.
2726  static const char* const reasons[] = {
2727  "Activation time of a neighbor is infinite.",
2728  "A neighboring node has already repolarized.",
2729  "Conduction velocity is zero.",
2730  "A successfully stimulated node is trying to stimulate a previously failed one.",
2731  "A neighboring node is still in the active list, so its activation time is not yet trusted."};
2732  constexpr size_t num_reasons = sizeof reasons / sizeof *reasons;
2733 
2734  fprintf(fp, " └─ → Candidate activation time was rejected due to:\n");
2735  for (size_t i = 0; i < num_contributors && i < num_reasons; ++i) {
2736  if (contributors[i]) fprintf(fp, " • %s\n", reasons[i]);
2737  }
2738 
2739  if (num_contributors != num_reasons) {
2740  fprintf(fp, " • (caller reported %zu rejection grounds, this logger knows %zu)\n",
2741  num_contributors, num_reasons);
2742  }
2743  }
2744  }
2745  fflush(fp);
2746 }
2747 
2748 void eikonal_solver::save_eikonal_state(const char* roe_fnm)
2749 {
2750  if (get_rank() != 0) return;
2751 
2752  const double save_time = user_globals::tm_manager->time;
2753 
2754  char buffer_writestate[1024];
2755  snprintf(buffer_writestate, sizeof buffer_writestate, "%s.dat", roe_fnm);
2756 
2757  FILE* file_writestate = fopen(buffer_writestate, "w");
2758  if (!file_writestate) {
2759  log_msg(NULL, 5, 0, "Could not open state save file %s for writing\n", buffer_writestate);
2760  return;
2761  }
2762 
2763  // Write header
2764  fprintf(file_writestate, "# openCARP DREAM eikonal state\n");
2765  fprintf(file_writestate, "# save_time %.17g\n", save_time);
2766  fprintf(file_writestate, "# num_pts %zu\n", static_cast<size_t>(List.size()));
2767  fprintf(file_writestate, "# fields: List num_changes nReadded2List TA RT TA_old D_I\n");
2768 
2769  // Captures by pulses before the save whose Idiff suppression is still running: the loader skips
2770  // those pulses and restores the suppression from here
2771  for (size_t j = 0; j < List.size(); ++j) {
2772  if (captured_onset[j] < save_time && save_time <= captured_TA[j] + 5.0)
2773  fprintf(file_writestate, "# captured_stim %zu %.17g %.17g\n", j, captured_onset[j], captured_TA[j]);
2774  }
2775  // Pulses before the save that did not capture a node since its last T_R: the excitation check of
2776  // the node (reject_non_firing_activations()) needs them, and the loader skips those pulses
2777  for (size_t j = 0; j < List.size(); ++j) {
2778  if (last_noncapturing_stim[j] < save_time && last_noncapturing_stim[j] > T_R[j])
2779  fprintf(file_writestate, "# noncapturing_stim %zu %.17g\n", j, last_noncapturing_stim[j]);
2780  }
2781 
2782  // Write state for each node
2783  // Preserve all nodes up to save_time, but clear nodes beyond to prevent protocol pollution when loading and running a different stim protocol than before
2784  const double tolerance = 1e-6; // Small tolerance to avoid floating point-precision issues around save_time
2785 
2786  for (size_t j = 0; j < List.size(); ++j) {
2787  const double orig_TA = T_A[j];
2788  const double orig_TR = T_R[j];
2789  const double orig_TA_old = TA_old[j];
2790  const double orig_DI = D_I[j];
2791 
2792  double outTA, outTR, outTA_old;
2793  int outList, outNumCh, outNumCh2;
2794  double outDI;
2795 
2796  // A predicted upstroke after the save of a pulse that started before it is kept: the loader skips that pulse
2797  const bool captured_by_started_pulse = captured_onset[j] < save_time && captured_TA[j] == orig_TA;
2798 
2799  if (!std::isfinite(orig_TA) || orig_TA <= save_time + tolerance || captured_by_started_pulse) {
2800  // Preserve all data for unactivated nodes and activations up to (and including) save_time
2801  outTA = orig_TA;
2802  outTR = orig_TR;
2803  outTA_old = orig_TA_old;
2804  outDI = orig_DI;
2805  outList = List[j];
2806  outNumCh = num_changes[j];
2807  outNumCh2 = nReadded2List[j];
2808  } else {
2809  // Clear future activations
2810  outTA = std::numeric_limits<double>::infinity();
2811  outTA_old = std::numeric_limits<double>::infinity();
2812  outDI = 0.0;
2813  if (std::isfinite(orig_TA_old)) {
2814  outTR = orig_TA - orig_DI; // RT = TA - DI to preserve previous cycle's repolarization time
2815  } else {
2816  outTR = orig_TR; // If no previous activation, keep initialized RT
2817  }
2818  outList = 0;
2819  outNumCh = 0;
2820  outNumCh2 = 0;
2821  }
2822 
2823  // A failed stimulus at or after save_time has already changed T_R (look-ahead), but the
2824  // loader replays it after loading. Save the T_R from before that stimulus.
2825  if (failed_stim_time[j] >= save_time) {
2826  outTR = T_R_before_failed_stim[j];
2827  }
2828 
2829  fprintf(file_writestate, "%d %d %d %.17g %.17g %.17g %.17g\n",
2830  outList, outNumCh, outNumCh2, outTA, outTR, outTA_old, outDI);
2831  }
2832 
2833  log_msg(NULL, 3, ECHO,
2834  "Saved DREAM eikonal state at time %.6f into %s\n",
2835  save_time, buffer_writestate);
2836 
2837  fclose(file_writestate);
2838 }
2839 
2840 void eikonal_solver::load_state_file()
2841 {
2842  set_dir(INPUT);
2843  FILE* file_startstate;
2844  char buffer_startstate[strlen(param_globals::start_statef) + 10];
2845 
2846  snprintf(buffer_startstate, sizeof buffer_startstate, "%s.dat", param_globals::start_statef);
2847  file_startstate = fopen(buffer_startstate, "r");
2848 
2849  if (file_startstate == NULL) {
2850  log_msg(NULL, 5, 0, "Not able to open state file: %s", buffer_startstate);
2851  EXIT(EXIT_FAILURE);
2852  } else if (param_globals::output_level) {
2853  log_msg(NULL, 0, 0, "Open state file for eikonal model: %s", buffer_startstate);
2854  }
2855 
2856  // Stays -1 if the file has no node count, which marks it as pre-dating the
2857  // header and so also pre-dating the save-side clearing of future activations.
2858  long long header_num_pts = -1;
2859 
2860  char linebuf[512];
2861  long pos = ftell(file_startstate);
2862  while (fgets(linebuf, sizeof linebuf, file_startstate)) {
2863  if (linebuf[0] == '#') {
2864  sscanf(linebuf, "# save_time %lf", &loaded_save_time);
2865  sscanf(linebuf, "# num_pts %lld", &header_num_pts);
2866  long long node;
2867  double onset, TA;
2868  if (sscanf(linebuf, "# captured_stim %lld %lf %lf", &node, &onset, &TA) == 3 && node >= 0 &&
2869  node < static_cast<long long>(List.size())) {
2870  captured_onset[node] = onset;
2871  captured_TA[node] = TA;
2872  }
2873  if (sscanf(linebuf, "# noncapturing_stim %lld %lf", &node, &onset) == 2 && node >= 0 &&
2874  node < static_cast<long long>(List.size()))
2875  last_noncapturing_stim[node] = onset;
2876  pos = ftell(file_startstate);
2877  } else {
2878  // First non-header line: rewind to start of data
2879  fseek(file_startstate, pos, SEEK_SET);
2880  break;
2881  }
2882  }
2883 
2884  // save_eikonal_state writes both fields, so a file missing either was written
2885  // before activations after the save time were cleared on save. It carries
2886  // provisional activation times this loader cannot detect from the data alone.
2887  if (loaded_save_time < 0 || header_num_pts < 0) {
2888  log_msg(NULL, 5, 0,
2889  "%s error: state file %s is missing '# save_time' or '# num_pts' and, therefore, predates the current state file format. "
2890  "Regenerate the checkpoint with this openCARP version. Aborting!",
2891  __func__, buffer_startstate);
2892  EXIT(EXIT_FAILURE);
2893  }
2894 
2895  // Reject a checkpoint from a different mesh.
2896  const long long expected_num_pts = static_cast<long long>(List.size());
2897  if (header_num_pts != expected_num_pts) {
2898  log_msg(NULL, 5, 0,
2899  "%s error: state file %s declares %lld nodes, but this mesh has %lld. Aborting!",
2900  __func__, buffer_startstate, header_num_pts, expected_num_pts);
2901  EXIT(EXIT_FAILURE);
2902  }
2903 
2904  // Read state data from file
2905  int ListVal, numChangesVal, numChanges2Val;
2906  double T_AVal, T_RVal, TA_oldVal, D_IVal;
2907  int index = 0;
2908 
2909  while (fscanf(file_startstate, "%d %d %d %lf %lf %lf %lf",
2910  &ListVal, &numChangesVal, &numChanges2Val,
2911  &T_AVal, &T_RVal, &TA_oldVal, &D_IVal) == 7) {
2912  // The header count matched above, so a longer body means a corrupt file.
2913  if (index >= expected_num_pts) {
2914  log_msg(NULL, 5, 0,
2915  "%s error: state file %s contains more rows than the %lld nodes of this mesh. Aborting!",
2916  __func__, buffer_startstate, expected_num_pts);
2917  EXIT(EXIT_FAILURE);
2918  }
2919 
2920  List[index] = ListVal;
2921  num_changes[index] = numChangesVal;
2922  nReadded2List[index] = numChanges2Val;
2923  T_A[index] = T_AVal;
2924  T_R[index] = T_RVal;
2925  TA_old[index] = TA_oldVal;
2926  D_I[index] = D_IVal;
2927  ++index;
2928  }
2929 
2930  fclose(file_startstate);
2931 
2932  // Too few rows is as wrong as too many, just quieter: the loop simply stops and
2933  // every remaining node silently keeps the values init() gave it.
2934  if (index != expected_num_pts) {
2935  log_msg(NULL, 5, 0,
2936  "%s error: state file %s contains %d rows, but this mesh has %lld nodes. Aborting!",
2937  __func__, buffer_startstate, index, expected_num_pts);
2938  EXIT(EXIT_FAILURE);
2939  }
2940 
2941  // Find wavefront nodes based on topology: activated nodes that still have an unactivated neighbor.
2942  std::vector<mesh_int_t> wavefront_nodes;
2943  for (size_t i = 0; i < List.size(); ++i) {
2944  if (!std::isfinite(T_A[i])) continue;
2945 
2946  bool has_inf_neighbor = false;
2947  for (int e_i = n2e_dsp[i]; e_i < n2e_dsp[i + 1] && !has_inf_neighbor; ++e_i) {
2948  int elem = n2e_con[e_i];
2949  for (int n = 0; n < MESH_SIZE && !has_inf_neighbor; ++n) {
2950  mesh_int_t nb = e2n_con[elem_start[elem] + n];
2951  if (nb != static_cast<mesh_int_t>(i) && std::isinf(T_A[nb])) {
2952  has_inf_neighbor = true;
2953  }
2954  }
2955  }
2956  if (has_inf_neighbor) {
2957  wavefront_nodes.push_back(i);
2958  }
2959  }
2960 
2961  // Clear List so wavefront nodes don't get reprocessed by the sweep. These nodes were
2962  // not stimulated, they are already-propagating wave sources reconstructed from the
2963  // checkpoint; is_not_valid_update() accepts them as sources until they repolarize.
2964  for (mesh_int_t node_idx : wavefront_nodes) {
2965  List[node_idx] = 0;
2966  }
2967 
2968  // Seed the active list with the immediate neighbors of the wavefront.
2969  std::vector<char> is_wavefront(List.size(), 0);
2970  for (mesh_int_t node_idx : wavefront_nodes) {
2971  is_wavefront[node_idx] = 1;
2972  }
2973 
2974  num_active_nodes = 0;
2975  for (mesh_int_t node_idx : wavefront_nodes) {
2976  // Get all elements this node belongs to
2977  for (int e_i = n2e_dsp[node_idx]; e_i < n2e_dsp[node_idx + 1]; e_i++) {
2978  int elem = n2e_con[e_i];
2979 
2980  // Check all nodes in this element
2981  for (int n = 0; n < MESH_SIZE; n++) {
2982  mesh_int_t neighbor = e2n_con[elem_start[elem] + n];
2983 
2984  // Add neighbor if: not self, not part of wavefront, not already in list
2985  // Include both unactivated nodes AND previously activated nodes (for multi-stimulus scenarios),
2986  // but not a kept predicted upstroke (see save_eikonal_state): it is fixed, as in the continuous run
2987  const bool captured_ahead = captured_onset[neighbor] < loaded_save_time &&
2988  captured_TA[neighbor] == T_A[neighbor] && T_A[neighbor] > loaded_save_time;
2989  if (neighbor != node_idx &&
2990  !is_wavefront[neighbor] &&
2991  !captured_ahead &&
2992  List[neighbor] == 0) {
2993  set_active(neighbor);
2994  num_changes[neighbor] = 0;
2995  nReadded2List[neighbor] = 0;
2996  }
2997  }
2998  }
2999  }
3000 
3001  // Seed actMIN from the wavefront before calling update_Ta_in_active_list(),
3002  // which needs a finite actMIN to find the active list minimum correctly.
3003  if (!wavefront_nodes.empty()) {
3004  actMIN = std::numeric_limits<double>::infinity();
3005  for (mesh_int_t node_idx : wavefront_nodes) {
3006  if (T_A[node_idx] < actMIN) {
3007  actMIN = T_A[node_idx];
3008  }
3009  }
3010  }
3011 
3013 
3014  update_Ta_in_active_list();
3015 
3016  if (param_globals::output_level) {
3017  log_msg(NULL, 0, 0, "Loaded state from time %.2f ms", loaded_save_time);
3018  log_msg(NULL, 0, 0, "Number of nodes in active list: %i", sum(List));
3019  }
3020 }
3021 
3023 {
3024  logger = f_open(filename, "w");
3025 
3026  const char* h1 = " ------ ---------- ---------- ------- ------- | List logic ----- -------- | Neighbor node ---- |";
3027  const char* h2 = " cycle AT old AT RT DI | Status Entry Exit | ID AT |";
3028 
3029  if (logger == NULL)
3030  log_msg(NULL, 3, 0, "%s error: Could not open file %s in %s. Turning off logging.\n",
3031  __func__, filename);
3032  else {
3033  log_msg(logger, 0, 0, "%s", h1);
3034  log_msg(logger, 0, 0, "%s", h2);
3035  }
3036 }
3037 
3038 void node_stats::log_stats(double time, bool cflg)
3039 {
3040  if (!this->logger) return;
3041 
3042  char abuf[256];
3043  char bbuf[256];
3044  char cbuf[256];
3045 
3046  // create nicer output in logger for inf, -inf, nan
3047  std::ostringstream oss_TA, oss_TA_, oss_TR, oss_DI, oss_nbnTA;
3048  oss_TA << this->T_A;
3049  oss_TA_ << this->T_A_;
3050  oss_TR << this->T_R;
3051  oss_DI << this->D_I;
3052  oss_nbnTA << this->nbn_T_A;
3053 
3054  if (this->idXNB == std::numeric_limits<Int>::min()) {
3055  snprintf(cbuf, sizeof cbuf, "%7s %10s", "-", "-");
3056  } else {
3057  snprintf(cbuf, sizeof cbuf, "%7lld %10s", static_cast<long long>(this->idXNB), oss_nbnTA.str().c_str());
3058  }
3059 
3060  snprintf(abuf, sizeof abuf, "%6lld %10s %10s %7s %7s",
3061  static_cast<long long>(this->cycle),
3062  oss_TA.str().c_str(), oss_TA_.str().c_str(), oss_TR.str().c_str(), oss_DI.str().c_str());
3063  snprintf(bbuf, sizeof bbuf, "%7s %8s %8s", this->status, this->reasonIn, this->reasonOut);
3064 
3065  unsigned char flag = cflg ? ECHO : 0;
3066  log_msg(this->logger, 0, flag | FLUSH | NONL, "%9.3f %s | %s | %s |\n", time, abuf, bbuf, cbuf);
3067 
3068  this->reasonIn = "-";
3069  this->reasonOut = "-";
3070  this->T_A_ = this->T_A;
3071  this->T_A = std::numeric_limits<double>::quiet_NaN();
3072  this->T_R = std::numeric_limits<double>::quiet_NaN();
3073  this->D_I = std::numeric_limits<double>::quiet_NaN();
3075  this->nbn_T_A = std::numeric_limits<double>::quiet_NaN();
3076  this->cycle++;
3077 }
3078 
3080 {
3081  // directly convert enums to strings for logging
3082  const char* stat_str;
3083  const char* reas_str;
3084  switch (s) {
3085  case node_stats::in: stat_str = "in"; break;
3086  case node_stats::out: stat_str = "out"; break;
3087  }
3088 
3089  switch (r) {
3090  case node_stats::none: reas_str = "-"; break;
3091  case node_stats::nbn: reas_str = "nbn"; break;
3092  case node_stats::conv: reas_str = "conv"; break;
3093  case node_stats::stim: reas_str = "stim"; break;
3094  }
3095 
3096  this->status = stat_str;
3097  if (s == in) {
3098  this->reasonIn = reas_str;
3099  } else {
3100  this->reasonOut = reas_str;
3101  }
3102 }
3103 
3104 template <int MESH_SIZE>
3106 {
3107  const SF::Point& x1 = points[0];
3108  const SF::Point& x2 = points[1];
3109 
3110  const double& u1 = values[0];
3111 
3112  if constexpr (MESH_SIZE == 2) {
3113  return tsitsiklis_update_line({x1, x2}, D, u1);
3114 
3115  } else if constexpr (MESH_SIZE == 3) {
3116  const SF::Point& x3 = points[2];
3117  const double& u2 = values[1];
3118  return tsitsiklis_update_triangle({x1, x2, x3}, D, {u1, u2});
3119 
3120  } else if constexpr (MESH_SIZE == 4) {
3121  const SF::Point& x3 = points[2];
3122  const SF::Point& x4 = points[3];
3123  const double& u2 = values[1];
3124  const double& u3 = values[2];
3125 
3126  double u_tet = tsitsiklis_update_tetra({x1, x2, x3, x4}, D, {u1, u2, u3});
3127  if (isnan(u_tet)) {
3128  u_tet = std::numeric_limits<double>::infinity();
3129  }
3130  // face calculations (contains edge update as fallback)
3131  double u_face1 = tsitsiklis_update_triangle({x1, x2, x4}, D, {u1, u2});
3132  double u_face2 = tsitsiklis_update_triangle({x1, x3, x4}, D, {u1, u3});
3133  double u_face3 = tsitsiklis_update_triangle({x2, x3, x4}, D, {u2, u3});
3134 
3135  double u_tri = std::min({u_face1, u_face2, u_face3});
3136  return std::min(u_tet, u_tri);
3137  }
3138 }
3139 
3140 template <int MESH_SIZE>
3141 double LocalSolver<MESH_SIZE>::tsitsiklis_update_line(const std::array<SF::Point, 2>& base,
3142  const SF::dmat<double>& D,
3143  const double& value)
3144 {
3145  // Compute the difference vector: a1 = x2 - x1
3146  SF::Point a1 = base[1] - base[0];
3147  // Return updated value at x2: u1 + norm
3148  return value + std::sqrt(SF::inner_prod(a1, D * a1));
3149 }
3150 
3151 template <int MESH_SIZE>
3152 double LocalSolver<MESH_SIZE>::tsitsiklis_update_triangle(const std::array<SF::Point, 3>& base,
3153  const SF::dmat<double>& D,
3154  const std::array<double, 2>& values)
3155 {
3156  const SF::Point& x1 = base[0];
3157  const SF::Point& x2 = base[1];
3158  const SF::Point& x3 = base[2];
3159  const double& u1 = values[0];
3160  const double& u2 = values[1];
3161  double result = std::numeric_limits<double>::infinity();
3162 
3163  SF::Point z1 = x1 - x2;
3164  SF::Point z2 = x2 - x3;
3165  double k = u1 - u2;
3166 
3167  // Squared Mahalanobis norms
3168  const SF::Point Dz1 = D * z1;
3169  const SF::Point Dz2 = D * z2;
3170  double p11 = SF::inner_prod(z1, Dz1);
3171  double p12 = SF::inner_prod(z1, Dz2);
3172  double p22 = SF::inner_prod(z2, Dz2);
3173 
3174  double denominator = p11 - k * k;
3175  double sqrt_val = (p11 * p22 - p12 * p12) / denominator;
3176 
3177  if (denominator > 1e-12) { // avoid dividing by zero or near zero -> k very small, likely due to collapsed triangle/coinciding points
3178  const double sqrt_val = (p11 * p22 - p12 * p12) / denominator;
3179  if (sqrt_val >= 0.0) { // only real solutions are considered
3180  const double rhs = k * std::sqrt(sqrt_val);
3181  double alpha1 = -(p12 + rhs) / p11;
3182  double alpha2 = -(p12 - rhs) / p11;
3183 
3184  alpha1 = std::clamp(alpha1, 0.0, 1.0);
3185  alpha2 = std::clamp(alpha2, 0.0, 1.0);
3186 
3187  for (double alpha : {alpha1, alpha2}) {
3188  SF::Point x_interp = x1 * alpha + x2 * (1.0 - alpha);
3189  SF::Point dist = x3 - x_interp;
3190  double norm_D = std::sqrt(SF::inner_prod(dist, D * dist));
3191  double u3 = alpha * u1 + (1.0 - alpha) * u2 + norm_D;
3192  result = std::min(result, u3);
3193  }
3194  }
3195  }
3196 
3197  // Fallback: point-based update if square root was invalid or denominator is too small
3198  double u_edge1 = tsitsiklis_update_line({x1, x3}, D, u1);
3199  double u_edge2 = tsitsiklis_update_line({x2, x3}, D, u2);
3200 
3201  return std::min({result, u_edge1, u_edge2});
3202 }
3203 
3204 template <int MESH_SIZE>
3205 double LocalSolver<MESH_SIZE>::tsitsiklis_update_tetra(const std::array<SF::Point, 4>& base,
3206  const SF::dmat<double>& D,
3207  const std::array<double, 3>& values)
3208 {
3209  const SF::Point& x1 = base[0];
3210  const SF::Point& x2 = base[1];
3211  const SF::Point& x3 = base[2];
3212  const SF::Point& x4 = base[3];
3213 
3214  const double& u1 = values[0];
3215  const double& u2 = values[1];
3216  const double& u3 = values[2];
3217 
3218  // edge vectors
3219  const SF::Point y1 = x3 - x1;
3220  const SF::Point y2 = x3 - x2;
3221  const SF::Point y3 = x4 - x3;
3222 
3223  const double k1 = u1 - u3;
3224  const double k2 = u2 - u3;
3225 
3226  // Matrix products (squared norms and dot products under metric D)
3227  const SF::Point Dy1 = D * y1;
3228  const SF::Point Dy2 = D * y2;
3229  const SF::Point Dy3 = D * y3;
3230  const double r11 = SF::inner_prod(y1, Dy1);
3231  const double r12 = SF::inner_prod(y1, Dy2);
3232  const double r13 = SF::inner_prod(y1, Dy3);
3233  const double r21 = r12;
3234  const double r22 = SF::inner_prod(y2, Dy2);
3235  const double r23 = SF::inner_prod(y2, Dy3);
3236  const double r31 = r13;
3237  const double r32 = r23;
3238 
3239  const double A1 = k2 * r11 - k1 * r12;
3240  const double A2 = k2 * r21 - k1 * r22;
3241  const double B = k2 * r31 - k1 * r32;
3242  const double k = k1 - (A1 / A2) * k2;
3243  const SF::Point z1 = y1 - (A1 / A2) * y2;
3244  const SF::Point z2 = y3 - (B / A2) * y2;
3245 
3246  // compute quadratic equation
3247  const SF::Point Dz1 = D * z1;
3248  const SF::Point Dz2 = D * z2;
3249  const double p11 = SF::inner_prod(z1, Dz1);
3250  const double p12 = SF::inner_prod(z1, Dz2);
3251  const double p22 = SF::inner_prod(z2, Dz2);
3252  const double denominator = p11 - k * k;
3253  const double sqrt_val = (p11 * p22 - (p12 * p12)) / denominator;
3254  const double rhs = k * std::sqrt(sqrt_val);
3255 
3256  double alpha1 = -(p12 + rhs) / p11;
3257  double alpha2 = -(B + alpha1 * A1) / A2;
3258 
3259  // handle degenerate cases
3260  const double EPS = 1e-16;
3261  if ((std::abs(A1) < EPS) && (std::abs(A2) < EPS)) {
3262  alpha1 = (r12 * r23 - r13 * r22) / (r11 * r22 - (r12 * r12));
3263  alpha2 = (r12 * r13 - r11 * r23) / (r11 * r22 - (r12 * r12));
3264  } else if ((std::abs(A1) < EPS) && (std::abs(A2) > EPS)) {
3265  alpha1 = 0;
3266  alpha2 = -B / A2;
3267  } else if ((std::abs(A1) > EPS) && (std::abs(A2) < EPS)) {
3268  alpha1 = -B / A1;
3269  alpha2 = 0;
3270  }
3271 
3272  double alpha3 = 1 - alpha1 - alpha2;
3273  const SF::Point dist = x4 - (alpha1 * x1 + alpha2 * x2 + alpha3 * x3);
3274  // barycentric coordinate should be inside the tetrahedron
3275  if (alpha1 < -EPS || alpha2 < -EPS || alpha3 < -EPS ||
3276  alpha1 > 1.0 + EPS || alpha2 > 1.0 + EPS || alpha3 > 1.0 + EPS) {
3277  return std::numeric_limits<double>::infinity();
3278  } else {
3279  return alpha1 * u1 + alpha2 * u2 + alpha3 * u3 + std::sqrt(SF::inner_prod(dist, D * dist));
3280  }
3281 }
3282 
3283 } // 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
#define data_t
Definition: IGBops.cc:123
opencarp::local_index_t mesh_int_t
Definition: SF_container.h:31
float mesh_real_t
Definition: SF_container.h:32
opencarp::real_t SF_real
Global scalar type.
Definition: SF_globals.h:30
Starts and stops the linear algebra backend the flavor parameter selects.
#define EXIT(A)
finalize the backend, if it runs, and exit
Definition: backend.h:23
Basic utility structs and functions, mostly IO related.
#define FLUSH
Definition: basics.h:305
#define ECHO
Definition: basics.h:302
#define NONL
Definition: basics.h:306
virtual 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
vector< S > xyz
node cooridnates
Definition: SF_container.h:412
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
double dt
time step (ms)
Definition: MULTI_ION_IF.h:215
node_count_t * N_Nodes
#nodes for each IMP
Definition: MULTI_ION_IF.h:196
int numSubDt
number of sub-dt time steps
Definition: MULTI_ION_IF.h:216
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:82
void compute_step()
Definition: ionics.cc:20
void initialize()
Definition: ionics.cc:45
void destroy()
Definition: ionics.cc:37
int check_quiescence(double tm, double dt)
check for quiescence
Definition: electrics.cc:1805
void output_initial_activations()
output one nodal vector of initial activation time
Definition: electrics.cc:1920
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:1614
int check_acts(double tm)
check activations at sim time tm
Definition: electrics.cc:1737
std::vector< bool > stim_failed_now
SF::vector< SF_real > captured_onset
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 > StimulusDurations
SF::vector< SF_real > T_R
SF::vector< SF_real > StimulusStrengths
SF::vector< mesh_int_t > n2e_dsp
void save_eikonal_state(const char *roe_fnm)
Save the current state of variables related to the Eikonal simulation to a file to initialize a futur...
SF::vector< SF_real > T_A
SF::vector< SF_real > stim_strength
SF::vector< SF_real > last_noncapturing_stim
SF::vector< SF_real > captured_TA
SF::vector< SF_real > rejected_at
SF::vector< SF_real > TA_old
SF::vector< SF_real > T_R_before_failed_stim
SF::vector< diffusion_current > diff_cur
void init()
Initialize vectors and variables in the eikonal_solver class.
SF::vector< SF_real > stim_duration
SF::vector< mesh_int_t > e2n_con
SF::vector< SF_real > stim_start
SF::vector< mesh_int_t > elem_start
std::vector< bool > is_stimulus_target
SF::vector< mesh_int_t > StimulusPoints
SF::vector< SF_real > rho_cvrest
void cycFIM(const Ionics &ion)
Implementation of the cyclical fast iterative method used in step A of the DREAM model.
std::vector< double > CV_L
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< size_t > last_noncapturing_row
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
SF::vector< StimStatus > stim_status
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
std::vector< bool > warned_zero_strength
std::vector< mesh_int_t > stim_failed_nodes
void LogPhaseOneVerify(mesh_int_t indX, SF_real ta_sweep, SF_real ta_verified, VerifyResult result, bool forceConverge)
Logs the outcome of post-sweep Phase 1 verification for a freshly-converged node.
static constexpr size_t NO_PULSE
void update_repolarization_times(const Ionics &ion, RepolMode mode)
Estimates repolarization times (T_R) via a short ionic-model-only integration.
SF::vector< SF_real > theta_cvrest
SF::vector< mesh_int_t > num_changes
static constexpr double STIM_CAPTURE_WINDOW
std::vector< mesh_int_t > n2n_dsp
SF::vector< SF_real > StimulusTimes
SF::vector< SF_real > failed_stim_time
SF::vector< SF_real > kappa_cvrest
SF::vector< mesh_int_t > n2e_cnt
SF::vector< SF_real > rejected_TA
SF::vector< int > StimulusOrigIndex
eikonal_solver_stats stats
void LogEikonalCandidate(ElementCandidate type, mesh_int_t ind_target, const int *contributors, size_t num_contributors, mesh_real_t candidate_TA, mesh_real_t candidate_scaling_CV, int counter)
Logs detailed information about an Eikonal candidate update for a specific node.
std::vector< long > capture_candidate
bool should_solve_reaction_diffusion(double &time)
Determine the next model to run in the alternation between RD and Eikonal.
void deep_debug_log(DebugCase debug_case, mesh_int_t index_ref=0, mesh_int_t ind_target=0)
Logs detailed debug information for a specific node in the Eikonal simulation.
std::vector< bool > warned_failed_capture
void init_imp_region_properties(FILE_SPEC logger)
Initializes diffusion current models and CV restitution parameters per mesh node.
std::vector< SF::dmat< double > > S
void write_data()
write registered data to disk
Definition: sim_utils.cc:2167
void close_files_and_cleanup()
close file descriptors
Definition: sim_utils.cc:2223
void register_output(sf_vec *inp_data, const mesh_t inp_meshid, const int dpn, const char *name, const char *units, const SF::vector< mesh_int_t > *idx=NULL, bool elem_data=false)
Register a data vector for output.
Definition: sim_utils.cc:2134
sf_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:1255
void solve(sf_vec &phie_i)
Definition: electrics.cc:1369
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
SF::vector< mesh_int_t > vertices
Definition: stimulate.h:138
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.
void interval(vector< T > &vec, size_t start, size_t end)
Create an integer interval between start and end.
Definition: SF_vector.h:335
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:127
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
void region_mask(mesh_t meshspec, SF::vector< RegionSpecs > &regspec, SF::vector< int > &regionIDs, bool mask_elem, const char *reglist, FILE_SPEC logger)
classify elements/points as belonging to a region
Definition: ionics.cc:367
int stimidx_from_timeridx(const SF::vector< stimulus > &stimuli, const int timer_id)
determine link between timer and stimulus
Definition: electrics.cc:839
@ 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
int get_size(MPI_Comm comm=SF_COMM)
Definition: basics.h:284
SF::scattering * get_permutation(const int mesh_id, const int perm_id, const int dpn)
Get the PETSC to canonical permutation scattering for a given mesh and number of dpn.
SF::meshdata< mesh_int_t, mesh_real_t > sf_mesh
Definition: sf_interface.h:33
void apply_stim_to_vector(const stimulus &s, sf_vec &vec, bool add)
Definition: electrics.cc:435
int set_dir(IO_t dest)
Definition: sim_utils.cc:896
vec3< V > cross(const vec3< V > &a, const vec3< V > &b)
Definition: vect.h:130
V dist(const vec3< V > &p1, const vec3< V > &p2)
Definition: vect.h:100
@ 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:111
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:652
void assemble_sv_gvec(gvec_data &gvecs, limpet::MULTI_IF *miif)
Definition: ionics.cc:723
void dump_region_mask(mesh_t meshspec, const SF::vector< int > &regionIDs, const char *reglist)
dump a nodal region mask as produced by region_mask() to reglist+".dat"
Definition: ionics.cc:513
char * dupstr(const char *old_str)
Definition: basics.cc:27
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
Definition: basics.cc:55
mesh_t
The enum identifying the different meshes we might want to load.
Definition: sf_interface.h:44
@ extra_elec_msh
Definition: sf_interface.h:46
@ intra_elec_msh
Definition: sf_interface.h:45
void get_time(double &tm)
Definition: basics.h:430
bool mesh_is_registered(const mesh_t gt)
check wheter a SF mesh is set
Definition: sf_interface.cc:48
SF::abstract_vector< SF_int, SF_real > sf_vec
Definition: sf_interface.h:35
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:595
const char * get_tsav_ext(double time)
Definition: electrics.cc:925
int get_rank(MPI_Comm comm=SF_COMM)
Definition: basics.h:270
V timing(V &t2, const V &t1)
Definition: basics.h:442
void f_close(FILE_SPEC &f)
Close a FILE_SPEC.
Definition: basics.cc:138
@ 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:47
double maxAD
DREAM: time horizon this sweep batch may search up to. Pure Eikonal: actual latest activation time re...
Definition: timers.h:44
void log_stats(double time, bool cflg)
Definition: timers.cc:138
double minAT
minimum activation time in current solve
Definition: timers.h:43
int activeList
number of nodes currently in list
Definition: timers.h:41
void update_iter(const int curiter)
Definition: timers.cc:170
double slvtime_B
total time in Step B
Definition: timers.h:49
void init_logger(const char *filename, bool dream_mode)
Definition: timers.cc:117
double slvtime_D
total time in Step D
Definition: timers.h:51
bool bc_status
boundary conditions were applied?
Definition: timers.h:55
void update_cli(double time, bool cflg)
Definition: timers.cc:176
File descriptor struct.
Definition: basics.h:121
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:75
double tot_time
total time, this is incremented externally
Definition: timers.h:77
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)