30 log_msg(NULL, 5, 0,
"DREAM/Eikonal physics currently do not support MPI parallelization. Use openMP instead. Aborting!");
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!",
48 logger =
f_open(
"eikonal.log", param_globals::experiment != 4 ?
"w" :
"r");
58 if (
eik_tech ==
DREAM && !param_globals::operator_splitting) {
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!");
81 param_globals::dt, 0,
"elec::ref_dt",
"TS");
105 log_msg(NULL, 0, 0,
"All done in %f sec.",
float(t2 - t1));
113 m->
regions.resize(param_globals::num_gregions);
116 log_msg(
logger, 0, 0,
"Setting up %s tissue poperties for %d regions ..", grid_name,
117 param_globals::num_gregions);
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);
128 reg->
regname = strdup(param_globals::gregion[i].
name);
130 reg->
nsubregs = param_globals::gregion[i].num_IDs;
136 for (
int j = 0; j < reg->
nsubregs; j++)
137 reg->
subregtags[j] = param_globals::gregion[i].ID[j];
141 elecMaterial* emat =
new elecMaterial();
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;
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;
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;
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;
167 const char* file = g ==
Eikonal::intra_grid ? param_globals::gi_scale_vec : param_globals::ge_scale_vec;
173 void Eikonal::setup_mappings()
182 log_msg(
logger, 0, 0,
"%s: Setting up intracellular algebraic-to-nodal scattering.", __func__);
186 log_msg(
logger, 0, 0,
"%s: Setting up intracellular PETSc to canonical permutation.", __func__);
197 case EIKONAL: solve_EIKONAL();
break;
198 case DREAM: solve_DREAM();
break;
199 default: solve_RE();
break;
230 double curtime =
timing(t2, t1);
252 "DREAM: %lld activation times were set before the current time; "
253 "those nodes may not have depolarized.",
268 void Eikonal::setup_stimuli()
273 stimuli.resize(param_globals::num_stim);
274 for (
int i = 0; i < param_globals::num_stim; i++) {
278 if (param_globals::stim[i].crct.type != 0 && param_globals::stim[i].crct.type != 9) {
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);
285 if (strlen(param_globals::stim[i].ptcl.stimlist) > 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!",
306 log_msg(NULL, 2, 0,
"Only geometry, start time, npls, and bcl of stim[%i] are used", i);
308 if (param_globals::stim[i].pulse.dumpTrace &&
get_rank() == 0) {
317 void Eikonal::stimulate_intracellular()
327 if (param_globals::operator_splitting) {
337 *ps.tmp_i1 = *ps.IIon;
338 *ps.tmp_i1 -= *ps.Irhs;
343 ps.mass_i->mult(*ps.tmp_i1, *ps.Irhs);
345 *ps.Irhs = *ps.tmp_i1;
353 if (illum_vec == NULL) {
354 log_msg(0, 5, 0,
"Cannot apply illumination stim: global vector not present!");
369 void Eikonal::clamp_Vm()
377 void Eikonal::setup_output()
385 restr_i, param_globals::num_io_nodes > 0);
387 if (param_globals::dataout_i) {
396 if (strcmp(param_globals::dream.
output.idifffile,
"") != 0) {
403 if (strcmp(param_globals::dream.
output.idifffile,
"") != 0) {
411 if (param_globals::num_trace) {
413 open_trace(
ion.
miif, param_globals::num_trace, param_globals::trace_node, NULL, &imesh);
420 void Eikonal::dump_matrices()
422 std::string bsname = param_globals::dump_basename;
428 if (param_globals::parab_solve == 1) {
430 fn = bsname +
"_Ki_CN.bin";
433 fn = bsname +
"_Ki.bin";
436 fn = bsname +
"_Mi.bin";
450 val = std::nan(
"NaN");
464 s_unit =
stimuli[sidx].pulse.wave.f_unit;
469 void Eikonal::setup_solvers()
482 if (param_globals::dump2MatLab) dump_matrices();
486 void Eikonal::checkpointing()
495 snprintf(save_fnm,
sizeof save_fnm,
"%s.%s.roe", param_globals::write_statef, tsav_ext);
504 snprintf(save_fnm,
sizeof save_fnm,
"checkpoint.%.1f.roe", tm.time);
510 void Eikonal::solve_EIKONAL()
520 void Eikonal::solve_RE()
531 void Eikonal::solve_DREAM()
538 int stalled_cycles = 0;
544 const int cycle_cap = 2 * param_globals::dream.fim.max_iter;
570 stalled_cycles = made_progress ? 0 : stalled_cycles + 1;
573 const bool stalled = stalled_cycles >= 5;
574 const bool at_cap = cycles >= cycle_cap;
576 if (stalled || at_cap) {
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.",
584 stalled ?
"made no progress over 5 cycles" :
"did not settle within its cycle limit",
596 void Eikonal::solve_RD()
609 stimulate_intracellular();
634 if (pidx >= 0) idiff[pidx] = 0.0;
656 if (param_globals::output_level > 1)
log_msg(0, 0, 0,
"\n *** Initializing Eikonal Solver ***\n");
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);
667 if (param_globals::dream.
output.debugNode >= 0) {
668 nodeData.
idX = param_globals::dream.output.debugNode;
670 snprintf(buf,
sizeof buf,
"node_%lld.dat",
static_cast<long long>(
nodeData.
idX));
713 switch (mesh.
type[0]) {
727 log_msg(0, 5, 0,
"Error: Type of element is not compatible with this version of the eikonal model. Use tetrahedra or triangles");
735 const int idx = param_globals::dream.output.detailed_debugNode;
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");
759 fprintf(fp,
"Tetrahedron %d: [%d, %d, %d, %d]\n",
count,
765 fprintf(fp,
"Triangle %d: [%d, %d, %d]\n",
count,
778 if (strlen(param_globals::start_statef) > 0) load_state_file();
780 create_node_to_node_graph();
782 translate_stim_to_eikonal();
784 precompute_squared_anisotropy_metric();
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;
808 if (rs.
size() == 1) {
818 #pragma omp parallel for schedule(dynamic)
819 for (
size_t i = 0; i < alg_nod.
size(); i++) {
821 int reg = regionIDs[i];
823 const auto& region_diff = param_globals::imp_region[reg].dream.Idiff;
824 const auto& region_rest = param_globals::imp_region[reg].dream.CVrest;
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];
841 diff_cur[v].tau_F = region_diff.tau_F;
842 diff_cur[v].V_th = region_diff.V_th;
848 denom_cvrest[v] = log(region_rest.rho) / region_rest.psi;
850 if (param_globals::output_level)
log_msg(NULL, 0, 0,
"Diffusion current and CV restitution initialized in %f sec.",
timing(t2, t1));
853 void eikonal_solver::translate_stim_to_eikonal()
860 std::vector<std::tuple<SF_real, const stimulus*, int>> stim_events;
862 stim_events.reserve(param_globals::num_stim * 8);
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) {
868 stim_events.emplace_back(start_time, &s, stim_idx);
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); });
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]);
885 if (std::isfinite(shortest_interval) && param_globals::dream.tau_inc >= shortest_interval) {
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);
897 size_t total_nodes = 0;
898 for (
auto& ev : stim_events)
899 total_nodes += (*std::get<1>(ev)).electrode.vertices.size();
908 for (
auto& ev : stim_events) {
909 const stimulus& s = *std::get<1>(ev);
910 const int stim_idx = std::get<2>(ev);
928 if (param_globals::output_level) {
929 size_t skipped_events = 0;
930 for (
const auto& ev : stim_events)
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",
937 log_msg(NULL, 0, 0,
"No stimulus scheduled at or after the save time %.2f ms; %zu event(s) before it were skipped",
955 void eikonal_solver::create_node_to_node_graph()
964 std::vector<std::vector<mesh_int_t>> thread_neighbors(
num_pts);
969 std::vector<char> mark(
num_pts, 0);
971 #pragma omp for schedule(dynamic)
972 for (
int point_idx = 0; point_idx <
num_pts; point_idx++) {
974 std::vector<mesh_int_t> neighbors;
978 for (
int eedsp = 0; eedsp < numNBElem; eedsp++) {
982 for (
int nndsp = 0; nndsp <
MESH_SIZE; nndsp++) {
985 if (nb == point_idx)
continue;
994 for (
int nb : neighbors) mark[nb] = 0;
997 thread_neighbors[point_idx] = std::move(neighbors);
1002 for (
int i = 0; i <
num_pts; i++) {
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(),
1016 if (param_globals::output_level) {
1017 log_msg(NULL, 0, 0,
"Node-to-node graph done in %f sec.",
timing(t2, t1));
1021 void eikonal_solver::precompute_squared_anisotropy_metric()
1028 S.resize(mesh.l_numelem);
1029 CV_L.resize(mesh.l_numelem);
1036 #pragma omp parallel
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;
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]) {
1066 double AR_T2 = (vl / vt) * (vl / vt);
1067 double AR_N2 = (vl / vn) * (vl / vn);
1069 f.
x = mesh.fib[3 * eidx + 0];
1070 f.
y = mesh.fib[3 * eidx + 1];
1071 f.
z = mesh.fib[3 * eidx + 2];
1074 s.
x = mesh.she[3 * eidx + 0];
1075 s.
y = mesh.she[3 * eidx + 1];
1076 s.
z = mesh.she[3 * eidx + 2];
1094 if (param_globals::output_level)
1095 log_msg(NULL, 0, 0,
"Anisotropy tensors precomputed in %f sec.",
timing(t2, t1));
1107 std::vector<mesh_int_t> activeList;
1108 activeList.reserve(
num_pts / 10);
1109 std::vector<char> in_active(
num_pts, 0);
1122 add_to_active(activeList, in_active, nb);
1129 while (!activeList.empty() && niter <= param_globals::dream.fim.max_iter) {
1130 const std::vector<mesh_int_t> activeVec = std::move(activeList);
1133 #pragma omp parallel
1135 std::vector<mesh_int_t> local_active;
1136 local_active.reserve(64);
1138 #pragma omp for schedule(dynamic)
1139 for (
size_t i = 0; i < activeVec.size(); ++i) {
1141 remove_from_active(in_active,
id);
1146 #pragma omp atomic write
1149 if (std::fabs(p - q) < param_globals::dream.fim.tol) {
1155 #pragma omp atomic write
1161 local_active.push_back(
id);
1166 #pragma omp critical
1169 add_to_active(activeList, in_active, nb);
1178 auto [minIt, maxIt] = std::minmax_element(
T_A.
begin(),
T_A.
end());
1184 double* atc =
AT->
ptr();
1185 #pragma omp parallel for
1186 for (
size_t i = 0; i < alg_nod.
size(); ++i) {
1188 atc[i] = (ta ==
inf ? -1.0 : ta);
1193 auto dur =
timing(t1, t0);
1215 compute_bc(ion,
true, 0);
1221 actMIN = std::numeric_limits<double>::quiet_NaN();
1222 actMAX = std::numeric_limits<double>::quiet_NaN();
1226 double time2stop_eikonal = param_globals::dream.tau_inc;
1229 int stalled_iterations = 0;
1231 std::vector<mesh_int_t> freshlyConverged;
1234 freshlyConverged.clear();
1240 compute_bc(ion,
false,
actMAX);
1250 if (
List[indX] == 0)
continue;
1255 q = compute_coherence(indX);
1259 if (!std::isfinite(q)) {
1267 check_past_activation(indX);
1274 if (abs(p - q) < param_globals::dream.fim.tol || (
num_changes[indX] > param_globals::dream.fim.max_iter) || (q ==
inf || p ==
inf)) {
1279 freshlyConverged.push_back(indX);
1281 if (param_globals::dream.
output.debugNode == indX) {
1288 reject_non_firing_activations(ion, freshlyConverged);
1292 std::vector<VerifyEntry> verifyResults;
1293 verifyResults.reserve(freshlyConverged.size());
1297 SF_real ta_verified = compute_coherence(indX,
true);
1303 bool verified = std::isfinite(ta_verified) &&
1304 (ta_sweep <= ta_verified + param_globals::dream.fim.tol);
1308 bool forceConverge = (
num_changes[indX] > param_globals::dream.fim.max_iter);
1311 if (verified || forceConverge) {
1313 }
else if (std::isfinite(ta_verified)) {
1321 verifyResults.push_back({indX, ta_verified, vr});
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);
1333 std::vector<mesh_int_t> masked_untrusted;
1334 for (
const auto& vr : verifyResults) {
1336 if (
List[vr.indX] == 0) {
1337 mask_untrusted(vr.indX);
1339 masked_untrusted.push_back(vr.indX);
1343 for (
const auto& vr : verifyResults) {
1351 if (list_snapshot[indXNB] == 1)
continue;
1359 SF_real qNB = compute_coherence(indXNB,
true);
1364 std::fabs(qNB -
rejected_TA[indXNB]) < param_globals::dream.fim.tol) {
1373 bool ignore_L2_if_valid = node_is_valid && qNB > pNB &&
nReadded2List[indXNB] >= param_globals::dream.fim.max_addpt;
1375 if (node_is_valid && ((
nReadded2List[indXNB] < param_globals::dream.fim.max_addpt) || ignore_L2_if_valid)) {
1377 if (!std::isfinite(pending_q[indXNB]) || qNB < pending_q[indXNB]) {
1378 pending_q[indXNB] = qNB;
1379 pending_src[indXNB] = indX;
1389 unmask_untrusted(indX);
1394 for (
const auto& vr : verifyResults) {
1401 T_A[indX] = vr.ta_verified;
1403 check_past_activation(indX);
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;
1419 SF_real qNB = pending_q[indXNB];
1427 check_past_activation(indXNB);
1434 if (param_globals::dream.
output.debugNode == indXNB) {
1445 update_Ta_in_active_list();
1447 if (
actMIN > actMIN_old) {
1448 progress_time =
actMIN - actMIN_old;
1453 time2stop_eikonal -= progress_time;
1460 stalled_iterations = (progress_time > 0) ? 0 : stalled_iterations + 1;
1462 if (stalled_iterations > 2 * param_globals::dream.fim.max_iter) {
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.",
1483 double* atc =
AT->
ptr();
1484 double* rpt =
RT->
ptr();
1485 for (
size_t i = 0; i < alg_nod.
size(); i++) {
1499 auto dur =
timing(t1, t0);
1509 if (param_globals::dream.
output.debugNode >= 0) {
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);
1530 SF_real eikonal_solver::update_impl(
mesh_int_t& indX,
SF_real CVrest_factor,
bool CheckValidity,
bool convergedOnly)
1542 std::array<int, 4> winning_ids;
1543 size_t winning_count = 0;
1550 std::array<SF::Point, N> base;
1551 std::array<double, N> values;
1552 std::array<int, N> nodeIDs;
1555 for (std::size_t j = 0; j < N; j++) {
1556 int n_i =
e2n_con[indEle + j];
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];
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;
1574 double cv =
CV_L[Elem_i] * CVrest_factor;
1576 is_not_valid_update<N>(nodeIDs, time, e_i, cv, convergedOnly);
1583 if (!CheckValidity || !is_not_valid_update<N>(nodeIDs, time, e_i, cv, convergedOnly)) {
1584 LocalSolver<N> solver(D, base, values);
1586 SF_real H = compute_H(indX, tmp);
1591 if (
min > tmp && tmp >
T_R[indX] && H > 0.0) {
1594 std::copy_n(nodeIDs.begin(), N, winning_ids.begin());
1603 const bool previous_wave_in_simplex = CheckValidity && std::isfinite(tmp) && tmp <=
T_R[indX];
1604 if (!previous_wave_in_simplex)
continue;
1610 if constexpr (N - 1 == 3) {
1612 for (
int i = 0; i < (N - 1); ++i) {
1613 for (
int j = i + 1; j < (N - 1); ++j) {
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;
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]};
1621 LocalSolver<3> solver(D, tri_pts, tri_vals);
1624 SF_real H = compute_H(indX, tmp);
1629 if (
min > tmp && tmp >
T_R[indX] && H > 0.0) {
1632 std::copy_n(tri_ids.begin(), 3, winning_ids.begin());
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;
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]};
1649 LocalSolver<2> solver(D, edge_pts, edge_vals);
1651 SF_real H = compute_H(indX, tmp);
1656 if (
min > tmp && tmp >
T_R[indX] && H > 0.0) {
1659 std::copy_n(edge_ids.begin(), 2, winning_ids.begin());
1671 winning_ids.data(), winning_count,
min, winning_H, -1);
1683 bool eikonal_solver::is_not_valid_update(
const std::array<int, N>& nodeIDs,
double time,
int e_i,
double cv,
bool convergedOnly)
1685 const int target = nodeIDs[N - 1];
1693 for (
int i = 0; i < N - 1; i++) {
1694 const int nb = nodeIDs[i];
1696 bool neighborActivationTimeInvalid =
false;
1697 bool neighborTimePrevCycle =
false;
1698 bool conductionVelocityZero =
false;
1699 bool stimulatedNodeActivatesFailedOne =
false;
1700 bool neighborNotYetConverged =
false;
1705 if (std::isinf(
T_A[nb]))
1706 neighborActivationTimeInvalid =
true;
1708 if (
T_A[nb] <
T_R[nb] &&
T_R[nb] < time)
1709 neighborTimePrevCycle =
true;
1715 if (convergedOnly &&
List[nb] == 1)
1716 neighborNotYetConverged =
true;
1719 stimulatedNodeActivatesFailedOne =
true;
1722 conductionVelocityZero =
true;
1724 if (neighborActivationTimeInvalid ||
1725 neighborTimePrevCycle ||
1726 conductionVelocityZero ||
1727 stimulatedNodeActivatesFailedOne ||
1728 neighborNotYetConverged) {
1730 std::array<int, 5> conditions = {
1731 neighborActivationTimeInvalid,
1732 neighborTimePrevCycle,
1733 conductionVelocityZero,
1734 stimulatedNodeActivatesFailedOne,
1735 neighborNotYetConverged};
1740 conditions.data(), conditions.size(),
1752 void eikonal_solver::record_D_I(
mesh_int_t indX)
1760 if (!std::isfinite(ta) ||
T_R[indX] == -400.0 ||
T_R[indX] > ta)
return;
1762 D_I[indX] = ta -
T_R[indX];
1769 (
T_R[indX]) == -400.0 ||
1770 std::fabs(tmpTA -
TA_old[indX]) < param_globals::dream.fim.tol ||
1771 T_R[indX] > tmpTA) {
1777 const double DI = tmpTA - (
T_R[indX]);
1781 const double Factor_DI = 1.0 -
rho_cvrest[indX] * std::exp(exponent);
1783 if (Factor_DI <= 0.0) {
1788 return (DI <=
theta_cvrest[indX]) ? -Factor_DI : Factor_DI;
1795 SF_real q = update(indX, scaling,
true, convergedOnly);
1797 for (
int niter = 0; niter < param_globals::dream.fim.max_coh; ++niter) {
1798 scaling = compute_H(indX, p);
1799 q = update(indX, std::fabs(scaling),
true, convergedOnly);
1801 if (std::fabs(p - q) < param_globals::dream.fim.tol || !std::isfinite(q))
1817 if (TA >
T_A[node]) {
1827 void eikonal_solver::warn_zero_strength_stimulus(
int stim_idx,
SF_real stimTime)
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);
1838 void eikonal_solver::set_unsuccessful_stimulus(
mesh_int_t node,
size_t stimIndex,
SF_real stimTime)
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"
1872 (*stimuliRef)[stim_idx].name.c_str(), stimTime,
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"
1883 void eikonal_solver::check_past_activation(
mesh_int_t indX)
1886 if (!(
T_A[indX] < now))
return;
1888 constexpr
long long max_reported = 20;
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,
1899 void eikonal_solver::set_active(
mesh_int_t i)
1907 void eikonal_solver::clear_active(
mesh_int_t i)
1915 void eikonal_solver::mask_untrusted(
mesh_int_t i)
1920 void eikonal_solver::unmask_untrusted(
mesh_int_t i)
1925 void eikonal_solver::activate_neighbors(
mesh_int_t& node)
1929 if (
List[nb] == 0) {
1936 void eikonal_solver::compute_bc(
const Ionics& ion,
bool EmptyList,
SF_real time_upper_bound)
1949 SF_real stimTimeUpperBound = time_upper_bound;
1963 auto capture = [&](
size_t row,
SF_real TA) {
1966 set_successful_stimulus(indNode, TA);
1967 if (s.phys.type ==
I_tm && std::fabs(s.pulse.strength) > 1e-9) {
1971 activate_neighbors(indNode);
1979 if (
List[indNode] == 1) {
1980 clear_active(indNode);
1983 for (
int ii =
n2n_dsp[indNode]; ii <
n2n_dsp[indNode + 1]; ++ii) {
1995 std::vector<size_t> cand_rows;
1996 std::vector<mesh_int_t> subthreshold;
2003 if (stimTime > stimTimeUpperBound) {
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;
2012 if (!(can_activate && can_propagate)) {
2013 set_unsuccessful_stimulus(indNode, j, stimTime);
2018 if (s.phys.type !=
I_tm) {
2019 capture(j, stimTime);
2022 if (std::fabs(s.pulse.strength) < 1e-9) {
2026 subthreshold.push_back(indNode);
2031 cand_rows.push_back(j);
2039 if (cand_rows.empty()) {
2040 for (
mesh_int_t node : subthreshold) set_active(node);
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++) {
2051 if (std::isfinite(t_up[k])) {
2052 capture(cand_rows[k], t_up[k]);
2057 subthreshold.push_back(node);
2060 for (
mesh_int_t node : subthreshold) set_active(node);
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)
2067 t_up.assign(rows.size(),
inf);
2068 if (vm_end) vm_end->assign(rows.size(), 0.0);
2071 int max_threads = omp_get_max_threads();
2072 omp_set_num_threads(1);
2079 const double thresh = param_globals::dream.depol_time_thresh;
2081 for (
int i = 0; i < miif->
N_IIF; i++) {
2082 if (!miif->
N_Nodes[i])
continue;
2085 std::vector<limpet::IonIfBase*> imps{miif->
IIF[i]};
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__);
2093 imps[m]->get_sv_layout(layouts[m]);
2095 auto** ldata = miif->
ldata[i];
2096 using data_t = std::remove_reference_t<decltype(ldata[0][0])>;
2098 for (
int current = 0; current < static_cast<int>(miif->
N_Nodes[i]); current++) {
2102 if (k < 0)
continue;
2103 const size_t row = rows[k];
2104 const bool with_idiff = idiff_TA !=
nullptr;
2109 long d_on = 0, d_dur = 0;
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);
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]);
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)];
2132 for (
int sub = 0; sub < miif->
numSubDt; sub++) {
2134 vm += iion * (-miif->
dt);
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;
2140 if (vm_start <= thresh && vm > thresh && !std::isfinite(t_up[k])) {
2142 if (!with_idiff)
break;
2145 if (vm_end) (*vm_end)[k] = vm;
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; });
2152 for (
int d = 0; d < NUM_IMP_DATA_TYPES; d++)
2153 if (ldata[d]) ldata[d][current] = data_backup[pos++];
2158 omp_set_num_threads(max_threads);
2163 void eikonal_solver::reject_non_firing_activations(
const Ionics& ion, std::vector<mesh_int_t>& converged)
2171 std::vector<mesh_int_t> nodes;
2172 std::vector<size_t> rows;
2173 std::vector<SF_real> idiff_TA;
2180 idiff_TA.push_back(
T_A[n]);
2182 if (nodes.empty())
return;
2184 std::vector<SF_real> t_up, vm_end;
2185 predict_upstroke(ion, rows, t_up, &idiff_TA, &vm_end);
2187 std::vector<mesh_int_t> rejected;
2188 for (
size_t k = 0; k < nodes.size(); k++) {
2191 if (vm_end[k] > param_globals::dream.depol_time_thresh)
continue;
2196 rejected.push_back(n);
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(); }),
2207 const double tau_s = param_globals::dream.tau_s;
2212 if (!active_node_list_is_empty) {
2223 if (no_more_stimuli) {
2229 if (time_to_next_stimulus > tau_s) {
2236 void eikonal_solver::update_Ta_in_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();
2247 for (
size_t j = 0; j <
List.size(); j++) {
2248 if (
T_A[j] < 0 || !std::isfinite(
T_A[j]))
continue;
2250 if (
List[j] == 1 &&
T_A[j] < min_TA_in_active_list) {
2251 min_TA_in_active_list =
T_A[j];
2254 if ((
List[j] == 1 ||
T_A[j] >= now) &&
T_A[j] > max_relevant) {
2255 max_relevant =
T_A[j];
2259 if (std::isfinite(min_TA_in_active_list)) {
2260 actMIN = min_TA_in_active_list;
2263 SF_real min_TA_anywhere = std::numeric_limits<double>::infinity();
2265 for (
size_t j = 0; j <
List.size(); j++) {
2266 if (std::isfinite(
T_A[j]) &&
2268 T_A[j] < min_TA_anywhere) {
2269 min_TA_anywhere =
T_A[j];
2272 actMIN = std::isfinite(min_TA_anywhere) ? min_TA_anywhere : now;
2275 actMAX = std::isfinite(max_relevant) ? max_relevant : now;
2280 for (
size_t j = 0; j <
List.size(); j++) {
2300 return ((
RT < newTA) && (newTA < oldTA)) ||
2301 ((oldTA <
RT) && (
RT < newTA));
2309 const double thresh = param_globals::dream.repol_time_thresh;
2313 for (
size_t i = 0; i < alg_nod.
size(); i++) {
2315 bool crossed_threshold = (old_ptr[i] >= thresh && new_ptr[i] < thresh);
2322 if (crossed_threshold && time >=
T_R[n]) {
2337 int max_threads = omp_get_max_threads();
2338 omp_set_num_threads(1);
2346 threshold = param_globals::dream.repol_time_thresh;
2348 for (
int i = 0; i < miif->
N_IIF; i++) {
2349 if (!miif->
N_Nodes[i])
continue;
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;
2366 const double stim_begin =
stim_start[loc_nodal_idx];
2367 const double stim_end = stim_begin +
stim_duration[loc_nodal_idx];
2370 bool should_check_repolarization =
false;
2372 should_check_repolarization =
2373 T_R[loc_nodal_idx] <=
T_A[loc_nodal_idx] &&
2374 T_A[loc_nodal_idx] !=
inf &&
2379 should_check_repolarization =
2381 (Vm_old > threshold || std::fabs(
stim_strength[loc_nodal_idx]) > 1e-9);
2383 if (should_check_repolarization) {
2384 bool activated_node =
false;
2386 for (
double elapsed = dt; elapsed < MAX_ELAPSED; elapsed += dt) {
2387 const double t_abs = time + elapsed;
2392 double I_stim = 0.0;
2393 if (failed_stim_mode &&
2394 t_abs >= stim_begin &&
2395 t_abs <= stim_end) {
2399 miif->
ldata[i][limpet::Vm][current] -=
2400 (miif->
ldata[i][limpet::Iion][current] - I_stim) * dt;
2402 const double Vm = miif->
ldata[i][limpet::Vm][current];
2404 if (failed_stim_mode &&
2406 t_abs >= stim_end &&
2408 activated_node =
true;
2411 const bool crossed_repol = Vm < threshold;
2412 const bool repol_allowed =
2415 : (
T_R[loc_nodal_idx] < t_abs + RT_SAFETY_MARGIN);
2417 if (crossed_repol && repol_allowed) {
2418 T_R[loc_nodal_idx] = t_abs;
2424 miif->
ldata[i][limpet::Vm][current] = Vm_old;
2425 miif->
ldata[i][limpet::Iion][current] = Iion_old;
2428 }
while (current < miif->N_Nodes[i]);
2433 omp_set_num_threads(max_threads);
2437 auto dur =
timing(t1, t0);
2453 for (
size_t j = 0; j < alg_nod.
size(); j++) {
2457 double TA =
T_A[loc_nodal_idx];
2458 double TAold =
TA_old[loc_nodal_idx];
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);
2463 if (!time_in_TA_window && !time_in_TAold_window)
2466 if (time_in_TA_window)
2471 c[loc_petsc_idx] = idiff_template(
diff_cur[loc_nodal_idx], dT, v[loc_petsc_idx]);
2482 switch (node.model) {
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);
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;
2499 mesh_int_t idx = param_globals::dream.output.detailed_debugNode;
2501 if (idx < 0 || idx != ind_target)
return;
2504 const char* tag =
nullptr;
2505 switch (debug_case) {
2518 default: tag =
"UNKNOWN DEBUG CASE";
break;
2522 for (
int i = 0; i < 5; i++) {
2523 fprintf(fp,
"\n ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n");
2525 fprintf(fp,
"\n================= %s =================\n", tag);
2526 fprintf(fp,
"Target Node Index : %d\n", idx);
2529 fprintf(fp,
"Entered List from Neighbor : %d (Converged Node)\n", index_ref);
2531 fprintf(fp,
"Failed to Enter from Neighbor : %d (Converged Node)\n", index_ref);
2533 fprintf(fp,
"Entered List from Neighbor : %d (Stimulated Node)\n", index_ref);
2537 auto print_time = [&](
double value) {
2539 if (std::isinf(value))
2540 snprintf(time_str,
sizeof time_str,
"inf");
2542 snprintf(time_str,
sizeof time_str,
"%6.2f", value);
2543 return std::string(time_str);
2547 std::string stim_status_str;
2551 stim_status_str =
"Stimulation Status : Not attempted";
2555 stim_status_str =
"Stimulation Status : Successfully stimulated";
2559 stim_status_str =
"Stimulation Status : Attempted, not successful";
2563 stim_status_str =
"Stimulation Status : Attempted, cell predicted not to fire";
2567 stim_status_str =
"Stimulation Status : Unknown";
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]),
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])};
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)};
2589 fprintf(fp,
"\n%-42s%-42s%-40s\n",
2590 "==== Activation & Recovery ====",
2591 "==== List Status ====",
2592 "==== Global & List Metrics ====");
2595 for (
int i = 0; i < 4; ++i) {
2596 fprintf(fp,
"%-42s", left_col[i].c_str());
2598 fprintf(fp,
"%-42s%-40s\n", center_col[i].c_str(), right_col[i].c_str());
2600 fprintf(fp,
"%-42s%-40s\n",
"",
"");
2603 fprintf(fp,
"--------------------------------------------------------------------------\n");
2609 mesh_int_t idx = param_globals::dream.output.detailed_debugNode;
2610 if (idx < 0 || idx != indX)
return;
2613 const char* result_str =
nullptr;
2618 default: result_str =
"Unknown";
break;
2622 auto print_time = [&](
double value) {
2624 if (std::isinf(value))
2625 snprintf(time_str,
sizeof time_str,
"inf");
2627 snprintf(time_str,
sizeof time_str,
"%6.2f", value);
2628 return std::string(time_str);
2632 for (
int i = 0; i < 5; i++) {
2633 fprintf(fp,
"\n ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n");
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");
2646 mesh_int_t idx = param_globals::dream.output.detailed_debugNode;
2648 if (idx < 0 || idx != ind_target)
return;
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");
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]);
2663 int positive_count = std::count_if(contributors, contributors + num_contributors, [](
int x) {
return x >= 0; });
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;
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]);
2681 if (candidate_scaling_CV < 0.0) {
2682 fprintf(fp,
" CV is unfeasible (likely below propagation threshold).\n");
2686 const char* type_tag =
nullptr;
2693 default: type_tag =
"UNKNOWN";
break;
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");
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]);
2704 fprintf(fp,
"[%s #%d]\n", type_tag, counter);
2706 fprintf(fp,
"[%s #%d] \n", type_tag, counter);
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]]);
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);
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]);
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");
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;
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]);
2739 if (num_contributors != num_reasons) {
2740 fprintf(fp,
" • (caller reported %zu rejection grounds, this logger knows %zu)\n",
2741 num_contributors, num_reasons);
2754 char buffer_writestate[1024];
2755 snprintf(buffer_writestate,
sizeof buffer_writestate,
"%s.dat", roe_fnm);
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);
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");
2771 for (
size_t j = 0; j <
List.size(); ++j) {
2777 for (
size_t j = 0; j <
List.size(); ++j) {
2784 const double tolerance = 1e-6;
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];
2792 double outTA, outTR, outTA_old;
2793 int outList, outNumCh, outNumCh2;
2799 if (!std::isfinite(orig_TA) || orig_TA <= save_time + tolerance || captured_by_started_pulse) {
2803 outTA_old = orig_TA_old;
2810 outTA = std::numeric_limits<double>::infinity();
2811 outTA_old = std::numeric_limits<double>::infinity();
2813 if (std::isfinite(orig_TA_old)) {
2814 outTR = orig_TA - orig_DI;
2829 fprintf(file_writestate,
"%d %d %d %.17g %.17g %.17g %.17g\n",
2830 outList, outNumCh, outNumCh2, outTA, outTR, outTA_old, outDI);
2834 "Saved DREAM eikonal state at time %.6f into %s\n",
2835 save_time, buffer_writestate);
2837 fclose(file_writestate);
2840 void eikonal_solver::load_state_file()
2843 FILE* file_startstate;
2844 char buffer_startstate[strlen(param_globals::start_statef) + 10];
2846 snprintf(buffer_startstate,
sizeof buffer_startstate,
"%s.dat", param_globals::start_statef);
2847 file_startstate = fopen(buffer_startstate,
"r");
2849 if (file_startstate == NULL) {
2850 log_msg(NULL, 5, 0,
"Not able to open state file: %s", buffer_startstate);
2852 }
else if (param_globals::output_level) {
2853 log_msg(NULL, 0, 0,
"Open state file for eikonal model: %s", buffer_startstate);
2858 long long header_num_pts = -1;
2861 long pos = ftell(file_startstate);
2862 while (fgets(linebuf,
sizeof linebuf, file_startstate)) {
2863 if (linebuf[0] ==
'#') {
2865 sscanf(linebuf,
"# num_pts %lld", &header_num_pts);
2868 if (sscanf(linebuf,
"# captured_stim %lld %lf %lf", &node, &onset, &TA) == 3 && node >= 0 &&
2869 node <
static_cast<long long>(
List.size())) {
2873 if (sscanf(linebuf,
"# noncapturing_stim %lld %lf", &node, &onset) == 2 && node >= 0 &&
2874 node <
static_cast<long long>(
List.size()))
2876 pos = ftell(file_startstate);
2879 fseek(file_startstate, pos, SEEK_SET);
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);
2896 const long long expected_num_pts =
static_cast<long long>(
List.size());
2897 if (header_num_pts != expected_num_pts) {
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);
2905 int ListVal, numChangesVal, numChanges2Val;
2906 double T_AVal, T_RVal, TA_oldVal, D_IVal;
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) {
2913 if (index >= expected_num_pts) {
2915 "%s error: state file %s contains more rows than the %lld nodes of this mesh. Aborting!",
2916 __func__, buffer_startstate, expected_num_pts);
2920 List[index] = ListVal;
2923 T_A[index] = T_AVal;
2924 T_R[index] = T_RVal;
2925 TA_old[index] = TA_oldVal;
2926 D_I[index] = D_IVal;
2930 fclose(file_startstate);
2934 if (index != expected_num_pts) {
2936 "%s error: state file %s contains %d rows, but this mesh has %lld nodes. Aborting!",
2937 __func__, buffer_startstate, index, expected_num_pts);
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;
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) {
2949 for (
int n = 0; n <
MESH_SIZE && !has_inf_neighbor; ++n) {
2951 if (nb !=
static_cast<mesh_int_t>(i) && std::isinf(
T_A[nb])) {
2952 has_inf_neighbor =
true;
2956 if (has_inf_neighbor) {
2964 for (
mesh_int_t node_idx : wavefront_nodes) {
2969 std::vector<char> is_wavefront(
List.size(), 0);
2970 for (
mesh_int_t node_idx : wavefront_nodes) {
2971 is_wavefront[node_idx] = 1;
2975 for (
mesh_int_t node_idx : wavefront_nodes) {
2977 for (
int e_i =
n2e_dsp[node_idx]; e_i <
n2e_dsp[node_idx + 1]; e_i++) {
2989 if (neighbor != node_idx &&
2990 !is_wavefront[neighbor] &&
2992 List[neighbor] == 0) {
2993 set_active(neighbor);
3003 if (!wavefront_nodes.empty()) {
3004 actMIN = std::numeric_limits<double>::infinity();
3005 for (
mesh_int_t node_idx : wavefront_nodes) {
3014 update_Ta_in_active_list();
3016 if (param_globals::output_level) {
3018 log_msg(NULL, 0, 0,
"Number of nodes in active list: %i",
sum(
List));
3026 const char* h1 =
" ------ ---------- ---------- ------- ------- | List logic ----- -------- | Neighbor node ---- |";
3027 const char* h2 =
" cycle AT old AT RT DI | Status Entry Exit | ID AT |";
3030 log_msg(NULL, 3, 0,
"%s error: Could not open file %s in %s. Turning off logging.\n",
3040 if (!this->logger)
return;
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;
3055 snprintf(cbuf,
sizeof cbuf,
"%7s %10s",
"-",
"-");
3057 snprintf(cbuf,
sizeof cbuf,
"%7lld %10s",
static_cast<long long>(this->
idXNB), oss_nbnTA.str().c_str());
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());
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);
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();
3082 const char* stat_str;
3083 const char* reas_str;
3104 template <
int MESH_SIZE>
3110 const double& u1 = values[0];
3112 if constexpr (MESH_SIZE == 2) {
3113 return tsitsiklis_update_line({x1, x2}, D, u1);
3115 }
else if constexpr (MESH_SIZE == 3) {
3117 const double& u2 = values[1];
3118 return tsitsiklis_update_triangle({x1, x2, x3}, D, {u1, u2});
3120 }
else if constexpr (MESH_SIZE == 4) {
3123 const double& u2 = values[1];
3124 const double& u3 = values[2];
3126 double u_tet = tsitsiklis_update_tetra({x1, x2, x3, x4}, D, {u1, u2, u3});
3128 u_tet = std::numeric_limits<double>::infinity();
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});
3135 double u_tri =
std::min({u_face1, u_face2, u_face3});
3140 template <
int MESH_SIZE>
3143 const double& value)
3151 template <
int MESH_SIZE>
3152 double LocalSolver<MESH_SIZE>::tsitsiklis_update_triangle(
const std::array<SF::Point, 3>& base,
3154 const std::array<double, 2>& values)
3159 const double& u1 = values[0];
3160 const double& u2 = values[1];
3161 double result = std::numeric_limits<double>::infinity();
3174 double denominator = p11 - k * k;
3175 double sqrt_val = (p11 * p22 - p12 * p12) / denominator;
3177 if (denominator > 1e-12) {
3178 const double sqrt_val = (p11 * p22 - p12 * p12) / denominator;
3179 if (sqrt_val >= 0.0) {
3180 const double rhs = k * std::sqrt(sqrt_val);
3181 double alpha1 = -(p12 + rhs) / p11;
3182 double alpha2 = -(p12 - rhs) / p11;
3187 for (
double alpha : {alpha1, alpha2}) {
3188 SF::Point x_interp = x1 * alpha + x2 * (1.0 - alpha);
3191 double u3 = alpha * u1 + (1.0 - alpha) * u2 + norm_D;
3198 double u_edge1 = tsitsiklis_update_line({x1, x3}, D, u1);
3199 double u_edge2 = tsitsiklis_update_line({x2, x3}, D, u2);
3201 return std::min({result, u_edge1, u_edge2});
3204 template <
int MESH_SIZE>
3205 double LocalSolver<MESH_SIZE>::tsitsiklis_update_tetra(
const std::array<SF::Point, 4>& base,
3207 const std::array<double, 3>& values)
3214 const double& u1 = values[0];
3215 const double& u2 = values[1];
3216 const double& u3 = values[2];
3223 const double k1 = u1 - u3;
3224 const double k2 = u2 - u3;
3233 const double r21 = r12;
3236 const double r31 = r13;
3237 const double r32 = r23;
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;
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);
3256 double alpha1 = -(p12 + rhs) / p11;
3257 double alpha2 = -(B + alpha1 * A1) / A2;
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)) {
3267 }
else if ((std::abs(A1) > EPS) && (std::abs(A2) < EPS)) {
3272 double alpha3 = 1 - alpha1 - alpha2;
3273 const SF::Point dist = x4 - (alpha1 * x1 + alpha2 * x2 + alpha3 * x3);
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();
opencarp::local_index_t mesh_int_t
opencarp::real_t SF_real
Global scalar type.
Starts and stops the linear algebra backend the flavor parameter selects.
#define EXIT(A)
finalize the backend, if it runs, and exit
Basic utility structs and functions, mostly IO related.
virtual void write(const char *filename) const =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
vector< T > dsp
connectivity starting index of each element
vector< S > she
sheet direction
vector< elem_t > type
element type
vector< S > xyz
node cooridnates
size_t l_numpts
local number of points
size_t size() const
The current size of the vector.
void resize(size_t n)
Resize a vector.
const T * end() const
Pointer to the vector's end.
void assign(InputIterator s, InputIterator e)
Assign a memory range.
const T * begin() const
Pointer to the vector's start.
Represents the ionic model and plug-in (IMP) data structure.
const IonType & get_type() const
Gets this IMP's model type.
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.
Target get_target() const
node_count_t get_num_node() const
Gets the number of nodes handled by this IMP.
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
opencarp::sf_vec * gdata[NUM_IMP_DATA_TYPES]
data used by all IMPs
std::vector< IonTypeList > plugtypes
plugins types for each region
void dump_state(char *, float, opencarp::mesh_t gid, bool, unsigned int)
GlobalData_t *** ldata
data local to each IMP
int N_IIF
how many different IIF's
node_count_t * N_Nodes
#nodes for each IMP
int numSubDt
number of sub-dt time steps
node_index_t ** NodeLists
local partitioned node lists for each IMP stored
int timer_idx
the timer index received from the timer manager
FILE_SPEC logger
The logger of the physic, each physic should have one.
const char * name
The name of the physic, each physic should have one.
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
int check_quiescence(double tm, double dt)
check for quiescence
void output_initial_activations()
output one nodal vector of initial activation time
void init(sf_vec &vm, sf_vec &phie, int offset, enum physic_t=elec_phys)
initializes all datastructs after electric solver setup
int check_acts(double tm)
check activations at sim time tm
std::vector< bool > stim_failed_now
SF::vector< SF_real > captured_onset
mesh_int_t num_active_nodes
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
FILE_SPEC deepDebugLogger
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
bool detailed_debug_enabled
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
long long num_past_activations
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
void close_files_and_cleanup()
close file descriptors
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.
sf_mat * rhs_parab
rhs matrix to solve parabolic
void rebuild_matrices(MaterialType *mtype, limpet::MULTI_IF &miif, FILE_SPEC logger)
void solve(sf_vec &phie_i)
sf_mat * mass_i
lumped for parabolic problem
sf_mat * lhs_parab
lhs matrix (CN) to solve parabolic
sf_vec * Vmv
global Vm vector
sf_vec * old_vm
older Vm needed for 2nd order dT
int write_trace()
write traces to file
SF::vector< mesh_int_t > vertices
stim_t type
type of stimulus
int npls
number of stimulus pulses
double pcl
pacing cycle length
double start
start time of protocol
sig::time_trace wave
wave form of stimulus pulse
stim_protocol ptcl
applied stimulation protocol used
stim_electrode electrode
electrode geometry
stim_pulse pulse
stimulus wave form
void translate(int id)
convert legacy definitions to new format
bool is_active() const
Return whether stim is active.
void setup(int idx)
Setup from a param stimulus index.
void dump_vtx_file(int idx)
Export the vertices to vtx file.
stim_physics phys
physics of stimulus
std::string name
label stimulus
double time_step
global reference time step
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.
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.
double inner_prod(const Point &a, const Point &b)
T sum(const vector< T > &vec)
Compute sum of a vector's entries.
void count(const vector< T > &data, vector< S > &cnt)
Count number of occurrences of indices.
void outer_prod(const Point &a, const Point &b, const double s, double *buff, const bool add=false)
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)
V clamp(const V val, const W start, const W end)
Clamp a value into an interval [start, end].
void cnt_from_dsp(const std::vector< T > &dsp, std::vector< T > &cnt)
Compute counts from displacements.
void dsp_from_cnt(const std::vector< T > &cnt, std::vector< T > &dsp)
Compute displacements from counts.
constexpr T min(T a, T b)
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
bool using_legacy_stimuli
flag storing whether legacy stimuli are used
void region_mask(mesh_t meshspec, SF::vector< RegionSpecs > ®spec, SF::vector< int > ®ionIDs, bool mask_elem, const char *reglist, FILE_SPEC logger)
classify elements/points as belonging to a region
int stimidx_from_timeridx(const SF::vector< stimulus > &stimuli, const int timer_id)
determine link between timer and stimulus
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.
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 ...
int get_size(MPI_Comm comm=SF_COMM)
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
void apply_stim_to_vector(const stimulus &s, sf_vec &vec, bool add)
vec3< V > cross(const vec3< V > &a, const vec3< V > &b)
V dist(const vec3< V > &p1, const vec3< V > &p2)
void init_stim_info(void)
uses potential for stimulation
FILE_SPEC f_open(const char *fname, const char *mode)
Open a FILE_SPEC.
SF::scattering * register_permutation(const int mesh_id, const int perm_id, const int dpn)
Register a permutation between two orderings for a mesh.
void init_sv_gvec(gvec_data &GVs, limpet::MULTI_IF *miif, sf_vec &tmpl, igb_output_manager &output_manager)
void assemble_sv_gvec(gvec_data &gvecs, limpet::MULTI_IF *miif)
void dump_region_mask(mesh_t meshspec, const SF::vector< int > ®ionIDs, const char *reglist)
dump a nodal region mask as produced by region_mask() to reglist+".dat"
char * dupstr(const char *old_str)
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
mesh_t
The enum identifying the different meshes we might want to load.
void get_time(double &tm)
bool mesh_is_registered(const mesh_t gt)
check wheter a SF mesh is set
SF::abstract_vector< SF_int, SF_real > sf_vec
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)
const char * get_tsav_ext(double time)
int get_rank(MPI_Comm comm=SF_COMM)
V timing(V &t2, const V &t1)
void f_close(FILE_SPEC &f)
Close a FILE_SPEC.
#define PETSC_TO_CANONICAL
Permute algebraic data from PETSC to canonical ordering.
#define ALG_TO_NODAL
Scatter algebraic to nodal.
Electrical stimulation functions.
description of materal properties in a mesh
SF::vector< RegionSpecs > regions
array with region params
SF::vector< double > el_scale
optionally provided per-element params scale
int el_scale_dpn
0=disabled, 1=isotropic scalar, 3=anisotropic (sl, st, sn) per element
region based variations of arbitrary material parameters
physMaterial * material
material parameter description
int nsubregs
#subregions forming this region
int * subregtags
FEM tags forming this region.
char * regname
name of region
double slvtime_A
total time in Step A
double maxAD
DREAM: time horizon this sweep batch may search up to. Pure Eikonal: actual latest activation time re...
void log_stats(double time, bool cflg)
double minAT
minimum activation time in current solve
int activeList
number of nodes currently in list
void update_iter(const int curiter)
double slvtime_B
total time in Step B
void init_logger(const char *filename, bool dream_mode)
double slvtime_D
total time in Step D
bool bc_status
boundary conditions were applied?
void update_cli(double time, bool cflg)
void log_stats(double tm, bool cflg)
void init_logger(const char *filename)
int calls
# calls for this interval, this is incremented externally
double tot_time
total time, this is incremented externally
void log_stats(double tm, bool cflg)
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.
void update_status(enum status s, enum reason r)