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