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 {
616  sf_mesh & mesh = get_mesh(grid);
617 
618  switch(dataout) {
619 
620  case DATAOUT_SURF: {
621  sf_mesh surfmesh;
622  compute_surface_mesh(mesh, SF::NBR_SUBMESH, surfmesh);
623 
624  SF::vector<mesh_int_t> idxbuff(surfmesh.con);
625  binary_sort(idxbuff); unique_resize(idxbuff);
626 
627  restr = new SF::vector<mesh_int_t>();
628 
629  // for sync output, we need restr to hold the local indices in the petsc vectors
630  // that have been permuted to canonical numbering. For async, we need the
631  // non-overlapping decomposition of indices in NBR_SUBMESH numbering. The petsc indices will be
632  // computed at a later stage. The only reason we need to call compute_restr_idx_async,
633  // is that surface nodes in NBR_SUBMESH, may
634  // reside on partitions where they are not part of the algebraic nodes. thus we need to
635  // recommunicate to make sure the data layout is correct. We do not have this problem for
636  // DATAOUT_VTX.
637  if(!async)
638  compute_restr_idx(mesh, idxbuff, *restr);
639  else
640  compute_restr_idx_async(mesh, idxbuff, *restr);
641 
642  break;
643  }
644 
645  case DATAOUT_VTX: {
646  SF::vector<mesh_int_t> idxbuff;
647 
648  update_cwd();
649 
650  set_dir(INPUT);
651  read_indices(idxbuff, dataout_vtx, mesh, SF::NBR_REF, true, PETSC_COMM_WORLD);
652  set_dir(CURDIR);
653 
654  restr = new SF::vector<mesh_int_t>();
655 
656  if(!async) {
658  for(mesh_int_t & i : idxbuff) i = nbr[i];
659 
660  compute_restr_idx(mesh, idxbuff, *restr);
661  } else {
662  *restr = idxbuff;
663  }
664 
665  break;
666  }
667 
668  case DATAOUT_NONE:
669  case DATAOUT_VOL:
670  default: break;
671  }
672 }
673 
674 void Electrics::setup_output()
675 {
676  int rank = get_rank();
677  SF::vector<mesh_int_t>* restr_i = NULL;
678  SF::vector<mesh_int_t>* restr_e = NULL;
679  set_dir(OUTPUT);
680 
681  setup_dataout(param_globals::dataout_i, param_globals::dataout_i_vtx, intra_elec_msh,
682  restr_i, param_globals::num_io_nodes > 0);
683 
684  if(param_globals::dataout_i)
685  output_manager.register_output(parab_solver.Vmv, intra_elec_msh, 1, param_globals::vofile, "mV", restr_i);
686 
687  if(param_globals::bidomain) {
688  setup_dataout(param_globals::dataout_e, param_globals::dataout_e_vtx, extra_elec_msh,
689  restr_e, param_globals::num_io_nodes > 0);
690 
691  if(param_globals::dataout_i)
692  output_manager.register_output(ellip_solver.phie_i, intra_elec_msh, 1, param_globals::phieifile, "mV", restr_i);
693  if(param_globals::dataout_e)
694  output_manager.register_output(ellip_solver.phie, extra_elec_msh, 1, param_globals::phiefile, "mV", restr_e);
695  }
696 
697  if(param_globals::dump_data & DUMP_IC) {
698  output_manager.register_output(parab_solver.Ic, intra_elec_msh, 1, "Ic.igb", "uA/cm^2", restr_i);
699  output_manager.register_output(parab_solver.IIon, intra_elec_msh, 1, "Iion.igb","uA/cm^2", restr_i);
700  }
701 
702  if(param_globals::dump_data & DUMP_IVOL)
703  output_manager.register_output(parab_solver.Ivol, intra_elec_msh, 1, "Ivol.igb", "uA", restr_i);
704  if(param_globals::dump_data & DUMP_IACT)
705  output_manager.register_output(parab_solver.Iact, intra_elec_msh, 1, "Iact.igb", "uA", restr_i);
706 
707  if(phie_rcv.pts.size())
708  output_manager.register_output_sync(phie_rcv.phie_rec, phie_recv_msh, 1, param_globals::phie_recovery_file, "mV");
709 
711 
712  if(param_globals::num_trace) {
713  sf_mesh & imesh = get_mesh(intra_elec_msh);
714  open_trace(ion.miif, param_globals::num_trace, param_globals::trace_node, NULL, &imesh);
715  }
716 
717  // initialize generic logger for IO timings per time_dt
718  IO_stats.init_logger("IO_stats.dat");
719 }
720 
721 void Electrics::dump_matrices()
722 {
723  std::string bsname = param_globals::dump_basename;
724  std::string fn;
725 
726  set_dir(OUTPUT);
727 
728  // dump monodomain matrices
729  if ( param_globals::parab_solve==1 ) {
730  // using Crank-Nicolson
731  fn = bsname + "_Ki_CN.bin";
732  parab_solver.lhs_parab->write(fn.c_str());
733  }
734  fn = bsname + "_Ki.bin";
735  parab_solver.rhs_parab->write(fn.c_str());
736 
737  fn = bsname + "_Mi.bin";
738  parab_solver.mass_i->write(fn.c_str());
739 
740  if ( param_globals::bidomain ) {
741  fn = bsname + "_Kie.bin";
742  ellip_solver.phie_mat->write(fn.c_str());
743 
744  fn = bsname + "_Me.bin";
745  ellip_solver.mass_e->write(fn.c_str());
746  }
747 }
748 
749 
752 double Electrics::timer_val(const int timer_id)
753 {
754  // determine
755  int sidx = stimidx_from_timeridx(stimuli, timer_id);
756  double val = 0.0;
757  if(sidx != -1) {
758  stimuli[sidx].value(val);
759  }
760  else
761  val = std::nan("NaN");
762 
763  return val;
764 }
765 
768 std::string Electrics::timer_unit(const int timer_id)
769 {
770  int sidx = stimidx_from_timeridx(stimuli, timer_id);
771  std::string s_unit;
772 
773  if(sidx != -1)
774  // found a timer-linked stimulus
775  s_unit = stimuli[sidx].pulse.wave.f_unit;
776 
777  return s_unit;
778 }
779 
782 int stimidx_from_timeridx(const SF::vector<stimulus> & stimuli, const int timer_id)
783 {
784  // the only electrical quantities linked to a timer are stimuli
785  // thus we search for timer links only among stimuli for now
786 
787  // iterate over stimuli
788  for(size_t i = 0; i<stimuli.size(); i++)
789  {
790  const stimulus & s = stimuli[i];
791 
792  if(s.ptcl.timer_id == timer_id)
793  return s.idx;
794  }
795 
796  // invalid timer index not linked to any stimulus
797  return -1;
798 }
799 
810 void get_kappa(sf_vec & kappa, IMPregion *ir, limpet::MULTI_IF & miif, double k)
811 {
812  double* reg_kappa = new double[miif.N_IIF];
813 
814  for(int i=0; i<miif.N_IIF; i++)
815  reg_kappa[i] = k * miif.IIF[i]->cgeom().SVratio * ir[i].volFrac;
816 
817  double *kd = kappa.ptr();
818 
819  for(int i = 0; i < miif.numNode; i++)
820  kd[i] = reg_kappa[(int) miif.IIFmask[i]];
821 
822  kappa.release_ptr(kd);
823  delete [] reg_kappa;
824 }
825 
826 
835 {
836  for(size_t i=0; i < m.regions.size(); i++) {
837  elecMaterial *emat = static_cast<elecMaterial*>(m.regions[i].material);
838  emat->g = type;
839  }
840 }
841 
842 void Electrics::setup_solvers()
843 {
844  set_dir(OUTPUT);
845  parab_solver.init();
847 
848  if (param_globals::bidomain) {
849  ellip_solver.init();
851  }
852 
853  if(param_globals::dump2MatLab)
854  dump_matrices();
855 
856  log_msg(logger,0,ECHO, "Electrics::setup_solvers");
857 }
858 
860 {
861  for(const stimulus & s : stimuli) {
862  if(is_dbc(s.phys.type))
863  return true;
864  }
865  return false;
866 }
867 
868 const char* get_tsav_ext(double time)
869 {
870  int min_idx = -1;
871  double min_diff = 1e100;
872 
873  for(int i=0; i<param_globals::num_tsav; i++)
874  {
875  double diff = fabs(param_globals::tsav[i] - time);
876  if(min_diff > diff) {
877  min_diff = diff;
878  min_idx = i;
879  }
880  }
881 
882  if(min_idx == -1)
883  min_idx = 0;
884 
885  return param_globals::tsav_ext[min_idx];
886 }
887 
888 void Electrics::checkpointing()
889 {
890  const timer_manager & tm = *user_globals::tm_manager;
891 
892  // regular user selected state save
893  if (tm.trigger(iotm_chkpt_list)) {
894  char save_fnm[1024];
895  const char* tsav_ext = get_tsav_ext(tm.time);
896 
897  snprintf(save_fnm, sizeof save_fnm, "%s.%s.roe", param_globals::write_statef, tsav_ext);
898 
899  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
900  }
901 
902  // checkpointing based on interval
903  if (tm.trigger(iotm_chkpt_intv)) {
904  char save_fnm[1024];
905  snprintf(save_fnm, sizeof save_fnm, "checkpoint.%.1f.roe", tm.time);
906  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
907  }
908 }
909 
911 {
913  double t0, t1, dur;
914  get_time(t0);
915  stats.init_logger("ell_stats.dat");
916 
917  // here we can differentiate the solvers
919  sf_mesh & extra_mesh = get_mesh(extra_elec_msh);
920  sf_vec::ltype alg_type = sf_vec::algebraic;
921  const int dpn = 1;
922 
923  SF::init_vector(&phie, extra_mesh, dpn, alg_type);
924  SF::init_vector(&phiesrc, extra_mesh, dpn, alg_type);
925  SF::init_vector(&currtmp, extra_mesh, dpn, alg_type);
926 
928  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
929  SF::init_vector(&phie_i, intra_mesh, dpn, alg_type);
930  }
931 
932  int max_row_entries = max_nodal_edgecount(extra_mesh);
933 
936 
937  // alloc stiffness matrix
938  phie_mat->init(extra_mesh, dpn, dpn, max_row_entries);
939  // alloc mass matrix
940  mass_e ->init(extra_mesh, dpn, dpn, param_globals::mass_lumping ? 1 : max_row_entries);
941  dur = timing(t1, t0);
942 }
943 
945  SF::vector<stimulus> & stimuli,
946  FILE_SPEC logger)
947 {
949  double t0, t1, dur;
950  get_time(t0);
951  rebuild_stiffness(mtype, stimuli, logger);
952  rebuild_mass(logger);
953  dur = timing(t1, t0);
954 }
955 
957  SF::vector<stimulus> & stimuli,
958  FILE_SPEC logger)
959 {
961  double t0, t1, dur;
962  int log_flag = param_globals::output_level > 1 ? ECHO : 0;
963 
964  MaterialType & mt = mtype[Electrics::extra_grid];
965  const bool have_dbc = have_dbc_stims(stimuli);
966 
967  cond_t condType = sum_cond;
968  set_cond_type(mt, condType);
969 
970  // get mesh reference
971  sf_mesh & mesh = get_mesh(extra_elec_msh);
972 
973  get_time(t0);
974 
975  // fill the system
976  elec_stiffness_integrator stfn_integ(mt);
977 
978  phie_mat->zero();
979  SF::assemble_matrix(*phie_mat, mesh, stfn_integ);
980  phie_mat->scale(-1.0);
981 
982  dur = timing(t1,t0);
983  log_msg(logger,0,log_flag, "Computed ellipitc stiffness matrix in %.3f seconds.", dur);
984 
985  // set boundary conditions
986  if(have_dbc) {
987  log_msg(logger,0,log_flag, "Elliptic lhs matrix enforcing Dirichlet boundaries.");
988  get_time(t0);
989 
990  if(dbc == nullptr)
991  dbc = new dbc_manager(*phie_mat, stimuli);
992  else
993  dbc->recompute_dbcs();
994 
995  dbc->enforce_dbc_lhs();
996 
997  dur = timing(t1,t0);
998  log_msg(logger,0,log_flag, "Elliptic lhs matrix Dirichlet enforcing done in %.3f seconds.", dur);
999  }
1000  else {
1001  log_msg(logger,1,ECHO, "Elliptic lhs matrix is singular!");
1002  // we are dealing with a singular system
1003  phie_mat_has_nullspace = true;
1004  }
1005 
1006  // solver has not been initialized yet
1007  set_dir(INPUT);
1008  get_time(t0);
1009 
1010  setup_linear_solver(logger);
1011 
1012  dur = timing(t1,t0);
1013  log_msg(logger,0,log_flag, "Initializing elliptic solver in %.5f seconds.", dur);
1014  set_dir(OUTPUT);
1015 }
1016 
1018 {
1020  int log_flag = param_globals::output_level > 1 ? ECHO : 0;
1021  double t0, t1, dur;
1022  mass_integrator mass_integ;
1023 
1024  // get mesh reference
1025  sf_mesh & mesh = get_mesh(extra_elec_msh);
1026  get_time(t0);
1027  mass_e->zero();
1028 
1029  if(param_globals::mass_lumping) {
1030  SF::assemble_lumped_matrix(*mass_e, mesh, mass_integ);
1031  } else {
1032  SF::assemble_matrix(*mass_e, mesh, mass_integ);
1033  }
1034 
1035  dur = timing(t1,t0);
1036  log_msg(logger,0,log_flag, "Computed elliptic mass matrix in %.3f seconds.", dur);
1037 }
1038 
1039 void elliptic_solver::setup_linear_solver(FILE_SPEC logger)
1040 {
1042 
1043  tol = param_globals::cg_tol_ellip;
1044  max_it = param_globals::cg_maxit_ellip;
1045 
1046  std::string default_opts;
1047  std::string solver_file;
1048  solver_file = param_globals::ellip_options_file;
1049  if (param_globals::flavor == std::string("ginkgo")) {
1050  default_opts = std::string(
1051  R"({
1052  "type": "solver::Cg",
1053  "criteria": [
1054  {
1055  "type": "Iteration",
1056  "max_iters": 100
1057  },
1058  {
1059  "type": "ResidualNorm",
1060  "reduction_factor": 1e-4
1061  }
1062  ],
1063  "preconditioner": {
1064  "type": "solver::Multigrid",
1065  "mg_level": [
1066  {
1067  "type": "multigrid::Pgm",
1068  "deterministic": true
1069  }
1070  ],
1071  "criteria": [
1072  {
1073  "type": "Iteration",
1074  "max_iters": 1
1075  }
1076  ],
1077  "coarsest_solver": {
1078  "type": "preconditioner::Schwarz",
1079  "local_solver": {
1080  "type": "preconditioner::Ilu"
1081  }
1082  },
1083  "max_levels": 10,
1084  "min_coarse_rows": 8,
1085  "default_initial_guess": "zero"
1086  }
1087 })");
1088  } else if (param_globals::flavor == std::string("petsc")) {
1089  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");
1090  }
1091 
1092  lin_solver->setup_solver(*phie_mat, tol, max_it, param_globals::cg_norm_ellip,
1093  "elliptic PDE", phie_mat_has_nullspace,
1094  logger, solver_file.c_str(), default_opts.c_str());
1095 }
1096 
1097 void elliptic_solver::solve(sf_mat & Ki, sf_vec & Vmv, sf_vec & tmp_i)
1100  double t0,t1;
1102  // assembly of rhs for FE
1103  if (phiesrc->mag() > 0.0) {
1104  mass_e->mult(*phiesrc, *currtmp);
1106  }
1107 
1108  Ki.mult(Vmv, tmp_i);
1109 
1110  bool add = true;
1111  i2e->forward(tmp_i, *phiesrc, add);
1112 
1113  if(dbc != nullptr)
1115 
1116  get_time(t0);
1117  (*lin_solver)(*phie, *phiesrc);
1118 
1119  // treat solver statistics
1120  auto dur = timing(t1, t0);
1121  lin_solver->time += dur;
1122  stats.slvtime += dur;
1124  if(lin_solver->reason < 0) {
1125  log_msg(0, 5, 0,"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1126  petsc_get_converged_reason_str(lin_solver->reason));
1127  EXIT(1);
1128  }
1130  add = false;
1131  i2e->backward(*phie, *phie_i, add);
1132 }
1133 
1135 {
1137  double t0,t1;
1138 
1139  if(dbc != nullptr)
1141 
1142  get_time(t0);
1143  (*lin_solver)(*phie, *phiesrc);
1144 
1145  // treat solver statistics
1146  auto dur = timing(t1, t0);
1147  lin_solver->time += dur;
1148  stats.slvtime += dur;
1150 
1151  if(lin_solver->reason < 0) {
1152  log_msg(0, 5, 0,"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1153  petsc_get_converged_reason_str(lin_solver->reason));
1154  EXIT(1);
1155  }
1156 
1157  // phie_i is only set up when we have an IntraMesh registered
1158  if(is_init(phie_i)) {
1159  bool add = false;
1161  i2e->backward(*phie, *phie_i, add);
1162  }
1163 }
1164 
1166 {
1168  double t0, t1, dur;
1169  get_time(t0);
1170  stats.init_logger("par_stats.dat");
1171 
1172  // here we can differentiate the solvers
1174 
1175  sf_vec* vm_ptr = get_data(vm_vec);
1176  sf_vec* iion_ptr = get_data(iion_vec);
1177 
1178  if(!(vm_ptr != NULL && iion_ptr != NULL)) {
1179  log_msg(0,5,0, "%s error: global Vm and Iion vectors not properly set up! Ionics seem invalid! Aborting!",
1180  __func__);
1181  EXIT(1);
1182  }
1183 
1184  SF::init_vector(&Vmv);
1186  Vmv-> shallow_copy(*vm_ptr);
1187  IIon->shallow_copy(*iion_ptr);
1188 
1189  if(param_globals::dump_data & DUMP_IC) SF::init_vector(&Ic , Vmv);
1190  if(param_globals::dump_data & DUMP_IVOL) SF::init_vector(&Ivol, Vmv);
1191  if(param_globals::dump_data & DUMP_IACT) SF::init_vector(&Iact, Vmv);
1192 
1195 
1196  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
1197  sf_vec::ltype alg_type = sf_vec::algebraic;
1198 
1199  int dpn = 1;
1200  SF::init_vector(&kappa_i, intra_mesh, dpn, alg_type);
1201  SF::init_vector(&tmp_i1, intra_mesh, dpn, alg_type);
1202  SF::init_vector(&tmp_i2, intra_mesh, dpn, alg_type);
1203  SF::init_vector(&old_vm, intra_mesh, dpn, alg_type);
1204 
1205  if(!param_globals::operator_splitting)
1206  SF::init_vector(&Irhs, intra_mesh, dpn, alg_type);
1207 
1208  // alloc matrices
1209  int max_row_entries = max_nodal_edgecount(intra_mesh);
1210 
1214 
1215  rhs_parab->init(intra_mesh, dpn, dpn, max_row_entries);
1216  mass_i ->init(intra_mesh, dpn, dpn, param_globals::mass_lumping ? 1 : max_row_entries);
1217 
1218  parab_tech = static_cast<parabolic_solver::parabolic_t>(param_globals::parab_solve);
1219  dur = timing(t1, t0);
1220 }
1221 
1223 {
1225  double start, end, period;
1226  get_time(start);
1227  double t0, t1, dur;
1228  mass_integrator mass_integ;
1229  int dpn = 1;
1230 
1231  int log_flag = param_globals::output_level > 1 ? ECHO : 0;
1232  MaterialType & mt = mtype[Electrics::intra_grid];
1233 
1234  double Dt = user_globals::tm_manager->time_step;
1235  get_kappa(*kappa_i, param_globals::imp_region, miif, UM2_to_CM2 / Dt);
1236 
1237  cond_t condType = intra_cond;
1238  sf_mesh & mesh = get_mesh(intra_elec_msh);
1239 
1240  if( (param_globals::bidomain == MONODOMAIN && param_globals::bidm_eqv_mono) ||
1241  (param_globals::bidomain == PSEUDO_BIDM) )
1242  condType = para_cond;
1243 
1244  // set material and conductivity type
1245  set_cond_type(mt, condType);
1246 
1247  // fill the system
1248  {
1249  get_time(t0);
1250 
1251  elec_stiffness_integrator stfn_integ(mt);
1252  SF::assemble_matrix(*rhs_parab, mesh, stfn_integ);
1253 
1254  dur = timing(t1,t0);
1255  log_msg(logger,0,log_flag, "Computed parabolic stiffness matrix in %.3f seconds.", dur);
1256  get_time(t0);
1257 
1258  if(param_globals::mass_lumping)
1259  SF::assemble_lumped_matrix(*mass_i, mesh, mass_integ);
1260  else
1261  SF::assemble_matrix(*mass_i, mesh, mass_integ);
1262 
1263  sf_vec* empty; SF::init_vector(&empty);
1264  mass_i->mult_LR(*kappa_i, *empty);
1265 
1266  dur = timing(t1,t0);
1267  log_msg(logger,0,log_flag, "Computed parabolic mass matrix in %.3f seconds.", dur);
1268  delete empty;
1269  }
1270 
1271  // initialize parab lhs
1272  if(parab_tech != EXPLICIT) {
1274  // if we have mass lumping, then the nonzero pattern between Mi and Ki is different
1275  bool same_nonzero = param_globals::mass_lumping == false;
1276 
1277  if (parab_tech==CN) {
1278  lhs_parab->scale(-param_globals::theta);
1279  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1280  }
1281  else if (parab_tech==O2dT) {
1282  lhs_parab->scale(-0.5);
1283  mass_i->scale(0.5);
1284  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1285  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1286  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1287  }
1288  }
1289  else {
1292 
1293  SF_real* p = inv_mass_diag->ptr();
1294 
1295  for(int i=0; i<inv_mass_diag->lsize(); i++)
1296  p[i] = 1.0 / p[i];
1297 
1299  }
1301  if(parab_tech == CN || parab_tech == O2dT) {
1302  set_dir(INPUT);
1303  get_time(t0);
1304 
1305  setup_linear_solver(logger);
1306 
1307  dur = timing(t1,t0);
1308  log_msg(logger,0,log_flag, "Initializing parabolic solver in %.5f seconds.", dur);
1309  set_dir(OUTPUT);
1310  }
1311  period = timing(end, start);
1312  log_msg(logger,0,ECHO, "Done rebuild mat");
1313 }
1314 
1315 void parabolic_solver::setup_linear_solver(FILE_SPEC logger)
1316 {
1318  tol = param_globals::cg_tol_parab;
1319  max_it = param_globals::cg_maxit_parab;
1320 
1321  std::string default_opts;
1322  std::string solver_file;
1323  solver_file = param_globals::parab_options_file;
1324  if (param_globals::flavor == std::string("ginkgo")) {
1325  default_opts = std::string(
1326  R"(
1327 {
1328  "type": "solver::Cg",
1329  "criteria": [
1330  {
1331  "type": "Iteration",
1332  "max_iters": 100
1333  },
1334  {
1335  "type": "ResidualNorm",
1336  "reduction_factor": 1e-4
1337  }
1338  ],
1339  "preconditioner": {
1340  "type": "preconditioner::Schwarz",
1341  "local_solver": {
1342  "type": "preconditioner::Ilu"
1343  }
1344  }
1345 }
1346  )");
1347  } else if (param_globals::flavor == std::string("petsc")) {
1348  default_opts = std::string("-pc_type bjacobi -sub_pc_type ilu -ksp_type cg");
1349  }
1350 
1351  lin_solver->setup_solver(*lhs_parab, tol, max_it, param_globals::cg_norm_parab,
1352  "parabolic PDE", false, logger, solver_file.c_str(),
1353  default_opts.c_str());
1354 }
1355 
1356 void parabolic_solver::solve(sf_vec & phie_i)
1357 {
1359  switch (parab_tech) {
1360  case CN: solve_CN(phie_i); break;
1361  case O2dT: solve_O2dT(phie_i); break;
1362  default: solve_EF(phie_i); break;
1363  }
1364 }
1365 
1366 void parabolic_solver::solve_CN(sf_vec & phie_i)
1367 {
1369  double t0,t1;
1370  // assembly of rhs for CN
1371  if (param_globals::bidomain == BIDOMAIN) {
1372  tmp_i1->deep_copy(phie_i);
1373  tmp_i1->add_scaled(*Vmv, 1.0 - param_globals::theta);
1374  rhs_parab->mult(*tmp_i1, *tmp_i2);
1375  }
1376  else {
1377  rhs_parab->mult(*Vmv, *tmp_i2);
1378  *tmp_i2 *= 1.0 - param_globals::theta;
1379  }
1380 
1381  mass_i->mult(*Vmv, *tmp_i1);
1382  *tmp_i1 += *tmp_i2;
1383 
1384  // add current contributions to rhs
1385  if(!param_globals::operator_splitting)
1386  tmp_i1->add_scaled(*Irhs, -1.0);
1387 
1388  get_time(t0);
1389 
1390  (*lin_solver)(*Vmv, *tmp_i1);
1391 
1392  if(lin_solver->reason < 0) {
1393  log_msg(0, 5, 0,"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1394  petsc_get_converged_reason_str(lin_solver->reason));
1395  EXIT(1);
1396  }
1397 
1398  // treat solver statistics
1399  auto dur = timing(t1, t0);
1400  lin_solver->time += dur;
1401  stats.slvtime += dur;
1403 }
1404 
1405 void parabolic_solver::solve_O2dT(sf_vec & phie_i)
1406 {
1408  double t0,t1;
1409  // assembly of rhs for FE
1410  if (param_globals::bidomain == BIDOMAIN) {
1411  tmp_i2->deep_copy(phie_i);
1412  tmp_i2->add_scaled(*Vmv, 0.5);
1413  rhs_parab->mult(*tmp_i2, *tmp_i1); // tmp_i1 = K_i(Vm^t * 0.5 + phi_e)
1414  }
1415  else {
1416  rhs_parab->mult(*Vmv, *tmp_i1);
1417  *tmp_i1 *= 0.5; // tmp_i1 = 0.5 * K_i Vm^t
1418  }
1419 
1420  mass_i->mult(*Vmv, *tmp_i2); // tmp_i2 = M/2 Vm^t
1421  tmp_i1->add_scaled(*tmp_i2, 4.0); // tmp_i1 = (2M+K_i/2)Vm^t
1422  mass_i->mult(*old_vm, *tmp_i2); // tmp_i2 = M/2 Vm^{t-1}
1423 
1424  tmp_i1->add_scaled(*tmp_i2, -1.0); // tmp_i1 = (2M+K_i/2)Vm^t-M/2 Vm^{t-1}
1425  *old_vm = *Vmv;
1426 
1427  get_time(t0);
1428 
1429  // solve
1430  (*lin_solver)(*Vmv, *tmp_i1);
1431 
1432  // treat solver statistics
1433  stats.slvtime += timing(t1, t0);
1435 }
1436 
1437 void parabolic_solver::solve_EF(sf_vec & phie_i)
1438 {
1440  double t0,t1,t2;
1441  get_time(t0);
1442 
1443  // assembly of rhs for FE
1444  if (param_globals::bidomain == BIDOMAIN) {
1445  tmp_i2->deep_copy(phie_i);
1446  *tmp_i2 += *Vmv;
1447  rhs_parab->mult(*tmp_i2, *tmp_i1);
1448  }
1449  else {
1450  rhs_parab->mult(*Vmv, *tmp_i1);
1451  }
1452 
1453  *tmp_i1 *= *inv_mass_diag;
1454  Vmv->add_scaled(*tmp_i1, 1.0);
1455 
1456  if(param_globals::operator_splitting == false)
1457  Vmv->add_scaled(*Irhs, -1.0);
1458 
1459  // record rhs timing
1460  stats.slvtime += timing(t1, t0);
1461 }
1462 
1464 {
1465  char* prvSimDir = strlen(param_globals::start_statef) ?
1466  get_file_dir(param_globals::start_statef) : NULL;
1467 
1468  const char* extn = ".dat";
1469 
1470  // if compute_APD we need an extra 2 acts
1471  int addLATs = param_globals::compute_APD ? 2 : 0;
1472 
1473  bool have_sentinel = param_globals::t_sentinel > 0.0;
1474  bool need_to_add_sentinel = have_sentinel && (param_globals::sentinel_ID < 0);
1475 
1476  addLATs += need_to_add_sentinel ? 1 : 0;
1477  acts.resize(param_globals::num_LATs + addLATs);
1478 
1479  int j=0;
1480  for (int i = 0; i < param_globals::num_LATs; i++ )
1481  {
1482  // using Ph only with bidomain runs
1483  if (param_globals::lats[i].method <= 0 || (param_globals::lats[i].measurand == PHIE && !param_globals::bidomain)) {
1484  log_msg(NULL, 3, 0, "Phie-based LAT measurement requires bidomain >=1 Ignoring lats[%d].", i);
1485  continue;
1486  }
1487 
1488  acts[j].method = (ActMethod)param_globals::lats[i].method;
1489  acts[j].threshold = param_globals::lats[i].threshold;
1490  acts[j].mode = param_globals::lats[i].mode;
1491  acts[j].all = param_globals::lats[i].all;
1492  acts[j].measurand = (PotType)param_globals::lats[i].measurand;
1493  acts[j].ID = param_globals::lats[i].ID;
1494  acts[j].fout = NULL;
1495 
1496  if(param_globals::lats[i].all) {
1497  acts[j].fname = (char*) malloc((strlen(param_globals::lats[i].ID)+strlen(extn)+1)*sizeof(char));
1498  snprintf(acts[j].fname, strlen(param_globals::lats[i].ID)+strlen(extn)+1, "%s%s", param_globals::lats[i].ID, extn);
1499  }
1500  else {
1501  char prfx[] = "init_acts_";
1502  int max_len = strlen(prfx) + strlen(param_globals::lats[i].ID) + strlen(extn) + 1;
1503 
1504  acts[j].fname = (char*) malloc(max_len*sizeof(char));
1505  snprintf(acts[j].fname, max_len, "%s%s%s", prfx, param_globals::lats[i].ID, extn);
1506  }
1507 
1508  // restarting
1509  if(prvSimDir != NULL) {
1510  int len_fname = strlen(prvSimDir)+strlen(acts[j].fname)+2;
1511  acts[j].prv_fname = (char*) malloc(len_fname*sizeof(char));
1512  snprintf(acts[j].prv_fname, len_fname, "%s/%s", prvSimDir, acts[j].fname);
1513  }
1514 
1515  j++;
1516  }
1517 
1518  if(param_globals::compute_APD) {
1519  acts[j].method = ACT_THRESH; // threshold crossing
1520  acts[j].threshold = param_globals::actthresh;
1521  acts[j].mode = 0; // upstroke
1522  acts[j].all = true;
1523  acts[j].measurand = VM; // Vm
1524  //acts[j].ID = dupstr("Vm_Activation");
1525  acts[j].fout = NULL;
1526  acts[j].fname = dupstr("vm_activation.dat");
1527 
1528  j++;
1529  acts[j].method = ACT_THRESH; // threshold crossing
1530  acts[j].threshold = param_globals::recovery_thresh;
1531  acts[j].mode = 1; // repol
1532  acts[j].all = true;
1533  acts[j].measurand = VM; // Vm
1534  //(*acts)[j+1].ID = param_globals::lats[i].ID;
1535  acts[j].fout = NULL;
1536  acts[j].fname = dupstr("vm_repolarisation.dat");
1537 
1538  j++;
1539  }
1540 
1541  // set up sentinel for activity checking
1542  sntl.activated = have_sentinel;
1543  sntl.t_start = param_globals::t_sentinel_start;
1544  sntl.t_window = param_globals::t_sentinel;
1545  sntl.t_quiesc =-1.;
1546  sntl.ID = param_globals::sentinel_ID;
1547 
1548  if(need_to_add_sentinel) {
1549  // add a default LAT detector as sentinel
1550  acts[j].method = ACT_THRESH; // threshold crossing
1551  acts[j].threshold = param_globals::actthresh;
1552  acts[j].mode = 0; // upstroke
1553  acts[j].all = true;
1554  acts[j].measurand = VM; // Vm
1555  //(*acts)[j].ID = dupstr("Vm_Activation");
1556  acts[j].fout = NULL;
1557  acts[j].fname = dupstr("vm_sentinel.dat");
1558  // set sentinel index
1559  sntl.ID = j;
1560  j++;
1561  }
1562 
1563  if(prvSimDir) free(prvSimDir);
1564 }
1565 
1566 void print_act_log(FILE_SPEC logger, const SF::vector<Activation> & acts, int idx)
1567 {
1568  const Activation & act = acts[idx];
1569 
1570  log_msg(logger, 0, 0, "\n");
1571  log_msg(logger, 0, 0, "LAT detector [%2d]", idx);
1572  log_msg(logger, 0, 0, "-----------------\n");
1573 
1574  log_msg(logger, 0, 0, "Measurand: %s", act.measurand ? "Phie" : "Vm");
1575  log_msg(logger, 0, 0, "All: %s", act.all ? "All" : "Only first");
1576  log_msg(logger, 0, 0, "Method: %s", act.method==ACT_DT ? "Derivative" : "Threshold crossing");
1577 
1578  char buf[64], gt[2], sgn[2];
1579  snprintf(sgn, sizeof sgn, "%s", act.mode?"-":"+");
1580  snprintf(gt, sizeof gt, "%s", act.mode?"<":">");
1581 
1582  if(act.method==ACT_DT)
1583  snprintf(buf, sizeof buf, "Maximum %sdf/dt %s %.2f mV", sgn, gt, act.threshold);
1584  else
1585  snprintf(buf, sizeof buf, "Intersection %sdf/dt with %.2f", sgn, act.threshold);
1586 
1587  log_msg(logger, 0, 0, "Mode: %s", buf);
1588  log_msg(logger, 0, 0, "Threshold: %.2f mV\n", act.threshold);
1589 }
1590 
1591 void LAT_detector::init(sf_vec & vm, sf_vec & phie, int offset, enum physic_t phys_t)
1592 {
1593  if(!get_physics(phys_t)) {
1594  log_msg(0,0,5, "There seems to be no EP is defined. LAT detector requires active EP! Aborting LAT setup!");
1595  return;
1596  }
1597 
1598  // we use the electrics logger for output
1599  FILE_SPEC logger = get_physics(phys_t)->logger;
1600 
1601  // TODO(init): except for the shallow copies, shouldn't these be deleted?
1602  // When to delete them?
1603  for(size_t i = 0; i < acts.size(); ++i) {
1604  acts[i].init = 1;
1605  SF::init_vector(&(acts[i].phi));
1606  acts[i].phi->shallow_copy(!acts[i].measurand ? vm : phie);
1607  acts[i].offset = offset;
1608 
1609  SF::init_vector(&(acts[i].phip), acts[i].phi);
1610  *acts[i].phip = *acts[i].phi;
1611 
1612  // derivative based detector
1613  if (acts[i].method == ACT_DT) {
1614  SF::init_vector(&(acts[i].dvp0), acts[i].phi);
1615  SF::init_vector(&(acts[i].dvp1), acts[i].phi);
1616  if(acts[i].mode)
1617  log_msg(NULL,2,0, "Detection of -df/dt|max not implemented, +df/dt|max will be detected.");
1618  }
1619 
1620  // allocate additional local buffers
1621  acts[i].ibuf = (int *)malloc(acts[i].phi->lsize()*sizeof(int));
1622  acts[i].actbuf = (double *)malloc(acts[i].phi->lsize()*sizeof(double));
1623 
1624  if (!acts[i].all) {
1625  SF::init_vector(&acts[i].tm, acts[i].phi->gsize(), acts[i].phi->lsize());
1626  acts[i].tm->set(-1.);
1627 
1628  // initialize with previous initial activations
1629  if(acts[i].prv_fname != NULL) {
1630  set_dir(INPUT);
1631  size_t nread = acts[i].tm->read_ascii(acts[i].prv_fname);
1632  set_dir(OUTPUT);
1633 
1634  if(nread == 0) {
1635  log_msg(NULL,2,ECHO,"Warning: Initialization of LAT[%2d] failed.", i);
1636  } else {
1637  // the file is in canonical order (written with forward=true); permute back to PETSc layout
1639  assert(sc != NULL);
1640  (*sc)(*acts[i].tm, /*forward=*/false);
1641  }
1642  }
1643  }
1644  else {
1645  if ( !get_rank() ) {
1646  // here we should copy over previous file and open in append mode
1647  if(acts[i].prv_fname!=NULL) {
1648  set_dir(INPUT);
1649  FILE_SPEC in = f_open( acts[i].prv_fname, "r" );
1650  if(in) {
1651  log_msg(NULL,2,0, "Copying over of previous activation file not implemented.\n"); f_close(in);
1652  }
1653  else
1654  log_msg(NULL,3,0,"Warning: Initialization in %s - \n"
1655  "Failed to read activation file %s.\n", __func__, acts[i].prv_fname);
1656 
1657  set_dir(OUTPUT);
1658  }
1659  acts[i].fout = f_open( acts[i].fname, acts[i].prv_fname==NULL?"w":"a" );
1660  }
1661  }
1662  print_act_log(logger, acts, i);
1663  }
1664 
1665  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
1667 }
1668 
1669 
1670 int output_all_activations(FILE_SPEC fp, int *ibuf, double *act_tbuf, int nlacts)
1671 {
1672  int rank = get_rank(), gacts = 0, numProc = get_size();
1673 
1674  if (rank == 0) {
1675  // rank 0 writes directly to the table
1676  for (int i=0; i<nlacts; i++)
1677  fprintf(fp->fd, "%d\t%.6f\n", ibuf[i], act_tbuf[i]);
1678 
1679  gacts += nlacts;
1680 
1681  SF::vector<int> buf_inds;
1682  SF::vector<double> buf_acts;
1683 
1684  for (int j=1; j<numProc; j++) {
1685  int acts = 0;
1686  MPI_Status status;
1687  MPI_Recv(&acts, 1, MPI_INT, j, 110, PETSC_COMM_WORLD, &status);
1688 
1689  if (acts) {
1690  buf_inds.resize(acts);
1691  buf_acts.resize(acts);
1692 
1693  MPI_Recv(buf_inds.data(), acts, MPI_INT, j, 110, PETSC_COMM_WORLD, &status);
1694  MPI_Recv(buf_acts.data(), acts, MPI_DOUBLE, j, 110, PETSC_COMM_WORLD, &status);
1695 
1696  for(int ii=0; ii<acts; ii++)
1697  fprintf(fp->fd, "%d\t%.6f\n", buf_inds[ii], buf_acts[ii]);
1698 
1699  gacts += acts;
1700  }
1701  }
1702  fflush(fp->fd);
1703  }
1704  else {
1705  MPI_Send(&nlacts, 1, MPI_INT, 0, 110, PETSC_COMM_WORLD);
1706  if (nlacts) {
1707  MPI_Send(ibuf, nlacts, MPI_INT, 0, 110, PETSC_COMM_WORLD);
1708  MPI_Send(act_tbuf, nlacts, MPI_DOUBLE, 0, 110, PETSC_COMM_WORLD);
1709  }
1710  }
1711 
1712  MPI_Bcast(&gacts, 1, MPI_INT, 0, PETSC_COMM_WORLD);
1713  return gacts;
1714 }
1716 int LAT_detector::check_acts(double tm)
1717 {
1718  int nacts = 0;
1719  double *a;
1720 
1721  for(Activation* aptr = acts.data(); aptr != acts.end(); aptr++)
1722  {
1723  int lacts = 0;
1724  switch (aptr->method) {
1725  case ACT_THRESH:
1726  lacts = check_cross_threshold(*aptr->phi, *aptr->phip, tm,
1727  aptr->ibuf, aptr->actbuf, aptr->threshold, aptr->mode);
1728  break;
1729 
1730  case ACT_DT:
1731  lacts = check_mx_derivative (*aptr->phi, *aptr->phip, tm,
1732  aptr->ibuf, aptr->actbuf, *aptr->dvp0, *aptr->dvp1,
1733  aptr->threshold, aptr->mode);
1734  break;
1735 
1736  default:
1737  break;
1738  }
1739 
1740  if (!aptr->all)
1741  a = aptr->tm->ptr();
1742 
1744 
1745  for(int j=0; j<lacts; j++) {
1746  if(aptr->all) {
1747  int nodal_idx = this->petsc_to_nodal.forward_map(aptr->ibuf[j]);
1748  aptr->ibuf[j] = canon_nbr[nodal_idx] + aptr->offset;
1749  }
1750  else {
1751  if(a[aptr->ibuf[j]] == -1)
1752  a[aptr->ibuf[j]] = aptr->actbuf[j];
1753  }
1754  }
1755 
1756  if(aptr->all)
1757  output_all_activations(aptr->fout, aptr->ibuf, aptr->actbuf, lacts);
1758  else
1759  aptr->tm->release_ptr(a);
1760 
1761  MPI_Allreduce(MPI_IN_PLACE, &lacts, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD);
1762  nacts += lacts;
1763 
1764  aptr->nacts = nacts;
1765  }
1766 
1767  return nacts > 0;
1768 }
1769 
1770 
1771 int LAT_detector::check_quiescence(double tm, double dt)
1772 {
1773  static int savequitFlag = 0;
1774  int numNodesActivated = -1;
1775 
1776  if(sntl.activated) {
1777  // initialization
1778  if(sntl.t_quiesc < 0. && sntl.t_window >= 0.0 ) {
1779  log_msg(0,0,ECHO | NONL, "================================================================================================\n");
1780  log_msg(0,0,ECHO | NONL, "%s() WARNING: simulation is configured to savequit() after %.2f ms of quiescence\n", __func__, sntl.t_window);
1781  log_msg(0,0,ECHO | NONL, "================================================================================================\n");
1782  sntl.t_quiesc = 0.0;
1783  }
1784 
1785  if(tm >= sntl.t_start && !savequitFlag)
1786  {
1787  numNodesActivated = acts[sntl.ID].nacts;
1788 
1789  if(numNodesActivated) sntl.t_quiesc = 0.0;
1790  else sntl.t_quiesc += dt;
1791 
1792  if(sntl.t_window >= 0.0 && sntl.t_quiesc > sntl.t_window && !savequitFlag) {
1793  savequitFlag++;
1794  savequit();
1795  }
1796  }
1797  }
1798 
1799  return numNodesActivated;
1800 }
1801 
1802 
1803 
1804 
1805 int LAT_detector::check_cross_threshold(sf_vec & vm, sf_vec & vmp, double tm,
1806  int *ibuf, double *actbuf, float threshold, int mode)
1807 {
1808  SF_real *c = vm.ptr();
1809  SF_real *p = vmp.ptr();
1810  int lsize = vm.lsize();
1811  int nacts = 0, gnacts = 0;
1812 
1813  for (int i=0; i<lsize; i++) {
1814  int sgn = 1;
1815  bool triggered = false;
1816  if(mode==0) {// detect +slope crossing
1817  triggered = p[i] <= threshold && c[i] > threshold; }
1818  else { // detect -slope crossing
1819  triggered = p[i] >= threshold && c[i] < threshold;
1820  sgn = -1;
1821  }
1822 
1823  if (triggered) {
1824  double tact = tm - param_globals::dt + (threshold-p[i])/(c[i]-p[i])*sgn*param_globals::dt;
1825  ibuf [nacts] = i;
1826  actbuf[nacts] = tact;
1827  nacts++;
1828  }
1829  p[i] = c[i];
1830  }
1831 
1832  vm.release_ptr(c);
1833  vmp.release_ptr(p);
1834  return nacts;
1835 }
1836 
1837 int LAT_detector::check_mx_derivative(sf_vec & vm, sf_vec & vmp, double tm,
1838  int *ibuf, double *actbuf, sf_vec & dvp0, sf_vec & dvp1,
1839  float threshold, int mode)
1840 {
1841  int nacts = 0, gnacts = 0;
1842  double tact, dt2 = 2 * param_globals::dt;
1843  int lsize = vm.lsize();
1844  SF_real ddv0, ddv1, dv, dvdt;
1845  SF_real *c, *p, *pd0, *pd1;
1846 
1847  c = vm.ptr();
1848  p = vmp.ptr();
1849  pd0 = dvp0.ptr();
1850  pd1 = dvp1.ptr();
1851 
1852  for (int i=0; i<lsize; i++ ) {
1853  dv = (c[i]-p[i]);
1854  dvdt = dv/param_globals::dt;
1855  ddv0 = pd1[i]-pd0[i];
1856  ddv1 = dv -pd1[i];
1857 
1858  if (dvdt>=threshold && ddv0>0 && ddv1<0) {
1859  tact = tm-dt2+(ddv0/(ddv0-ddv1))*param_globals::dt;
1860  ibuf [nacts] = i;
1861  actbuf[nacts] = tact;
1862  nacts++;
1863  }
1864  p [i] = c[i];
1865  pd0[i] = pd1[i];
1866  pd1[i] = dv;
1867  }
1868 
1869  vm .release_ptr(c);
1870  vmp .release_ptr(p);
1871  dvp0.release_ptr(pd0);
1872  dvp1.release_ptr(pd1);
1873 
1874  return nacts;
1875 }
1876 
1881 {
1883  assert(sc != NULL);
1884 
1885  bool forward = true;
1886 
1887  for (size_t i = 0; i < acts.size(); i++) {
1888  if (is_init(acts[i].tm)) {
1889  (*sc)(*acts[i].tm, forward);
1890  acts[i].tm->write_ascii(acts[i].fname, false);
1891  }
1892  }
1893 }
1894 
1895 void Electrics::prepace() {
1896  log_msg(NULL, 0, 0, "Using activation times from file %s to distribute prepacing states\n",
1897  param_globals::prepacing_lats);
1898  log_msg(NULL, 0, 0, "Assuming stimulus strength %f uA/uF with duration %f ms for prepacing\n",
1899  param_globals::prepacing_stimstr, param_globals::prepacing_stimdur);
1900 
1901  limpet::MULTI_IF* miif = this->ion.miif;
1902 
1903  const sf_mesh & mesh = get_mesh(intra_elec_msh);
1904  sf_vec* read_lats; SF::init_vector(&read_lats, mesh, 1, sf_vec::algebraic);
1905 
1906  // read in the global distributed vector of all activation times
1907  set_dir(INPUT);
1908  size_t numread = read_lats->read_ascii(param_globals::prepacing_lats);
1909  if (numread == 0) {
1910  log_msg(NULL, 5, 0, "Failed reading required LATs! Skipping prepacing!");
1911  return;
1912  }
1913  set_dir(OUTPUT);
1914 
1916  assert(sc != NULL);
1917 
1918  // permute in-place to petsc permutation
1919  bool forward = false;
1920  (*sc)(*read_lats, forward);
1921 
1922  // take care of negative LAT values
1923  {
1924  PetscReal* lp = read_lats->ptr();
1925  for(int i=0; i<read_lats->lsize(); i++)
1926  if(lp[i] < 0.0) lp[i] = param_globals::tend + 10.0;
1927 
1928  read_lats->release_ptr(lp);
1929  }
1930 
1931  // make LATs relative and figure out the first LAT
1932  // so we know when to save state of each point
1933  SF_real LATmin = read_lats->min();
1934 
1935  if(LATmin < 0.0) {
1936  log_msg(0,3,0, "LAT data is not complete. Skipping prepacing.");
1937  return;
1938  }
1940  SF_real offset = floor(LATmin / param_globals::prepacing_bcl) * param_globals::prepacing_bcl;
1941  SF_real last_tm = param_globals::prepacing_bcl * param_globals::prepacing_beats;
1942 
1943  // compute read_lats[i] = last_tm - (read_lats[i] - offset)
1944  *read_lats += -offset;
1945  *read_lats *= -1.;
1946  *read_lats += last_tm;
1947 
1948  miif->getRealData();
1949  SF_real *save_tm = read_lats->ptr();
1950  SF_real *vm = miif->gdata[limpet::Vm]->ptr();
1951 
1952  for (int ii = 0; ii < miif->N_IIF; ii++) {
1953  if (!miif->N_Nodes[ii]) continue;
1954 
1955  // create sorted array of save times.
1956  SF::vector<SF::mixed_tuple<double,limpet::node_index_t>> sorted_save(miif->N_Nodes[ii]); // v1 = time, v2 = index
1957  for (limpet::node_index_t kk = 0; kk < miif->N_Nodes[ii]; kk++) {
1958  sorted_save[kk].v1 = save_tm[miif->NodeLists[ii][kk]];
1959  sorted_save[kk].v2 = kk;
1960  }
1961  std::sort(sorted_save.begin(), sorted_save.end());
1962 
1963  size_t lastidx = sorted_save.size() - 1;
1964  limpet::node_index_t paced = sorted_save[lastidx].v2; // IMP index of latest node
1965  limpet::node_index_t csav = 0;
1966 
1967  for (double t = 0; t < sorted_save[lastidx].v1; t += param_globals::dt) {
1968  if (fmod(t, param_globals::prepacing_bcl) < param_globals::prepacing_stimdur &&
1969  t < param_globals::prepacing_bcl * param_globals::prepacing_beats - 1)
1970  miif->ldata[ii][limpet::Vm][paced] += param_globals::prepacing_stimstr * param_globals::dt;
1971 
1972  compute_IIF(*miif->IIF[ii], miif->ldata[ii], paced);
1973 
1974  // Vm update always happens now outside of the imp
1975  miif->ldata[ii][limpet::Vm][paced] -= miif->ldata[ii][limpet::Iion][paced] * param_globals::dt;
1976  vm[miif->NodeLists[ii][paced]] = miif->ldata[ii][limpet::Vm][paced];
1977 
1978  while (csav < miif->N_Nodes[ii] - 1 && t >= sorted_save[csav].v1)
1979  dup_IMP_node_state(*miif->IIF[ii], paced, sorted_save[csav++].v2, miif->ldata[ii]);
1980  }
1981 
1982  // get nodes which may be tied for last
1983  while (csav < miif->N_Nodes[ii] - 1)
1984  dup_IMP_node_state(*miif->IIF[ii], paced, sorted_save[csav++].v2, miif->ldata[ii]);
1985  // ipdate global Vm vector
1986  for (limpet::node_index_t k = 0; k < miif->N_Nodes[ii]; k++) vm[miif->NodeLists[ii][k]] = miif->ldata[ii][limpet::Vm][k];
1987  }
1988 
1989  read_lats->release_ptr(save_tm);
1990  miif->gdata[limpet::Vm]->release_ptr(vm);
1991  miif->releaseRealData();
1992 }
1993 
1994 
1995 void recover_phie_std(sf_vec & vm, phie_recovery_data & rcv)
1996 {
1998  if (!rcv.pts.size())
1999  return;
2000 
2001  int rank = get_rank();
2002 
2003  if(!get_physics(elec_phys)) {
2004  log_msg(0,0,5, "There seems to be no EP is defined. Phie recovery requires active EP! Aborting!");
2005  return;
2006  }
2007 
2008  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
2009  sf_mat & Ki = *elec->parab_solver.rhs_parab;
2010 
2011  const sf_mesh & imesh = get_mesh(intra_elec_msh);
2012  const SF::vector<mesh_int_t> & alg_nod = imesh.pl.algebraic_nodes();
2013 
2014  SF_int start, end;
2015  vm.get_ownership_range(start, end);
2016 
2017  if(!rcv.Im) {
2018  SF::init_vector(&rcv.Im, &vm);
2019  SF::init_vector(&rcv.dphi, &vm);
2020  }
2021 
2022  SF_int r_start, r_end;
2023  rcv.phie_rec->get_ownership_range(r_start, r_end);
2024 
2025  SF_real *ph_r = rcv.phie_rec->ptr();
2026 
2027  // use minimum distance to ensure r>0
2028  // consistent with the line source approximation, the "cable radius"
2029  // is used as a lower limit for the source-field point distance
2030  float minDist = 2. / param_globals::imp_region[0].cellSurfVolRatio; // radius in um
2031 
2032  Ki.mult(vm, *rcv.Im);
2033  int numpts = rcv.pts.size() / 3;
2034  Point fpt, cpt;
2035 
2036  for (int j=0; j<numpts; j++) {
2037  fpt = rcv.pts.data() + j*3;
2038 
2039  *rcv.dphi = *rcv.Im;
2040  SF_real* dp = rcv.dphi->ptr();
2041 
2042  for (size_t i = 0; i<alg_nod.size(); i++)
2043  {
2044  mesh_int_t loc_nodal_idx = alg_nod[i];
2045  mesh_int_t loc_petsc_idx = local_nodal_to_local_petsc(imesh, rank, loc_nodal_idx);
2046  cpt = imesh.xyz.data()+loc_nodal_idx*3;
2047 
2048  double r = dist(fpt, cpt) + minDist;
2049  dp[loc_petsc_idx] /= r;
2050  }
2051 
2052  rcv.dphi->release_ptr(dp);
2053 
2054  SF_real phi = rcv.dphi->sum() / 4. / M_PI / rcv.gBath;
2055  if ( (j>=r_start) && (j<r_end) )
2056  ph_r[j-r_start] = phi;
2057  }
2058 
2059  rcv.phie_rec->release_ptr(ph_r);
2060 }
2061 
2063 {
2064  int err = 0, rank = get_rank();
2065 
2067  log_msg(0,0,5, "There seems to be no EP is defined. Phie recovery requires active EP! Aborting!");
2068  return 1;
2069  }
2070 
2071  sf_mesh & imesh = get_mesh(intra_elec_msh);
2072  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
2073  phie_recovery_data & phie_rcv = elec->phie_rcv;
2074 
2075  // we close the files of the default electrics if there are any open
2076  elec->output_manager.close_files_and_cleanup();
2077 
2078  // register output
2079  set_dir(POSTPROC);
2080  igb_output_manager phie_rec_out;
2081  phie_rec_out.register_output(phie_rcv.phie_rec, phie_recv_msh, 1,
2082  param_globals::phie_recovery_file, "mV");
2083 
2084  // Buffer for Vm data
2085  sf_vec* vm = get_data(vm_vec); assert(vm);
2086 
2087  // set up igb header and point fd to start of Vm file
2088  set_dir(OUTPUT);
2089  IGBheader vm_igb;
2090  if(rank == 0) {
2091  FILE_SPEC file = f_open(param_globals::vofile, "r");
2092  if(file != NULL) {
2093  vm_igb.fileptr(file->fd);
2094  vm_igb.read();
2095 
2096  if(vm_igb.x() != vm->gsize()) {
2097  log_msg(0,4,0, "%s error: Vm dimension does not fit to %s file. Aborting recovery! \n",
2098  __func__, param_globals::vofile);
2099  err++;
2100  }
2101 
2102  delete file;
2103  }
2104  else err++;
2105  }
2106 
2107  err = get_global(err, MPI_MAX);
2108 
2109  if(err == 0) {
2110  FILE* fd = static_cast<FILE*>(vm_igb.fileptr());
2111 
2112  // number of data slices
2113  const int num_io = user_globals::tm_manager->timers[iotm_spacedt]->numIOs;
2114 
2115  // scatterers
2117  assert(petsc_to_canonical != NULL);
2118 
2119  // loop over vm slices and recover phie
2120  for(int i=0; i<num_io; i++) {
2121  log_msg(0,0,0, "Step %d / %d", i+1, num_io);
2122  size_t nread = vm->read_binary<float>(fd);
2123 
2124  if(nread != size_t(vm->gsize())) {
2125  log_msg(0,3,0, "%s warning: read incomplete data slice! Aborting!", __func__);
2126  err++;
2127  break;
2128  }
2129 
2130  // permute vm_buff
2131  bool forward = false;
2132  (*petsc_to_canonical)(*vm, forward);
2133 
2134  // do phie computation
2135  recover_phie_std(*vm, phie_rcv);
2136 
2137  phie_rec_out.write_data();
2138  }
2139 
2140  phie_rec_out.close_files_and_cleanup();
2141  }
2142  return err;
2143 }
2144 
2145 void setup_phie_recovery_data(phie_recovery_data & data)
2146 {
2148  if(!get_physics(elec_phys) ) {
2149  log_msg(0,0,5, "There seems to be no EP is defined. Phie recovery requires active EP! Aborting!");
2150  return;
2151  }
2152 
2153  int rank = get_rank(), size = get_size();
2154  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
2155 
2156  sf_mesh & imesh = get_mesh(intra_elec_msh);
2157  const std::string basename = param_globals::phie_rec_ptf;
2158  SF::vector<mesh_int_t> ptsidx;
2159 
2160  set_dir(INPUT);
2161  SF::read_points(basename, imesh.comm, data.pts, ptsidx);
2162  make_global(data.pts, imesh.comm); // we want all ranks to have all points
2163 
2164  // set up parallel layout of recovery points
2165  SF::vector<mesh_int_t> layout;
2166  layout_from_count(mesh_int_t(ptsidx.size()), layout, imesh.comm);
2167 
2168  // set up petsc_vector for recovered potentials
2169  SF::init_vector(&data.phie_rec, layout[size], layout[rank+1]-layout[rank], 1, sf_vec::algebraic);
2170 
2171  // get conductivty
2172  SF::vector<RegionSpecs> & intra_regions = elec->mtype[Electrics::intra_grid].regions;
2173  data.gBath = static_cast<elecMaterial*>(intra_regions[0].material)->BathVal[0];
2174 }
2175 
2176 
2177 void Laplace::initialize()
2178 {
2180  int rank = get_rank();
2181 
2182  assert(param_globals::bidomain == BIDOMAIN);
2183  double t1, t2;
2184  get_time(t1);
2185 
2186  // set up Extracellular tissue
2189  mtype[Electrics::extra_grid].regionIDs, true, "gregion_e");
2190 
2191  // set up a subset of the complete electrical mappings
2192  int dpn = 1;
2194 
2196  // set up Intracellular tissue
2199  mtype[Electrics::intra_grid].regionIDs, true, "gregion_i");
2200 
2203  }
2204 
2205  // set up stimuli
2206  init_stim_info();
2207  stimuli.resize(param_globals::num_stim);
2209  for(int i=0; i<param_globals::num_stim; i++) {
2210  // construct new stimulus
2211  stimulus & s = stimuli[i];
2212 
2214  s.translate(i);
2215 
2216  s.setup(i);
2217 
2218  if(s.phys.type == Phi_ex) {
2219  s.pulse.wform = constPulse;
2220  sample_wave_form(s.pulse, i);
2221  }
2222  }
2223 
2224  set_dir(OUTPUT);
2225 
2226  ellip_solver.init();
2228 
2229  if(param_globals::dump2MatLab) {
2230  std::string bsname = param_globals::dump_basename;
2231  std::string fn;
2232 
2233  set_dir(OUTPUT);
2234  fn = bsname + "_Kie.bin";
2235  ellip_solver.phie_mat->write(fn.c_str());
2236  }
2237 
2238  // the laplace solver executes only once, thus we need a singlestep timer
2239  timer_idx = user_globals::tm_manager->add_singlestep_timer(0.0, 0.0, "laplace trigger", nullptr);
2240 
2241  SF::vector<mesh_int_t>* restr_i = NULL;
2242  SF::vector<mesh_int_t>* restr_e = NULL;
2243 
2244  setup_dataout(param_globals::dataout_e, param_globals::dataout_e_vtx, extra_elec_msh,
2245  restr_e, param_globals::num_io_nodes > 0);
2246  if(param_globals::dataout_e)
2247  output_manager.register_output(ellip_solver.phie, extra_elec_msh, 1, param_globals::phiefile, "mV", restr_e);
2248 
2250  setup_dataout(param_globals::dataout_i, param_globals::dataout_i_vtx, intra_elec_msh,
2251  restr_i, param_globals::num_io_nodes > 0);
2252  if(param_globals::dataout_i)
2253  output_manager.register_output(ellip_solver.phie_i, intra_elec_msh, 1, param_globals::phieifile, "mV", restr_i);
2254  }
2255 
2256  this->initialize_time += timing(t2, t1);
2258  this->compute_step();
2259 }
2260 
2261 void Laplace::destroy()
2262 {}
2263 
2264 void Laplace::compute_step()
2265 {
2267  // Laplace compute might be called multiple times, we want to run only once..
2268  if(!ellip_solver.lin_solver) return;
2269 
2270  double t0, t1, dur;
2271  log_msg(0,0,0, "Solving Laplace problem ..");
2272 
2273  get_time(t0);
2275  dur = timing(t1,t0);
2276 
2277  log_msg(0,0,0, "Done in %.5f seconds.", dur);
2278 
2280  this->compute_time += timing(t1, t0);
2281  set_dir(OUTPUT);
2284 
2285  // we clear the elliptic matrices and solver to save some memory when computing
2286  // the laplace solution on-the-fly
2287  delete ellip_solver.mass_e; ellip_solver.mass_e = NULL;
2288  delete ellip_solver.phie_mat; ellip_solver.phie_mat = NULL;
2290 }
2291 
2292 void Laplace::output_step()
2293 {}
2294 
2295 double Laplace::timer_val(const int timer_id)
2296 {
2297  int sidx = stimidx_from_timeridx(stimuli, timer_id);
2298  double val = 0.0;
2299 
2300  if(sidx != -1) stimuli[sidx].value(val);
2301  else val = std::nan("NaN");
2302  return val;
2303 }
2304 
2305 std::string Laplace::timer_unit(const int timer_id)
2306 {
2307  int sidx = stimidx_from_timeridx(stimuli, timer_id);
2308  std::string s_unit;
2309  if(sidx != -1) s_unit = stimuli[sidx].pulse.wave.f_unit;
2310  return s_unit;
2311 }
2312 
2314  sf_mat & mass_i,
2315  sf_mat & mass_e,
2316  limpet::MULTI_IF *miif,
2317  FILE_SPEC logger)
2318 {
2320 
2321  for(stimulus & s : stimuli) {
2322  if(is_current(s.phys.type) && s.phys.total_current) {
2323  // extracellular current injection
2324  if (s.phys.type == I_ex) {
2325  // compute affected volume in um^3
2326  SF_real vol = get_volume_from_nodes(mass_e, s.electrode.vertices);
2327 
2328  // s->strength holds the total current in uA, compute current density in uA/cm^3
2329  // Theoretically, we don't need to scale the volume to cm^3 here since we later
2330  // multiply with the mass matrix and we get um^3 * uA/um^3 = uA.
2331  // However, for I_ex there is an additional um^3 to cm^3 scaling in phys.scale,
2332  // since I_e is expected to be in uA/cm^3. Therefore, we need to compensate for that to arrive at uA later.
2333  float scale = 1.e12/vol;
2334 
2335  s.pulse.strength *= scale;
2336 
2337  log_msg(logger,0,ECHO,
2338  "%s [Stimulus %d]: current density scaled to %.4g uA/cm^3\n",
2339  s.name.c_str(), s.idx, s.pulse.strength);
2340  }
2341  else if (s.phys.type == I_tm) {
2342  // compute affected volume in um^3
2343  SF_real vol = get_volume_from_nodes(mass_i, s.electrode.vertices);
2344  const sf_mesh & imesh = get_mesh(intra_elec_msh);
2345  const SF::vector<mesh_int_t> & alg_nod = imesh.pl.algebraic_nodes();
2346 
2347  if(alg_idx_map.size() == 0) {
2348  mesh_int_t lidx = 0;
2349  for(mesh_int_t n : alg_nod) {
2350  alg_idx_map[n] = lidx;
2351  lidx++;
2352  }
2353  }
2354 
2355  SF_real surf = 0.0;
2356  for(mesh_int_t n : s.electrode.vertices) {
2357  if(alg_idx_map.count(n)) {
2358  mesh_int_t lidx = alg_idx_map[n];
2359  int r = miif->IIFmask[lidx];
2360  // surf = vol*beta [1/um], surf is in [um^2]
2361  surf = vol * miif->IIF[r]->cgeom().SVratio * param_globals::imp_region[r].volFrac;
2362  //convert to cm^2
2363  surf /= 1.e8;
2364  break;
2365  }
2366  }
2367  surf = get_global(surf, MPI_MAX, PETSC_COMM_WORLD);
2368 
2369  // scale surface density now to result in correct total current
2370  s.pulse.strength /= surf;
2371  log_msg(logger, 0, ECHO,
2372  "%s [Stimulus %d]: current density scaled to %.4g uA/cm^2\n",
2373  s.name.c_str(), s.idx, s.pulse.strength);
2374  }
2375  }
2376  }
2377 }
2378 
2379 
2380 
2381 } // namespace opencarp
#define M_PI
Definition: ION_IF.h:52
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
std::vector< IonIfBase * > IIF
array of IIF's
Definition: MULTI_ION_IF.h:202
opencarp::sf_vec * gdata[NUM_IMP_DATA_TYPES]
data used by all IMPs
Definition: MULTI_ION_IF.h:216
node_count_t numNode
local number of nodes
Definition: MULTI_ION_IF.h:210
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:205
int N_IIF
how many different IIF's
Definition: MULTI_ION_IF.h:211
node_count_t * N_Nodes
#nodes for each IMP
Definition: MULTI_ION_IF.h:200
node_index_t ** NodeLists
local partitioned node lists for each IMP stored
Definition: MULTI_ION_IF.h:201
IIF_Mask_t * IIFmask
region for each node
Definition: MULTI_ION_IF.h:214
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:768
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:752
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:1715
void output_initial_activations()
output one nodal vector of initial activation time
Definition: electrics.cc:1824
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:1535
int check_acts(double tm)
check activations at sim time tm
Definition: electrics.cc:1660
SF::vector< Activation > acts
Definition: electrics.h:219
LAT_detector()
constructor, sets up basic datastructs from global_params
Definition: electrics.cc:1407
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:2239
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
Definition: electrics.cc:2249
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:956
void rebuild_matrices(MaterialType *mtype, SF::vector< stimulus > &stimuli, FILE_SPEC logger)
Definition: electrics.cc:944
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:1061
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:1017
void write_data()
write registered data to disk
Definition: sim_utils.cc:2430
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:2266
void close_files_and_cleanup()
close file descriptors
Definition: sim_utils.cc:2477
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:2397
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:1186
parabolic_t parab_tech
manner in which parabolic equations are solved
Definition: electrics.h:134
void solve(sf_vec &phie_i)
Definition: electrics.cc:1300
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:810
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:782
@ 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:1800
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:834
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:1510
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:1939
int set_dir(IO_t dest)
Definition: sim_utils.cc:1347
@ 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:1614
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:2596
bool have_dbc_stims(const SF::vector< stimulus > &stimuli)
return wheter any stimuli require dirichlet boundary conditions
Definition: electrics.cc:859
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
void setup_dataout(const int dataout, std::string dataout_vtx, mesh_t grid, SF::vector< mesh_int_t > *&restr, bool async)
Definition: electrics.cc:613
char * get_file_dir(const char *file)
Definition: sim_utils.cc:2225
@ 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:2257
int postproc_recover_phie()
Definition: electrics.cc:2006
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
void setup_phie_recovery_data(phie_recovery_data &data)
Definition: electrics.cc:2089
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:1784
const char * get_tsav_ext(double time)
Definition: electrics.cc:868
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 update_cwd()
save the current working directory to curdir so that we can switch back to it if needed.
Definition: sim_utils.cc:1342
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:154
#define DATAOUT_VOL
Definition: sim_utils.h:60
#define MONODOMAIN
Definition: sim_utils.h:153
#define EXP_POSTPROCESS
Definition: sim_utils.h:172
#define DATAOUT_NONE
Definition: sim_utils.h:58
#define PSEUDO_BIDM
Definition: sim_utils.h:155
#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