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  // solver parabolic system
305 
306  clamp_Vm();
307 
308  if(user_globals::tm_manager->trigger(iotm_console)) {
309  // output lin solver stats
311  if(param_globals::bidomain == BIDOMAIN)
313  }
314  this->compute_time += timing(t2, t1);
315 
316  // since the traces have their own timing, we check for trace dumps in the compute step loop
319 
320 }
321 
323 {
324  double t1, t2;
325  get_time(t1);
326  // for pseudo-bidomain we compute extracellular potential only for output
327  if(param_globals::bidomain == PSEUDO_BIDM) {
331  }
332 
333  // recover phie
334  if(phie_rcv.pts.size()) {
336  }
337 
340 
341  double curtime = timing(t2, t1);
342  this->output_time += curtime;
343 
344  IO_stats.calls++;
345  IO_stats.tot_time += curtime;
346 
349 }
350 
355 {
356  // output LAT data
358 
359  // close logger
360  f_close(logger);
361 
362  // close output files
364 
365  // destroy ionics
366  ion.destroy();
367 }
368 
369 void balance_electrode(elliptic_solver & ellip, SF::vector<stimulus> & stimuli, int balance_from, int balance_to)
370 {
371  log_msg( NULL, 0, 0, "Balancing stimulus %d with %d %s-wise.",balance_from, balance_to,
372  is_current(stimuli[balance_from].phys.type) ? "current" : "voltage" );
373 
374  stimulus & from = stimuli[balance_from];
375  stimulus & to = stimuli[balance_to];
376 
377  to.pulse = from.pulse;
378  to.ptcl = from.ptcl;
379  to.phys = from.phys;
380  to.pulse.strength *= -1.0;
381 
382  if (from.phys.type == I_ex)
383  {
384  sf_mat & mass = *ellip.mass_e;
385  SF_real vol0 = get_volume_from_nodes(mass, from.electrode.vertices);
387 
388  to.pulse.strength *= fabs(vol0/vol1);
389  }
390 }
391 
392 void Electrics::balance_electrodes()
393 {
394  for(int i=0; i<param_globals::num_stim; i++) {
395  if(param_globals::stim[i].crct.balance != -1) {
396  int from = param_globals::stim[i].crct.balance;
397  int to = i;
398 
399  balance_electrode(this->ellip_solver, stimuli, from, to);
400  }
401  }
402 }
403 
404 void Electrics::setup_stimuli()
405 {
406  // initialize basic stim info data (used units, supported types, etc)
407  init_stim_info();
408  bool dumpTrace = true;
409 
410  if(dumpTrace) set_dir(OUTPUT);
411 
412  stimuli.resize(param_globals::num_stim);
413  for(int i=0; i<param_globals::num_stim; i++)
414  {
415  // construct new stimulus
416  stimulus & s = stimuli[i];
417 
419  s.translate(i);
420 
421  s.setup(i);
422 
423  if(dumpTrace && get_rank() == 0)
424  s.pulse.wave.write_trace(s.name+".trc");
425  }
426 }
427 
428 void apply_stim_to_vector(const stimulus & s, sf_vec & vec, bool add)
429 {
430  double val; s.value(val);
431  const SF::vector<mesh_int_t> & idx = s.electrode.vertices;
432  const int rank = get_rank();
433  SF::vector<mesh_int_t> local_idx = idx;
434  for (size_t i = 0; i < idx.size(); i++) {
435  local_idx[i] = local_nodal_to_local_petsc(*vec.mesh, rank, idx[i]);
436  }
437  vec.set(local_idx, val, add, true);
438 }
439 
440 void Electrics::stimulate_intracellular()
441 {
443 
444  // iterate over stimuli
445  for(stimulus & s : stimuli) {
446  if(s.is_active()) {
447  // for active stimuli, deal with the stimuli-type specific stimulus application
448  switch(s.phys.type)
449  {
450  case I_tm: {
451  if(param_globals::operator_splitting) {
452  apply_stim_to_vector(s, *ps.Vmv, true);
453  }
454  else {
455  SF_real Cm = 1.0;
457  SF_real sc = tm.time_step / Cm;
458 
459  ps.Irhs->set(0.0);
460  apply_stim_to_vector(s, *ps.Irhs, true);
461 
462  *ps.tmp_i1 = *ps.IIon;
463  *ps.tmp_i1 -= *ps.Irhs;
464  *ps.tmp_i1 *= sc; // tmp_i1 = sc * (IIon - Irhs)
465 
466  // add ionic, transmembrane and intracellular currents to rhs
467  if(param_globals::parab_solve != parabolic_solver::EXPLICIT)
468  ps.mass_i->mult(*ps.tmp_i1, *ps.Irhs);
469  else
470  *ps.Irhs = *ps.tmp_i1;
471  }
472  break;
473  }
474 
475  case Illum: {
476  sf_vec* illum_vec = ion.miif->gdata[limpet::illum];
477 
478  if(illum_vec == NULL) {
479  log_msg(0,5,0, "Cannot apply illumination stim: global vector not present!");
480  EXIT(EXIT_FAILURE);
481  } else {
482  apply_stim_to_vector(s, *illum_vec, false);
483  }
484 
485  break;
486  }
487 
488  default: break;
489  }
490  }
491  }
492 }
493 
494 void Electrics::clamp_Vm() {
495  for(stimulus & s : stimuli) {
496  if(s.phys.type == Vm_clmp && s.is_active())
498  }
499 }
500 
501 void Electrics::stimulate_extracellular()
502 {
503  if(param_globals::bidomain) {
504  // we check if the DBC layout changed, if so we recompute the matrix and the dbc_manager
505  bool dbcs_have_updated = ellip_solver.dbc != nullptr && ellip_solver.dbc->dbc_update();
507 
508  if(dbcs_have_updated && time_not_final)
510 
511  ellip_solver.phiesrc->set(0.0);
512 
513  for(const stimulus & s : stimuli) {
514  if(s.is_active() && s.phys.type == I_ex)
516  }
517  }
518 }
519 
521  SF::vector<mesh_int_t> & inp_idx,
523 {
524  int mpi_rank = get_rank(), mpi_size = get_size();
525  const SF::vector<mesh_int_t> & layout = mesh.pl.algebraic_layout();
526 
527  SF::vector<mesh_int_t> sndbuff;
528 
529  size_t buffsize = 0;
530  idx.resize(0);
531 
532  for(int pid=0; pid < mpi_size; pid++) {
533  if(mpi_rank == pid) {
534  sndbuff = inp_idx;
535  buffsize = sndbuff.size();
536  }
537 
538  MPI_Bcast(&buffsize, sizeof(size_t), MPI_BYTE, pid, PETSC_COMM_WORLD);
539  sndbuff.resize(buffsize);
540  MPI_Bcast(sndbuff.data(), buffsize*sizeof(mesh_int_t), MPI_BYTE, pid, PETSC_COMM_WORLD);
541 
542  mesh_int_t start = layout[mpi_rank], stop = layout[mpi_rank+1];
543 
544  for(mesh_int_t i : sndbuff) {
545  if(i >= start && i < stop)
546  idx.push_back(i - start);
547  }
548  }
549 
550  binary_sort(idx); unique_resize(idx);
551 }
552 
554  SF::vector<mesh_int_t> & inp_idx,
556 {
557  int mpi_rank = get_rank(), mpi_size = get_size();
558  const SF::vector<mesh_int_t> & alg_nod = mesh.pl.algebraic_nodes();
560 
562  for(mesh_int_t ii : alg_nod)
563  amap[nbr[ii]] = ii;
564 
565  SF::vector<mesh_int_t> sndbuff;
566  size_t buffsize = 0;
567  idx.resize(0);
568 
569  for(int pid=0; pid < mpi_size; pid++) {
570  if(mpi_rank == pid) {
571  sndbuff = inp_idx;
572  buffsize = sndbuff.size();
573  }
574 
575  MPI_Bcast(&buffsize, sizeof(size_t), MPI_BYTE, pid, PETSC_COMM_WORLD);
576  sndbuff.resize(buffsize);
577  MPI_Bcast(sndbuff.data(), buffsize*sizeof(mesh_int_t), MPI_BYTE, pid, PETSC_COMM_WORLD);
578 
579  for(mesh_int_t i : sndbuff) {
580  if(amap.count(i))
581  idx.push_back(amap[i]);
582  }
583  }
584 
585  binary_sort(idx); unique_resize(idx);
586 }
587 
588 void setup_dataout(const int dataout, std::string dataout_vtx, mesh_t grid,
589  SF::vector<mesh_int_t>* & restr, bool async)
590 {
591  sf_mesh & mesh = get_mesh(grid);
592 
593  switch(dataout) {
594 
595  case DATAOUT_SURF: {
596  sf_mesh surfmesh;
597  compute_surface_mesh(mesh, SF::NBR_SUBMESH, surfmesh);
598 
599  SF::vector<mesh_int_t> idxbuff(surfmesh.con);
600  binary_sort(idxbuff); unique_resize(idxbuff);
601 
602  restr = new SF::vector<mesh_int_t>();
603 
604  // for sync output, we need restr to hold the local indices in the petsc vectors
605  // that have been permuted to canonical numbering. For async, we need the
606  // non-overlapping decomposition of indices in NBR_SUBMESH numbering. The petsc indices will be
607  // computed at a later stage. The only reason we need to call compute_restr_idx_async,
608  // is that surface nodes in NBR_SUBMESH, may
609  // reside on partitions where they are not part of the algebraic nodes. thus we need to
610  // recommunicate to make sure the data layout is correct. We do not have this problem for
611  // DATAOUT_VTX.
612  if(!async)
613  compute_restr_idx(mesh, idxbuff, *restr);
614  else
615  compute_restr_idx_async(mesh, idxbuff, *restr);
616 
617  break;
618  }
619 
620  case DATAOUT_VTX: {
621  SF::vector<mesh_int_t> idxbuff;
622 
623  update_cwd();
624 
625  set_dir(INPUT);
626  read_indices(idxbuff, dataout_vtx, mesh, SF::NBR_REF, true, PETSC_COMM_WORLD);
627  set_dir(CURDIR);
628 
629  restr = new SF::vector<mesh_int_t>();
630 
631  if(!async) {
633  for(mesh_int_t & i : idxbuff) i = nbr[i];
634 
635  compute_restr_idx(mesh, idxbuff, *restr);
636  } else {
637  *restr = idxbuff;
638  }
639 
640  break;
641  }
642 
643  case DATAOUT_NONE:
644  case DATAOUT_VOL:
645  default: break;
646  }
647 }
648 
649 void Electrics::setup_output()
650 {
651  int rank = get_rank();
652  SF::vector<mesh_int_t>* restr_i = NULL;
653  SF::vector<mesh_int_t>* restr_e = NULL;
654  set_dir(OUTPUT);
655 
656  setup_dataout(param_globals::dataout_i, param_globals::dataout_i_vtx, intra_elec_msh,
657  restr_i, param_globals::num_io_nodes > 0);
658 
659  if(param_globals::dataout_i)
660  output_manager.register_output(parab_solver.Vmv, intra_elec_msh, 1, param_globals::vofile, "mV", restr_i);
661 
662  if(param_globals::bidomain) {
663  setup_dataout(param_globals::dataout_e, param_globals::dataout_e_vtx, extra_elec_msh,
664  restr_e, param_globals::num_io_nodes > 0);
665 
666  if(param_globals::dataout_i)
667  output_manager.register_output(ellip_solver.phie_i, intra_elec_msh, 1, param_globals::phieifile, "mV", restr_i);
668  if(param_globals::dataout_e)
669  output_manager.register_output(ellip_solver.phie, extra_elec_msh, 1, param_globals::phiefile, "mV", restr_e);
670  }
671 
672  if(phie_rcv.pts.size())
673  output_manager.register_output_sync(phie_rcv.phie_rec, phie_recv_msh, 1, param_globals::phie_recovery_file, "mV");
674 
676 
677  if(param_globals::num_trace) {
678  sf_mesh & imesh = get_mesh(intra_elec_msh);
679  open_trace(ion.miif, param_globals::num_trace, param_globals::trace_node, NULL, &imesh);
680  }
681 
682  // initialize generic logger for IO timings per time_dt
683  IO_stats.init_logger("IO_stats.dat");
684 }
685 
686 void Electrics::dump_matrices()
687 {
688  std::string bsname = param_globals::dump_basename;
689  std::string fn;
690 
691  set_dir(OUTPUT);
692 
693  // dump monodomain matrices
694  if ( param_globals::parab_solve==1 ) {
695  // using Crank-Nicolson
696  fn = bsname + "_Ki_CN.bin";
697  parab_solver.lhs_parab->write(fn.c_str());
698  }
699  fn = bsname + "_Ki.bin";
700  parab_solver.rhs_parab->write(fn.c_str());
701 
702  fn = bsname + "_Mi.bin";
703  parab_solver.mass_i->write(fn.c_str());
704 
705  if ( param_globals::bidomain ) {
706  fn = bsname + "_Kie.bin";
707  ellip_solver.phie_mat->write(fn.c_str());
708 
709  fn = bsname + "_Me.bin";
710  ellip_solver.mass_e->write(fn.c_str());
711  }
712 }
713 
714 
717 double Electrics::timer_val(const int timer_id)
718 {
719  // determine
720  int sidx = stimidx_from_timeridx(stimuli, timer_id);
721  double val = 0.0;
722  if(sidx != -1) {
723  stimuli[sidx].value(val);
724  }
725  else
726  val = std::nan("NaN");
727 
728  return val;
729 }
730 
733 std::string Electrics::timer_unit(const int timer_id)
734 {
735  int sidx = stimidx_from_timeridx(stimuli, timer_id);
736  std::string s_unit;
737 
738  if(sidx != -1)
739  // found a timer-linked stimulus
740  s_unit = stimuli[sidx].pulse.wave.f_unit;
741 
742  return s_unit;
743 }
744 
747 int stimidx_from_timeridx(const SF::vector<stimulus> & stimuli, const int timer_id)
748 {
749  // the only electrical quantities linked to a timer are stimuli
750  // thus we search for timer links only among stimuli for now
751 
752  // iterate over stimuli
753  for(size_t i = 0; i<stimuli.size(); i++)
754  {
755  const stimulus & s = stimuli[i];
756 
757  if(s.ptcl.timer_id == timer_id)
758  return s.idx;
759  }
760 
761  // invalid timer index not linked to any stimulus
762  return -1;
763 }
764 
775 void get_kappa(sf_vec & kappa, IMPregion *ir, limpet::MULTI_IF & miif, double k)
776 {
777  double* reg_kappa = new double[miif.N_IIF];
778 
779  for(int i=0; i<miif.N_IIF; i++)
780  reg_kappa[i] = k * miif.IIF[i]->cgeom().SVratio * ir[i].volFrac;
781 
782  double *kd = kappa.ptr();
783 
784  for(int i = 0; i < miif.numNode; i++)
785  kd[i] = reg_kappa[(int) miif.IIFmask[i]];
786 
787  kappa.release_ptr(kd);
788  delete [] reg_kappa;
789 }
790 
791 
800 {
801  for(size_t i=0; i < m.regions.size(); i++) {
802  elecMaterial *emat = static_cast<elecMaterial*>(m.regions[i].material);
803  emat->g = type;
804  }
805 }
806 
807 void Electrics::setup_solvers()
808 {
809  set_dir(OUTPUT);
810  parab_solver.init();
812 
813  if (param_globals::bidomain) {
814  ellip_solver.init();
816  }
817 
818  if(param_globals::dump2MatLab)
819  dump_matrices();
820 }
821 
823 {
824  for(const stimulus & s : stimuli) {
825  if(is_dbc(s.phys.type))
826  return true;
827  }
828  return false;
829 }
830 
831 const char* get_tsav_ext(double time)
832 {
833  int min_idx = -1;
834  double min_diff = 1e100;
835 
836  for(int i=0; i<param_globals::num_tsav; i++)
837  {
838  double diff = fabs(param_globals::tsav[i] - time);
839  if(min_diff > diff) {
840  min_diff = diff;
841  min_idx = i;
842  }
843  }
844 
845  if(min_idx == -1)
846  min_idx = 0;
847 
848  return param_globals::tsav_ext[min_idx];
849 }
850 
851 void Electrics::checkpointing()
852 {
854 
855  // regular user selected state save
856  if (tm.trigger(iotm_chkpt_list)) {
857  char save_fnm[1024];
858  const char* tsav_ext = get_tsav_ext(tm.time);
859 
860  snprintf(save_fnm, sizeof save_fnm, "%s.%s.roe", param_globals::write_statef, tsav_ext);
861 
862  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
863  }
864 
865  // checkpointing based on interval
866  if (tm.trigger(iotm_chkpt_intv)) {
867  char save_fnm[1024];
868  snprintf(save_fnm, sizeof save_fnm, "checkpoint.%.1f.roe", tm.time);
869  ion.miif->dump_state(save_fnm, tm.time, intra_elec_msh, false, GIT_COMMIT_COUNT);
870  }
871 }
872 
874 {
875  double t0, t1, dur;
876  get_time(t0);
877  stats.init_logger("ell_stats.dat");
878 
879  // here we can differentiate the solvers
880  SF::init_solver(&lin_solver);
881  sf_mesh & extra_mesh = get_mesh(extra_elec_msh);
882  sf_vec::ltype alg_type = sf_vec::algebraic;
883  const int dpn = 1;
884 
885  SF::init_vector(&phie, extra_mesh, dpn, alg_type);
886  SF::init_vector(&phiesrc, extra_mesh, dpn, alg_type);
887  SF::init_vector(&currtmp, extra_mesh, dpn, alg_type);
888 
890  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
891  SF::init_vector(&phie_i, intra_mesh, dpn, alg_type);
892  }
893 
894  int max_row_entries = max_nodal_edgecount(extra_mesh);
895 
896  SF::init_matrix(&phie_mat);
897  SF::init_matrix(&mass_e);
898 
899  // alloc stiffness matrix
900  phie_mat->init(extra_mesh, dpn, dpn, max_row_entries);
901  // alloc mass matrix
902  mass_e ->init(extra_mesh, dpn, dpn, param_globals::mass_lumping ? 1 : max_row_entries);
903  dur = timing(t1, t0);
904 }
905 
909 {
910  double t0, t1, dur;
911  get_time(t0);
912  rebuild_stiffness(mtype, stimuli, logger);
913  rebuild_mass(logger);
914  dur = timing(t1, t0);
915 }
916 
920 {
921  double t0, t1, dur;
922  int log_flag = param_globals::output_level > 1 ? ECHO : 0;
923 
924  MaterialType & mt = mtype[Electrics::extra_grid];
925  const bool have_dbc = have_dbc_stims(stimuli);
926 
927  cond_t condType = sum_cond;
928  set_cond_type(mt, condType);
929 
930  // get mesh reference
931  sf_mesh & mesh = get_mesh(extra_elec_msh);
932 
933  get_time(t0);
934 
935  // fill the system
936  elec_stiffness_integrator stfn_integ(mt);
937 
938  phie_mat->zero();
939  SF::assemble_matrix(*phie_mat, mesh, stfn_integ);
940  phie_mat->scale(-1.0);
941 
942  dur = timing(t1,t0);
943  log_msg(logger,0,log_flag, "Computed ellipitc stiffness matrix in %.3f seconds.", dur);
944 
945  // set boundary conditions
946  if(have_dbc) {
947  log_msg(logger,0,log_flag, "Elliptic lhs matrix enforcing Dirichlet boundaries.");
948  get_time(t0);
949 
950  if(dbc == nullptr)
951  dbc = new dbc_manager(*phie_mat, stimuli);
952  else
953  dbc->recompute_dbcs();
954 
955  dbc->enforce_dbc_lhs();
956 
957  dur = timing(t1,t0);
958  log_msg(logger,0,log_flag, "Elliptic lhs matrix Dirichlet enforcing done in %.3f seconds.", dur);
959  }
960  else {
961  log_msg(logger,1,ECHO, "Elliptic lhs matrix is singular!");
962  // we are dealing with a singular system
963  phie_mat_has_nullspace = true;
964  }
965 
966  // solver has not been initialized yet
967  set_dir(INPUT);
968  get_time(t0);
969 
970  setup_linear_solver(logger);
971 
972  dur = timing(t1,t0);
973  log_msg(logger,0,log_flag, "Initializing elliptic solver in %.5f seconds.", dur);
974  set_dir(OUTPUT);
975 }
976 
978 {
979  int log_flag = param_globals::output_level > 1 ? ECHO : 0;
980  double t0, t1, dur;
981  mass_integrator mass_integ;
982 
983  // get mesh reference
984  sf_mesh & mesh = get_mesh(extra_elec_msh);
985  get_time(t0);
986  mass_e->zero();
987 
988  if(param_globals::mass_lumping) {
989  SF::assemble_lumped_matrix(*mass_e, mesh, mass_integ);
990  } else {
991  SF::assemble_matrix(*mass_e, mesh, mass_integ);
992  }
993 
994  dur = timing(t1,t0);
995  log_msg(logger,0,log_flag, "Computed elliptic mass matrix in %.3f seconds.", dur);
996 }
997 
998 void elliptic_solver::setup_linear_solver(FILE_SPEC logger)
999 {
1000 
1001  tol = param_globals::cg_tol_ellip;
1002  max_it = param_globals::cg_maxit_ellip;
1003 
1004  std::string solver_file;
1005  solver_file = param_globals::ellip_options_file;
1006  lin_solver->setup_solver(*phie_mat, tol, max_it, param_globals::cg_norm_ellip,
1007  "elliptic PDE", phie_mat_has_nullspace,
1008  logger, solver_file.c_str(),
1009  "-ksp_type cg -pc_type hypre -pc_hypre_type boomeramg "
1010  "-pc_hypre_boomeramg_max_iter 1 "
1011  "-pc_hypre_boomeramg_strong_threshold 0.0 -options_left");
1012 }
1013 
1014 void elliptic_solver::solve(sf_mat & Ki, sf_vec & Vmv, sf_vec & tmp_i)
1015 {
1016  double t0,t1;
1018  // assembly of rhs for FE
1019  if (phiesrc->mag() > 0.0) {
1020  mass_e->mult(*phiesrc, *currtmp);
1021  phiesrc->deep_copy(*currtmp);
1022  }
1023 
1024  Ki.mult(Vmv, tmp_i);
1025 
1026  bool add = true;
1027  i2e->forward(tmp_i, *phiesrc, add);
1028 
1029  if(dbc != nullptr)
1030  dbc->enforce_dbc_rhs(*phiesrc);
1031 
1032  get_time(t0);
1033  (*lin_solver)(*phie, *phiesrc);
1034 
1035  // treat solver statistics
1036  auto dur = timing(t1, t0);
1037  lin_solver->time += dur;
1038  stats.slvtime += dur;
1039  stats.update_iter(lin_solver->niter);
1040  if(lin_solver->reason < 0) {
1041  log_msg(0, 5, 0,"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1042  petsc_get_converged_reason_str(lin_solver->reason));
1043  EXIT(1);
1044  }
1045 
1046  add = false;
1047  i2e->backward(*phie, *phie_i, add);
1048 }
1049 
1051 {
1052  double t0,t1;
1053 
1054  if(dbc != nullptr)
1055  dbc->enforce_dbc_rhs(*phiesrc);
1056 
1057  get_time(t0);
1058  (*lin_solver)(*phie, *phiesrc);
1059 
1060  // treat solver statistics
1061  auto dur = timing(t1, t0);
1062  lin_solver->time += dur;
1063  stats.slvtime += dur;
1064  stats.update_iter(lin_solver->niter);
1065 
1066  if(lin_solver->reason < 0) {
1067  log_msg(0, 5, 0,"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1068  petsc_get_converged_reason_str(lin_solver->reason));
1069  EXIT(1);
1070  }
1071 
1072  // phie_i is only set up when we have an IntraMesh registered
1073  if(is_init(phie_i)) {
1074  bool add = false;
1076  i2e->backward(*phie, *phie_i, add);
1077  }
1078 }
1079 
1081 {
1082  double t0, t1, dur;
1083  get_time(t0);
1084  stats.init_logger("par_stats.dat");
1085 
1086  // here we can differentiate the solvers
1087  SF::init_solver(&lin_solver);
1088 
1089  sf_vec* vm_ptr = get_data(vm_vec);
1090  sf_vec* iion_ptr = get_data(iion_vec);
1091 
1092  if(!(vm_ptr != NULL && iion_ptr != NULL)) {
1093  log_msg(0,5,0, "%s error: global Vm and Iion vectors not properly set up! Ionics seem invalid! Aborting!",
1094  __func__);
1095  EXIT(1);
1096  }
1097 
1098  SF::init_vector(&Vmv, vm_ptr);
1099  Vmv->shallow_copy(*vm_ptr);
1100  SF::init_vector(&IIon, iion_ptr);
1101  IIon->shallow_copy(*iion_ptr);
1102 
1103  SF::init_vector(&Diff_term, Vmv);
1104  SF::init_vector(&old_vm, Vmv);
1105 
1106  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
1107  sf_vec::ltype alg_type = sf_vec::algebraic;
1108 
1109  int dpn = 1;
1110  SF::init_vector(&kappa_i, intra_mesh, dpn, alg_type);
1111  SF::init_vector(&tmp_i1, intra_mesh, dpn, alg_type);
1112  SF::init_vector(&tmp_i2, intra_mesh, dpn, alg_type);
1113  SF::init_vector(&old_vm, intra_mesh, dpn, alg_type);
1114 
1115  if(!param_globals::operator_splitting)
1116  SF::init_vector(&Irhs, intra_mesh, dpn, alg_type);
1117 
1118  // alloc matrices
1119  int max_row_entries = max_nodal_edgecount(intra_mesh);
1120 
1121  SF::init_matrix(&lhs_parab);
1122  SF::init_matrix(&rhs_parab);
1123  SF::init_matrix(&mass_i);
1124 
1125  rhs_parab->init(intra_mesh, dpn, dpn, max_row_entries);
1126  mass_i ->init(intra_mesh, dpn, dpn, param_globals::mass_lumping ? 1 : max_row_entries);
1127 
1128  parab_tech = static_cast<parabolic_solver::parabolic_t>(param_globals::parab_solve);
1129  dur = timing(t1, t0);
1130 }
1131 
1133 {
1134  double start, end, period;
1135  get_time(start);
1136  double t0, t1, dur;
1137  mass_integrator mass_integ;
1138  int dpn = 1;
1139 
1140  int log_flag = param_globals::output_level > 1 ? ECHO : 0;
1141  MaterialType & mt = mtype[Electrics::intra_grid];
1142 
1143  double Dt = user_globals::tm_manager->time_step;
1144  get_kappa(*kappa_i, param_globals::imp_region, miif, UM2_to_CM2 / Dt);
1145 
1146  cond_t condType = intra_cond;
1147  sf_mesh & mesh = get_mesh(intra_elec_msh);
1148 
1149  if( (param_globals::bidomain == MONODOMAIN && param_globals::bidm_eqv_mono) ||
1150  (param_globals::bidomain == PSEUDO_BIDM) )
1151  condType = para_cond;
1152 
1153  // set material and conductivity type
1154  set_cond_type(mt, condType);
1155 
1156  // fill the system
1157  {
1158  get_time(t0);
1159 
1160  elec_stiffness_integrator stfn_integ(mt);
1161  SF::assemble_matrix(*rhs_parab, mesh, stfn_integ);
1162 
1163  dur = timing(t1,t0);
1164  log_msg(logger,0,log_flag, "Computed parabolic stiffness matrix in %.3f seconds.", dur);
1165  get_time(t0);
1166 
1167  if(param_globals::mass_lumping)
1168  SF::assemble_lumped_matrix(*mass_i, mesh, mass_integ);
1169  else
1170  SF::assemble_matrix(*mass_i, mesh, mass_integ);
1171 
1172  sf_vec* empty; SF::init_vector(&empty);
1173  mass_i->mult_LR(*kappa_i, *empty);
1174 
1175  dur = timing(t1,t0);
1176  log_msg(logger,0,log_flag, "Computed parabolic mass matrix in %.3f seconds.", dur);
1177  delete empty;
1178  }
1179 
1180  // initialize parab lhs
1181  if(parab_tech != EXPLICIT) {
1182  lhs_parab->duplicate(*rhs_parab);
1183  // if we have mass lumping, then the nonzero pattern between Mi and Ki is different
1184  bool same_nonzero = param_globals::mass_lumping == false;
1185 
1186  if (parab_tech==CN) {
1187  lhs_parab->scale(-param_globals::theta);
1188  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1189  }
1190  else if (parab_tech==O2dT) {
1191  lhs_parab->scale(-0.5);
1192  mass_i->scale(0.5);
1193  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1194  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1195  lhs_parab->add_scaled_matrix(*mass_i, 1.0, same_nonzero);
1196  }
1197  }
1198  else {
1199  SF::init_vector(&inv_mass_diag, Vmv);
1200  mass_i->get_diagonal(*inv_mass_diag);
1201 
1202  SF_real* p = inv_mass_diag->ptr();
1203 
1204  for(int i=0; i<inv_mass_diag->lsize(); i++)
1205  p[i] = 1.0 / p[i];
1206 
1207  inv_mass_diag->release_ptr(p);
1208  }
1209 
1210  if(parab_tech == CN || parab_tech == O2dT) {
1211  set_dir(INPUT);
1212  get_time(t0);
1213 
1214  setup_linear_solver(logger);
1215 
1216  dur = timing(t1,t0);
1217  log_msg(logger,0,log_flag, "Initializing parabolic solver in %.5f seconds.", dur);
1218  set_dir(OUTPUT);
1219  }
1220  period = timing(end, start);
1221 }
1222 
1223 void parabolic_solver::setup_linear_solver(FILE_SPEC logger)
1224 {
1225  tol = param_globals::cg_tol_parab;
1226  max_it = param_globals::cg_maxit_parab;
1227 
1228  std::string solver_file;
1229  solver_file = param_globals::parab_options_file;
1230  lin_solver->setup_solver(*lhs_parab, tol, max_it, param_globals::cg_norm_parab,
1231  "parabolic PDE", false, logger, solver_file.c_str(),
1232  "-pc_type bjacobi -sub_pc_type ilu -ksp_type cg");
1233 }
1234 
1236 {
1237  switch (parab_tech) {
1238  case CN: solve_CN(phie_i); break;
1239  case O2dT: solve_O2dT(phie_i); break;
1240  default: solve_EF(phie_i); break;
1241  }
1242 }
1243 
1244 void parabolic_solver::solve_CN(sf_vec & phie_i)
1245 {
1246  double t0,t1;
1247  // assembly of rhs for CN
1248  if (param_globals::bidomain == BIDOMAIN) {
1249  tmp_i1->deep_copy(phie_i);
1250  tmp_i1->add_scaled(*Vmv, 1.0 - param_globals::theta);
1251  rhs_parab->mult(*tmp_i1, *tmp_i2);
1252  }
1253  else {
1254  rhs_parab->mult(*Vmv, *tmp_i2);
1255  *tmp_i2 *= 1.0 - param_globals::theta;
1256  }
1257 
1258  mass_i->mult(*Vmv, *tmp_i1);
1259  *tmp_i1 += *tmp_i2;
1260 
1261  // add current contributions to rhs
1262  if(!param_globals::operator_splitting)
1263  tmp_i1->add_scaled(*Irhs, -1.0);
1264 
1265  get_time(t0);
1266 
1267  (*lin_solver)(*Vmv, *tmp_i1);
1268 
1269  if(lin_solver->reason < 0) {
1270  log_msg(0, 5, 0,"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1271  petsc_get_converged_reason_str(lin_solver->reason));
1272  EXIT(1);
1273  }
1274 
1275  // treat solver statistics
1276  auto dur = timing(t1, t0);
1277  lin_solver->time += dur;
1278  stats.slvtime += dur;
1279  stats.update_iter(lin_solver->niter);
1280 }
1281 
1282 void parabolic_solver::solve_O2dT(sf_vec & phie_i)
1283 {
1284  double t0,t1;
1285  // assembly of rhs for FE
1286  if (param_globals::bidomain == BIDOMAIN) {
1287  tmp_i2->deep_copy(phie_i);
1288  tmp_i2->add_scaled(*Vmv, 0.5);
1289  rhs_parab->mult(*tmp_i2, *tmp_i1); // tmp_i1 = K_i(Vm^t * 0.5 + phi_e)
1290  }
1291  else {
1292  rhs_parab->mult(*Vmv, *tmp_i1);
1293  *tmp_i1 *= 0.5; // tmp_i1 = 0.5 * K_i Vm^t
1294  }
1295 
1296  mass_i->mult(*Vmv, *tmp_i2); // tmp_i2 = M/2 Vm^t
1297  tmp_i1->add_scaled(*tmp_i2, 4.0); // tmp_i1 = (2M+K_i/2)Vm^t
1298  mass_i->mult(*old_vm, *tmp_i2); // tmp_i2 = M/2 Vm^{t-1}
1299 
1300  tmp_i1->add_scaled(*tmp_i2, -1.0); // tmp_i1 = (2M+K_i/2)Vm^t-M/2 Vm^{t-1}
1301  *old_vm = *Vmv;
1302 
1303  get_time(t0);
1304 
1305  // solve
1306  (*lin_solver)(*Vmv, *tmp_i1);
1307 
1308  // treat solver statistics
1309  stats.slvtime += timing(t1, t0);
1310  stats.update_iter(lin_solver->niter);
1311 }
1312 
1313 void parabolic_solver::solve_EF(sf_vec & phie_i)
1314 {
1315  double t0,t1,t2;
1316  get_time(t0);
1317 
1318  // assembly of rhs for FE
1319  if (param_globals::bidomain == BIDOMAIN) {
1320  tmp_i2->deep_copy(phie_i);
1321  *tmp_i2 += *Vmv;
1322  rhs_parab->mult(*tmp_i2, *tmp_i1);
1323  }
1324  else {
1325  rhs_parab->mult(*Vmv, *tmp_i1);
1326  }
1327 
1328  *tmp_i1 *= *inv_mass_diag;
1329  Vmv->add_scaled(*tmp_i1, 1.0);
1330 
1331  if(param_globals::operator_splitting == false)
1332  Vmv->add_scaled(*Irhs, -1.0);
1333 
1334  // record rhs timing
1335  stats.slvtime += timing(t1, t0);
1336 }
1337 
1339 {
1340  char* prvSimDir = strlen(param_globals::start_statef) ?
1341  get_file_dir(param_globals::start_statef) : NULL;
1342 
1343  const char* extn = ".dat";
1344 
1345  // if compute_APD we need an extra 2 acts
1346  int addLATs = param_globals::compute_APD ? 2 : 0;
1347 
1348  bool have_sentinel = param_globals::t_sentinel > 0.0;
1349  bool need_to_add_sentinel = have_sentinel && (param_globals::sentinel_ID < 0);
1350 
1351  addLATs += need_to_add_sentinel ? 1 : 0;
1352  acts.resize(param_globals::num_LATs + addLATs);
1353 
1354  int j=0;
1355  for (int i = 0; i < param_globals::num_LATs; i++ )
1356  {
1357  // using Ph only with bidomain runs
1358  if (param_globals::lats[i].method <= 0 || (param_globals::lats[i].measurand == PHIE && !param_globals::bidomain)) {
1359  log_msg(NULL, 3, 0, "Phie-based LAT measurement requires bidomain >=1 Ignoring lats[%d].", i);
1360  continue;
1361  }
1362 
1363  acts[j].method = (ActMethod)param_globals::lats[i].method;
1364  acts[j].threshold = param_globals::lats[i].threshold;
1365  acts[j].mode = param_globals::lats[i].mode;
1366  acts[j].all = param_globals::lats[i].all;
1367  acts[j].measurand = (PotType)param_globals::lats[i].measurand;
1368  acts[j].ID = param_globals::lats[i].ID;
1369  acts[j].fout = NULL;
1370 
1371  if(param_globals::lats[i].all) {
1372  acts[j].fname = (char*) malloc((strlen(param_globals::lats[i].ID)+strlen(extn)+1)*sizeof(char));
1373  snprintf(acts[j].fname, strlen(param_globals::lats[i].ID)+strlen(extn)+1, "%s%s", param_globals::lats[i].ID, extn);
1374  }
1375  else {
1376  char prfx[] = "init_acts_";
1377  int max_len = strlen(prfx) + strlen(param_globals::lats[i].ID) + strlen(extn) + 1;
1378 
1379  acts[j].fname = (char*) malloc(max_len*sizeof(char));
1380  snprintf(acts[j].fname, max_len, "%s%s%s", prfx, param_globals::lats[i].ID, extn);
1381  }
1382 
1383  // restarting
1384  if(prvSimDir != NULL) {
1385  int len_fname = strlen(prvSimDir)+strlen(acts[j].fname)+2;
1386  acts[j].prv_fname = (char*) malloc(len_fname*sizeof(char));
1387  snprintf(acts[j].prv_fname, len_fname, "%s/%s", prvSimDir, acts[j].fname);
1388  }
1389 
1390  j++;
1391  }
1392 
1393  if(param_globals::compute_APD) {
1394  acts[j].method = ACT_THRESH; // threshold crossing
1395  acts[j].threshold = param_globals::actthresh;
1396  acts[j].mode = 0; // upstroke
1397  acts[j].all = true;
1398  acts[j].measurand = VM; // Vm
1399  //acts[j].ID = dupstr("Vm_Activation");
1400  acts[j].fout = NULL;
1401  acts[j].fname = dupstr("vm_activation.dat");
1402 
1403  j++;
1404  acts[j].method = ACT_THRESH; // threshold crossing
1405  acts[j].threshold = param_globals::recovery_thresh;
1406  acts[j].mode = 1; // repol
1407  acts[j].all = true;
1408  acts[j].measurand = VM; // Vm
1409  //(*acts)[j+1].ID = param_globals::lats[i].ID;
1410  acts[j].fout = NULL;
1411  acts[j].fname = dupstr("vm_repolarisation.dat");
1412 
1413  j++;
1414  }
1415 
1416  // set up sentinel for activity checking
1417  sntl.activated = have_sentinel;
1418  sntl.t_start = param_globals::t_sentinel_start;
1419  sntl.t_window = param_globals::t_sentinel;
1420  sntl.t_quiesc =-1.;
1421  sntl.ID = param_globals::sentinel_ID;
1422 
1423  if(need_to_add_sentinel) {
1424  // add a default LAT detector as sentinel
1425  acts[j].method = ACT_THRESH; // threshold crossing
1426  acts[j].threshold = param_globals::actthresh;
1427  acts[j].mode = 0; // upstroke
1428  acts[j].all = true;
1429  acts[j].measurand = VM; // Vm
1430  //(*acts)[j].ID = dupstr("Vm_Activation");
1431  acts[j].fout = NULL;
1432  acts[j].fname = dupstr("vm_sentinel.dat");
1433  // set sentinel index
1434  sntl.ID = j;
1435  j++;
1436  }
1437 
1438  if(prvSimDir) free(prvSimDir);
1439 }
1440 
1441 void print_act_log(FILE_SPEC logger, const SF::vector<Activation> & acts, int idx)
1442 {
1443  const Activation & act = acts[idx];
1444 
1445  log_msg(logger, 0, 0, "\n");
1446  log_msg(logger, 0, 0, "LAT detector [%2d]", idx);
1447  log_msg(logger, 0, 0, "-----------------\n");
1448 
1449  log_msg(logger, 0, 0, "Measurand: %s", act.measurand ? "Phie" : "Vm");
1450  log_msg(logger, 0, 0, "All: %s", act.all ? "All" : "Only first");
1451  log_msg(logger, 0, 0, "Method: %s", act.method==ACT_DT ? "Derivative" : "Threshold crossing");
1452 
1453  char buf[64], gt[2], sgn[2];
1454  snprintf(sgn, sizeof sgn, "%s", act.mode?"-":"+");
1455  snprintf(gt, sizeof gt, "%s", act.mode?"<":">");
1456 
1457  if(act.method==ACT_DT)
1458  snprintf(buf, sizeof buf, "Maximum %sdf/dt %s %.2f mV", sgn, gt, act.threshold);
1459  else
1460  snprintf(buf, sizeof buf, "Intersection %sdf/dt with %.2f", sgn, act.threshold);
1461 
1462  log_msg(logger, 0, 0, "Mode: %s", buf);
1463  log_msg(logger, 0, 0, "Threshold: %.2f mV\n", act.threshold);
1464 }
1465 
1466 void LAT_detector::init(sf_vec & vm, sf_vec & phie, int offset, enum physic_t phys_t)
1467 {
1468  if(!get_physics(phys_t)) {
1469  log_msg(0,0,5, "There seems to be no EP is defined. LAT detector requires active EP! Aborting LAT setup!");
1470  return;
1471  }
1472 
1473  // we use the electrics logger for output
1474  FILE_SPEC logger = get_physics(phys_t)->logger;
1475 
1476  // TODO(init): except for the shallow copies, shouldn't these be deleted?
1477  // When to delete them?
1478  for(size_t i = 0; i < acts.size(); ++i) {
1479  acts[i].init = 1;
1480  SF::init_vector(&(acts[i].phi));
1481  acts[i].phi->shallow_copy(!acts[i].measurand ? vm : phie);
1482  acts[i].offset = offset;
1483 
1484  SF::init_vector(&(acts[i].phip), acts[i].phi);
1485  *acts[i].phip = *acts[i].phi;
1486 
1487  // derivative based detector
1488  if (acts[i].method == ACT_DT) {
1489  SF::init_vector(&(acts[i].dvp0), acts[i].phi);
1490  SF::init_vector(&(acts[i].dvp1), acts[i].phi);
1491  if(acts[i].mode)
1492  log_msg(NULL,2,0, "Detection of -df/dt|max not implemented, +df/dt|max will be detected.");
1493  }
1494 
1495  // allocate additional local buffers
1496  acts[i].ibuf = (int *)malloc(acts[i].phi->lsize()*sizeof(int));
1497  acts[i].actbuf = (double *)malloc(acts[i].phi->lsize()*sizeof(double));
1498 
1499  if (!acts[i].all) {
1500  SF::init_vector(&acts[i].tm, acts[i].phi->gsize(), acts[i].phi->lsize());
1501  acts[i].tm->set(-1.);
1502 
1503  // initialize with previous initial activations
1504  if(acts[i].prv_fname != NULL) {
1505  set_dir(INPUT);
1506  size_t nread = acts[i].tm->read_ascii(acts[i].prv_fname);
1507 
1508  if(nread == 0)
1509  log_msg(NULL,2,ECHO,"Warning: Initialization of LAT[%2d] failed.", i);
1510 
1511  set_dir(OUTPUT);
1512  }
1513  }
1514  else {
1515  if ( !get_rank() ) {
1516  // here we should copy over previous file and open in append mode
1517  if(acts[i].prv_fname!=NULL) {
1518  set_dir(INPUT);
1519  FILE_SPEC in = f_open( acts[i].prv_fname, "r" );
1520  if(in) {
1521  log_msg(NULL,2,0, "Copying over of previous activation file not implemented.\n"); f_close(in);
1522  }
1523  else
1524  log_msg(NULL,3,0,"Warning: Initialization in %s - \n"
1525  "Failed to read activation file %s.\n", __func__, acts[i].prv_fname);
1526 
1527  set_dir(OUTPUT);
1528  }
1529  acts[i].fout = f_open( acts[i].fname, acts[i].prv_fname==NULL?"w":"a" );
1530  }
1531  }
1532  print_act_log(logger, acts, i);
1533  }
1534 
1535  sf_mesh & intra_mesh = get_mesh(intra_elec_msh);
1536  SF::local_petsc_to_nodal_mapping(intra_mesh, this->petsc_to_nodal);
1537 }
1538 
1539 
1540 int output_all_activations(FILE_SPEC fp, int *ibuf, double *act_tbuf, int nlacts)
1541 {
1542  int rank = get_rank(), gacts = 0, numProc = get_size();
1543 
1544  if (rank == 0) {
1545  // rank 0 writes directly to the table
1546  for (int i=0; i<nlacts; i++)
1547  fprintf(fp->fd, "%d\t%.6f\n", ibuf[i], act_tbuf[i]);
1548 
1549  gacts += nlacts;
1550 
1551  SF::vector<int> buf_inds;
1552  SF::vector<double> buf_acts;
1553 
1554  for (int j=1; j<numProc; j++) {
1555  int acts = 0;
1556  MPI_Status status;
1557  MPI_Recv(&acts, 1, MPI_INT, j, 110, PETSC_COMM_WORLD, &status);
1558 
1559  if (acts) {
1560  buf_inds.resize(acts);
1561  buf_acts.resize(acts);
1562 
1563  MPI_Recv(buf_inds.data(), acts, MPI_INT, j, 110, PETSC_COMM_WORLD, &status);
1564  MPI_Recv(buf_acts.data(), acts, MPI_DOUBLE, j, 110, PETSC_COMM_WORLD, &status);
1565 
1566  for(int ii=0; ii<acts; ii++)
1567  fprintf(fp->fd, "%d\t%.6f\n", buf_inds[ii], buf_acts[ii]);
1568 
1569  gacts += acts;
1570  }
1571  }
1572  fflush(fp->fd);
1573  }
1574  else {
1575  MPI_Send(&nlacts, 1, MPI_INT, 0, 110, PETSC_COMM_WORLD);
1576  if (nlacts) {
1577  MPI_Send(ibuf, nlacts, MPI_INT, 0, 110, PETSC_COMM_WORLD);
1578  MPI_Send(act_tbuf, nlacts, MPI_DOUBLE, 0, 110, PETSC_COMM_WORLD);
1579  }
1580  }
1581 
1582  MPI_Bcast(&gacts, 1, MPI_INT, 0, PETSC_COMM_WORLD);
1583  return gacts;
1584 }
1585 
1587 {
1588  int nacts = 0;
1589  double *a;
1590 
1591  for(Activation* aptr = acts.data(); aptr != acts.end(); aptr++)
1592  {
1593  int lacts = 0;
1594  switch (aptr->method) {
1595  case ACT_THRESH:
1596  lacts = check_cross_threshold(*aptr->phi, *aptr->phip, tm,
1597  aptr->ibuf, aptr->actbuf, aptr->threshold, aptr->mode);
1598  break;
1599 
1600  case ACT_DT:
1601  lacts = check_mx_derivative (*aptr->phi, *aptr->phip, tm,
1602  aptr->ibuf, aptr->actbuf, *aptr->dvp0, *aptr->dvp1,
1603  aptr->threshold, aptr->mode);
1604  break;
1605 
1606  default:
1607  break;
1608  }
1609 
1610  if (!aptr->all)
1611  a = aptr->tm->ptr();
1612 
1614 
1615  for(int j=0; j<lacts; j++) {
1616  if(aptr->all) {
1617  int nodal_idx = this->petsc_to_nodal.forward_map(aptr->ibuf[j]);
1618  aptr->ibuf[j] = canon_nbr[nodal_idx] + aptr->offset;
1619  }
1620  else {
1621  if(a[aptr->ibuf[j]] == -1)
1622  a[aptr->ibuf[j]] = aptr->actbuf[j];
1623  }
1624  }
1625 
1626  if(aptr->all)
1627  output_all_activations(aptr->fout, aptr->ibuf, aptr->actbuf, lacts);
1628  else
1629  aptr->tm->release_ptr(a);
1630 
1631  MPI_Allreduce(MPI_IN_PLACE, &lacts, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD);
1632  nacts += lacts;
1633 
1634  aptr->nacts = nacts;
1635  }
1636 
1637  return nacts > 0;
1638 }
1639 
1640 
1641 int LAT_detector::check_quiescence(double tm, double dt)
1642 {
1643  static int savequitFlag = 0;
1644  int numNodesActivated = -1;
1645 
1646  if(sntl.activated) {
1647  // initialization
1648  if(sntl.t_quiesc < 0. && sntl.t_window >= 0.0 ) {
1649  log_msg(0,0,ECHO | NONL, "================================================================================================\n");
1650  log_msg(0,0,ECHO | NONL, "%s() WARNING: simulation is configured to savequit() after %.2f ms of quiescence\n", __func__, sntl.t_window);
1651  log_msg(0,0,ECHO | NONL, "================================================================================================\n");
1652  sntl.t_quiesc = 0.0;
1653  }
1654 
1655  if(tm >= sntl.t_start && !savequitFlag)
1656  {
1657  numNodesActivated = acts[sntl.ID].nacts;
1658 
1659  if(numNodesActivated) sntl.t_quiesc = 0.0;
1660  else sntl.t_quiesc += dt;
1661 
1662  if(sntl.t_window >= 0.0 && sntl.t_quiesc > sntl.t_window && !savequitFlag) {
1663  savequitFlag++;
1664  savequit();
1665  }
1666  }
1667  }
1668 
1669  return numNodesActivated;
1670 }
1671 
1672 
1673 
1674 
1675 int LAT_detector::check_cross_threshold(sf_vec & vm, sf_vec & vmp, double tm,
1676  int *ibuf, double *actbuf, float threshold, int mode)
1677 {
1678  SF_real *c = vm.ptr();
1679  SF_real *p = vmp.ptr();
1680  int lsize = vm.lsize();
1681  int nacts = 0, gnacts = 0;
1682 
1683  for (int i=0; i<lsize; i++) {
1684  int sgn = 1;
1685  bool triggered = false;
1686  if(mode==0) {// detect +slope crossing
1687  triggered = p[i] <= threshold && c[i] > threshold; }
1688  else { // detect -slope crossing
1689  triggered = p[i] >= threshold && c[i] < threshold;
1690  sgn = -1;
1691  }
1692 
1693  if (triggered) {
1694  double tact = tm - param_globals::dt + (threshold-p[i])/(c[i]-p[i])*sgn*param_globals::dt;
1695  ibuf [nacts] = i;
1696  actbuf[nacts] = tact;
1697  nacts++;
1698  }
1699  p[i] = c[i];
1700  }
1701 
1702  vm.release_ptr(c);
1703  vmp.release_ptr(p);
1704  return nacts;
1705 }
1706 
1707 int LAT_detector::check_mx_derivative(sf_vec & vm, sf_vec & vmp, double tm,
1708  int *ibuf, double *actbuf, sf_vec & dvp0, sf_vec & dvp1,
1709  float threshold, int mode)
1710 {
1711  int nacts = 0, gnacts = 0;
1712  double tact, dt2 = 2 * param_globals::dt;
1713  int lsize = vm.lsize();
1714  SF_real ddv0, ddv1, dv, dvdt;
1715  SF_real *c, *p, *pd0, *pd1;
1716 
1717  c = vm.ptr();
1718  p = vmp.ptr();
1719  pd0 = dvp0.ptr();
1720  pd1 = dvp1.ptr();
1721 
1722  for (int i=0; i<lsize; i++ ) {
1723  dv = (c[i]-p[i]);
1724  dvdt = dv/param_globals::dt;
1725  ddv0 = pd1[i]-pd0[i];
1726  ddv1 = dv -pd1[i];
1727 
1728  if (dvdt>=threshold && ddv0>0 && ddv1<0) {
1729  tact = tm-dt2+(ddv0/(ddv0-ddv1))*param_globals::dt;
1730  ibuf [nacts] = i;
1731  actbuf[nacts] = tact;
1732  nacts++;
1733  }
1734  p [i] = c[i];
1735  pd0[i] = pd1[i];
1736  pd1[i] = dv;
1737  }
1738 
1739  vm .release_ptr(c);
1740  vmp .release_ptr(p);
1741  dvp0.release_ptr(pd0);
1742  dvp1.release_ptr(pd1);
1743 
1744  return nacts;
1745 }
1746 
1751 {
1753  assert(sc != NULL);
1754 
1755  bool forward = true;
1756 
1757  for (size_t i = 0; i < acts.size(); i++) {
1758  if (is_init(acts[i].tm)) {
1759  (*sc)(*acts[i].tm, forward);
1760  acts[i].tm->write_ascii(acts[i].fname, false);
1761  }
1762  }
1763 }
1764 
1765 void Electrics::prepace() {
1766  // Default stimulation parameters for the single cells
1767  // To be eventually be replaced by user input or info from bench
1768  float stimdur = 1.;
1769  float stimstr = 60.;
1770 
1771  log_msg(NULL, 0, 0, "Using activation times from file %s to distribute prepacing states\n",
1772  param_globals::prepacing_lats);
1773  log_msg(NULL, 1, 0, "Assuming stimulus strength %f uA/uF with duration %f ms for prepacing\n",
1774  stimstr, stimdur);
1775 
1776  limpet::MULTI_IF* miif = this->ion.miif;
1777 
1778  const sf_mesh & mesh = get_mesh(intra_elec_msh);
1779  sf_vec* read_lats; SF::init_vector(&read_lats, mesh, 1, sf_vec::algebraic);
1780 
1781  // read in the global distributed vector of all activation times
1782  set_dir(INPUT);
1783  size_t numread = read_lats->read_ascii(param_globals::prepacing_lats);
1784  if (numread == 0) {
1785  log_msg(NULL, 5, 0, "Failed reading required LATs! Skipping prepacing!");
1786  return;
1787  }
1788  set_dir(OUTPUT);
1789 
1791  assert(sc != NULL);
1792 
1793  // permute in-place to petsc permutation
1794  bool forward = false;
1795  (*sc)(*read_lats, forward);
1796 
1797  // take care of negative LAT values
1798  {
1799  PetscReal* lp = read_lats->ptr();
1800  for(int i=0; i<read_lats->lsize(); i++)
1801  if(lp[i] < 0.0) lp[i] = param_globals::tend + 10.0;
1802 
1803  read_lats->release_ptr(lp);
1804  }
1805 
1806  // make LATs relative and figure out the first LAT
1807  // so we know when to save state of each point
1808  SF_real LATmin = read_lats->min();
1809 
1810  if(LATmin < 0.0) {
1811  log_msg(0,3,0, "LAT data is not complete. Skipping prepacing.");
1812  return;
1813  }
1814 
1815  SF_real offset = floor(LATmin / param_globals::prepacing_bcl) * param_globals::prepacing_bcl;
1816  SF_real last_tm = param_globals::prepacing_bcl * param_globals::prepacing_beats;
1817 
1818  // compute read_lats[i] = last_tm - (read_lats[i] - offset)
1819  *read_lats += -offset;
1820  *read_lats *= -1.;
1821  *read_lats += last_tm;
1822 
1823  miif->getRealData();
1824  SF_real *save_tm = read_lats->ptr();
1825  SF_real *vm = miif->gdata[limpet::Vm]->ptr();
1826 
1827  for (int ii = 0; ii < miif->N_IIF; ii++) {
1828  if (!miif->N_Nodes[ii]) continue;
1829 
1830  // create sorted array of save times.
1831  SF::vector<SF::mixed_tuple<double,int>> sorted_save(miif->N_Nodes[ii]); // v1 = time, v2 = index
1832  for (int kk = 0; kk < miif->N_Nodes[ii]; kk++) {
1833  sorted_save[kk].v1 = save_tm[miif->NodeLists[ii][kk]];
1834  sorted_save[kk].v2 = kk;
1835  }
1836  std::sort(sorted_save.begin(), sorted_save.end());
1837 
1838  size_t lastidx = sorted_save.size() - 1;
1839  int paced = sorted_save[lastidx].v2; // IMP index of latest node
1840  int csav = 0;
1841 
1842  for (double t = 0; t < sorted_save[lastidx].v1; t += param_globals::dt) {
1843  if (fmod(t, param_globals::prepacing_bcl) < stimdur &&
1844  t < param_globals::prepacing_bcl * param_globals::prepacing_beats - 1)
1845  miif->ldata[ii][limpet::Vm][paced] += stimstr * param_globals::dt;
1846 
1847  compute_IIF(*miif->IIF[ii], miif->ldata[ii], paced);
1848 
1849  // Vm update always happens now outside of the imp
1850  miif->ldata[ii][limpet::Vm][paced] -= miif->ldata[ii][limpet::Iion][paced] * param_globals::dt;
1851  vm[miif->NodeLists[ii][paced]] = miif->ldata[ii][limpet::Vm][paced];
1852 
1853  while (csav < miif->N_Nodes[ii] - 1 && t >= sorted_save[csav].v1)
1854  dup_IMP_node_state(*miif->IIF[ii], paced, sorted_save[csav++].v2, miif->ldata[ii]);
1855  }
1856 
1857  // get nodes which may be tied for last
1858  while (csav < miif->N_Nodes[ii] - 1)
1859  dup_IMP_node_state(*miif->IIF[ii], paced, sorted_save[csav++].v2, miif->ldata[ii]);
1860  // ipdate global Vm vector
1861  for (int k = 0; k < miif->N_Nodes[ii]; k++) vm[miif->NodeLists[ii][k]] = miif->ldata[ii][limpet::Vm][k];
1862  }
1863 
1864  read_lats->release_ptr(save_tm);
1865  miif->gdata[limpet::Vm]->release_ptr(vm);
1866  miif->releaseRealData();
1867 }
1868 
1869 
1871 {
1872  if (!rcv.pts.size())
1873  return;
1874 
1875  int rank = get_rank();
1876 
1877  if(!get_physics(elec_phys)) {
1878  log_msg(0,0,5, "There seems to be no EP is defined. Phie recovery requires active EP! Aborting!");
1879  return;
1880  }
1881 
1882  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
1883  sf_mat & Ki = *elec->parab_solver.rhs_parab;
1884 
1885  const sf_mesh & imesh = get_mesh(intra_elec_msh);
1886  const SF::vector<mesh_int_t> & alg_nod = imesh.pl.algebraic_nodes();
1887 
1888  SF_int start, end;
1889  vm.get_ownership_range(start, end);
1890 
1891  if(!rcv.Im) {
1892  SF::init_vector(&rcv.Im, &vm);
1893  SF::init_vector(&rcv.dphi, &vm);
1894  }
1895 
1896  SF_int r_start, r_end;
1897  rcv.phie_rec->get_ownership_range(r_start, r_end);
1898 
1899  SF_real *ph_r = rcv.phie_rec->ptr();
1900 
1901  // use minimum distance to ensure r>0
1902  // consistent with the line source approximation, the "cable radius"
1903  // is used as a lower limit for the source-field point distance
1904  float minDist = 2. / param_globals::imp_region[0].cellSurfVolRatio; // radius in um
1905 
1906  Ki.mult(vm, *rcv.Im);
1907  int numpts = rcv.pts.size() / 3;
1908  Point fpt, cpt;
1909 
1910  for (int j=0; j<numpts; j++) {
1911  fpt = rcv.pts.data() + j*3;
1912 
1913  *rcv.dphi = *rcv.Im;
1914  SF_real* dp = rcv.dphi->ptr();
1915 
1916  for (size_t i = 0; i<alg_nod.size(); i++)
1917  {
1918  mesh_int_t loc_nodal_idx = alg_nod[i];
1919  mesh_int_t loc_petsc_idx = local_nodal_to_local_petsc(imesh, rank, loc_nodal_idx);
1920  cpt = imesh.xyz.data()+loc_nodal_idx*3;
1921 
1922  double r = dist(fpt, cpt) + minDist;
1923  dp[loc_petsc_idx] /= r;
1924  }
1925 
1926  rcv.dphi->release_ptr(dp);
1927 
1928  SF_real phi = rcv.dphi->sum() / 4. / M_PI / rcv.gBath;
1929  if ( (j>=r_start) && (j<r_end) )
1930  ph_r[j-r_start] = phi;
1931  }
1932 
1933  rcv.phie_rec->release_ptr(ph_r);
1934 }
1935 
1937 {
1938  int err = 0, rank = get_rank();
1939 
1941  log_msg(0,0,5, "There seems to be no EP is defined. Phie recovery requires active EP! Aborting!");
1942  return 1;
1943  }
1944 
1945  sf_mesh & imesh = get_mesh(intra_elec_msh);
1946  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
1948 
1949  // we close the files of the default electrics if there are any open
1951 
1952  // register output
1953  set_dir(POSTPROC);
1954  igb_output_manager phie_rec_out;
1955  phie_rec_out.register_output(phie_rcv.phie_rec, phie_recv_msh, 1,
1956  param_globals::phie_recovery_file, "mV");
1957 
1958  // Buffer for Vm data
1959  sf_vec* vm = get_data(vm_vec); assert(vm);
1960 
1961  // set up igb header and point fd to start of Vm file
1962  set_dir(OUTPUT);
1963  IGBheader vm_igb;
1964  if(rank == 0) {
1965  FILE_SPEC file = f_open(param_globals::vofile, "r");
1966  if(file != NULL) {
1967  vm_igb.fileptr(file->fd);
1968  vm_igb.read();
1969 
1970  if(vm_igb.x() != vm->gsize()) {
1971  log_msg(0,4,0, "%s error: Vm dimension does not fit to %s file. Aborting recovery! \n",
1972  __func__, param_globals::vofile);
1973  err++;
1974  }
1975 
1976  delete file;
1977  }
1978  else err++;
1979  }
1980 
1981  err = get_global(err, MPI_MAX);
1982 
1983  if(err == 0) {
1984  FILE* fd = static_cast<FILE*>(vm_igb.fileptr());
1985 
1986  // number of data slices
1987  const int num_io = user_globals::tm_manager->timers[iotm_spacedt]->numIOs;
1988 
1989  // scatterers
1991  assert(petsc_to_canonical != NULL);
1992 
1993  // loop over vm slices and recover phie
1994  for(int i=0; i<num_io; i++) {
1995  log_msg(0,0,0, "Step %d / %d", i+1, num_io);
1996  size_t nread = vm->read_binary<float>(fd);
1997 
1998  if(nread != size_t(vm->gsize())) {
1999  log_msg(0,3,0, "%s warning: read incomplete data slice! Aborting!", __func__);
2000  err++;
2001  break;
2002  }
2003 
2004  // permute vm_buff
2005  bool forward = false;
2006  (*petsc_to_canonical)(*vm, forward);
2007 
2008  // do phie computation
2009  recover_phie_std(*vm, phie_rcv);
2010 
2011  phie_rec_out.write_data();
2012  }
2013 
2014  phie_rec_out.close_files_and_cleanup();
2015  }
2016  return err;
2017 }
2018 
2020 {
2021  if(!get_physics(elec_phys) ) {
2022  log_msg(0,0,5, "There seems to be no EP is defined. Phie recovery requires active EP! Aborting!");
2023  return;
2024  }
2025 
2026  int rank = get_rank(), size = get_size();
2027  Electrics* elec = static_cast<Electrics*>(get_physics(elec_phys));
2028 
2029  sf_mesh & imesh = get_mesh(intra_elec_msh);
2030  const std::string basename = param_globals::phie_rec_ptf;
2031  SF::vector<mesh_int_t> ptsidx;
2032 
2033  set_dir(INPUT);
2034  SF::read_points(basename, imesh.comm, data.pts, ptsidx);
2035  make_global(data.pts, imesh.comm); // we want all ranks to have all points
2036 
2037  // set up parallel layout of recovery points
2038  SF::vector<mesh_int_t> layout;
2039  layout_from_count(mesh_int_t(ptsidx.size()), layout, imesh.comm);
2040 
2041  // set up petsc_vector for recovered potentials
2042  SF::init_vector(&data.phie_rec, layout[size], layout[rank+1]-layout[rank], 1, sf_vec::algebraic);
2043 
2044  // get conductivty
2046  data.gBath = static_cast<elecMaterial*>(intra_regions[0].material)->BathVal[0];
2047 }
2048 
2050 {
2051  int rank = get_rank();
2052 
2053  assert(param_globals::bidomain == BIDOMAIN);
2054  double t1, t2;
2055  get_time(t1);
2056 
2057  // set up Extracellular tissue
2060  mtype[Electrics::extra_grid].regionIDs, true, "gregion_e");
2061 
2062  // set up a subset of the complete electrical mappings
2063  int dpn = 1;
2065 
2067  // set up Intracellular tissue
2070  mtype[Electrics::intra_grid].regionIDs, true, "gregion_i");
2071 
2074  }
2075 
2076  // set up stimuli
2077  init_stim_info();
2078  stimuli.resize(param_globals::num_stim);
2079 
2080  for(int i=0; i<param_globals::num_stim; i++) {
2081  // construct new stimulus
2082  stimulus & s = stimuli[i];
2083 
2085  s.translate(i);
2086 
2087  s.setup(i);
2088 
2089  if(s.phys.type == V_ex) {
2090  s.pulse.wform = constPulse;
2091  sample_wave_form(s.pulse, i);
2092  }
2093  }
2094 
2095  set_dir(OUTPUT);
2096 
2097  ellip_solver.init();
2099 
2100  if(param_globals::dump2MatLab) {
2101  std::string bsname = param_globals::dump_basename;
2102  std::string fn;
2103 
2104  set_dir(OUTPUT);
2105  fn = bsname + "_Kie.bin";
2106  ellip_solver.phie_mat->write(fn.c_str());
2107  }
2108 
2109  // the laplace solver executes only once, thus we need a singlestep timer
2110  timer_idx = user_globals::tm_manager->add_singlestep_timer(0.0, 0.0, "laplace trigger", nullptr);
2111 
2112  SF::vector<mesh_int_t>* restr_i = NULL;
2113  SF::vector<mesh_int_t>* restr_e = NULL;
2114 
2115  setup_dataout(param_globals::dataout_e, param_globals::dataout_e_vtx, extra_elec_msh,
2116  restr_e, param_globals::num_io_nodes > 0);
2117  if(param_globals::dataout_e)
2118  output_manager.register_output(ellip_solver.phie, extra_elec_msh, 1, param_globals::phiefile, "mV", restr_e);
2119 
2121  setup_dataout(param_globals::dataout_i, param_globals::dataout_i_vtx, intra_elec_msh,
2122  restr_i, param_globals::num_io_nodes > 0);
2123  if(param_globals::dataout_i)
2124  output_manager.register_output(ellip_solver.phie_i, intra_elec_msh, 1, param_globals::phieifile, "mV", restr_i);
2125  }
2126 
2127  this->initialize_time += timing(t2, t1);
2128 
2129  this->compute_step();
2130 }
2131 
2133 {}
2134 
2136 {
2137  // Laplace compute might be called multiple times, we want to run only once..
2138  if(!ellip_solver.lin_solver) return;
2139 
2140  double t0, t1, dur;
2141  log_msg(0,0,0, "Solving Laplace problem ..");
2142 
2143  get_time(t0);
2145  dur = timing(t1,t0);
2146 
2147  log_msg(0,0,0, "Done in %.5f seconds.", dur);
2148 
2150  this->compute_time += timing(t1, t0);
2151  set_dir(OUTPUT);
2154 
2155  // we clear the elliptic matrices and solver to save some memory when computing
2156  // the laplace solution on-the-fly
2157  delete ellip_solver.mass_e; ellip_solver.mass_e = NULL;
2158  delete ellip_solver.phie_mat; ellip_solver.phie_mat = NULL;
2160 }
2161 
2163 {}
2164 
2165 double Laplace::timer_val(const int timer_id)
2166 {
2167  int sidx = stimidx_from_timeridx(stimuli, timer_id);
2168  double val = 0.0;
2169 
2170  if(sidx != -1) stimuli[sidx].value(val);
2171  else val = std::nan("NaN");
2172  return val;
2173 }
2174 
2175 std::string Laplace::timer_unit(const int timer_id)
2176 {
2177  int sidx = stimidx_from_timeridx(stimuli, timer_id);
2178  std::string s_unit;
2179  if(sidx != -1) s_unit = stimuli[sidx].pulse.wave.f_unit;
2180  return s_unit;
2181 }
2182 
2184  sf_mat & mass_i,
2185  sf_mat & mass_e,
2186  limpet::MULTI_IF *miif,
2187  FILE_SPEC logger)
2188 {
2190 
2191  for(stimulus & s : stimuli) {
2192  if(is_current(s.phys.type) && s.phys.total_current) {
2193  // extracellular current injection
2194  if (s.phys.type == I_ex) {
2195  // compute affected volume in um^3
2196  SF_real vol = get_volume_from_nodes(mass_e, s.electrode.vertices);
2197 
2198  // s->strength holds the total current in uA, compute current density
2199  // in uA/cm^3
2200  float scale = 1.e12/vol;
2201 
2202  s.pulse.strength *= scale;
2203 
2204  log_msg(logger,0,ECHO,
2205  "%s [Stimulus %d]: current density scaled to %.4g uA/cm^3\n",
2206  s.name.c_str(), s.idx, s.pulse.strength*1.e12);
2207  }
2208  else if (s.phys.type == I_tm) {
2209  // compute affected volume in um^3
2210  SF_real vol = get_volume_from_nodes(mass_i, s.electrode.vertices);
2211  const sf_mesh & imesh = get_mesh(intra_elec_msh);
2212  const SF::vector<mesh_int_t> & alg_nod = imesh.pl.algebraic_nodes();
2213 
2214  if(alg_idx_map.size() == 0) {
2215  mesh_int_t lidx = 0;
2216  for(mesh_int_t n : alg_nod) {
2217  alg_idx_map[n] = lidx;
2218  lidx++;
2219  }
2220  }
2221 
2222  SF_real surf = 0.0;
2223  for(mesh_int_t n : s.electrode.vertices) {
2224  if(alg_idx_map.count(n)) {
2225  mesh_int_t lidx = alg_idx_map[n];
2226  int r = miif->IIFmask[lidx];
2227  // surf = vol*beta [1/um], surf is in [um^2]
2228  surf = vol * miif->IIF[r]->cgeom().SVratio * param_globals::imp_region[r].volFrac;
2229  //convert to cm^2
2230  surf /= 1.e8;
2231  break;
2232  }
2233  }
2234  surf = get_global(surf, MPI_MAX, PETSC_COMM_WORLD);
2235 
2236  // scale surface density now to result in correct total current
2237  s.pulse.strength /= surf;
2238  log_msg(logger, 0, ECHO,
2239  "%s [Stimulus %d]: current density scaled to %.4g uA/cm^2\n",
2240  s.name.c_str(), s.idx, s.pulse.strength);
2241  }
2242  }
2243  }
2244 }
2245 
2246 
2247 
2248 } // namespace opencarp
SF::scattering * get_permutation(const int mesh_id, const int perm_id, const int dpn)
Get the PETSC to canonical permutation scattering for a given mesh and number of dpn.
SF_real gBath
Bath conductivity.
Definition: electrics.h:236
const vector< T > & algebraic_layout() const
Getter function for the global algebraic node layout.
bool have_dbc_stims(const SF::vector< stimulus > &stimuli)
return wheter any stimuli require dirichlet boundary conditions
Definition: electrics.cc:822
#define DATAOUT_NONE
Definition: sim_utils.h:57
int ** NodeLists
local partitioned node lists for each IMP stored
Definition: MULTI_ION_IF.h:201
stim_electrode electrode
electrode geometry
Definition: stimulate.h:168
dbc_manager * dbc
dbcs require a dbc manager
Definition: electrics.h:58
void init_solver(SF::abstract_linear_solver< T, S > **sol)
Definition: SF_init.h:220
igb_output_manager output_manager
class handling the igb output
Definition: electrics.h:272
gvec_data gvec
datastruct holding global IMP state variable output
Definition: electrics.h:269
int * subregtags
FEM tags forming this region.
Definition: fem_types.h:97
char * regname
name of region
Definition: fem_types.h:94
void log_stats(double tm, bool cflg)
Definition: timers.cc:93
virtual void release_ptr(S *&p)=0
vector< T > & get_numbering(SF_nbr nbr_type)
Get the vector defining a certain numbering.
Definition: SF_container.h:452
cond_t g
rule to build conductivity tensor
Definition: fem_types.h:64
stim_pulse pulse
stimulus wave form
Definition: stimulate.h:165
char * dupstr(const char *old_str)
Definition: basics.cc:44
description of materal properties in a mesh
Definition: fem_types.h:110
physMaterial * material
material parameter description
Definition: fem_types.h:98
sf_vec * Irhs
weighted transmembrane currents
Definition: electrics.h:105
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 setup_phie_recovery_data(phie_recovery_data &data)
Definition: electrics.cc:2019
void local_petsc_to_nodal_mapping(const meshdata< T, S > &mesh, index_mapping< T > &petsc_to_nodal)
MPI_Comm comm
the parallel mesh is defined on a MPI world
Definition: SF_container.h:392
void recover_phie_std(sf_vec &vm, phie_recovery_data &rcv)
Definition: electrics.cc:1870
SF::vector< mesh_real_t > pts
The phie recovery locations.
Definition: electrics.h:232
void layout_from_count(const T count, vector< T > &layout, MPI_Comm comm)
Definition: SF_network.h:201
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.
PETSc numbering of nodes.
Definition: SF_container.h:191
cond_t
description of electrical tissue properties
Definition: fem_types.h:42
#define PETSC_TO_CANONICAL
Permute algebraic data from PETSC to canonical ordering.
Definition: sf_interface.h:74
physMat_t material_type
ID of physics material.
Definition: fem_types.h:53
void solve(sf_mat &Ki, sf_vec &Vmv, sf_vec &tmp_i)
Definition: electrics.cc:1014
#define BIDOMAIN
Definition: sim_utils.h:144
overlapping_layout< T > pl
nodal parallel layout
Definition: SF_container.h:417
int calls
# calls for this interval, this is incremented externally
Definition: timers.h:70
IIF_Mask_t * IIFmask
region for each node
Definition: MULTI_ION_IF.h:214
virtual void set(const vector< T > &idx, const vector< S > &vals, const bool additive=false, const bool local=false)=0
elliptic_solver ellip_solver
Solver for the elliptic bidomain equation.
Definition: electrics.h:261
lin_solver_stats stats
Definition: electrics.h:55
double timer_val(const int timer_id)
figure out current value of a signal linked to a given timer
Definition: electrics.cc:717
void solve(sf_vec &phie_i)
Definition: electrics.cc:1235
void get_kappa(sf_vec &kappa, IMPregion *ir, limpet::MULTI_IF &miif, double k)
compute the vector
Definition: electrics.cc:775
void initialize()
Definition: ionics.cc:60
virtual T lsize() const =0
FILE_SPEC logger
The logger of the physic, each physic should have one.
Definition: physics_types.h:64
timer_manager * tm_manager
a manager for the various physics timers
Definition: main.cc:52
double ExVal[3]
extracellular conductivity eigenvalues
Definition: fem_types.h:62
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
Definition: electrics.cc:2175
The nodal numbering of the reference mesh (the one stored on HD).
Definition: SF_container.h:189
void unique_resize(vector< T > &_P)
Definition: SF_sort.h:348
bool is_current(stim_t type)
uses current as stimulation
Definition: stimulate.cc:71
const char * name
The name of the physic, each physic should have one.
Definition: physics_types.h:62
sf_mat * lhs_parab
lhs matrix (CN) to solve parabolic
Definition: electrics.h:111
int all
determine all or first instants of activation
Definition: electrics.h:170
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
SF::vector< mesh_int_t > vertices
Definition: stimulate.h:152
size_t read_ascii(FILE *fd)
double time_step
global reference time step
Definition: timer_utils.h:78
void savequit()
save state and quit simulator
Definition: sim_utils.cc:1646
void constant_total_stimulus_current(SF::vector< stimulus > &stimuli, sf_mat &mass_i, sf_mat &mass_e, limpet::MULTI_IF *miif, FILE_SPEC logger)
Definition: electrics.cc:2183
const char * get_mesh_type_name(mesh_t t)
get a char* to the name of a mesh type
Definition: sf_interface.cc:46
#define ECHO
Definition: basics.h:308
vector< S > xyz
node cooridnates
Definition: SF_container.h:415
void balance_electrode(elliptic_solver &ellip, SF::vector< stimulus > &stimuli, int balance_from, int balance_to)
Definition: electrics.cc:369
T * data()
Pointer to the vector&#39;s start.
Definition: SF_vector.h:91
vector< T > con
Definition: SF_container.h:400
sf_vec * tmp_i1
scratch vector for i-grid
Definition: electrics.h:103
mesh_t
The enum identifying the different meshes we might want to load.
Definition: sf_interface.h:58
T & push_back(T val)
Definition: SF_vector.h:283
bool trigger(int ID) const
Definition: timer_utils.h:166
SF_real get_volume_from_nodes(sf_mat &mass, SF::vector< mesh_int_t > &local_idx)
Definition: fem_utils.cc:202
double InVal[3]
intracellular conductivity eigenvalues
Definition: fem_types.h:61
int N_IIF
how many different IIF&#39;s
Definition: MULTI_ION_IF.h:211
void init_stim_info(void)
uses voltage for stimulation
Definition: stimulate.cc:49
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)
physic_t
Identifier for the different physics we want to set up.
Definition: physics_types.h:51
void close_files_and_cleanup()
close file descriptors
Definition: sim_utils.cc:1527
PotType measurand
quantity being monitored
Definition: electrics.h:183
generic_timing_stats IO_stats
Definition: electrics.h:277
#define DATAOUT_SURF
Definition: sim_utils.h:58
void init_logger(const char *filename)
Definition: timers.cc:77
virtual S sum() const =0
void init_vector(SF::abstract_vector< T, S > **vec)
Definition: SF_init.h:99
void rebuild_mass(FILE_SPEC logger)
Definition: electrics.cc:977
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
std::vector< IonIfBase * > IIF
array of IIF&#39;s
Definition: MULTI_ION_IF.h:202
#define ELEM_PETSC_TO_CANONICAL
Permute algebraic element data from PETSC to canonical ordering.
Definition: sf_interface.h:76
int mode
toggle mode from standard to reverse
Definition: electrics.h:169
bool value(double &v) const
Get the current value if the stimulus is active.
Definition: stimulate.cc:440
char * get_file_dir(const char *file)
Definition: sim_utils.cc:1275
bool is_init(const abstract_vector< T, S > *v)
sf_mat * phie_mat
lhs matrix to solve elliptic
Definition: electrics.h:49
const T * end() const
Pointer to the vector&#39;s end.
Definition: SF_vector.h:128
waveform_t wform
wave form of stimulus
Definition: stimulate.h:94
parabolic_solver parab_solver
Solver for the parabolic bidomain equation.
Definition: electrics.h:263
void compute_IIF(limpet::IonIfBase &pIF, limpet::GlobalData_t **impdata, int n)
Definition: ionics.cc:464
Tissue level electrics, main Electrics physics class.
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.
virtual S * ptr()=0
bool using_legacy_stimuli
flag storing whether legacy stimuli are used
Definition: main.cc:58
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:1466
virtual void mult(const abstract_vector< T, S > &x, abstract_vector< T, S > &b) const =0
event detection data structures
Definition: electrics.h:166
void dump_state(char *, float, opencarp::mesh_t gid, bool, unsigned int)
sf_vec * Vmv
global Vm vector
Definition: electrics.h:99
double tot_time
total time, this is incremented externally
Definition: timers.h:72
int mesh_int_t
Definition: SF_container.h:46
virtual void write(const char *filename) const =0
void fileptr(gzFile f)
Definition: IGBheader.cc:336
Submesh nodal numbering: The globally ascending sorted reference indices are reindexed.
Definition: SF_container.h:190
void assemble_sv_gvec(gvec_data &gvecs, limpet::MULTI_IF *miif)
Definition: ionics.cc:637
double time
current time
Definition: timer_utils.h:76
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
region based variations of arbitrary material parameters
Definition: fem_types.h:93
GlobalData_t *** ldata
data local to each IMP
Definition: MULTI_ION_IF.h:205
void forward(abstract_vector< T, S > &in, abstract_vector< T, S > &out, bool add=false)
Forward scattering.
int check_acts(double tm)
check activations at sim time tm
Definition: electrics.cc:1586
double BathVal[3]
bath conductivity eigenvalues
Definition: fem_types.h:63
std::string name
label stimulus
Definition: stimulate.h:164
ActMethod method
method to check whether activation occured
Definition: electrics.h:167
int timer_idx
the timer index received from the timer manager
Definition: physics_types.h:66
void write_data()
write registered data to disk
Definition: sim_utils.cc:1480
long d_time
current time instance index
Definition: timer_utils.h:77
sf_sol * lin_solver
petsc or ginkgo lin_solver
Definition: electrics.h:52
sf_mesh & get_mesh(const mesh_t gt)
Get a mesh by specifying the gridID.
Definition: sf_interface.cc:33
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
float threshold
threshold for detection of activation
Definition: electrics.h:168
SF::scattering * register_permutation(const int mesh_id, const int perm_id, const int dpn)
Register a permutation between two orderings for a mesh.
size_t read_binary(FILE *fd)
int idx
index in global input stimulus array
Definition: stimulate.h:163
const char * get_tsav_ext(double time)
Definition: electrics.cc:831
void init_matrix(SF::abstract_matrix< T, S > **mat)
Definition: SF_init.h:199
manager for dirichlet boundary conditions
Definition: stimulate.h:192
#define ALG_TO_NODAL
Scatter algebraic to nodal.
Definition: sf_interface.h:72
size_t size() const
Definition: hashmap.hpp:687
double timer_val(const int timer_id)
figure out current value of a signal linked to a given timer
Definition: electrics.cc:2165
void destroy()
Currently we only need to close the file logger.
Definition: electrics.cc:354
sf_vec * phie
phi_e
Definition: electrics.h:43
#define PSEUDO_BIDM
Definition: sim_utils.h:145
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 set_cond_type(MaterialType &m, cond_t type)
Definition: electrics.cc:799
void make_global(const vector< T > &vec, vector< T > &out, MPI_Comm comm)
make a parallel vector global
Definition: SF_network.h:225
SF::vector< double > el_scale
optionally provided per-element params scale
Definition: fem_types.h:116
void get_time(double &tm)
Definition: basics.h:436
Basic_physic * get_physics(physic_t p, bool error_if_missing)
Convinience function to get a physics.
Definition: sim_utils.cc:864
#define EXP_POSTPROCESS
Definition: sim_utils.h:161
int write_trace()
write traces to file
Definition: signals.h:701
bool dbc_update()
check if dbcs have updated
Definition: stimulate.cc:630
void initialize()
Initialize the Electrics.
Definition: electrics.cc:36
int timer_id
timer for stimulus
Definition: stimulate.h:121
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.
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
int * N_Nodes
#nodes for each IMP
Definition: MULTI_ION_IF.h:200
void destroy()
Definition: ionics.cc:52
size_t root_count_ascii_lines(std::string file, MPI_Comm comm)
count the lines in a ascii file
void print_act_log(FILE_SPEC logger, const SF::vector< Activation > &acts, int idx)
Definition: electrics.cc:1441
int check_quiescence(double tm, double dt)
check for quiescence
Definition: electrics.cc:1641
V timing(V &t2, const V &t1)
Definition: basics.h:448
void compute_restr_idx(sf_mesh &mesh, SF::vector< mesh_int_t > &inp_idx, SF::vector< mesh_int_t > &idx)
Definition: electrics.cc:520
sig::time_trace wave
wave form of stimulus pulse
Definition: stimulate.h:96
void setup(int idx)
Setup from a param stimulus index.
Definition: stimulate.cc:163
SF::vector< stimulus > stimuli
the electrical stimuli
Definition: electrics.h:254
sf_vec * dphi
Auxiliary vectors.
Definition: electrics.h:235
void rebuild_matrices(MaterialType *mtype, limpet::MULTI_IF &miif, FILE_SPEC logger)
Definition: electrics.cc:1132
MaterialType mtype[2]
the material types of intra_grid and extra_grid grids.
Definition: electrics.h:252
int regID
region ID
Definition: fem_types.h:95
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 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.
File descriptor struct.
Definition: basics.h:133
opencarp::sf_vec * gdata[NUM_IMP_DATA_TYPES]
data used by all IMPs
Definition: MULTI_ION_IF.h:216
int set_dir(IO_t dest)
Definition: sim_utils.cc:483
void dup_IMP_node_state(IonIfBase &IF, int from, int to, GlobalData_t **localdata)
hm_int count(const K &key) const
Check if key exists.
Definition: hashmap.hpp:579
sf_mat * mass_e
mass matrix for RHS elliptic calc
Definition: electrics.h:48
int read(bool quiet=false)
Definition: IGBheader.cc:761
sf_vec * phie_rec
The phie recovery output vector buffer.
Definition: electrics.h:233
size_t size() const
The current size of the vector.
Definition: SF_vector.h:104
void log_stats(double tm, bool cflg)
Definition: timers.cc:27
sf_vec * phiesrc
I_e.
Definition: electrics.h:45
void rebuild_stiffness(MaterialType *mtype, SF::vector< stimulus > &stimuli, FILE_SPEC logger)
Definition: electrics.cc:917
int nsubregs
#subregions forming this region
Definition: fem_types.h:96
Electrical stimulation functions.
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
Definition: basics.cc:72
#define NONL
Definition: basics.h:312
void init_sv_gvec(gvec_data &GVs, limpet::MULTI_IF *miif, sf_vec &tmpl, igb_output_manager &output_manager)
Definition: ionics.cc:566
#define MONODOMAIN
Definition: sim_utils.h:143
bool mesh_is_registered(const mesh_t gt)
check wheter a SF mesh is set
Definition: sf_interface.cc:59
stim_t type
type of stimulus
Definition: stimulate.h:136
#define M_PI
Definition: ION_IF.h:51
void sample_wave_form(stim_pulse &sp, int idx)
sample a signal given in analytic form
Definition: stimulate.cc:363
lin_solver_stats stats
Definition: electrics.h:120
#define DATAOUT_VTX
Definition: sim_utils.h:60
virtual void get_ownership_range(T &start, T &stop) const =0
void output_initial_activations()
output one nodal vector of initial activation time
Definition: electrics.cc:1750
void dump_trace(MULTI_IF *MIIF, limpet::Real time)
#define DATAOUT_VOL
Definition: sim_utils.h:59
grid_t
An electrics grid identifier to distinguish between intra and extra grids.
Definition: electrics.h:248
int numNode
local number of nodes
Definition: MULTI_ION_IF.h:210
const T * begin() const
Pointer to the vector&#39;s start.
Definition: SF_vector.h:116
void f_close(FILE_SPEC &f)
Close a FILE_SPEC.
Definition: basics.cc:162
std::vector< base_timer * > timers
vector containing individual timers
Definition: timer_utils.h:84
void compute_step()
Definition: ionics.cc:35
limpet::MULTI_IF * miif
Definition: ionics.h:66
const meshdata< mesh_int_t, mesh_real_t > * mesh
the connected mesh
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
Definition: electrics.cc:733
sf_mat * mass_i
lumped for parabolic problem
Definition: electrics.h:109
sf_vec * phie_i
phi_e on intracellular grid
Definition: electrics.h:44
sf_vec * IIon
ionic currents
Definition: electrics.h:98
V dist(const vec3< V > &p1, const vec3< V > &p2)
Definition: vect.h:114
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
LAT_detector lat
the activation time detector
Definition: electrics.h:266
void assign(InputIterator s, InputIterator e)
Assign a memory range.
Definition: SF_vector.h:161
const vector< T > & algebraic_nodes() const
Getter function for the local indices forming the local algebraic node set.
int output_all_activations(FILE_SPEC fp, int *ibuf, double *act_tbuf, int nlacts)
Definition: electrics.cc:1540
std::int32_t SF_int
Use the general std::int32_t as int type.
Definition: SF_globals.h:37
void rebuild_matrices(MaterialType *mtype, SF::vector< stimulus > &stimuli, FILE_SPEC logger)
Definition: electrics.cc:906
double strength
strength of stimulus
Definition: stimulate.h:92
size_t g_numelem
global number of elements
Definition: SF_container.h:386
stim_protocol ptcl
applied stimulation protocol used
Definition: stimulate.h:166
double SF_real
Use the general double as real type.
Definition: SF_globals.h:38
void binary_sort(vector< T > &_V)
Definition: SF_sort.h:284
void translate(int id)
convert legacy definitions to new format
Definition: stimulate.cc:100
stim_physics phys
physics of stimulus
Definition: stimulate.h:167
void apply_stim_to_vector(const stimulus &s, sf_vec &vec, bool add)
Definition: electrics.cc:428
virtual void get(const vector< T > &idx, S *out)=0
SF::vector< RegionSpecs > regions
array with region params
Definition: fem_types.h:115
void setup_dataout(const int dataout, std::string dataout_vtx, mesh_t grid, SF::vector< mesh_int_t > *&restr, bool async)
Definition: electrics.cc:588
void resize(size_t n)
Resize a vector.
Definition: SF_vector.h:209
sf_vec * get_data(datavec_t d)
Retrieve a petsc data vector from the data registry.
Definition: sim_utils.cc:880
int get_size(MPI_Comm comm=PETSC_COMM_WORLD)
Definition: basics.h:290
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
int stimidx_from_timeridx(const SF::vector< stimulus > &stimuli, const int timer_id)
determine link between timer and stimulus
Definition: electrics.cc:747
sf_mat * rhs_parab
rhs matrix to solve parabolic
Definition: electrics.h:110
bool is_dbc(stim_t type)
whether stimulus is a dirichlet type. implies boundary conditions on matrix
Definition: stimulate.cc:76
void backward(abstract_vector< T, S > &in, abstract_vector< T, S > &out, bool add=false)
Backward scattering.
phie_recovery_data phie_rcv
struct holding helper data for phie recovery
Definition: electrics.h:275
centralize time managment and output triggering
Definition: timer_utils.h:73
int get_rank(MPI_Comm comm=PETSC_COMM_WORLD)
Definition: basics.h:276
void compute_restr_idx_async(sf_mesh &mesh, SF::vector< mesh_int_t > &inp_idx, SF::vector< mesh_int_t > &idx)
Definition: electrics.cc:553
int postproc_recover_phie()
Definition: electrics.cc:1936
T local_nodal_to_local_petsc(const meshdata< T, S > &mesh, int rank, T local_nodal)
virtual T gsize() const =0
LAT_detector()
constructor, sets up basic datastructs from global_params
Definition: electrics.cc:1338
#define UM2_to_CM2
convert um^2 to cm^2
Definition: physics_types.h:35
long d_end
final index in multiples of dt
Definition: timer_utils.h:82
FILE_SPEC f_open(const char *fname, const char *mode)
Open a FILE_SPEC.
Definition: basics.cc:135
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
Container for a PETSc VecScatter.
int add_singlestep_timer(double tg, double idur, const char *iname, const char *poolname=nullptr)
Definition: timer_utils.h:143