openCARP
Doxygen code documentation for the open cardiac electrophysiology simulator openCARP
electrics.cc
Go to the documentation of this file.
1 // ----------------------------------------------------------------------------
2 // openCARP is an open cardiac electrophysiology simulator.
3 //
4 // Copyright (C) 2020 openCARP project
5 //
6 // This program is licensed under the openCARP Academic Public License (APL)
7 // v1.0: You can use and redistribute it and/or modify it in non-commercial
8 // academic environments under the terms of APL as published by the openCARP
9 // project v1.0, or (at your option) any later version. Commercial use requires
10 // a commercial license (info@opencarp.org).
11 //
12 // This program is distributed without any warranty; see the openCARP APL for
13 // more details.
14 //
15 // You should have received a copy of the openCARP APL along with this program
16 // and can find it online: http://www.opencarp.org/license
17 // ----------------------------------------------------------------------------
18 
26 #include <cstring>
27 #include "electrics.h"
28 #include "petsc_utils.h"
29 #include "timers.h"
30 #include "stimulate.h"
31 #include "electric_integrators.h"
32 
33 #include "SF_init.h" // for SF::init_xxx()
34 
35 #ifdef WITH_CALIPER
36 #include "caliper/cali.h"
37 #else
38 #include "caliper_hooks.h"
39 #endif
40 
41 
42 namespace opencarp {
43 
45 {
47  double t1, t2;
48  get_time(t1);
49 
50  set_dir(OUTPUT);
51 
52  // open logger
53  logger = f_open("electrics.log", param_globals::experiment != 4 ? "w" : "a");
54 
55  // setup mappings between extra and intra grids, algebraic and nodal,
56  // and between PETSc and canonical orderings
57  setup_mappings();
58 
59  // the ionic physics is currently triggered from inside the Electrics to have tighter
60  // control over it
61  ion.logger = logger;
62  ion.initialize();
63 
64  // set up Intracellular tissue
66  region_mask(intra_elec_msh, mtype[intra_grid].regions, mtype[intra_grid].regionIDs, true, "gregion_i");
67 
68  if (param_globals::bidomain || param_globals::extracell_monodomain_stim) {
69  // set up Extracellular tissue
71  region_mask(extra_elec_msh, mtype[extra_grid].regions, mtype[extra_grid].regionIDs, true, "gregion_e");
72  }
73 
74  // add electrics timer for time stepping, add to time stepper tool (TS)
75  double global_time = user_globals::tm_manager->time;
76  timer_idx = user_globals::tm_manager->add_eq_timer(global_time, param_globals::tend, 0,
77  param_globals::dt, 0, "elec::ref_dt", "TS");
78 
79  // electrics stimuli setup
80  setup_stimuli();
81 
82  // set up the linear equation systems. this needs to happen after the stimuli have been
83  // set up, since we need boundary condition info
84  setup_solvers();
85 
86  // the next setup steps require the solvers to be set up, since they use the matrices
87  // generated by those
88 
89  // balance electrodes, we may need the extracellular mass matrix
90  balance_electrodes();
91  // total current scaling
93  // initialize the LATs detector
95 
96  // initialize phie recovery data
97  if(strlen(param_globals::phie_rec_ptf) > 0)
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  if (param_globals::prepacing_bcl > 0)
105  prepace();
106  this->initialize_time += timing(t2, t1);
107 }
108 
110 {
111  MaterialType *m = mtype+g;
112 
113  // initialize random conductivity fluctuation structure with PrM values
114  m->regions.resize(param_globals::num_gregions);
115 
116  const char* grid_name = g == Electrics::intra_grid ? "intracellular" : "extracellular";
117  log_msg(logger, 0, 0, "Setting up %s tissue properties for %d regions ..", grid_name,
118  param_globals::num_gregions);
119 
120  char buf[64];
121  RegionSpecs* reg = m->regions.data();
122 
123  for (size_t i=0; i<m->regions.size(); i++, reg++) {
124  if(!strcmp(param_globals::gregion[i].name, "")) {
125  snprintf(buf, sizeof buf, ", gregion_%d", int(i));
126  param_globals::gregion[i].name = dupstr(buf);
127  }
128 
129  reg->regname = strdup(param_globals::gregion[i].name);
130  reg->regID = i;
131  reg->nsubregs = param_globals::gregion[i].num_IDs;
132  if(!reg->nsubregs)
133  reg->subregtags = NULL;
134  else {
135  reg->subregtags = new int[reg->nsubregs];
136  for (int j=0;j<reg->nsubregs;j++) {
137  reg->subregtags[j] = param_globals::gregion[i].ID[j];
138  if(reg->subregtags[j]==-1)
139  log_msg(NULL,3,ECHO, "Warning: not all %u IDs provided for gregion[%u]!\n", reg->nsubregs, i);
140  }
141  }
142 
143  // describe material in given region
144  elecMaterial *emat = new elecMaterial();
145  emat->material_type = ElecMat;
146 
147  emat->InVal[0] = param_globals::gregion[i].g_il;
148  emat->InVal[1] = param_globals::gregion[i].g_it;
149  emat->InVal[2] = param_globals::gregion[i].g_in;
150 
151  emat->ExVal[0] = param_globals::gregion[i].g_el;
152  emat->ExVal[1] = param_globals::gregion[i].g_et;
153  emat->ExVal[2] = param_globals::gregion[i].g_en;
154 
155  emat->BathVal[0] = param_globals::gregion[i].g_bath;
156  emat->BathVal[1] = param_globals::gregion[i].g_bath;
157  emat->BathVal[2] = param_globals::gregion[i].g_bath;
158 
159  // convert units from S/m -> mS/um
160  for (int j=0; j<3; j++) {
161  emat->InVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
162  emat->ExVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
163  emat->BathVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
164  }
165  reg->material = emat;
166  }
167 
168  {
170  const char* file = g == Electrics::intra_grid ? param_globals::gi_scale_vec : param_globals::ge_scale_vec;
171  if (strlen(file))
172  read_el_scale_vec(file, mt, m->el_scale, m->el_scale_dpn);
173  }
174 }
175 
176 void Electrics::setup_mappings()
177 {
179  bool intra_exits = mesh_is_registered(intra_elec_msh), extra_exists = mesh_is_registered(extra_elec_msh);
180  assert(intra_exits);
181  const int dpn = 1;
182 
183  // It may be that another physic (e.g. ionic models) has already computed the intracellular mappings,
184  // thus we first test their existence
185  if(get_scattering(intra_elec_msh, ALG_TO_NODAL, dpn) == NULL) {
186  log_msg(logger, 0, 0, "%s: Setting up intracellular algebraic-to-nodal scattering.", __func__);
188  }
190  log_msg(logger, 0, 0, "%s: Setting up intracellular PETSc to canonical permutation.", __func__);
192  }
193 
194  // extracellular mappings
195  if(extra_exists) {
196  log_msg(logger, 0, 0, "%s: Setting up extracellular algebraic-to-nodal scattering.", __func__);
198  log_msg(logger, 0, 0, "%s: Setting up extracellular PETSc to canonical permutation.", __func__);
200  log_msg(logger, 0, 0, "%s: Setting up intra-to-extra scattering.", __func__);
202  }
203 
204  bool check_i2e = false;
205  if(check_i2e && extra_exists) {
206  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
207  sf_mesh & extra_mesh = get_mesh(extra_elec_msh);
208  int rank = get_rank();
209 
211 
212  const SF::vector<mesh_int_t> & intra_alg_nod = intra_mesh.pl.algebraic_nodes();
213  const SF::vector<mesh_int_t> & extra_alg_nod = extra_mesh.pl.algebraic_nodes();
214  const SF::vector<mesh_int_t> & extra_petsc_nbr = extra_mesh.get_numbering(SF::NBR_PETSC);
215  const SF::vector<mesh_int_t> & intra_ref_nbr = intra_mesh.get_numbering(SF::NBR_REF);
216  const SF::vector<mesh_int_t> & extra_ref_nbr = extra_mesh.get_numbering(SF::NBR_REF);
217 
218  // TODO(init) : delete these three at the end of this section?
219  sf_vec *intra_testvec; SF::init_vector(&intra_testvec, intra_mesh, 1, sf_vec::algebraic);
220  sf_vec *extra_testvec; SF::init_vector(&extra_testvec, extra_mesh, 1, sf_vec::algebraic);
221  sf_vec *i2e_testvec; SF::init_vector(&i2e_testvec, extra_mesh, 1, sf_vec::algebraic);
222 
223  SF_real* id = intra_testvec->ptr();
224  for(size_t i=0; i<intra_alg_nod.size(); i++) {
225  int lpidx = local_nodal_to_local_petsc(intra_mesh, rank, intra_alg_nod[i]);
226  id[lpidx] = intra_ref_nbr[intra_alg_nod[i]];
227  }
228  intra_testvec->release_ptr(id);
229 
230  SF_real* ed = extra_testvec->ptr();
231  for(size_t i=0; i<extra_alg_nod.size(); i++) {
232  int lpidx = local_nodal_to_local_petsc(extra_mesh, rank, extra_alg_nod[i]);
233  ed[lpidx] = extra_ref_nbr[extra_alg_nod[i]];
234  }
235  extra_testvec->release_ptr(ed);
236 
237  i2e_testvec->set(-1.0);
238  i2e.forward(*intra_testvec, *i2e_testvec);
239 
240  int err = 0;
241  for(size_t i=0; i<extra_alg_nod.size(); i++) {
242  auto id = i2e_testvec->get(i);
243  auto ed = extra_testvec->get(i);
244  if(id > -1 && id != ed)
245  err++;
246  }
247 
248  if(get_global(err, MPI_SUM))
249  log_msg(0,5,0, "Electrics mapping test failed!");
250  else
251  log_msg(0,5,0, "Electrics mapping test succeeded!");
252  }
253 }
254 
256 {
258  double t1, t2;
259  get_time(t1);
260 
261  // if requested, we checkpoint the current state
262  checkpointing();
263 
264  // activation checking
265  const double time = user_globals::tm_manager->time,
266  time_step = user_globals::tm_manager->time_step;
267  lat.check_acts(time);
268  lat.check_quiescence(time, time_step);
269 
270  // I believe that we need to treat the stimuli in two ways:
271  // - Extracellular potential stimuli (this includes ground) affect the
272  // elliptic solver in a more delicate way, as such, there is a dbc_manager
273  // to take care of that.
274  // - Extracellular and Intracellular current stimuli are applied to the rhs vectors
275  // and can be managed by the stimulate() code directly.
276  stimulate_extracellular();
277 
278 if(param_globals::bidomain == BIDOMAIN)
280 
281  clamp_Vm();
282 
283  // compute ionics update
284  ion.compute_step();
285 
286  stimulate_intracellular();
287 
288  // store Vm before parabolic step, the full Ic we compute in the output step
289  if(param_globals::dump_data & DUMP_IC)
291 
292  // solver parabolic system
294 
295  clamp_Vm();
296 
297  if(user_globals::tm_manager->trigger(iotm_console)) {
298  // output lin solver stats
300  if(param_globals::bidomain == BIDOMAIN)
302  }
303  this->compute_time += timing(t2, t1);
304 
305  // since the traces have their own timing, we check for trace dumps in the compute step loop
308 
309 }
310 
312 {
314  double t1, t2;
315  get_time(t1);
316 
317  const double time = user_globals::tm_manager->time,
318  time_step = user_globals::tm_manager->time_step;
319 
320  // for pseudo-bidomain we compute extracellular potential only for output
321  if(param_globals::bidomain == PSEUDO_BIDM) {
324  ellip_solver.stats.log_stats(time, false);
325  }
326 
327  if(param_globals::dump_data & DUMP_IVOL)
329 
330  if(param_globals::bidomain && (param_globals::dump_data & DUMP_IACT)) {
332  }
333 
334  if(param_globals::dump_data & DUMP_IC) {
335  PetscReal *Ic = parab_solver.Ic->ptr(), *Vmv = parab_solver.Vmv->ptr();
336 
337  if (time <= time_step) {
338  for(PetscInt i=0; i < parab_solver.Ic->lsize(); i++)
339  Ic[i] = (Vmv[i] - Vmv[i]) / (-time_step); // first timestep: finite difference = 0 (no previous Vmv available)
340  }
341  else{
342  for(PetscInt i=0; i < parab_solver.Ic->lsize(); i++)
343  Ic[i] = (Ic[i] - Vmv[i]) / (-time_step);
344  }
345 
346 
348  }
349 
350  // recover phie
351  if(phie_rcv.pts.size()) {
353  }
354 
357 
358  double curtime = timing(t2, t1);
359  this->output_time += curtime;
360 
361  IO_stats.calls++;
362  IO_stats.tot_time += curtime;
363 
365  IO_stats.log_stats(time, false);
366 }
367 
372 {
374  // output LAT data
376 
377  // close logger
378  f_close(logger);
379 
380  // close output files
382 
383  // destroy ionics
384  ion.destroy();
385 }
386 
387 void balance_electrode(elliptic_solver & ellip, SF::vector<stimulus> & stimuli, int balance_from, int balance_to)
388 {
389  log_msg( NULL, 0, 0, "Balancing stimulus %d with %d %s-wise.",balance_from, balance_to,
390  is_current(stimuli[balance_from].phys.type) ? "current" : "voltage" );
391 
392  stimulus & from = stimuli[balance_from];
393  stimulus & to = stimuli[balance_to];
394 
395  to.pulse = from.pulse;
396  to.ptcl = from.ptcl;
397  to.phys = from.phys;
398  to.pulse.strength *= -1.0;
399 
400  if (from.phys.type == I_ex)
401  {
402  // if from is total current, skip volume based adjustment of strength
403  // otherwise, calling constant_total_stimulus_current() will undo the balanced scaling of to.pulse.strength
404  // constant_total_stimulus_current() will do the scaling based on the volume
405  if (!from.phys.total_current) {
406  sf_mat& mass = *ellip.mass_e;
407  SF_real vol0 = get_volume_from_nodes(mass, from.electrode.vertices);
409 
410  to.pulse.strength *= fabs(vol0 / vol1);
411  }
412  }
413 }
414 
415 void Electrics::balance_electrodes()
416 {
417  for(int i=0; i<param_globals::num_stim; i++) {
418  if(param_globals::stim[i].crct.balance != -1) {
419  int from = param_globals::stim[i].crct.balance;
420  int to = i;
421 
422  balance_electrode(this->ellip_solver, stimuli, from, to);
423  }
424  }
425 }
426 
427 void Electrics::setup_stimuli()
428 {
429  // initialize basic stim info data (used units, supported types, etc)
430  init_stim_info();
431 
432  stimuli.resize(param_globals::num_stim);
433  for(int i=0; i<param_globals::num_stim; i++)
434  {
435  // construct new stimulus
436  stimulus & s = stimuli[i];
437 
439  s.translate(i);
440 
441  s.setup(i);
442 
443  if (s.electrode.dump_vtx)
444  s.dump_vtx_file(i);
445 
446  if(param_globals::stim[i].pulse.dumpTrace && get_rank() == 0) {
447  set_dir(OUTPUT);
448  s.pulse.wave.write_trace(s.name+".trc");
449  }
450  }
451 }
452 
453 void apply_stim_to_vector(const stimulus & s, sf_vec & vec, bool add)
454 {
455  double val; s.value(val);
456  const SF::vector<mesh_int_t> & idx = s.electrode.vertices;
457  const int rank = get_rank();
458  SF::vector<SF_int> local_idx(idx.size());
459  for (size_t i = 0; i < idx.size(); i++) {
460  local_idx[i] = local_nodal_to_local_petsc(*vec.mesh, rank, idx[i]);
461  }
462  vec.set(local_idx, val, add, true);
463 }
464 
465 void Electrics::stimulate_intracellular()
466 {
467  parabolic_solver & ps = parab_solver;
468 
469  // iterate over stimuli
470  for(stimulus & s : stimuli) {
471  if(s.is_active()) {
472  // for active stimuli, deal with the stimuli-type specific stimulus application
473  switch(s.phys.type)
474  {
475  case I_tm: {
476  if(param_globals::operator_splitting) {
477  apply_stim_to_vector(s, *ps.Vmv, true);
478  }
479  else {
480  SF_real Cm = 1.0;
481  timer_manager & tm = *user_globals::tm_manager;
482  SF_real sc = tm.time_step / Cm;
483 
484  ps.Irhs->set(0.0);
485  apply_stim_to_vector(s, *ps.Irhs, true);
486 
487  *ps.tmp_i1 = *ps.IIon;
488  *ps.tmp_i1 -= *ps.Irhs;
489  *ps.tmp_i1 *= sc; // tmp_i1 = sc * (IIon - Irhs)
490 
491  // add ionic, transmembrane and intracellular currents to rhs
492  if(param_globals::parab_solve != parabolic_solver::EXPLICIT)
493  ps.mass_i->mult(*ps.tmp_i1, *ps.Irhs);
494  else
495  *ps.Irhs = *ps.tmp_i1;
496  }
497  break;
498  }
499 
500  case Illum: {
501  sf_vec* illum_vec = ion.miif->gdata[limpet::illum];
502 
503  if(illum_vec == NULL) {
504  log_msg(0,5,0, "Cannot apply illumination stim: global vector not present!");
505  EXIT(EXIT_FAILURE);
506  } else {
507  apply_stim_to_vector(s, *illum_vec, false);
508  }
509 
510  break;
511  }
512 
513  default: break;
514  }
515  }
516  }
517 }
518 
519 void Electrics::clamp_Vm() {
520  for(stimulus & s : stimuli) {
521  if(s.phys.type == Vm_clmp && s.is_active())
523  }
524 }
525 
526 void Electrics::stimulate_extracellular()
527 {
528  if(param_globals::bidomain) {
529  // we check if the DBC layout changed, if so we recompute the matrix and the dbc_manager
530  bool dbcs_have_updated = ellip_solver.dbc != nullptr && ellip_solver.dbc->dbc_update();
532 
533  if(dbcs_have_updated && time_not_final)
535 
536  ellip_solver.phiesrc->set(0.0);
537 
538  for(const stimulus & s : stimuli) {
539  if(s.is_active() && s.phys.type == I_ex)
541  }
542  }
543 }
544 
546  SF::vector<mesh_int_t> & inp_idx,
548 {
549  int mpi_rank = get_rank(), mpi_size = get_size();
550  const SF::vector<mesh_int_t> & layout = mesh.pl.algebraic_layout();
551 
552  SF::vector<mesh_int_t> sndbuff;
553 
554  size_t buffsize = 0;
555  idx.resize(0);
556 
557  for(int pid=0; pid < mpi_size; pid++) {
558  if(mpi_rank == pid) {
559  sndbuff = inp_idx;
560  buffsize = sndbuff.size();
561  }
562 
563  MPI_Bcast(&buffsize, sizeof(size_t), MPI_BYTE, pid, PETSC_COMM_WORLD);
564  sndbuff.resize(buffsize);
565  MPI_Bcast(sndbuff.data(), buffsize*sizeof(mesh_int_t), MPI_BYTE, pid, PETSC_COMM_WORLD);
566 
567  mesh_int_t start = layout[mpi_rank], stop = layout[mpi_rank+1];
568 
569  for(mesh_int_t i : sndbuff) {
570  if(i >= start && i < stop)
571  idx.push_back(i - start);
572  }
573  }
574 
575  binary_sort(idx); unique_resize(idx);
576 }
577 
579  SF::vector<mesh_int_t> & inp_idx,
581 {
582  int mpi_rank = get_rank(), mpi_size = get_size();
583  const SF::vector<mesh_int_t> & alg_nod = mesh.pl.algebraic_nodes();
585 
587  for(mesh_int_t ii : alg_nod)
588  amap[nbr[ii]] = ii;
589 
590  SF::vector<mesh_int_t> sndbuff;
591  size_t buffsize = 0;
592  idx.resize(0);
593 
594  for(int pid=0; pid < mpi_size; pid++) {
595  if(mpi_rank == pid) {
596  sndbuff = inp_idx;
597  buffsize = sndbuff.size();
598  }
599 
600  MPI_Bcast(&buffsize, sizeof(size_t), MPI_BYTE, pid, PETSC_COMM_WORLD);
601  sndbuff.resize(buffsize);
602  MPI_Bcast(sndbuff.data(), buffsize*sizeof(mesh_int_t), MPI_BYTE, pid, PETSC_COMM_WORLD);
603 
604  for(mesh_int_t i : sndbuff) {
605  if(amap.count(i))
606  idx.push_back(amap[i]);
607  }
608  }
609 
610  binary_sort(idx); unique_resize(idx);
611 }
612 
613 void setup_dataout(const int dataout, std::string dataout_vtx, mesh_t grid,
614  SF::vector<mesh_int_t>* & restr, bool async,
615  const hashmap::unordered_set<int>* output_tags)
616 {
617  sf_mesh & mesh = get_mesh(grid);
618 
619  switch(dataout) {
620 
621  case DATAOUT_SURF: {
622  sf_mesh surfmesh;
623  // The surface of the tagged region contains the faces cutting through the grid,
624  // so it is not a subset of the surface of the whole grid. It must be computed
625  // from the tags to line up with the restricted mesh written by output_meshes().
627  if(output_tags)
628  surf_tags.insert(output_tags->begin(), output_tags->end());
629 
630  compute_surface_mesh(mesh, SF::NBR_SUBMESH, surf_tags, surfmesh);
631 
632  SF::vector<mesh_int_t> idxbuff(surfmesh.con);
633  binary_sort(idxbuff); unique_resize(idxbuff);
634 
635  restr = new SF::vector<mesh_int_t>();
636 
637  // for sync output, we need restr to hold the local indices in the petsc vectors
638  // that have been permuted to canonical numbering. For async, we need the
639  // non-overlapping decomposition of indices in NBR_SUBMESH numbering. The petsc indices will be
640  // computed at a later stage. The only reason we need to call compute_restr_idx_async,
641  // is that surface nodes in NBR_SUBMESH, may
642  // reside on partitions where they are not part of the algebraic nodes. thus we need to
643  // recommunicate to make sure the data layout is correct. We do not have this problem for
644  // DATAOUT_VTX.
645  if(!async)
646  compute_restr_idx(mesh, idxbuff, *restr);
647  else
648  compute_restr_idx_async(mesh, idxbuff, *restr);
649 
650  break;
651  }
652 
653  case DATAOUT_VTX: {
654  SF::vector<mesh_int_t> idxbuff;
655 
656  update_cwd();
657 
658  set_dir(INPUT);
659  read_indices(idxbuff, dataout_vtx, mesh, SF::NBR_REF, true, PETSC_COMM_WORLD);
660  set_dir(CURDIR);
661 
662  restr = new SF::vector<mesh_int_t>();
663 
664  if(!async) {
666  for(mesh_int_t & i : idxbuff) i = nbr[i];
667 
668  compute_restr_idx(mesh, idxbuff, *restr);
669  } else {
670  *restr = idxbuff;
671  }
672 
673  break;
674  }
675 
676  case DATAOUT_NONE:
677  case DATAOUT_VOL:
678  default: break;
679  }
680 }
681 
682 namespace {
683 
686 void restrict_output_to_tags(SF::vector<mesh_int_t>*& restr,
687  const SF::vector<mesh_int_t>& tag_restr,
688  const char* domain,
689  const char* dataout_name)
690 {
691  const bool restricted_before = restr != NULL;
692  const long int num_dataout = restricted_before ?
693  get_global(static_cast<long int>(restr->size()), MPI_SUM, PETSC_COMM_WORLD) : 0;
694 
695  intersect_output_restriction(restr, tag_restr);
696 
697  const long int num_kept = get_global(static_cast<long int>(restr->size()), MPI_SUM, PETSC_COMM_WORLD);
698  if(num_kept == 0) {
699  log_msg(0, 5, ECHO, "gridout_tags and %s select no common %s output nodes.",
700  dataout_name, domain);
701  EXIT(EXIT_FAILURE);
702  }
703 
704  if(restricted_before && num_kept < num_dataout)
705  log_msg(0, 3, ECHO,
706  "Warning: gridout_tags keeps %ld of the %ld %s output nodes selected by %s, %ld are dropped.",
707  num_kept, num_dataout, domain, dataout_name, num_dataout - num_kept);
708 }
709 
710 } // namespace
711 
712 void Electrics::setup_output()
713 {
714  int rank = get_rank();
715  SF::vector<mesh_int_t>* restr_i = NULL;
716  SF::vector<mesh_int_t>* restr_e = NULL;
717  hashmap::unordered_set<int> output_tags;
718  const bool restrict_gridout = parse_gridout_tags(output_tags);
719  if(restrict_gridout) {
720  SF::vector<mesh_t> mesh_ids;
721  if(param_globals::dataout_i || param_globals::dump_data)
722  mesh_ids.push_back(intra_elec_msh);
723  if(param_globals::bidomain && param_globals::dataout_e)
724  mesh_ids.push_back(extra_elec_msh);
725  if(mesh_ids.size())
726  validate_gridout_tags(output_tags, mesh_ids);
727  }
728  set_dir(OUTPUT);
729 
730  setup_dataout(param_globals::dataout_i, param_globals::dataout_i_vtx, intra_elec_msh,
731  restr_i, param_globals::num_io_nodes > 0,
732  restrict_gridout ? &output_tags : NULL);
733 
734  if(restrict_gridout && (param_globals::dataout_i || param_globals::dump_data)) {
736  SF::vector<mesh_int_t> tag_restr_i;
737  build_tagged_nodal_output_restriction(mesh, output_tags, tag_restr_i,
738  param_globals::num_io_nodes > 0);
739  if(get_global(static_cast<long int>(tag_restr_i.size()), MPI_SUM, PETSC_COMM_WORLD) == 0) {
740  log_msg(0, 5, ECHO, "gridout_tags selected no intracellular output nodes.");
741  EXIT(EXIT_FAILURE);
742  }
743  restrict_output_to_tags(restr_i, tag_restr_i, "intracellular", "dataout_i");
744  }
745 
746  if(param_globals::dataout_i)
747  output_manager.register_output(parab_solver.Vmv, intra_elec_msh, 1, param_globals::vofile, "mV", restr_i);
748 
749  if(param_globals::bidomain) {
750  setup_dataout(param_globals::dataout_e, param_globals::dataout_e_vtx, extra_elec_msh,
751  restr_e, param_globals::num_io_nodes > 0,
752  restrict_gridout ? &output_tags : NULL);
753 
754  if(restrict_gridout && param_globals::dataout_e) {
756  SF::vector<mesh_int_t> tag_restr_e;
757  build_tagged_nodal_output_restriction(mesh, output_tags, tag_restr_e,
758  param_globals::num_io_nodes > 0);
759  if(get_global(static_cast<long int>(tag_restr_e.size()), MPI_SUM, PETSC_COMM_WORLD) == 0) {
760  log_msg(0, 5, ECHO, "gridout_tags selected no extracellular output nodes.");
761  EXIT(EXIT_FAILURE);
762  }
763  restrict_output_to_tags(restr_e, tag_restr_e, "extracellular", "dataout_e");
764  }
765 
766  if(param_globals::dataout_i)
767  output_manager.register_output(ellip_solver.phie_i, intra_elec_msh, 1, param_globals::phieifile, "mV", restr_i);
768  if(param_globals::dataout_e)
769  output_manager.register_output(ellip_solver.phie, extra_elec_msh, 1, param_globals::phiefile, "mV", restr_e);
770  }
771 
772  if(param_globals::dump_data & DUMP_IC) {
773  output_manager.register_output(parab_solver.Ic, intra_elec_msh, 1, "Ic.igb", "uA/cm^2", restr_i);
774  output_manager.register_output(parab_solver.IIon, intra_elec_msh, 1, "Iion.igb","uA/cm^2", restr_i);
775  }
776 
777  if(param_globals::dump_data & DUMP_IVOL)
778  output_manager.register_output(parab_solver.Ivol, intra_elec_msh, 1, "Ivol.igb", "uA", restr_i);
779  if(param_globals::dump_data & DUMP_IACT)
780  output_manager.register_output(parab_solver.Iact, intra_elec_msh, 1, "Iact.igb", "uA", restr_i);
781 
782  if(phie_rcv.pts.size())
783  output_manager.register_output_sync(phie_rcv.phie_rec, phie_recv_msh, 1, param_globals::phie_recovery_file, "mV");
784 
786 
787  if(param_globals::num_trace) {
788  sf_mesh & imesh = get_mesh(intra_elec_msh);
789  open_trace(ion.miif, param_globals::num_trace, param_globals::trace_node, NULL, &imesh);
790  }
791 
792  // initialize generic logger for IO timings per time_dt
793  IO_stats.init_logger("IO_stats.dat");
794 }
795 
796 void Electrics::dump_matrices()
797 {
798  std::string bsname = param_globals::dump_basename;
799  std::string fn;
800 
801  set_dir(OUTPUT);
802 
803  // dump monodomain matrices
804  if ( param_globals::parab_solve==1 ) {
805  // using Crank-Nicolson
806  fn = bsname + "_Ki_CN.bin";
807  parab_solver.lhs_parab->write(fn.c_str());
808  }
809  fn = bsname + "_Ki.bin";
810  parab_solver.rhs_parab->write(fn.c_str());
811 
812  fn = bsname + "_Mi.bin";
813  parab_solver.mass_i->write(fn.c_str());
814 
815  if ( param_globals::bidomain ) {
816  fn = bsname + "_Kie.bin";
817  ellip_solver.phie_mat->write(fn.c_str());
818 
819  fn = bsname + "_Me.bin";
820  ellip_solver.mass_e->write(fn.c_str());
821  }
822 }
823 
824 
827 double Electrics::timer_val(const int timer_id)
828 {
829  // determine
830  int sidx = stimidx_from_timeridx(stimuli, timer_id);
831  double val = 0.0;
832  if(sidx != -1) {
833  stimuli[sidx].value(val);
834  }
835  else
836  val = std::nan("NaN");
837 
838  return val;
839 }
840 
843 std::string Electrics::timer_unit(const int timer_id)
844 {
845  int sidx = stimidx_from_timeridx(stimuli, timer_id);
846  std::string s_unit;
847 
848  if(sidx != -1)
849  // found a timer-linked stimulus
850  s_unit = stimuli[sidx].pulse.wave.f_unit;
851 
852  return s_unit;
853 }
854 
857 int stimidx_from_timeridx(const SF::vector<stimulus> & stimuli, const int timer_id)
858 {
859  // the only electrical quantities linked to a timer are stimuli
860  // thus we search for timer links only among stimuli for now
861 
862  // iterate over stimuli
863  for(size_t i = 0; i<stimuli.size(); i++)
864  {
865  const stimulus & s = stimuli[i];
866 
867  if(s.ptcl.timer_id == timer_id)
868  return s.idx;
869  }
870 
871  // invalid timer index not linked to any stimulus
872  return -1;
873 }
874 
885 void get_kappa(sf_vec & kappa, IMPregion *ir, limpet::MULTI_IF & miif, double k)
886 {
887  double* reg_kappa = new double[miif.N_IIF];
888 
889  for(int i=0; i<miif.N_IIF; i++)
890  reg_kappa[i] = k * miif.IIF[i]->cgeom().SVratio * ir[i].volFrac;
891 
892  double *kd = kappa.ptr();
893 
894  for(int i = 0; i < miif.numNode; i++)
895  kd[i] = reg_kappa[(int) miif.IIFmask[i]];
896 
897  kappa.release_ptr(kd);
898  delete [] reg_kappa;
899 }
900 
901 
910 {
911  for(size_t i=0; i < m.regions.size(); i++) {
912  elecMaterial *emat = static_cast<elecMaterial*>(m.regions[i].material);
913  emat->g = type;
914  }
915 }
916 
917 void Electrics::setup_solvers()
918 {
919  set_dir(OUTPUT);
920  parab_solver.init();
922 
923  if (param_globals::bidomain) {
924  ellip_solver.init();
926  }
927 
928  if(param_globals::dump2MatLab)
929  dump_matrices();
930 
931  log_msg(logger,0,ECHO, "Electrics::setup_solvers");
932 }
933 
935 {
936  for(const stimulus & s : stimuli) {
937  if(is_dbc(s.phys.type))
938  return true;
939  }
940  return false;
941 }
942 
943 const char* get_tsav_ext(double time)
944 {
945  int min_idx = -1;
946  double min_diff = 1e100;
947 
948  for(int i=0; i<param_globals::num_tsav; i++)
949  {
950  double diff = fabs(param_globals::tsav[i] - time);
951  if(min_diff > diff) {
952  min_diff = diff;
953  min_idx = i;
954  }
955  }
956 
957  if(min_idx == -1)
958  min_idx = 0;
959 
960  return param_globals::tsav_ext[min_idx];
961 }
962 
963 void Electrics::checkpointing()
964 {
965  const timer_manager & tm = *user_globals::tm_manager;
966 
967  // regular user selected state save
968  if (tm.trigger(iotm_chkpt_list)) {
969  char save_fnm[1024];
970  const char* tsav_ext = get_tsav_ext(tm.time);
971 
972  snprintf(save_fnm, sizeof save_fnm, "%s.%s.roe", param_globals::write_statef, tsav_ext);
973 
974  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
975  }
976 
977  // checkpointing based on interval
978  if (tm.trigger(iotm_chkpt_intv)) {
979  char save_fnm[1024];
980  snprintf(save_fnm, sizeof save_fnm, "checkpoint.%.1f.roe", tm.time);
981  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
982  }
983 }
984 
986 {
988  double t0, t1, dur;
989  get_time(t0);
990  stats.init_logger("ell_stats.dat");
991 
992  // here we can differentiate the solvers
994  sf_mesh & extra_mesh = get_mesh(extra_elec_msh);
995  sf_vec::ltype alg_type = sf_vec::algebraic;
996  const int dpn = 1;
997 
998  SF::init_vector(&phie, extra_mesh, dpn, alg_type);
999  SF::init_vector(&phiesrc, extra_mesh, dpn, alg_type);
1000  SF::init_vector(&currtmp, extra_mesh, dpn, alg_type);
1001 
1003  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
1004  SF::init_vector(&phie_i, intra_mesh, dpn, alg_type);
1005  }
1006 
1007  int max_row_entries = max_nodal_edgecount(extra_mesh);
1008 
1011 
1012  // alloc stiffness matrix
1013  phie_mat->init(extra_mesh, dpn, dpn, max_row_entries);
1014  // alloc mass matrix
1015  mass_e ->init(extra_mesh, dpn, dpn, param_globals::mass_lumping ? 1 : max_row_entries);
1016  dur = timing(t1, t0);
1017 }
1018 
1020  SF::vector<stimulus> & stimuli,
1021  FILE_SPEC logger)
1022 {
1024  double t0, t1, dur;
1025  get_time(t0);
1026  rebuild_stiffness(mtype, stimuli, logger);
1027  rebuild_mass(logger);
1028  dur = timing(t1, t0);
1029 }
1030 
1032  SF::vector<stimulus> & stimuli,
1033  FILE_SPEC logger)
1034 {
1036  double t0, t1, dur;
1037  int log_flag = param_globals::output_level > 1 ? ECHO : 0;
1038 
1039  MaterialType & mt = mtype[Electrics::extra_grid];
1040  const bool have_dbc = have_dbc_stims(stimuli);
1041 
1042  cond_t condType = sum_cond;
1043  set_cond_type(mt, condType);
1044 
1045  // get mesh reference
1046  sf_mesh & mesh = get_mesh(extra_elec_msh);
1047 
1048  get_time(t0);
1049 
1050  // fill the system
1051  elec_stiffness_integrator stfn_integ(mt);
1052 
1053  phie_mat->zero();
1054  SF::assemble_matrix(*phie_mat, mesh, stfn_integ);
1055  phie_mat->scale(-1.0);
1056 
1057  dur = timing(t1,t0);
1058  log_msg(logger,0,log_flag, "Computed ellipitc stiffness matrix in %.3f seconds.", dur);
1059 
1060  // set boundary conditions
1061  if(have_dbc) {
1062  log_msg(logger,0,log_flag, "Elliptic lhs matrix enforcing Dirichlet boundaries.");
1063  get_time(t0);
1064 
1065  if(dbc == nullptr)
1066  dbc = new dbc_manager(*phie_mat, stimuli);
1067  else
1068  dbc->recompute_dbcs();
1069 
1070  dbc->enforce_dbc_lhs();
1071 
1072  dur = timing(t1,t0);
1073  log_msg(logger,0,log_flag, "Elliptic lhs matrix Dirichlet enforcing done in %.3f seconds.", dur);
1074  }
1075  else {
1076  log_msg(logger,1,ECHO, "Elliptic lhs matrix is singular!");
1077  // we are dealing with a singular system
1078  phie_mat_has_nullspace = true;
1079  }
1080 
1081  // solver has not been initialized yet
1082  set_dir(INPUT);
1083  get_time(t0);
1084 
1085  setup_linear_solver(logger);
1086 
1087  dur = timing(t1,t0);
1088  log_msg(logger,0,log_flag, "Initializing elliptic solver in %.5f seconds.", dur);
1089  set_dir(OUTPUT);
1090 }
1091 
1093 {
1095  int log_flag = param_globals::output_level > 1 ? ECHO : 0;
1096  double t0, t1, dur;
1097  mass_integrator mass_integ;
1098 
1099  // get mesh reference
1100  sf_mesh & mesh = get_mesh(extra_elec_msh);
1101  get_time(t0);
1102  mass_e->zero();
1103 
1104  if(param_globals::mass_lumping) {
1105  SF::assemble_lumped_matrix(*mass_e, mesh, mass_integ);
1106  } else {
1107  SF::assemble_matrix(*mass_e, mesh, mass_integ);
1108  }
1109 
1110  dur = timing(t1,t0);
1111  log_msg(logger,0,log_flag, "Computed elliptic mass matrix in %.3f seconds.", dur);
1112 }
1113 
1114 void elliptic_solver::setup_linear_solver(FILE_SPEC logger)
1115 {
1117 
1118  tol = param_globals::cg_tol_ellip;
1119  max_it = param_globals::cg_maxit_ellip;
1120 
1121  std::string default_opts;
1122  std::string solver_file;
1123  solver_file = param_globals::ellip_options_file;
1124  if (param_globals::flavor == std::string("ginkgo")) {
1125  default_opts = std::string(
1126  R"({
1127  "type": "solver::Cg",
1128  "criteria": [
1129  {
1130  "type": "Iteration",
1131  "max_iters": 100
1132  },
1133  {
1134  "type": "ResidualNorm",
1135  "reduction_factor": 1e-4
1136  }
1137  ],
1138  "preconditioner": {
1139  "type": "solver::Multigrid",
1140  "mg_level": [
1141  {
1142  "type": "multigrid::Pgm",
1143  "deterministic": true
1144  }
1145  ],
1146  "criteria": [
1147  {
1148  "type": "Iteration",
1149  "max_iters": 1
1150  }
1151  ],
1152  "coarsest_solver": {
1153  "type": "preconditioner::Schwarz",
1154  "local_solver": {
1155  "type": "preconditioner::Ilu"
1156  }
1157  },
1158  "max_levels": 10,
1159  "min_coarse_rows": 8,
1160  "default_initial_guess": "zero"
1161  }
1162 })");
1163  } else if (param_globals::flavor == std::string("petsc")) {
1164  default_opts = std::string("-ksp_type cg -pc_type hypre -pc_hypre_type boomeramg -pc_hypre_boomeramg_max_iter 1 -pc_hypre_boomeramg_strong_threshold 0.0 -options_left");
1165  }
1166 
1167  lin_solver->setup_solver(*phie_mat, tol, max_it, param_globals::cg_norm_ellip,
1168  "elliptic PDE", phie_mat_has_nullspace,
1169  logger, solver_file.c_str(), default_opts.c_str());
1170 }
1171 
1172 void elliptic_solver::solve(sf_mat & Ki, sf_vec & Vmv, sf_vec & tmp_i)
1175  double t0,t1;
1177  // assembly of rhs for FE
1178  if (phiesrc->mag() > 0.0) {
1179  mass_e->mult(*phiesrc, *currtmp);
1181  }
1182 
1183  Ki.mult(Vmv, tmp_i);
1184 
1185  bool add = true;
1186  i2e->forward(tmp_i, *phiesrc, add);
1187 
1188  if(dbc != nullptr)
1190 
1191  get_time(t0);
1192  (*lin_solver)(*phie, *phiesrc);
1193 
1194  // treat solver statistics
1195  auto dur = timing(t1, t0);
1196  lin_solver->time += dur;
1197  stats.slvtime += dur;
1199  if(lin_solver->reason < 0) {
1200  log_msg(0, 5, 0,"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1201  petsc_get_converged_reason_str(lin_solver->reason));
1202  EXIT(1);
1203  }
1205  add = false;
1206  i2e->backward(*phie, *phie_i, add);
1207 }
1208 
1210 {
1212  double t0,t1;
1213 
1214  if(dbc != nullptr)
1216 
1217  get_time(t0);
1218  (*lin_solver)(*phie, *phiesrc);
1219 
1220  // treat solver statistics
1221  auto dur = timing(t1, t0);
1222  lin_solver->time += dur;
1223  stats.slvtime += dur;
1225 
1226  if(lin_solver->reason < 0) {
1227  log_msg(0, 5, 0,"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1228  petsc_get_converged_reason_str(lin_solver->reason));
1229  EXIT(1);
1230  }
1231 
1232  // phie_i is only set up when we have an IntraMesh registered
1233  if(is_init(phie_i)) {
1234  bool add = false;
1236  i2e->backward(*phie, *phie_i, add);
1237  }
1238 }
1239 
1241 {
1243  double t0, t1, dur;
1244  get_time(t0);
1245  stats.init_logger("par_stats.dat");
1246 
1247  // here we can differentiate the solvers
1249 
1250  sf_vec* vm_ptr = get_data(vm_vec);
1251  sf_vec* iion_ptr = get_data(iion_vec);
1252 
1253  if(!(vm_ptr != NULL && iion_ptr != NULL)) {
1254  log_msg(0,5,0, "%s error: global Vm and Iion vectors not properly set up! Ionics seem invalid! Aborting!",
1255  __func__);
1256  EXIT(1);
1257  }
1258 
1259  SF::init_vector(&Vmv);
1261  Vmv-> shallow_copy(*vm_ptr);
1262  IIon->shallow_copy(*iion_ptr);
1263 
1264  if(param_globals::dump_data & DUMP_IC) SF::init_vector(&Ic , Vmv);
1265  if(param_globals::dump_data & DUMP_IVOL) SF::init_vector(&Ivol, Vmv);
1266  if(param_globals::dump_data & DUMP_IACT) SF::init_vector(&Iact, Vmv);
1267 
1270 
1271  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
1272  sf_vec::ltype alg_type = sf_vec::algebraic;
1273 
1274  int dpn = 1;
1275  SF::init_vector(&kappa_i, intra_mesh, dpn, alg_type);
1276  SF::init_vector(&tmp_i1, intra_mesh, dpn, alg_type);
1277  SF::init_vector(&tmp_i2, intra_mesh, dpn, alg_type);
1278  SF::init_vector(&old_vm, intra_mesh, dpn, alg_type);
1279 
1280  if(!param_globals::operator_splitting)
1281  SF::init_vector(&Irhs, intra_mesh, dpn, alg_type);
1282 
1283  // alloc matrices
1284  int max_row_entries = max_nodal_edgecount(intra_mesh);
1285 
1289 
1290  rhs_parab->init(intra_mesh, dpn, dpn, max_row_entries);
1291  mass_i ->init(intra_mesh, dpn, dpn, param_globals::mass_lumping ? 1 : max_row_entries);
1292 
1293  parab_tech = static_cast<parabolic_solver::parabolic_t>(param_globals::parab_solve);
1294  dur = timing(t1, t0);
1295 }
1296 
1298 {
1300  double start, end, period;
1301  get_time(start);
1302  double t0, t1, dur;
1303  mass_integrator mass_integ;
1304  int dpn = 1;
1305 
1306  int log_flag = param_globals::output_level > 1 ? ECHO : 0;
1307  MaterialType & mt = mtype[Electrics::intra_grid];
1308 
1309  double Dt = user_globals::tm_manager->time_step;
1310  get_kappa(*kappa_i, param_globals::imp_region, miif, UM2_to_CM2 / Dt);
1311 
1312  cond_t condType = intra_cond;
1313  sf_mesh & mesh = get_mesh(intra_elec_msh);
1314 
1315  if( (param_globals::bidomain == MONODOMAIN && param_globals::bidm_eqv_mono) ||
1316  (param_globals::bidomain == PSEUDO_BIDM) )
1317  condType = para_cond;
1318 
1319  // set material and conductivity type
1320  set_cond_type(mt, condType);
1321 
1322  // fill the system
1323  {
1324  get_time(t0);
1325 
1326  elec_stiffness_integrator stfn_integ(mt);
1327  SF::assemble_matrix(*rhs_parab, mesh, stfn_integ);
1328 
1329  dur = timing(t1,t0);
1330  log_msg(logger,0,log_flag, "Computed parabolic stiffness matrix in %.3f seconds.", dur);
1331  get_time(t0);
1332 
1333  if(param_globals::mass_lumping)
1334  SF::assemble_lumped_matrix(*mass_i, mesh, mass_integ);
1335  else
1336  SF::assemble_matrix(*mass_i, mesh, mass_integ);
1337 
1338  sf_vec* empty; SF::init_vector(&empty);
1339  mass_i->mult_LR(*kappa_i, *empty);
1340 
1341  dur = timing(t1,t0);
1342  log_msg(logger,0,log_flag, "Computed parabolic mass matrix in %.3f seconds.", dur);
1343  delete empty;
1344  }
1345 
1346  // initialize parab lhs
1347  if(parab_tech != EXPLICIT) {
1349  // if we have mass lumping, then the nonzero pattern between Mi and Ki is different
1350  bool same_nonzero = param_globals::mass_lumping == false;
1351 
1352  if (parab_tech==CN) {
1353  lhs_parab->scale(-param_globals::theta);
1354  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1355  }
1356  else if (parab_tech==O2dT) {
1357  lhs_parab->scale(-0.5);
1358  mass_i->scale(0.5);
1359  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1360  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1361  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1362  }
1363  }
1364  else {
1367 
1368  SF_real* p = inv_mass_diag->ptr();
1369 
1370  for(int i=0; i<inv_mass_diag->lsize(); i++)
1371  p[i] = 1.0 / p[i];
1372 
1374  }
1376  if(parab_tech == CN || parab_tech == O2dT) {
1377  set_dir(INPUT);
1378  get_time(t0);
1379 
1380  setup_linear_solver(logger);
1381 
1382  dur = timing(t1,t0);
1383  log_msg(logger,0,log_flag, "Initializing parabolic solver in %.5f seconds.", dur);
1384  set_dir(OUTPUT);
1385  }
1386  period = timing(end, start);
1387  log_msg(logger,0,ECHO, "Done rebuild mat");
1388 }
1389 
1390 void parabolic_solver::setup_linear_solver(FILE_SPEC logger)
1391 {
1393  tol = param_globals::cg_tol_parab;
1394  max_it = param_globals::cg_maxit_parab;
1395 
1396  std::string default_opts;
1397  std::string solver_file;
1398  solver_file = param_globals::parab_options_file;
1399  if (param_globals::flavor == std::string("ginkgo")) {
1400  default_opts = std::string(
1401  R"(
1402 {
1403  "type": "solver::Cg",
1404  "criteria": [
1405  {
1406  "type": "Iteration",
1407  "max_iters": 100
1408  },
1409  {
1410  "type": "ResidualNorm",
1411  "reduction_factor": 1e-4
1412  }
1413  ],
1414  "preconditioner": {
1415  "type": "preconditioner::Schwarz",
1416  "local_solver": {
1417  "type": "preconditioner::Ilu"
1418  }
1419  }
1420 }
1421  )");
1422  } else if (param_globals::flavor == std::string("petsc")) {
1423  default_opts = std::string("-pc_type bjacobi -sub_pc_type ilu -ksp_type cg");
1424  }
1425 
1426  lin_solver->setup_solver(*lhs_parab, tol, max_it, param_globals::cg_norm_parab,
1427  "parabolic PDE", false, logger, solver_file.c_str(),
1428  default_opts.c_str());
1429 }
1430 
1431 void parabolic_solver::solve(sf_vec & phie_i)
1432 {
1434  switch (parab_tech) {
1435  case CN: solve_CN(phie_i); break;
1436  case O2dT: solve_O2dT(phie_i); break;
1437  default: solve_EF(phie_i); break;
1438  }
1439 }
1440 
1441 void parabolic_solver::solve_CN(sf_vec & phie_i)
1442 {
1444  double t0,t1;
1445  // assembly of rhs for CN
1446  if (param_globals::bidomain == BIDOMAIN) {
1447  tmp_i1->deep_copy(phie_i);
1448  tmp_i1->add_scaled(*Vmv, 1.0 - param_globals::theta);
1449  rhs_parab->mult(*tmp_i1, *tmp_i2);
1450  }
1451  else {
1452  rhs_parab->mult(*Vmv, *tmp_i2);
1453  *tmp_i2 *= 1.0 - param_globals::theta;
1454  }
1455 
1456  mass_i->mult(*Vmv, *tmp_i1);
1457  *tmp_i1 += *tmp_i2;
1458 
1459  // add current contributions to rhs
1460  if(!param_globals::operator_splitting)
1461  tmp_i1->add_scaled(*Irhs, -1.0);
1462 
1463  get_time(t0);
1464 
1465  (*lin_solver)(*Vmv, *tmp_i1);
1466 
1467  if(lin_solver->reason < 0) {
1468  log_msg(0, 5, 0,"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1469  petsc_get_converged_reason_str(lin_solver->reason));
1470  EXIT(1);
1471  }
1472 
1473  // treat solver statistics
1474  auto dur = timing(t1, t0);
1475  lin_solver->time += dur;
1476  stats.slvtime += dur;
1478 }
1479 
1480 void parabolic_solver::solve_O2dT(sf_vec & phie_i)
1481 {
1483  double t0,t1;
1484  // assembly of rhs for FE
1485  if (param_globals::bidomain == BIDOMAIN) {
1486  tmp_i2->deep_copy(phie_i);
1487  tmp_i2->add_scaled(*Vmv, 0.5);
1488  rhs_parab->mult(*tmp_i2, *tmp_i1); // tmp_i1 = K_i(Vm^t * 0.5 + phi_e)
1489  }
1490  else {
1491  rhs_parab->mult(*Vmv, *tmp_i1);
1492  *tmp_i1 *= 0.5; // tmp_i1 = 0.5 * K_i Vm^t
1493  }
1494 
1495  mass_i->mult(*Vmv, *tmp_i2); // tmp_i2 = M/2 Vm^t
1496  tmp_i1->add_scaled(*tmp_i2, 4.0); // tmp_i1 = (2M+K_i/2)Vm^t
1497  mass_i->mult(*old_vm, *tmp_i2); // tmp_i2 = M/2 Vm^{t-1}
1498 
1499  tmp_i1->add_scaled(*tmp_i2, -1.0); // tmp_i1 = (2M+K_i/2)Vm^t-M/2 Vm^{t-1}
1500  *old_vm = *Vmv;
1501 
1502  get_time(t0);
1503 
1504  // solve
1505  (*lin_solver)(*Vmv, *tmp_i1);
1506 
1507  // treat solver statistics
1508  stats.slvtime += timing(t1, t0);
1510 }
1511 
1512 void parabolic_solver::solve_EF(sf_vec & phie_i)
1513 {
1515  double t0,t1,t2;
1516  get_time(t0);
1517 
1518  // assembly of rhs for FE
1519  if (param_globals::bidomain == BIDOMAIN) {
1520  tmp_i2->deep_copy(phie_i);
1521  *tmp_i2 += *Vmv;
1522  rhs_parab->mult(*tmp_i2, *tmp_i1);
1523  }
1524  else {
1525  rhs_parab->mult(*Vmv, *tmp_i1);
1526  }
1527 
1528  *tmp_i1 *= *inv_mass_diag;
1529  Vmv->add_scaled(*tmp_i1, 1.0);
1530 
1531  if(param_globals::operator_splitting == false)
1532  Vmv->add_scaled(*Irhs, -1.0);
1533 
1534  // record rhs timing
1535  stats.slvtime += timing(t1, t0);
1536 }
1537 
1539 {
1540  char* prvSimDir = strlen(param_globals::start_statef) ?
1541  get_file_dir(param_globals::start_statef) : NULL;
1542 
1543  const char* extn = ".dat";
1544 
1545  // if compute_APD we need an extra 2 acts
1546  int addLATs = param_globals::compute_APD ? 2 : 0;
1547 
1548  bool have_sentinel = param_globals::t_sentinel > 0.0;
1549  bool need_to_add_sentinel = have_sentinel && (param_globals::sentinel_ID < 0);
1550 
1551  addLATs += need_to_add_sentinel ? 1 : 0;
1552  acts.resize(param_globals::num_LATs + addLATs);
1553 
1554  int j=0;
1555  for (int i = 0; i < param_globals::num_LATs; i++ )
1556  {
1557  // using Ph only with bidomain runs
1558  if (param_globals::lats[i].method <= 0 || (param_globals::lats[i].measurand == PHIE && !param_globals::bidomain)) {
1559  log_msg(NULL, 3, 0, "Phie-based LAT measurement requires bidomain >=1 Ignoring lats[%d].", i);
1560  continue;
1561  }
1562 
1563  acts[j].method = (ActMethod)param_globals::lats[i].method;
1564  acts[j].threshold = param_globals::lats[i].threshold;
1565  acts[j].mode = param_globals::lats[i].mode;
1566  acts[j].all = param_globals::lats[i].all;
1567  acts[j].measurand = (PotType)param_globals::lats[i].measurand;
1568  acts[j].ID = param_globals::lats[i].ID;
1569  acts[j].fout = NULL;
1570 
1571  if(param_globals::lats[i].all) {
1572  acts[j].fname = (char*) malloc((strlen(param_globals::lats[i].ID)+strlen(extn)+1)*sizeof(char));
1573  snprintf(acts[j].fname, strlen(param_globals::lats[i].ID)+strlen(extn)+1, "%s%s", param_globals::lats[i].ID, extn);
1574  }
1575  else {
1576  char prfx[] = "init_acts_";
1577  int max_len = strlen(prfx) + strlen(param_globals::lats[i].ID) + strlen(extn) + 1;
1578 
1579  acts[j].fname = (char*) malloc(max_len*sizeof(char));
1580  snprintf(acts[j].fname, max_len, "%s%s%s", prfx, param_globals::lats[i].ID, extn);
1581  }
1582 
1583  // restarting
1584  if(prvSimDir != NULL) {
1585  int len_fname = strlen(prvSimDir)+strlen(acts[j].fname)+2;
1586  acts[j].prv_fname = (char*) malloc(len_fname*sizeof(char));
1587  snprintf(acts[j].prv_fname, len_fname, "%s/%s", prvSimDir, acts[j].fname);
1588  }
1589 
1590  j++;
1591  }
1592 
1593  if(param_globals::compute_APD) {
1594  acts[j].method = ACT_THRESH; // threshold crossing
1595  acts[j].threshold = param_globals::actthresh;
1596  acts[j].mode = 0; // upstroke
1597  acts[j].all = true;
1598  acts[j].measurand = VM; // Vm
1599  //acts[j].ID = dupstr("Vm_Activation");
1600  acts[j].fout = NULL;
1601  acts[j].fname = dupstr("vm_activation.dat");
1602 
1603  j++;
1604  acts[j].method = ACT_THRESH; // threshold crossing
1605  acts[j].threshold = param_globals::recovery_thresh;
1606  acts[j].mode = 1; // repol
1607  acts[j].all = true;
1608  acts[j].measurand = VM; // Vm
1609  //(*acts)[j+1].ID = param_globals::lats[i].ID;
1610  acts[j].fout = NULL;
1611  acts[j].fname = dupstr("vm_repolarisation.dat");
1612 
1613  j++;
1614  }
1615 
1616  // set up sentinel for activity checking
1617  sntl.activated = have_sentinel;
1618  sntl.t_start = param_globals::t_sentinel_start;
1619  sntl.t_window = param_globals::t_sentinel;
1620  sntl.t_quiesc =-1.;
1621  sntl.ID = param_globals::sentinel_ID;
1622 
1623  if(need_to_add_sentinel) {
1624  // add a default LAT detector as sentinel
1625  acts[j].method = ACT_THRESH; // threshold crossing
1626  acts[j].threshold = param_globals::actthresh;
1627  acts[j].mode = 0; // upstroke
1628  acts[j].all = true;
1629  acts[j].measurand = VM; // Vm
1630  //(*acts)[j].ID = dupstr("Vm_Activation");
1631  acts[j].fout = NULL;
1632  acts[j].fname = dupstr("vm_sentinel.dat");
1633  // set sentinel index
1634  sntl.ID = j;
1635  j++;
1636  }
1637 
1638  if(prvSimDir) free(prvSimDir);
1639 }
1640 
1641 void print_act_log(FILE_SPEC logger, const SF::vector<Activation> & acts, int idx)
1642 {
1643  const Activation & act = acts[idx];
1644 
1645  log_msg(logger, 0, 0, "\n");
1646  log_msg(logger, 0, 0, "LAT detector [%2d]", idx);
1647  log_msg(logger, 0, 0, "-----------------\n");
1648 
1649  log_msg(logger, 0, 0, "Measurand: %s", act.measurand ? "Phie" : "Vm");
1650  log_msg(logger, 0, 0, "All: %s", act.all ? "All" : "Only first");
1651  log_msg(logger, 0, 0, "Method: %s", act.method==ACT_DT ? "Derivative" : "Threshold crossing");
1652 
1653  char buf[64], gt[2], sgn[2];
1654  snprintf(sgn, sizeof sgn, "%s", act.mode?"-":"+");
1655  snprintf(gt, sizeof gt, "%s", act.mode?"<":">");
1656 
1657  if(act.method==ACT_DT)
1658  snprintf(buf, sizeof buf, "Maximum %sdf/dt %s %.2f mV", sgn, gt, act.threshold);
1659  else
1660  snprintf(buf, sizeof buf, "Intersection %sdf/dt with %.2f", sgn, act.threshold);
1661 
1662  log_msg(logger, 0, 0, "Mode: %s", buf);
1663  log_msg(logger, 0, 0, "Threshold: %.2f mV\n", act.threshold);
1664 }
1665 
1666 void LAT_detector::init(sf_vec & vm, sf_vec & phie, int offset, enum physic_t phys_t)
1667 {
1668  if(!get_physics(phys_t)) {
1669  log_msg(0,0,5, "There seems to be no EP is defined. LAT detector requires active EP! Aborting LAT setup!");
1670  return;
1671  }
1672 
1673  // we use the electrics logger for output
1674  FILE_SPEC logger = get_physics(phys_t)->logger;
1675 
1676  // TODO(init): except for the shallow copies, shouldn't these be deleted?
1677  // When to delete them?
1678  for(size_t i = 0; i < acts.size(); ++i) {
1679  acts[i].init = 1;
1680  SF::init_vector(&(acts[i].phi));
1681  acts[i].phi->shallow_copy(!acts[i].measurand ? vm : phie);
1682  acts[i].offset = offset;
1683 
1684  SF::init_vector(&(acts[i].phip), acts[i].phi);
1685  *acts[i].phip = *acts[i].phi;
1686 
1687  // derivative based detector
1688  if (acts[i].method == ACT_DT) {
1689  SF::init_vector(&(acts[i].dvp0), acts[i].phi);
1690  SF::init_vector(&(acts[i].dvp1), acts[i].phi);
1691  if(acts[i].mode)
1692  log_msg(NULL,2,0, "Detection of -df/dt|max not implemented, +df/dt|max will be detected.");
1693  }
1694 
1695  // allocate additional local buffers
1696  acts[i].ibuf = (int *)malloc(acts[i].phi->lsize()*sizeof(int));
1697  acts[i].actbuf = (double *)malloc(acts[i].phi->lsize()*sizeof(double));
1698 
1699  if (!acts[i].all) {
1700  SF::init_vector(&acts[i].tm, acts[i].phi->gsize(), acts[i].phi->lsize());
1701  acts[i].tm->set(-1.);
1702 
1703  // initialize with previous initial activations
1704  if(acts[i].prv_fname != NULL) {
1705  set_dir(INPUT);
1706  size_t nread = acts[i].tm->read_ascii(acts[i].prv_fname);
1707  set_dir(OUTPUT);
1708 
1709  if(nread == 0) {
1710  log_msg(NULL,2,ECHO,"Warning: Initialization of LAT[%2d] failed.", i);
1711  } else {
1712  // the file is in canonical order (written with forward=true); permute back to PETSc layout
1714  assert(sc != NULL);
1715  (*sc)(*acts[i].tm, /*forward=*/false);
1716  }
1717  }
1718  }
1719  else {
1720  if ( !get_rank() ) {
1721  // here we should copy over previous file and open in append mode
1722  if(acts[i].prv_fname!=NULL) {
1723  set_dir(INPUT);
1724  FILE_SPEC in = f_open( acts[i].prv_fname, "r" );
1725  if(in) {
1726  log_msg(NULL,2,0, "Copying over of previous activation file not implemented.\n"); f_close(in);
1727  }
1728  else
1729  log_msg(NULL,3,0,"Warning: Initialization in %s - \n"
1730  "Failed to read activation file %s.\n", __func__, acts[i].prv_fname);
1731 
1732  set_dir(OUTPUT);
1733  }
1734  acts[i].fout = f_open( acts[i].fname, acts[i].prv_fname==NULL?"w":"a" );
1735  }
1736  }
1737  print_act_log(logger, acts, i);
1738  }
1739 
1740  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
1742 }
1743 
1744 
1745 int output_all_activations(FILE_SPEC fp, int *ibuf, double *act_tbuf, int nlacts)
1746 {
1747  int rank = get_rank(), gacts = 0, numProc = get_size();
1748 
1749  if (rank == 0) {
1750  // rank 0 writes directly to the table
1751  for (int i=0; i<nlacts; i++)
1752  fprintf(fp->fd, "%d\t%.6f\n", ibuf[i], act_tbuf[i]);
1753 
1754  gacts += nlacts;
1755 
1756  SF::vector<int> buf_inds;
1757  SF::vector<double> buf_acts;
1758 
1759  for (int j=1; j<numProc; j++) {
1760  int acts = 0;
1761  MPI_Status status;
1762  MPI_Recv(&acts, 1, MPI_INT, j, 110, PETSC_COMM_WORLD, &status);
1763 
1764  if (acts) {
1765  buf_inds.resize(acts);
1766  buf_acts.resize(acts);
1767 
1768  MPI_Recv(buf_inds.data(), acts, MPI_INT, j, 110, PETSC_COMM_WORLD, &status);
1769  MPI_Recv(buf_acts.data(), acts, MPI_DOUBLE, j, 110, PETSC_COMM_WORLD, &status);
1770 
1771  for(int ii=0; ii<acts; ii++)
1772  fprintf(fp->fd, "%d\t%.6f\n", buf_inds[ii], buf_acts[ii]);
1773 
1774  gacts += acts;
1775  }
1776  }
1777  fflush(fp->fd);
1778  }
1779  else {
1780  MPI_Send(&nlacts, 1, MPI_INT, 0, 110, PETSC_COMM_WORLD);
1781  if (nlacts) {
1782  MPI_Send(ibuf, nlacts, MPI_INT, 0, 110, PETSC_COMM_WORLD);
1783  MPI_Send(act_tbuf, nlacts, MPI_DOUBLE, 0, 110, PETSC_COMM_WORLD);
1784  }
1785  }
1786 
1787  MPI_Bcast(&gacts, 1, MPI_INT, 0, PETSC_COMM_WORLD);
1788  return gacts;
1789 }
1791 int LAT_detector::check_acts(double tm)
1792 {
1793  int nacts = 0;
1794  double *a;
1795 
1796  for(Activation* aptr = acts.data(); aptr != acts.end(); aptr++)
1797  {
1798  int lacts = 0;
1799  switch (aptr->method) {
1800  case ACT_THRESH:
1801  lacts = check_cross_threshold(*aptr->phi, *aptr->phip, tm,
1802  aptr->ibuf, aptr->actbuf, aptr->threshold, aptr->mode);
1803  break;
1804 
1805  case ACT_DT:
1806  lacts = check_mx_derivative (*aptr->phi, *aptr->phip, tm,
1807  aptr->ibuf, aptr->actbuf, *aptr->dvp0, *aptr->dvp1,
1808  aptr->threshold, aptr->mode);
1809  break;
1810 
1811  default:
1812  break;
1813  }
1814 
1815  if (!aptr->all)
1816  a = aptr->tm->ptr();
1817 
1819 
1820  for(int j=0; j<lacts; j++) {
1821  if(aptr->all) {
1822  int nodal_idx = this->petsc_to_nodal.forward_map(aptr->ibuf[j]);
1823  aptr->ibuf[j] = canon_nbr[nodal_idx] + aptr->offset;
1824  }
1825  else {
1826  if(a[aptr->ibuf[j]] == -1)
1827  a[aptr->ibuf[j]] = aptr->actbuf[j];
1828  }
1829  }
1830 
1831  if(aptr->all)
1832  output_all_activations(aptr->fout, aptr->ibuf, aptr->actbuf, lacts);
1833  else
1834  aptr->tm->release_ptr(a);
1835 
1836  MPI_Allreduce(MPI_IN_PLACE, &lacts, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD);
1837  nacts += lacts;
1838 
1839  aptr->nacts = nacts;
1840  }
1841 
1842  return nacts > 0;
1843 }
1844 
1845 
1846 int LAT_detector::check_quiescence(double tm, double dt)
1847 {
1848  static int savequitFlag = 0;
1849  int numNodesActivated = -1;
1850 
1851  if(sntl.activated) {
1852  // initialization
1853  if(sntl.t_quiesc < 0. && sntl.t_window >= 0.0 ) {
1854  log_msg(0,0,ECHO | NONL, "================================================================================================\n");
1855  log_msg(0,0,ECHO | NONL, "%s() WARNING: simulation is configured to savequit() after %.2f ms of quiescence\n", __func__, sntl.t_window);
1856  log_msg(0,0,ECHO | NONL, "================================================================================================\n");
1857  sntl.t_quiesc = 0.0;
1858  }
1859 
1860  if(tm >= sntl.t_start && !savequitFlag)
1861  {
1862  numNodesActivated = acts[sntl.ID].nacts;
1863 
1864  if(numNodesActivated) sntl.t_quiesc = 0.0;
1865  else sntl.t_quiesc += dt;
1866 
1867  if(sntl.t_window >= 0.0 && sntl.t_quiesc > sntl.t_window && !savequitFlag) {
1868  savequitFlag++;
1869  savequit();
1870  }
1871  }
1872  }
1873 
1874  return numNodesActivated;
1875 }
1876 
1877 
1878 
1879 
1880 int LAT_detector::check_cross_threshold(sf_vec & vm, sf_vec & vmp, double tm,
1881  int *ibuf, double *actbuf, float threshold, int mode)
1882 {
1883  SF_real *c = vm.ptr();
1884  SF_real *p = vmp.ptr();
1885  int lsize = vm.lsize();
1886  int nacts = 0, gnacts = 0;
1887 
1888  for (int i=0; i<lsize; i++) {
1889  int sgn = 1;
1890  bool triggered = false;
1891  if(mode==0) {// detect +slope crossing
1892  triggered = p[i] <= threshold && c[i] > threshold; }
1893  else { // detect -slope crossing
1894  triggered = p[i] >= threshold && c[i] < threshold;
1895  sgn = -1;
1896  }
1897 
1898  if (triggered) {
1899  double tact = tm - param_globals::dt + (threshold-p[i])/(c[i]-p[i])*sgn*param_globals::dt;
1900  ibuf [nacts] = i;
1901  actbuf[nacts] = tact;
1902  nacts++;
1903  }
1904  p[i] = c[i];
1905  }
1906 
1907  vm.release_ptr(c);
1908  vmp.release_ptr(p);
1909  return nacts;
1910 }
1911 
1912 int LAT_detector::check_mx_derivative(sf_vec & vm, sf_vec & vmp, double tm,
1913  int *ibuf, double *actbuf, sf_vec & dvp0, sf_vec & dvp1,
1914  float threshold, int mode)
1915 {
1916  int nacts = 0, gnacts = 0;
1917  double tact, dt2 = 2 * param_globals::dt;
1918  int lsize = vm.lsize();
1919  SF_real ddv0, ddv1, dv, dvdt;
1920  SF_real *c, *p, *pd0, *pd1;
1921 
1922  c = vm.ptr();
1923  p = vmp.ptr();
1924  pd0 = dvp0.ptr();
1925  pd1 = dvp1.ptr();
1926 
1927  for (int i=0; i<lsize; i++ ) {
1928  dv = (c[i]-p[i]);
1929  dvdt = dv/param_globals::dt;
1930  ddv0 = pd1[i]-pd0[i];
1931  ddv1 = dv -pd1[i];
1932 
1933  if (dvdt>=threshold && ddv0>0 && ddv1<0) {
1934  tact = tm-dt2+(ddv0/(ddv0-ddv1))*param_globals::dt;
1935  ibuf [nacts] = i;
1936  actbuf[nacts] = tact;
1937  nacts++;
1938  }
1939  p [i] = c[i];
1940  pd0[i] = pd1[i];
1941  pd1[i] = dv;
1942  }
1943 
1944  vm .release_ptr(c);
1945  vmp .release_ptr(p);
1946  dvp0.release_ptr(pd0);
1947  dvp1.release_ptr(pd1);
1948 
1949  return nacts;
1950 }
1951 
1956 {
1958  assert(sc != NULL);
1959 
1960  bool forward = true;
1961 
1962  for (size_t i = 0; i < acts.size(); i++) {
1963  if (is_init(acts[i].tm)) {
1964  (*sc)(*acts[i].tm, forward);
1965  acts[i].tm->write_ascii(acts[i].fname, false);
1966  }
1967  }
1968 }
1969 
1970 void Electrics::prepace() {
1971  log_msg(NULL, 0, 0, "Using activation times from file %s to distribute prepacing states\n",
1972  param_globals::prepacing_lats);
1973  log_msg(NULL, 0, 0, "Assuming stimulus strength %f uA/uF with duration %f ms for prepacing\n",
1974  param_globals::prepacing_stimstr, param_globals::prepacing_stimdur);
1975 
1976  limpet::MULTI_IF* miif = this->ion.miif;
1977 
1978  const sf_mesh & mesh = get_mesh(intra_elec_msh);
1979  sf_vec* read_lats; SF::init_vector(&read_lats, mesh, 1, sf_vec::algebraic);
1980 
1981  // read in the global distributed vector of all activation times
1982  set_dir(INPUT);
1983  size_t numread = read_lats->read_ascii(param_globals::prepacing_lats);
1984  if (numread == 0) {
1985  log_msg(NULL, 5, 0, "Failed reading required LATs! Skipping prepacing!");
1986  return;
1987  }
1988  set_dir(OUTPUT);
1989 
1991  assert(sc != NULL);
1992 
1993  // permute in-place to petsc permutation
1994  bool forward = false;
1995  (*sc)(*read_lats, forward);
1996 
1997  // take care of negative LAT values
1998  {
1999  PetscReal* lp = read_lats->ptr();
2000  for(int i=0; i<read_lats->lsize(); i++)
2001  if(lp[i] < 0.0) lp[i] = param_globals::tend + 10.0;
2002 
2003  read_lats->release_ptr(lp);
2004  }
2005 
2006  // make LATs relative and figure out the first LAT
2007  // so we know when to save state of each point
2008  SF_real LATmin = read_lats->min();
2009 
2010  if(LATmin < 0.0) {
2011  log_msg(0,3,0, "LAT data is not complete. Skipping prepacing.");
2012  return;
2013  }
2015  SF_real offset = floor(LATmin / param_globals::prepacing_bcl) * param_globals::prepacing_bcl;
2016  SF_real last_tm = param_globals::prepacing_bcl * param_globals::prepacing_beats;
2017 
2018  // compute read_lats[i] = last_tm - (read_lats[i] - offset)
2019  *read_lats += -offset;
2020  *read_lats *= -1.;
2021  *read_lats += last_tm;
2022 
2023  miif->getRealData();
2024  SF_real *save_tm = read_lats->ptr();
2025  SF_real *vm = miif->gdata[limpet::Vm]->ptr();
2026 
2027  for (int ii = 0; ii < miif->N_IIF; ii++) {
2028  if (!miif->N_Nodes[ii]) continue;
2029 
2030  // create sorted array of save times.
2031  SF::vector<SF::mixed_tuple<double,limpet::node_index_t>> sorted_save(miif->N_Nodes[ii]); // v1 = time, v2 = index
2032  for (limpet::node_index_t kk = 0; kk < miif->N_Nodes[ii]; kk++) {
2033  sorted_save[kk].v1 = save_tm[miif->NodeLists[ii][kk]];
2034  sorted_save[kk].v2 = kk;
2035  }
2036  std::sort(sorted_save.begin(), sorted_save.end());
2037 
2038  size_t lastidx = sorted_save.size() - 1;
2039  limpet::node_index_t paced = sorted_save[lastidx].v2; // IMP index of latest node
2040  limpet::node_index_t csav = 0;
2041 
2042  for (double t = 0; t < sorted_save[lastidx].v1; t += param_globals::dt) {
2043  if (fmod(t, param_globals::prepacing_bcl) < param_globals::prepacing_stimdur &&
2044  t < param_globals::prepacing_bcl * param_globals::prepacing_beats - 1)
2045  miif->ldata[ii][limpet::Vm][paced] += param_globals::prepacing_stimstr * param_globals::dt;
2046 
2047  compute_IIF(*miif->IIF[ii], miif->ldata[ii], paced);
2048 
2049  // Vm update always happens now outside of the imp
2050  miif->ldata[ii][limpet::Vm][paced] -= miif->ldata[ii][limpet::Iion][paced] * param_globals::dt;
2051  vm[miif->NodeLists[ii][paced]] = miif->ldata[ii][limpet::Vm][paced];
2052 
2053  while (csav < miif->N_Nodes[ii] - 1 && t >= sorted_save[csav].v1)
2054  dup_IMP_node_state(*miif->IIF[ii], paced, sorted_save[csav++].v2, miif->ldata[ii]);
2055  }
2056 
2057  // get nodes which may be tied for last
2058  while (csav < miif->N_Nodes[ii] - 1)
2059  dup_IMP_node_state(*miif->IIF[ii], paced, sorted_save[csav++].v2, miif->ldata[ii]);
2060  // ipdate global Vm vector
2061  for (limpet::node_index_t k = 0; k < miif->N_Nodes[ii]; k++) vm[miif->NodeLists[ii][k]] = miif->ldata[ii][limpet::Vm][k];
2062  }
2063 
2064  read_lats->release_ptr(save_tm);
2065  miif->gdata[limpet::Vm]->release_ptr(vm);
2066  miif->releaseRealData();
2067 }
2068 
2069 
2070 void recover_phie_std(sf_vec & vm, phie_recovery_data & rcv)
2071 {
2073  if (!rcv.pts.size())
2074  return;
2075 
2076  int rank = get_rank();
2077 
2078  if(!get_physics(elec_phys)) {
2079  log_msg(0,0,5, "There seems to be no EP is defined. Phie recovery requires active EP! Aborting!");
2080  return;
2081  }
2082 
2083  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
2084  sf_mat & Ki = *elec->parab_solver.rhs_parab;
2085 
2086  const sf_mesh & imesh = get_mesh(intra_elec_msh);
2087  const SF::vector<mesh_int_t> & alg_nod = imesh.pl.algebraic_nodes();
2088 
2089  SF_int start, end;
2090  vm.get_ownership_range(start, end);
2091 
2092  if(!rcv.Im) {
2093  SF::init_vector(&rcv.Im, &vm);
2094  SF::init_vector(&rcv.dphi, &vm);
2095  }
2096 
2097  SF_int r_start, r_end;
2098  rcv.phie_rec->get_ownership_range(r_start, r_end);
2099 
2100  SF_real *ph_r = rcv.phie_rec->ptr();
2101 
2102  // use minimum distance to ensure r>0
2103  // consistent with the line source approximation, the "cable radius"
2104  // is used as a lower limit for the source-field point distance
2105  float minDist = 2. / param_globals::imp_region[0].cellSurfVolRatio; // radius in um
2106 
2107  Ki.mult(vm, *rcv.Im);
2108  int numpts = rcv.pts.size() / 3;
2109  Point fpt, cpt;
2110 
2111  for (int j=0; j<numpts; j++) {
2112  fpt = rcv.pts.data() + j*3;
2113 
2114  *rcv.dphi = *rcv.Im;
2115  SF_real* dp = rcv.dphi->ptr();
2116 
2117  for (size_t i = 0; i<alg_nod.size(); i++)
2118  {
2119  mesh_int_t loc_nodal_idx = alg_nod[i];
2120  mesh_int_t loc_petsc_idx = local_nodal_to_local_petsc(imesh, rank, loc_nodal_idx);
2121  cpt = imesh.xyz.data()+loc_nodal_idx*3;
2122 
2123  double r = dist(fpt, cpt) + minDist;
2124  dp[loc_petsc_idx] /= r;
2125  }
2126 
2127  rcv.dphi->release_ptr(dp);
2128 
2129  SF_real phi = rcv.dphi->sum() / 4. / M_PI / rcv.gBath;
2130  if ( (j>=r_start) && (j<r_end) )
2131  ph_r[j-r_start] = phi;
2132  }
2133 
2134  rcv.phie_rec->release_ptr(ph_r);
2135 }
2136 
2138 {
2139  int err = 0, rank = get_rank();
2140 
2142  log_msg(0,0,5, "There seems to be no EP is defined. Phie recovery requires active EP! Aborting!");
2143  return 1;
2144  }
2145 
2146  sf_mesh & imesh = get_mesh(intra_elec_msh);
2147  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
2148  phie_recovery_data & phie_rcv = elec->phie_rcv;
2149 
2150  // we close the files of the default electrics if there are any open
2151  elec->output_manager.close_files_and_cleanup();
2152 
2153  // register output
2154  set_dir(POSTPROC);
2155  igb_output_manager phie_rec_out;
2156  phie_rec_out.register_output(phie_rcv.phie_rec, phie_recv_msh, 1,
2157  param_globals::phie_recovery_file, "mV");
2158 
2159  // Buffer for Vm data
2160  sf_vec* vm = get_data(vm_vec); assert(vm);
2161 
2162  // set up igb header and point fd to start of Vm file
2163  set_dir(OUTPUT);
2164  IGBheader vm_igb;
2165  if(rank == 0) {
2166  FILE_SPEC file = f_open(param_globals::vofile, "r");
2167  if(file != NULL) {
2168  vm_igb.fileptr(file->fd);
2169  vm_igb.read();
2170 
2171  if(vm_igb.x() != vm->gsize()) {
2172  log_msg(0,4,0, "%s error: Vm dimension does not fit to %s file. Aborting recovery! \n",
2173  __func__, param_globals::vofile);
2174  err++;
2175  }
2176 
2177  delete file;
2178  }
2179  else err++;
2180  }
2181 
2182  err = get_global(err, MPI_MAX);
2183 
2184  if(err == 0) {
2185  FILE* fd = static_cast<FILE*>(vm_igb.fileptr());
2186 
2187  // number of data slices
2188  const int num_io = user_globals::tm_manager->timers[iotm_spacedt]->numIOs;
2189 
2190  // scatterers
2192  assert(petsc_to_canonical != NULL);
2193 
2194  // loop over vm slices and recover phie
2195  for(int i=0; i<num_io; i++) {
2196  log_msg(0,0,0, "Step %d / %d", i+1, num_io);
2197  size_t nread = vm->read_binary<float>(fd);
2198 
2199  if(nread != size_t(vm->gsize())) {
2200  log_msg(0,3,0, "%s warning: read incomplete data slice! Aborting!", __func__);
2201  err++;
2202  break;
2203  }
2204 
2205  // permute vm_buff
2206  bool forward = false;
2207  (*petsc_to_canonical)(*vm, forward);
2208 
2209  // do phie computation
2210  recover_phie_std(*vm, phie_rcv);
2211 
2212  phie_rec_out.write_data();
2213  }
2214 
2215  phie_rec_out.close_files_and_cleanup();
2216  }
2217  return err;
2218 }
2219 
2220 void setup_phie_recovery_data(phie_recovery_data & data)
2221 {
2223  if(!get_physics(elec_phys) ) {
2224  log_msg(0,0,5, "There seems to be no EP is defined. Phie recovery requires active EP! Aborting!");
2225  return;
2226  }
2227 
2228  int rank = get_rank(), size = get_size();
2229  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
2230 
2231  sf_mesh & imesh = get_mesh(intra_elec_msh);
2232  const std::string basename = param_globals::phie_rec_ptf;
2233  SF::vector<mesh_int_t> ptsidx;
2234 
2235  set_dir(INPUT);
2236  SF::read_points(basename, imesh.comm, data.pts, ptsidx);
2237  make_global(data.pts, imesh.comm); // we want all ranks to have all points
2238 
2239  // set up parallel layout of recovery points
2240  SF::vector<mesh_int_t> layout;
2241  layout_from_count(mesh_int_t(ptsidx.size()), layout, imesh.comm);
2242 
2243  // set up petsc_vector for recovered potentials
2244  SF::init_vector(&data.phie_rec, layout[size], layout[rank+1]-layout[rank], 1, sf_vec::algebraic);
2245 
2246  // get conductivty
2247  SF::vector<RegionSpecs> & intra_regions = elec->mtype[Electrics::intra_grid].regions;
2248  data.gBath = static_cast<elecMaterial*>(intra_regions[0].material)->BathVal[0];
2249 }
2250 
2251 
2252 void Laplace::initialize()
2253 {
2255  int rank = get_rank();
2256 
2257  assert(param_globals::bidomain == BIDOMAIN);
2258  double t1, t2;
2259  get_time(t1);
2260 
2261  // set up Extracellular tissue
2264  mtype[Electrics::extra_grid].regionIDs, true, "gregion_e");
2265 
2266  // set up a subset of the complete electrical mappings
2267  int dpn = 1;
2269 
2271  // set up Intracellular tissue
2274  mtype[Electrics::intra_grid].regionIDs, true, "gregion_i");
2275 
2278  }
2279 
2280  // set up stimuli
2281  init_stim_info();
2282  stimuli.resize(param_globals::num_stim);
2284  for(int i=0; i<param_globals::num_stim; i++) {
2285  // construct new stimulus
2286  stimulus & s = stimuli[i];
2287 
2289  s.translate(i);
2290 
2291  s.setup(i);
2292 
2293  if(s.phys.type == Phi_ex) {
2294  s.pulse.wform = constPulse;
2295  sample_wave_form(s.pulse, i);
2296  }
2297  }
2298 
2299  set_dir(OUTPUT);
2300 
2301  ellip_solver.init();
2303 
2304  if(param_globals::dump2MatLab) {
2305  std::string bsname = param_globals::dump_basename;
2306  std::string fn;
2307 
2308  set_dir(OUTPUT);
2309  fn = bsname + "_Kie.bin";
2310  ellip_solver.phie_mat->write(fn.c_str());
2311  }
2312 
2313  // the laplace solver executes only once, thus we need a singlestep timer
2314  timer_idx = user_globals::tm_manager->add_singlestep_timer(0.0, 0.0, "laplace trigger", nullptr);
2315 
2316  SF::vector<mesh_int_t>* restr_i = NULL;
2317  SF::vector<mesh_int_t>* restr_e = NULL;
2318 
2319  setup_dataout(param_globals::dataout_e, param_globals::dataout_e_vtx, extra_elec_msh,
2320  restr_e, param_globals::num_io_nodes > 0);
2321  if(param_globals::dataout_e)
2322  output_manager.register_output(ellip_solver.phie, extra_elec_msh, 1, param_globals::phiefile, "mV", restr_e);
2323 
2325  setup_dataout(param_globals::dataout_i, param_globals::dataout_i_vtx, intra_elec_msh,
2326  restr_i, param_globals::num_io_nodes > 0);
2327  if(param_globals::dataout_i)
2328  output_manager.register_output(ellip_solver.phie_i, intra_elec_msh, 1, param_globals::phieifile, "mV", restr_i);
2329  }
2330 
2331  this->initialize_time += timing(t2, t1);
2333  this->compute_step();
2334 }
2335 
2336 void Laplace::destroy()
2337 {}
2338 
2339 void Laplace::compute_step()
2340 {
2342  // Laplace compute might be called multiple times, we want to run only once..
2343  if(!ellip_solver.lin_solver) return;
2344 
2345  double t0, t1, dur;
2346  log_msg(0,0,0, "Solving Laplace problem ..");
2347 
2348  get_time(t0);
2350  dur = timing(t1,t0);
2351 
2352  log_msg(0,0,0, "Done in %.5f seconds.", dur);
2353 
2355  this->compute_time += timing(t1, t0);
2356  set_dir(OUTPUT);
2359 
2360  // we clear the elliptic matrices and solver to save some memory when computing
2361  // the laplace solution on-the-fly
2362  delete ellip_solver.mass_e; ellip_solver.mass_e = NULL;
2363  delete ellip_solver.phie_mat; ellip_solver.phie_mat = NULL;
2365 }
2366 
2367 void Laplace::output_step()
2368 {}
2369 
2370 double Laplace::timer_val(const int timer_id)
2371 {
2372  int sidx = stimidx_from_timeridx(stimuli, timer_id);
2373  double val = 0.0;
2374 
2375  if(sidx != -1) stimuli[sidx].value(val);
2376  else val = std::nan("NaN");
2377  return val;
2378 }
2379 
2380 std::string Laplace::timer_unit(const int timer_id)
2381 {
2382  int sidx = stimidx_from_timeridx(stimuli, timer_id);
2383  std::string s_unit;
2384  if(sidx != -1) s_unit = stimuli[sidx].pulse.wave.f_unit;
2385  return s_unit;
2386 }
2387 
2389  sf_mat & mass_i,
2390  sf_mat & mass_e,
2391  limpet::MULTI_IF *miif,
2392  FILE_SPEC logger)
2393 {
2395 
2396  for(stimulus & s : stimuli) {
2397  if(is_current(s.phys.type) && s.phys.total_current) {
2398  // extracellular current injection
2399  if (s.phys.type == I_ex) {
2400  // compute affected volume in um^3
2401  SF_real vol = get_volume_from_nodes(mass_e, s.electrode.vertices);
2402 
2403  // s->strength holds the total current in uA, compute current density in uA/cm^3
2404  // Theoretically, we don't need to scale the volume to cm^3 here since we later
2405  // multiply with the mass matrix and we get um^3 * uA/um^3 = uA.
2406  // However, for I_ex there is an additional um^3 to cm^3 scaling in phys.scale,
2407  // since I_e is expected to be in uA/cm^3. Therefore, we need to compensate for that to arrive at uA later.
2408  float scale = 1.e12/vol;
2409 
2410  s.pulse.strength *= scale;
2411 
2412  log_msg(logger,0,ECHO,
2413  "%s [Stimulus %d]: current density scaled to %.4g uA/cm^3\n",
2414  s.name.c_str(), s.idx, s.pulse.strength);
2415  }
2416  else if (s.phys.type == I_tm) {
2417  // compute affected volume in um^3
2418  SF_real vol = get_volume_from_nodes(mass_i, s.electrode.vertices);
2419  const sf_mesh & imesh = get_mesh(intra_elec_msh);
2420  const SF::vector<mesh_int_t> & alg_nod = imesh.pl.algebraic_nodes();
2421 
2422  if(alg_idx_map.size() == 0) {
2423  mesh_int_t lidx = 0;
2424  for(mesh_int_t n : alg_nod) {
2425  alg_idx_map[n] = lidx;
2426  lidx++;
2427  }
2428  }
2429 
2430  SF_real surf = 0.0;
2431  for(mesh_int_t n : s.electrode.vertices) {
2432  if(alg_idx_map.count(n)) {
2433  mesh_int_t lidx = alg_idx_map[n];
2434  int r = miif->IIFmask[lidx];
2435  // surf = vol*beta [1/um], surf is in [um^2]
2436  surf = vol * miif->IIF[r]->cgeom().SVratio * param_globals::imp_region[r].volFrac;
2437  //convert to cm^2
2438  surf /= 1.e8;
2439  break;
2440  }
2441  }
2442  surf = get_global(surf, MPI_MAX, PETSC_COMM_WORLD);
2443 
2444  // scale surface density now to result in correct total current
2445  s.pulse.strength /= surf;
2446  log_msg(logger, 0, ECHO,
2447  "%s [Stimulus %d]: current density scaled to %.4g uA/cm^2\n",
2448  s.name.c_str(), s.idx, s.pulse.strength);
2449  }
2450  }
2451  }
2452 }
2453 
2454 
2455 
2456 } // namespace opencarp
#define M_PI
Definition: ION_IF.h:54
opencarp::local_index_t mesh_int_t
Definition: SF_container.h:46
opencarp::real_t SF_real
Global scalar type.
Definition: SF_globals.h:33
opencarp::global_index_t SF_int
Global algebraic index type.
Definition: SF_globals.h:32
#define ECHO
Definition: basics.h:316
#define NONL
Definition: basics.h:320
#define CALI_CXX_MARK_FUNCTION
Definition: caliper_hooks.h:5
virtual void mult(const abstract_vector< T, S > &x, abstract_vector< T, S > &b) const =0
virtual void scale(S s)=0
virtual void zero()=0
virtual void get_diagonal(abstract_vector< T, S > &vec) const =0
virtual void mult_LR(const abstract_vector< T, S > &L, const abstract_vector< T, S > &R)=0
virtual void init(T iNRows, T iNCols, T ilrows, T ilcols, T loc_offset, T mxent)
virtual void duplicate(const abstract_matrix< T, S > &M)=0
virtual void add_scaled_matrix(const abstract_matrix< T, S > &A, const S s, const bool same_nnz)=0
virtual void write(const char *filename) const =0
virtual S mag() const =0
virtual S * ptr()=0
virtual void release_ptr(S *&p)=0
virtual void deep_copy(const abstract_vector< T, S > &v)=0
virtual void shallow_copy(const abstract_vector< T, S > &v)=0
virtual void add_scaled(const abstract_vector< T, S > &vec, S k)=0
virtual T lsize() const =0
virtual void set(const vector< T > &idx, const vector< S > &vals, const bool additive=false, const bool local=false)=0
const meshdata< mesh_int_t, mesh_real_t > * mesh
the connected mesh
T forward_map(T idx) const
Map one index from a to b.
Definition: SF_container.h:264
overlapping_layout< T > pl
nodal parallel layout
Definition: SF_container.h:429
vector< T > con
Definition: SF_container.h:412
vector< T > & get_numbering(SF_nbr nbr_type)
Get the vector defining a certain numbering.
Definition: SF_container.h:464
Container for a PETSc VecScatter.
void forward(abstract_vector< T, S > &in, abstract_vector< T, S > &out, bool add=false)
Forward scattering.
void backward(abstract_vector< T, S > &in, abstract_vector< T, S > &out, bool add=false)
Backward scattering.
size_t size() const
The current size of the vector.
Definition: SF_vector.h:104
void resize(size_t n)
Resize a vector.
Definition: SF_vector.h:209
const T * end() const
Pointer to the vector's end.
Definition: SF_vector.h:128
const T * begin() const
Pointer to the vector's start.
Definition: SF_vector.h:116
T * data()
Pointer to the vector's start.
Definition: SF_vector.h:91
T & push_back(T val)
Definition: SF_vector.h:283
hm_int count(const K &key) const
Check if key exists.
Definition: hashmap.hpp:627
size_t size() const
Definition: hashmap.hpp:735
void insert(InputIterator first, InputIterator last)
Definition: hashmap.hpp:1052
std::vector< IonIfBase * > IIF
array of IIF's
Definition: MULTI_ION_IF.h:213
opencarp::sf_vec * gdata[NUM_IMP_DATA_TYPES]
data used by all IMPs
Definition: MULTI_ION_IF.h:227
node_count_t numNode
local number of nodes
Definition: MULTI_ION_IF.h:221
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:216
int N_IIF
how many different IIF's
Definition: MULTI_ION_IF.h:222
node_count_t * N_Nodes
#nodes for each IMP
Definition: MULTI_ION_IF.h:211
node_index_t ** NodeLists
local partitioned node lists for each IMP stored
Definition: MULTI_ION_IF.h:212
IIF_Mask_t * IIFmask
region for each node
Definition: MULTI_ION_IF.h:225
int timer_idx
the timer index received from the timer manager
Definition: physics_types.h:66
FILE_SPEC logger
The logger of the physic, each physic should have one.
Definition: physics_types.h:64
SF::vector< stimulus > stimuli
the electrical stimuli
Definition: electrics.h:264
LAT_detector lat
the activation time detector
Definition: electrics.h:276
grid_t
An electrics grid identifier to distinguish between intra and extra grids.
Definition: electrics.h:258
phie_recovery_data phie_rcv
struct holding helper data for phie recovery
Definition: electrics.h:285
generic_timing_stats IO_stats
Definition: electrics.h:287
void destroy()
Currently we only need to close the file logger.
Definition: electrics.cc:371
gvec_data gvec
datastruct holding global IMP state variable output
Definition: electrics.h:279
elliptic_solver ellip_solver
Solver for the elliptic bidomain equation.
Definition: electrics.h:271
MaterialType mtype[2]
the material types of intra_grid and extra_grid grids.
Definition: electrics.h:262
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
Definition: electrics.cc:843
parabolic_solver parab_solver
Solver for the parabolic bidomain equation.
Definition: electrics.h:273
double timer_val(const int timer_id)
figure out current value of a signal linked to a given timer
Definition: electrics.cc:827
void initialize()
Initialize the Electrics.
Definition: electrics.cc:44
igb_output_manager output_manager
class handling the igb output
Definition: electrics.h:282
int read(bool quiet=false)
Definition: IGBheader.cc:761
void fileptr(gzFile f)
Definition: IGBheader.cc:336
limpet::MULTI_IF * miif
Definition: ionics.h:67
void compute_step()
Definition: ionics.cc:35
void initialize()
Definition: ionics.cc:60
void destroy()
Definition: ionics.cc:52
SF::index_mapping< mesh_int_t > petsc_to_nodal
Definition: electrics.h:220
int check_quiescence(double tm, double dt)
check for quiescence
Definition: electrics.cc:1790
void output_initial_activations()
output one nodal vector of initial activation time
Definition: electrics.cc:1899
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:1610
int check_acts(double tm)
check activations at sim time tm
Definition: electrics.cc:1735
SF::vector< Activation > acts
Definition: electrics.h:219
LAT_detector()
constructor, sets up basic datastructs from global_params
Definition: electrics.cc:1482
SF::vector< stimulus > stimuli
the electrical stimuli
Definition: electrics.h:392
elliptic_solver ellip_solver
Solver for the elliptic bidomain equation.
Definition: electrics.h:395
double timer_val(const int timer_id)
figure out current value of a signal linked to a given timer
Definition: electrics.cc:2314
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
Definition: electrics.cc:2324
MaterialType mtype[2]
the material types of intra_grid and extra_grid grids.
Definition: electrics.h:390
igb_output_manager output_manager
class handling the igb output
Definition: electrics.h:397
manager for dirichlet boundary conditions
Definition: stimulate.h:206
void enforce_dbc_rhs(sf_vec &rhs)
Definition: stimulate.cc:691
void recompute_dbcs()
recompute the dbc data.
Definition: stimulate.cc:612
bool dbc_update()
check if dbcs have updated
Definition: stimulate.cc:651
sf_mat * phie_mat
lhs matrix to solve elliptic
Definition: electrics.h:54
void rebuild_stiffness(MaterialType *mtype, SF::vector< stimulus > &stimuli, FILE_SPEC logger)
Definition: electrics.cc:1031
void rebuild_matrices(MaterialType *mtype, SF::vector< stimulus > &stimuli, FILE_SPEC logger)
Definition: electrics.cc:1019
lin_solver_stats stats
Definition: electrics.h:60
sf_vec * phie_i
phi_e on intracellular grid
Definition: electrics.h:49
void solve(sf_mat &Ki, sf_vec &Vmv, sf_vec &tmp_i)
Definition: electrics.cc:1136
sf_vec * phie
phi_e
Definition: electrics.h:48
sf_sol * lin_solver
petsc or ginkgo lin_solver
Definition: electrics.h:57
sf_mat * mass_e
mass matrix for RHS elliptic calc
Definition: electrics.h:53
double tol
CG stopping tolerance.
Definition: electrics.h:67
sf_vec * currtmp
temp vector for phiesrc
Definition: electrics.h:51
dbc_manager * dbc
dbcs require a dbc manager
Definition: electrics.h:63
int max_it
maximum number of iterations
Definition: electrics.h:68
sf_vec * phiesrc
I_e.
Definition: electrics.h:50
void rebuild_mass(FILE_SPEC logger)
Definition: electrics.cc:1092
void write_data()
write registered data to disk
Definition: sim_utils.cc:2816
void register_output_sync(sf_vec *inp_data, const mesh_t inp_meshid, const int dpn, const char *name, const char *units, const SF::vector< mesh_int_t > *idx=NULL, bool elem_data=false)
Definition: sim_utils.cc:2642
void close_files_and_cleanup()
close file descriptors
Definition: sim_utils.cc:2872
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:2783
sf_vec * Ivol
global Vm vector
Definition: electrics.h:107
double tol
CG stopping tolerance.
Definition: electrics.h:132
sf_vec * Iact
global Vm vector
Definition: electrics.h:108
sf_vec * Diff_term
Diffusion current.
Definition: electrics.h:123
sf_mat * rhs_parab
rhs matrix to solve parabolic
Definition: electrics.h:119
sf_vec * kappa_i
scaling vector for intracellular mass matrix, M
Definition: electrics.h:111
lin_solver_stats stats
Definition: electrics.h:129
void rebuild_matrices(MaterialType *mtype, limpet::MULTI_IF &miif, FILE_SPEC logger)
Definition: electrics.cc:1261
parabolic_t parab_tech
manner in which parabolic equations are solved
Definition: electrics.h:134
void solve(sf_vec &phie_i)
Definition: electrics.cc:1375
sf_vec * inv_mass_diag
inverse diagonal of mass matrix, for EXPLICIT solving
Definition: electrics.h:115
sf_mat * mass_i
lumped for parabolic problem
Definition: electrics.h:118
sf_vec * Ic
global Vm vector
Definition: electrics.h:106
sf_vec * tmp_i2
scratch vector for i-grid
Definition: electrics.h:113
int max_it
maximum number of iterations
Definition: electrics.h:133
sf_vec * tmp_i1
scratch vector for i-grid
Definition: electrics.h:112
sf_mat * lhs_parab
lhs matrix (CN) to solve parabolic
Definition: electrics.h:120
sf_vec * Vmv
global Vm vector
Definition: electrics.h:104
sf_vec * Irhs
weighted transmembrane currents
Definition: electrics.h:114
sf_vec * old_vm
older Vm needed for 2nd order dT
Definition: electrics.h:110
sf_sol * lin_solver
petsc or ginkgo lin_solver
Definition: electrics.h:126
sf_vec * IIon
ionic currents
Definition: electrics.h:103
SF::vector< mesh_int_t > vertices
Definition: stimulate.h:153
bool total_current
whether we apply total current scaling
Definition: stimulate.h:141
stim_t type
type of stimulus
Definition: stimulate.h:138
int timer_id
timer for stimulus
Definition: stimulate.h:123
waveform_t wform
wave form of stimulus
Definition: stimulate.h:96
double strength
strength of stimulus
Definition: stimulate.h:94
stim_protocol ptcl
applied stimulation protocol used
Definition: stimulate.h:169
int idx
index in global input stimulus array
Definition: stimulate.h:165
stim_electrode electrode
electrode geometry
Definition: stimulate.h:171
stim_pulse pulse
stimulus wave form
Definition: stimulate.h:168
void translate(int id)
convert legacy definitions to new format
Definition: stimulate.cc:107
void setup(int idx)
Setup from a param stimulus index.
Definition: stimulate.cc:168
stim_physics phys
physics of stimulus
Definition: stimulate.h:170
bool value(double &v) const
Get the current value if the stimulus is active.
Definition: stimulate.cc:449
long d_time
current time instance index
Definition: timer_utils.h:77
double time_step
global reference time step
Definition: timer_utils.h:78
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:78
int add_singlestep_timer(double tg, double idur, const char *iname, const char *poolname=nullptr)
Definition: timer_utils.h:143
long d_end
final index in multiples of dt
Definition: timer_utils.h:82
std::vector< base_timer * > timers
vector containing individual timers
Definition: timer_utils.h:84
double time
current time
Definition: timer_utils.h:76
Tissue level electrics, main Electrics physics class.
#define DUMP_IC
Definition: electrics.h:39
#define DUMP_IACT
Definition: electrics.h:41
#define DUMP_IVOL
Definition: electrics.h:40
void init_solver(SF::abstract_linear_solver< T, S > **sol)
Definition: SF_init.h:229
void compute_surface_mesh(const meshdata< T, S > &mesh, const SF_nbr numbering, const hashmap::unordered_set< T > &tags, meshdata< T, S > &surfmesh)
Compute the surface of a given mesh.
void read_points(const std::string basename, const MPI_Comm comm, vector< S > &pts, vector< T > &ptsidx)
Read the points and insert them into a list of meshes.
Definition: SF_mesh_io.h:953
void make_global(const vector< T > &vec, vector< T > &out, MPI_Comm comm)
make a parallel vector global
Definition: SF_network.h:225
void unique_resize(vector< T > &_P)
Definition: SF_sort.h:348
void assemble_matrix(abstract_matrix< T, S > &mat, meshdata< mesh_int_t, mesh_real_t > &domain, matrix_integrator< mesh_int_t, mesh_real_t > &integrator)
Generalized matrix assembly.
int max_nodal_edgecount(const meshdata< T, S > &mesh)
Compute the maximum number of node-to-node edges for a mesh.
Definition: SF_container.h:608
void local_petsc_to_nodal_mapping(const meshdata< T, S > &mesh, index_mapping< T > &petsc_to_nodal)
T local_nodal_to_local_petsc(const meshdata< T, S > &mesh, int rank, T local_nodal)
void assemble_lumped_matrix(abstract_matrix< T, S > &mat, meshdata< mesh_int_t, mesh_real_t > &domain, matrix_integrator< mesh_int_t, mesh_real_t > &integrator)
bool is_init(const abstract_vector< T, S > *v)
void layout_from_count(const T count, vector< T > &layout, MPI_Comm comm)
Definition: SF_network.h:201
void init_vector(SF::abstract_vector< T, S > **vec)
Definition: SF_init.h:107
void binary_sort(vector< T > &_V)
Definition: SF_sort.h:284
void init_matrix(SF::abstract_matrix< T, S > **mat)
Definition: SF_init.h:208
@ NBR_PETSC
PETSc numbering of nodes.
Definition: SF_container.h:203
@ NBR_REF
The nodal numbering of the reference mesh (the one stored on HD).
Definition: SF_container.h:201
@ NBR_SUBMESH
Submesh nodal numbering: The globally ascending sorted reference indices are reindexed.
Definition: SF_container.h:202
void dup_IMP_node_state(IonIfBase &IF, node_index_t from, node_index_t to, GlobalData_t **localdata)
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.
opencarp::local_index_t node_index_t
Definition: limpet_types.h:28
timer_manager * tm_manager
a manager for the various physics timers
Definition: main.cc:55
bool using_legacy_stimuli
flag storing whether legacy stimuli are used
Definition: main.cc:61
void get_kappa(sf_vec &kappa, IMPregion *ir, limpet::MULTI_IF &miif, double k)
compute the vector
Definition: electrics.cc:885
void compute_IIF(limpet::IonIfBase &pIF, limpet::GlobalData_t **impdata, limpet::node_index_t n)
Definition: ionics.cc:508
physic_t
Identifier for the different physics we want to set up.
Definition: physics_types.h:51
int stimidx_from_timeridx(const SF::vector< stimulus > &stimuli, const int timer_id)
determine link between timer and stimulus
Definition: electrics.cc:857
@ iotm_chkpt_list
Definition: timer_utils.h:44
@ iotm_console
Definition: timer_utils.h:44
@ iotm_spacedt
Definition: timer_utils.h:44
@ iotm_trace
Definition: timer_utils.h:44
@ iotm_chkpt_intv
Definition: timer_utils.h:44
sf_vec * get_data(datavec_t d)
Retrieve a petsc data vector from the data registry.
Definition: sim_utils.cc:2013
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 set_cond_type(MaterialType &m, cond_t type)
Definition: electrics.cc:909
void sample_wave_form(stim_pulse &sp, int idx)
sample a signal given in analytic form
Definition: stimulate.cc:349
void read_el_scale_vec(const char *file, mesh_t mt, SF::vector< double > &el_scale, int &el_scale_dpn)
SF_real get_volume_from_nodes(sf_mat &mass, SF::vector< mesh_int_t > &local_idx)
Definition: fem_utils.cc:217
sf_mesh & get_mesh(const mesh_t gt)
Get a mesh by specifying the gridID.
Definition: sf_interface.cc:33
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:69
cond_t
description of electrical tissue properties
Definition: fem_types.h:42
@ sum_cond
Definition: fem_types.h:43
@ intra_cond
Definition: fem_types.h:43
@ para_cond
Definition: fem_types.h:43
void print_act_log(FILE_SPEC logger, const SF::vector< Activation > &acts, int idx)
Definition: electrics.cc:1585
SF::scattering * get_permutation(const int mesh_id, const int perm_id, const int dpn)
Get the PETSC to canonical permutation scattering for a given mesh and number of dpn.
void region_mask(mesh_t meshspec, SF::vector< RegionSpecs > &regspec, SF::vector< int > &regionIDs, bool mask_elem, const char *reglist, bool warn_on_default_tags)
classify elements/points as belonging to a region
Definition: ionics.cc:404
bool is_dbc(stim_t type)
whether stimulus is a dirichlet type. implies boundary conditions on matrix
Definition: stimulate.cc:78
SF::meshdata< mesh_int_t, mesh_real_t > sf_mesh
Definition: sf_interface.h:48
@ constPulse
Definition: stimulate.h:75
void compute_restr_idx_async(sf_mesh &mesh, SF::vector< mesh_int_t > &inp_idx, SF::vector< mesh_int_t > &idx)
Definition: electrics.cc:578
void apply_stim_to_vector(const stimulus &s, sf_vec &vec, bool add)
Definition: electrics.cc:453
void recover_phie_std(sf_vec &vm, phie_recovery_data &rcv)
Definition: electrics.cc:2014
int set_dir(IO_t dest)
Definition: sim_utils.cc:1549
@ ACT_THRESH
Definition: electrics.h:172
int get_rank(MPI_Comm comm=PETSC_COMM_WORLD)
Definition: basics.h:284
T get_global(T in, MPI_Op OP, MPI_Comm comm=PETSC_COMM_WORLD)
Do a global reduction on a variable.
Definition: basics.h:233
V dist(const vec3< V > &p1, const vec3< V > &p2)
Definition: vect.h:114
@ Phi_ex
Definition: stimulate.h:79
@ Vm_clmp
Definition: stimulate.h:79
void init_stim_info(void)
uses potential for stimulation
Definition: stimulate.cc:49
int output_all_activations(FILE_SPEC fp, int *ibuf, double *act_tbuf, int nlacts)
Definition: electrics.cc:1689
FILE_SPEC f_open(const char *fname, const char *mode)
Open a FILE_SPEC.
Definition: basics.cc:138
void savequit()
save state and quit simulator
Definition: sim_utils.cc:2991
bool have_dbc_stims(const SF::vector< stimulus > &stimuli)
return wheter any stimuli require dirichlet boundary conditions
Definition: electrics.cc:934
SF::scattering * register_permutation(const int mesh_id, const int perm_id, const int dpn)
Register a permutation between two orderings for a mesh.
bool is_current(stim_t type)
uses current as stimulation
Definition: stimulate.cc:73
char * get_file_dir(const char *file)
Definition: sim_utils.cc:2601
@ POSTPROC
Definition: sim_utils.h:54
@ CURDIR
Definition: sim_utils.h:54
@ OUTPUT
Definition: sim_utils.h:54
void init_sv_gvec(gvec_data &GVs, limpet::MULTI_IF *miif, sf_vec &tmpl, igb_output_manager &output_manager)
Definition: ionics.cc:610
void assemble_sv_gvec(gvec_data &gvecs, limpet::MULTI_IF *miif)
Definition: ionics.cc:681
void constant_total_stimulus_current(SF::vector< stimulus > &stimuli, sf_mat &mass_i, sf_mat &mass_e, limpet::MULTI_IF *miif, FILE_SPEC logger)
Scales stimulus current to maintain constant total current across affected regions.
Definition: electrics.cc:2332
void intersect_output_restriction(SF::vector< mesh_int_t > *&restr, const SF::vector< mesh_int_t > &selected_idx)
Intersect an existing output restriction with another local index set.
Definition: sim_utils.cc:2456
int postproc_recover_phie()
Definition: electrics.cc:2081
char * dupstr(const char *old_str)
Definition: basics.cc:44
void balance_electrode(elliptic_solver &ellip, SF::vector< stimulus > &stimuli, int balance_from, int balance_to)
Definition: electrics.cc:387
void set_elec_tissue_properties(MaterialType *mtype, Electrics::grid_t g, FILE_SPEC logger)
Fill the RegionSpec of an electrics grid with the associated inputs from the param parameters.
Definition: electrics.cc:109
void compute_restr_idx(sf_mesh &mesh, SF::vector< mesh_int_t > &inp_idx, SF::vector< mesh_int_t > &idx)
Definition: electrics.cc:545
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
Definition: basics.cc:72
mesh_t
The enum identifying the different meshes we might want to load.
Definition: sf_interface.h:59
@ extra_elec_msh
Definition: sf_interface.h:61
@ phie_recv_msh
Definition: sf_interface.h:70
@ intra_elec_msh
Definition: sf_interface.h:60
void get_time(double &tm)
Definition: basics.h:444
bool mesh_is_registered(const mesh_t gt)
check wheter a SF mesh is set
Definition: sf_interface.cc:63
bool parse_gridout_tags(hashmap::unordered_set< int > &output_tags)
Parse the gridout_tags idset into a unique set of region IDs.
Definition: sim_utils.cc:2367
void validate_gridout_tags(hashmap::unordered_set< int > &output_tags, const SF::vector< mesh_t > &mesh_ids)
Warn about selected gridout tags that are absent from the relevant meshes.
Definition: sim_utils.cc:2406
void setup_phie_recovery_data(phie_recovery_data &data)
Definition: electrics.cc:2164
SF::abstract_vector< SF_int, SF_real > sf_vec
Definition: sf_interface.h:50
int get_size(MPI_Comm comm=PETSC_COMM_WORLD)
Definition: basics.h:298
Basic_physic * get_physics(physic_t p, bool error_if_missing)
Convinience function to get a physics.
Definition: sim_utils.cc:1997
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:613
const char * get_tsav_ext(double time)
Definition: electrics.cc:943
SF::abstract_matrix< SF_int, SF_real > sf_mat
Definition: sf_interface.h:52
V timing(V &t2, const V &t1)
Definition: basics.h:456
void read_indices(SF::vector< T > &idx, const std::string filename, const hashmap::unordered_map< mesh_int_t, mesh_int_t > &dd_map, MPI_Comm comm)
Read indices from a file.
Definition: fem_utils.h:120
void build_tagged_nodal_output_restriction(sf_mesh &mesh, const hashmap::unordered_set< int > &output_tags, SF::vector< mesh_int_t > &output_idx, bool async)
Build a local output-vector restriction from mesh element tags.
Definition: sim_utils.cc:2389
void update_cwd()
save the current working directory to curdir so that we can switch back to it if needed.
Definition: sim_utils.cc:1544
void f_close(FILE_SPEC &f)
Close a FILE_SPEC.
Definition: basics.cc:165
@ ElecMat
Definition: fem_types.h:39
vec3< POINT_REAL > Point
Definition: vect.h:93
file_desc * FILE_SPEC
Definition: basics.h:140
#define UM2_to_CM2
convert um^2 to cm^2
Definition: physics_types.h:35
#define PETSC_TO_CANONICAL
Permute algebraic data from PETSC to canonical ordering.
Definition: sf_interface.h:79
#define ALG_TO_NODAL
Scatter algebraic to nodal.
Definition: sf_interface.h:77
#define DATAOUT_SURF
Definition: sim_utils.h:59
#define BIDOMAIN
Definition: sim_utils.h:189
#define DATAOUT_VOL
Definition: sim_utils.h:60
#define MONODOMAIN
Definition: sim_utils.h:188
#define EXP_POSTPROCESS
Definition: sim_utils.h:207
#define DATAOUT_NONE
Definition: sim_utils.h:58
#define PSEUDO_BIDM
Definition: sim_utils.h:190
#define DATAOUT_VTX
Definition: sim_utils.h:61
Electrical stimulation functions.
SF_int niter
number of iterations
SF_int reason
number of iterations
std::string name
the solver name
virtual void setup_solver(abstract_matrix< T, S > &mat, double tol, int max_it, short norm, std::string name, bool has_nullspace, void *logger, const char *solver_opts_file, const char *default_opts)=0
event detection data structures
Definition: electrics.h:175
description of materal properties in a mesh
Definition: fem_types.h:121
SF::vector< RegionSpecs > regions
array with region params
Definition: fem_types.h:126
SF::vector< double > el_scale
optionally provided per-element params scale
Definition: fem_types.h:127
int el_scale_dpn
0=disabled, 1=isotropic scalar, 3=anisotropic (sl, st, sn) per element
Definition: fem_types.h:128
region based variations of arbitrary material parameters
Definition: fem_types.h:93
physMaterial * material
material parameter description
Definition: fem_types.h:98
int nsubregs
#subregions forming this region
Definition: fem_types.h:96
int * subregtags
FEM tags forming this region.
Definition: fem_types.h:97
char * regname
name of region
Definition: fem_types.h:94
int regID
region ID
Definition: fem_types.h:95
bool activated
flag sentinel activation
Definition: electrics.h:199
int ID
ID of LAT detector used as sentinel.
Definition: electrics.h:203
double t_start
start of observation window
Definition: electrics.h:200
double t_window
duration of observation window
Definition: electrics.h:201
double t_quiesc
measure current duration of quiescence
Definition: electrics.h:202
double ExVal[3]
extracellular conductivity eigenvalues
Definition: fem_types.h:62
cond_t g
rule to build conductivity tensor
Definition: fem_types.h:64
double InVal[3]
intracellular conductivity eigenvalues
Definition: fem_types.h:61
double BathVal[3]
bath conductivity eigenvalues
Definition: fem_types.h:63
File descriptor struct.
Definition: basics.h:135
void log_stats(double tm, bool cflg)
Definition: timers.cc:93
void init_logger(const char *filename)
Definition: timers.cc:77
int calls
# calls for this interval, this is incremented externally
Definition: timers.h:70
double tot_time
total time, this is incremented externally
Definition: timers.h:72
void init_logger(const char *filename)
Definition: timers.cc:11
void log_stats(double tm, bool cflg)
Definition: timers.cc:27
void update_iter(const int curiter)
Definition: timers.cc:69
double slvtime
total solver time
Definition: timers.h:21
sf_vec * phie_rec
The phie recovery output vector buffer.
Definition: electrics.h:242
SF::vector< mesh_real_t > pts
The phie recovery locations.
Definition: electrics.h:241
physMat_t material_type
ID of physics material.
Definition: fem_types.h:53