openCARP
Doxygen code documentation for the open cardiac electrophysiology simulator openCARP
ionics.cc
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: Copyright (c) NumeriCor GmbH
2 // SPDX-License-Identifier: LicenseRef-APL-1.1
3 
12 #include "ionics.h"
13 
14 #include "SF_init.h"
15 #include <limits>
16 #include <cmath>
17 
18 namespace opencarp {
19 
21 {
22  double t1, t2;
23  get_time(t1);
24 
26 
27  double comp_time = timing(t2, t1);
28  this->compute_time += comp_time;
29 
30  comp_stats.calls++;
31  comp_stats.tot_time += comp_time;
32 
35 }
36 
38 {
39  miif->free_MIIF();
40 }
41 
43 {}
44 
46 {
47  double t1, t2;
48  get_time(t1);
49 
50  set_dir(OUTPUT);
51 
52  // initialize generic logger for ODE timings per time_dt
53  comp_stats.init_logger("ODE_stats.dat");
54 
55  double tstart = 0.;
56  sf_mesh & mesh = get_mesh(ion_domain);
57  limpet::node_count_t loc_size = mesh.pl.num_algebraic_idx();
58 
59  // create ionic current vector and register it
60  sf_vec *IIon;
61  sf_vec *Vmv;
62  SF::init_vector(&IIon, mesh, 1, sf_vec::algebraic);
63  SF::init_vector(&Vmv, mesh, 1, sf_vec::algebraic);
64  register_data(IIon, iion_vec);
65  register_data(Vmv, vm_vec);
66 
67  // setup miif
68  miif = new limpet::MULTI_IF();
69  // hand down the physics log file, so that what MULTI_IF reports while setting up and
70  // restoring state is recorded rather than only echoed to the console
71  miif->logger = logger;
72  // store IIF_IDs and Plugins in arrays
73  miif->name = "myocardium";
74  miif->gdata[limpet::Vm] = Vmv;
75  miif->gdata[limpet::Iion] = IIon;
76 
77  SF::vector<RegionSpecs> rs(param_globals::num_imp_regions);
78  for (size_t i = 0; i < rs.size(); i++ ) {
79  rs[i].nsubregs = param_globals::imp_region[i].num_IDs;
80  rs[i].subregtags = param_globals::imp_region[i].ID;
81  }
82 
83  SF::vector<int> reg_mask;
84  region_mask(ion_domain, rs, reg_mask, false, "imp_region", logger);
85 
86  if(strlen(param_globals::imp_region_nodefile)) {
87  // with a single region, region_mask() leaves reg_mask empty and there is nothing to override
88  if(param_globals::num_imp_regions < 2) {
89  log_msg(0, 5, 0, "%s error: imp_region_nodefile requires num_imp_regions >= 2. Aborting!",
90  __func__);
91  EXIT(1);
92  }
93 
94  set_dir(INPUT);
95  override_region_mask(ion_domain, reg_mask, param_globals::imp_region_nodefile,
96  param_globals::num_imp_regions);
97  set_dir(OUTPUT);
98  }
99 
100  dump_region_mask(ion_domain, reg_mask, "imp_region");
101 
102  int purkfLen = 1;
103  tstart = setup_MIIF(loc_size, param_globals::num_imp_regions, param_globals::imp_region,
104  reg_mask.data(), param_globals::start_statef, param_globals::num_adjustments,
105  param_globals::adjustment, param_globals::dt, purkfLen > 0);
106 
107  miif->extUpdateVm = !param_globals::operator_splitting;
108 
109  // if we start at a non-zero time (i.e. we have restored a state), we notify the
110  // timer manager
111  if(tstart > 0.) {
112  log_msg(logger, 0, 0, "Changing simulation start time to %.2lf", tstart);
113  user_globals::tm_manager->setup(param_globals::dt, tstart, param_globals::tend);
115  }
116 
117  set_dir(INPUT);
118 
119  this->initialize_time += timing(t2, t1);
120 }
121 
122 double Ionics::setup_MIIF(limpet::node_count_t nnodes, int nreg, IMPregion* impreg, int* mask,
123  const char *start_fn, int numadjust, IMPVariableAdjustment *adjust,
124  double time_step, bool close)
125 {
126  double tstart = 0;
127 
128  // the region mask handed to limpet is stored as IIF_Mask_t, so region ids beyond its
129  // range would wrap around and corrupt the per-region node lists
130  const int max_regions = int(std::numeric_limits<limpet::IIF_Mask_t>::max()) + 1;
131  if(nreg > max_regions) {
132  log_msg(0, 5, 0, "%s error: %d imp_regions requested, but at most %d are supported "
133  "(limited by limpet::IIF_Mask_t). Aborting!", __func__, nreg, max_regions);
134  EXIT(1);
135  }
136 
137  miif->N_IIF = nreg;
138  miif->numNode = nnodes;
139  miif->iontypes = {};
140  miif->numplugs = (int*)calloc( miif->N_IIF, sizeof(int));
141  miif->plugtypes = std::vector<limpet::IonTypeList>(miif->N_IIF);
142  miif->targets = std::vector<limpet::Target>(miif->N_IIF, limpet::Target::AUTO);
143 
144  log_msg(logger,0,ECHO, "\nSetting up ionic models and plugins\n" \
145  "-----------------------------------\n\n" \
146  "Assigning IMPS to tagged regions:" );
147 
148  for (int i=0;i<miif->N_IIF;i++) {
149  auto pT = limpet::get_ion_type(std::string(impreg[i].im));
150  if (pT != NULL)
151  {
152  miif->iontypes.push_back(*pT);
153  log_msg(logger, 0, ECHO|NONL, "\tIonic model: %s to tag region(s)", impreg[i].im);
154 
155  // a single region covers the whole mesh regardless of its ID list
156  if(miif->N_IIF == 1) {
157  log_msg(logger,0,ECHO, " all");
158  }
159  else if(impreg[i].num_IDs > 0) {
160  for(int j = 0; j < impreg[i].num_IDs; j++)
161  log_msg(logger,0,ECHO|NONL, " [%d],", impreg[i].ID[j]);
162  log_msg(logger,0,ECHO,"\b.");
163  }
164  else {
165  log_msg(logger,0,ECHO, " none");
166  }
167  }
168  else {
169  log_msg(NULL,5,ECHO, "Illegal IM specified: %s\n", impreg[i].im );
170  log_msg(NULL,5,ECHO, "Run bench --list-imps for a list of all available models.\n" );
171  EXIT(1);
172  }
173  if (limpet::get_plug_flag( impreg[i].plugins, &miif->numplugs[i], miif->plugtypes[i]))
174  {
175  if(impreg[i].plugins[0] != '\0') {
176  log_msg(logger,0, ECHO|NONL, "\tPlug-in(s) : %s to tag region(s)", impreg[i].plugins);
177 
178  for(int j = 0; j < impreg[i].num_IDs; j++)
179  log_msg(logger,0,ECHO|NONL, " [%d],", impreg[i].ID[j]);
180  log_msg(logger,0,ECHO,"\b.");
181  }
182  }
183  else {
184  log_msg(NULL,5,ECHO,"Illegal plugin specified: %s\n", impreg[i].plugins);
185  log_msg(NULL,5,ECHO, "Run bench --list-imps for a list of all available plugins.\n" );
186  EXIT(1);
187  }
188  }
189 
191 
192  // The mask is a nodal vector with the region IDs of each node.
193  // It is already reduced during the region_mask call to guarantee unique values
194  // for overlapping interface nodes
195  if (mask) {
196  for (limpet::node_index_t i=0; i<miif->numNode; i++)
197  miif->IIFmask[i] = (limpet::IIF_Mask_t) mask[i];
198  }
199 
201 
202  for(int i=0; i<miif->N_IIF; i++)
203  if(!miif->IIF[i]->cgeom().SVratio)
204  miif->IIF[i]->cgeom().SVratio = param_globals::imp_region[i].cellSurfVolRatio;
205 
206  for (int i=0;i<miif->N_IIF;i++) {
207  // the IMP tuning does not handle spaces well, thus we remove them here
208  remove_char(impreg[i].im_param, strlen(impreg[i].im_param), ' ');
209  miif->IIF[i]->tune(impreg[i].im_param, impreg[i].plugins, impreg[i].plug_param);
210  }
211 
212  set_dir(INPUT);
213  miif->initialize_currents(time_step, param_globals::ode_fac);
214 
215  // overriding initial values goes here
216  // read in single cell state vector and spread it out over the entire region
217  set_dir(INPUT);
218  for (int i=0;i<miif->N_IIF;i++) {
219  if (impreg[i].im_sv_init && strlen(impreg[i].im_sv_init) > 0)
220  if (read_sv(miif, i, impreg[i].im_sv_init)) {
221  log_msg(NULL, 5, ECHO|FLUSH, "State vector initialization failed for %s.\n", impreg[i].name);
222  EXIT(-1);
223  }
224  }
225 
226  if( !start_fn || strlen(start_fn)>0 )
227  tstart = (double) miif->restore_state(start_fn, ion_domain, close);
228 
229  for (int i=0; i<numadjust; i++)
230  {
231  set_dir(INPUT);
232 
233  SF::vector<SF_int> indices;
234  SF::vector<SF_real> values;
235  bool restrict_to_algebraic = true;
236 
237  sf_mesh & imesh = get_mesh(ion_domain);
238  std::map<std::string,std::string> metadata;
239  read_metadata(adjust[i].file, metadata, SF_COMM);
240 
241  SF::SF_nbr nbr = SF::NBR_REF;
242  if(metadata.count("grid") && metadata["grid"].compare("intra") == 0) {
243  nbr = SF::NBR_SUBMESH;
244  }
245  read_indices_with_data(indices, values, adjust[i].file, imesh, nbr, restrict_to_algebraic, 1, SF_COMM);
246 
247  int rank = get_rank();
248 
249  for(size_t gi = 0; gi < indices.size(); gi++)
250  indices[gi] = SF::local_nodal_to_local_petsc<mesh_int_t,mesh_real_t>(imesh, rank, indices[gi]);
251 
252  // debug, output parameters on global intracellular vector
253  if(adjust[i].dump) {
254  sf_vec* adjPars;
255  SF::init_vector(&adjPars, imesh, 1, sf_vec::algebraic);
256  adjPars->set(indices, values, false, true);
257 
258  set_dir(OUTPUT);
259  char fname[2085];
260  snprintf(fname, sizeof fname, "adj_%s_perm.dat", adjust[i].variable);
261  adjPars->write_ascii(fname, false);
262 
263  // get the scattering to the canonical permutation
265  if(sc == NULL) {
266  log_msg(0,3,0, "%s warning: PETSC_TO_CANONICAL permutation needed registering!", __func__);
268  }
269 
270  (*sc)(*adjPars, true);
271  snprintf(fname, sizeof fname, "adj_%s_canonical.dat", adjust[i].variable);
272  adjPars->write_ascii(fname, false);
273  }
274 
275  int nc = miif->adjust_MIIF_variables(adjust[i].variable, indices, values);
276  log_msg(logger, 0, 0, "Adjusted %d values for %s", nc, adjust[i].variable);
277  }
278 
279  return tstart;
280 }
281 
294  const char* gridname, const char* reglist, FILE_SPEC logger)
295 {
296  bool AllTagsExist = true;
297 
299  tagset.insert(tags.begin(), tags.end());
300 
301  // cycle through all user-specified regions
302  for (size_t reg=0; reg<regspec.size(); reg++)
303  // cycle through all tags which belong to the region
304  for (int k=0; k<regspec[reg].nsubregs; k++) {
305  // check whether this tag exists in element list
306  int n = 0;
307  if(tagset.count(regspec[reg].subregtags[k])) n++;
308  // globalize n
309  int N = get_global(n, MPI_SUM);
310  if (N==0) {
311  if(strcmp(reglist, "gregion_vol"))
312  log_msg(logger, 3, ECHO,
313  "%s[%d] references tag %d, but no element in the %s grid carries this tag — region will have no elements.\n",
314  reglist, reg, regspec[reg].subregtags[k], gridname);
315  AllTagsExist = false;
316  }
317  }
318 
319  if (!AllTagsExist) {
320  log_msg(logger, 4, ECHO,"One or more configured regions are empty. Check that region tag IDs match the tags in your mesh or tagfile.\n");
321  }
322 
323  return AllTagsExist;
324 }
325 
326 static const char* one_region_per_tag = "Every element tag must be listed in exactly one region.\n";
327 
334  const hashmap::unordered_map<mesh_int_t,int> & tag_to_reg,
335  const char* gridname, const char* reglist, FILE_SPEC logger)
336 {
337  SF::vector<mesh_int_t> unmatched;
338  long int n_unassigned = 0;
339  for (const mesh_int_t & t : tags) {
340  if (!tag_to_reg.count(t)) {
341  unmatched.push_back(t);
342  n_unassigned++;
343  }
344  }
345 
346  n_unassigned = get_global(n_unassigned, MPI_SUM);
347  if (!n_unassigned) return;
348 
349  binary_sort(unmatched);
350  unique_resize(unmatched);
351  make_global(unmatched, SF_COMM);
352  binary_sort(unmatched);
353  unique_resize(unmatched);
354 
355  std::string taglist;
356  for (size_t i = 0; i < unmatched.size(); i++) {
357  if (i) taglist += ", ";
358  taglist += std::to_string(unmatched[i]);
359  }
360 
361  log_msg(logger, 5, ECHO|FLUSH,
362  "%s: %ld element(s) in %s grid carry tags {%s} not assigned to any %s region.\n%s",
363  __func__, n_unassigned, gridname, taglist.c_str(), reglist, one_region_per_tag);
364  EXIT(EXIT_FAILURE);
365 }
366 
367 void region_mask(mesh_t meshspec, SF::vector<RegionSpecs> & regspec,
368  SF::vector<int> & regionIDs, bool mask_elem, const char* reglist,
369  FILE_SPEC logger)
370 {
371  if(regspec.size() == 1) return;
372 
373  sf_mesh & mesh = get_mesh(meshspec);
375 
376  size_t rIDsize = mask_elem ? mesh.l_numelem : mesh.l_numpts;
377 
378  size_t nelem = mesh.l_numelem;
379  const SF::vector<mesh_int_t> & tags = mesh.tag;
380 
381  // the parameter parser fills IDs missing from a list shorter than num_IDs with -1
382  for (size_t reg=0; reg < regspec.size(); reg++)
383  for (int k=0; k < regspec[reg].nsubregs; k++)
384  if (regspec[reg].subregtags[k] == -1) {
385  log_msg(logger, 5, ECHO|FLUSH, "%s: %s[%zu] lists fewer tags than its num_IDs.\n",
386  __func__, reglist, reg);
387  EXIT(EXIT_FAILURE);
388  }
389 
390  // check whether all specified tags exist in the element list
391  check_tags_in_elems(tags, regspec, mesh.name.c_str(), reglist, logger);
392 
393  // A tag listed in two regions has no well-defined owner, so the region layout is rejected
394  // rather than resolved by list order. regspec is identical on all ranks, so every rank
395  // reaches the same verdict.
397  for (size_t reg=0; reg < regspec.size(); reg++) {
398  for (int k=0; k < regspec[reg].nsubregs; k++) {
399  mesh_int_t curtag = regspec[reg].subregtags[k];
400  auto it = tag_to_reg.find(curtag);
401  if (it != tag_to_reg.end() && it->second != int(reg)) {
402  log_msg(logger, 5, ECHO|FLUSH, "%s: tag %ld is listed in both %s[%d] and %s[%zu].\n%s",
403  __func__, long(curtag), reglist, it->second, reglist, reg, one_region_per_tag);
404  EXIT(EXIT_FAILURE);
405  }
406  tag_to_reg[curtag] = reg;
407  }
408  }
409 
410  check_unassigned_tags(tags, tag_to_reg, mesh.name.c_str(), reglist, logger);
411 
412  regionIDs.resize(rIDsize);
413 
414  SF::vector<mesh_int_t> mx_tag(regionIDs.size(), -1);
415 
416  // cycle through the element list
417  for(size_t i=0; i<nelem; i++) {
418  const mesh_int_t & cur_tag = tags[i];
419 
420  if (mask_elem) regionIDs[i] = tag_to_reg.at(cur_tag);
421  else {
422  eview.set_elem(i);
423 
424  for (int j=0; j < eview.num_nodes(); j++) {
425  mesh_int_t n = eview.node(j);
426  if (cur_tag > mx_tag[n]) mx_tag[n] = cur_tag;
427  }
428  }
429  }
430 
431  if(mask_elem) return;
432 
433  // The tie between the tags meeting at a node must be broken on the tags themselves.
434  // Reducing the region IDs instead would let the highest region win at nodes shared
435  // between ranks while the highest tag wins everywhere else, making the assignment
436  // depend on the partitioning whenever the tags are not listed in ascending order.
437  mesh.pl.reduce(mx_tag, "max");
438 
439  for(size_t i=0; i < regionIDs.size(); i++)
440  regionIDs[i] = tag_to_reg.at(mx_tag[i]);
441 
442  const SF::vector<mesh_int_t> & alg_nod = mesh.pl.algebraic_nodes();
443 
444  SF::vector<int> alg_reg(alg_nod.size());
445 
446  for(size_t i=0; i<alg_nod.size(); i++)
447  alg_reg[i] = regionIDs[alg_nod[i]];
448 
449  regionIDs = alg_reg;
450 }
451 
452 void override_region_mask(mesh_t meshspec, SF::vector<int> & regionIDs,
453  const std::string & filename, int num_regions)
454 {
455  sf_mesh & mesh = get_mesh(meshspec);
456 
457  // regionIDs must be the algebraic nodal mask produced by region_mask()
458  int size_err = regionIDs.size() != mesh.pl.num_algebraic_idx() ? 1 : 0;
459  if(get_global(size_err, MPI_SUM)) {
460  log_msg(0, 5, 0, "%s error: region mask size does not match the number of algebraic nodes. Aborting!",
461  __func__);
462  EXIT(1);
463  }
464 
465  SF::vector<SF_int> indices;
466  SF::vector<SF_real> values;
467  bool restrict_to_algebraic = true;
468 
469  std::map<std::string,std::string> metadata;
470  read_metadata(filename, metadata, SF_COMM);
471 
472  SF::SF_nbr nbr_type = SF::NBR_REF;
473  if(metadata.count("grid") && metadata["grid"].compare("intra") == 0) {
474  nbr_type = SF::NBR_SUBMESH;
475  }
476  read_indices_with_data(indices, values, filename, mesh, nbr_type, restrict_to_algebraic, 1, SF_COMM);
477 
478  int rank = get_rank();
479  int num_set = 0;
480  int num_err = 0;
481 
482  for(size_t i=0; i<indices.size(); i++) {
483  mesh_int_t local_alg = SF::local_nodal_to_local_petsc<mesh_int_t,mesh_real_t>(mesh, rank, indices[i]);
484  const SF_real val = values[i];
485 
486  // check before casting: non-integral values would be silently truncated, and casting
487  // NaN or out-of-range values to int is undefined behaviour
488  if(!std::isfinite(val) || val != std::floor(val) || val < 0 || val >= num_regions) {
489  num_err++;
490  continue;
491  }
492 
493  int reg = (int) val;
494 
495  regionIDs[local_alg] = reg;
496  num_set++;
497  }
498 
499  // the points are distributed over the ranks, so a single rank aborting would leave the
500  // others blocked in the next collective call. reduce first, then abort on all ranks.
501  num_err = get_global(num_err, MPI_SUM);
502  if(num_err) {
503  log_msg(0, 5, 0, "%s error: %d point(s) in %s have an invalid region id (must be an integer in [0,%d)). Aborting!",
504  __func__, num_err, filename.c_str(), num_regions);
505  EXIT(1);
506  }
507 
508  num_set = get_global(num_set, MPI_SUM);
509  log_msg(0, 0, 0, "%s: directly assigned %d point(s) to explicit imp_region indices from %s, "
510  "overriding any tag-derived assignment.", __func__, num_set, filename.c_str());
511 }
512 
513 void dump_region_mask(mesh_t meshspec, const SF::vector<int> & regionIDs, const char* reglist)
514 {
515  if(!param_globals::dump_imp_region) return;
516 
517  // region_mask() leaves the mask empty if there is only a single region; nothing to dump then
518  int num_entries = regionIDs.size();
519  if(get_global(num_entries, MPI_SUM) == 0) return;
520 
521  sf_mesh & mesh = get_mesh(meshspec);
522  const SF::vector<mesh_int_t> & alg_nod = mesh.pl.algebraic_nodes();
524 
525  SF::vector<int> gids(alg_nod.size());
526  for(size_t i=0; i<alg_nod.size(); i++)
527  gids[i] = nbr[alg_nod[i]];
528 
529  set_dir(OUTPUT);
530  write_data_ascii(SF_COMM, gids, regionIDs, std::string(reglist)+".dat");
531 }
532 
535 double Ionics::timer_val(const int timer_id)
536 {
537  double val = std::nan("NaN");
538  return val;
539 }
540 
543 std::string Ionics::timer_unit(const int timer_id)
544 {
545  std::string s_unit;
546  return s_unit;
547 }
548 
550 {
551  if (impdata[limpet::Iion] != NULL)
552  impdata[limpet::Iion][n] = 0;
553 
554  pIF.for_each([&](limpet::IonIfBase& imp) {
555  update_ts(&imp.get_tstp());
556  imp.compute(n, n + 1, impdata);
557  });
558 }
559 
571 void* find_SV_in_IMP(limpet::MULTI_IF* miif, const int idx, const char *IMP, const char *SV,
572  int* offset, int* sz, int* plugin_idx)
573 {
574  *plugin_idx = -1;
575 
576  if(strcmp(IMP, miif->iontypes[idx].get().get_name().c_str()) == 0) {
577  return (void*) miif->iontypes[idx].get().get_sv_offset(SV, offset, sz);
578  }
579  else {
580  for(int k=0; k<miif->numplugs[idx]; k++)
581  if(strcmp(IMP, miif->plugtypes[idx][k].get().get_name().c_str()) == 0) {
582  *plugin_idx = k;
583  return (void*) miif->plugtypes[idx][k].get().get_sv_offset(SV, offset, sz);
584  }
585  }
586 
587  return NULL;
588 }
589 
590 
600 void alloc_gvec_data(const int nGVcs, const int nRegs,
601  GVecs *prmGVecs, gvec_data &glob_vecs)
602 {
603  glob_vecs.nRegs = nRegs;
604 
605  if (nGVcs) {
606  glob_vecs.vecs.resize(nGVcs);
607 
608  for (size_t i = 0; i < glob_vecs.vecs.size(); i++) {
609  sv_data &gvec = glob_vecs.vecs[i];
610 
611  gvec.name = dupstr(prmGVecs[i].name);
612  gvec.units = dupstr(prmGVecs[i].units);
613  gvec.bogus = prmGVecs[i].bogus;
614 
615  gvec.imps = (char**) calloc(nRegs, sizeof(char *));
616  gvec.svNames = (char**) calloc(nRegs, sizeof(char *));
617  gvec.svSizes = (int*) calloc(nRegs, sizeof(int));
618  gvec.svOff = (int*) calloc(nRegs, sizeof(int));
619  gvec.plugin_idx = (int*) calloc(nRegs, sizeof(int));
620  gvec.getsv = (void**) calloc(nRegs, sizeof(limpet::SVgetfcn));
621 
622  for (int j = 0; j < nRegs; j++) {
623  gvec.plugin_idx[j] = -1;
624  if (strlen(prmGVecs[i].imp)) gvec.imps[j] = dupstr(prmGVecs[i].imp);
625 #ifdef WITH_PURK
626  else if (j < param_globals::num_imp_regions)
627  gvec.imps[j] = dupstr(param_globals::imp_region[j].im);
628  else
629  gvec.imps[j] = dupstr(param_globals::PurkIon[j - param_globals::num_imp_regions].im);
630 #else
631  else if (j < param_globals::num_imp_regions)
632  gvec.imps[j] = dupstr(param_globals::imp_region[j].im);
633 #endif
634  gvec.svNames[j] = dupstr(prmGVecs[i].ID[j]);
635  }
636  }
637  }
638 }
639 
653  igb_output_manager & output_manager)
654 {
655  GVs.inclPS = false;
656  // int num_purk_regions = GVs->inclPS ? purk->ion.N_IIF : 0;
657  int num_purk_regions = 0;
658  int nRegs = param_globals::num_imp_regions + num_purk_regions;
659 
660  alloc_gvec_data(param_globals::num_gvecs, nRegs, param_globals::gvec, GVs);
661 
662 #ifdef WITH_PURK
663  if (GVs->inclPS) sample_PS_ionSVs(purk);
664 #endif
665 
666  for (unsigned int i = 0; i < GVs.vecs.size(); i++) {
667  sv_data & gv = GVs.vecs[i];
668  int noSV = 0;
669 
670  for (int j = 0; j < miif->N_IIF; j++) {
671  gv.getsv[j] = find_SV_in_IMP(miif, j, gv.imps[j], gv.svNames[j], gv.svOff + j, gv.svSizes + j, gv.plugin_idx + j);
672 
673  if (gv.getsv[j] == NULL) {
674  log_msg(NULL, 3, ECHO, "\tWarning: SV(%s) not found in region %d\n", gv.svNames[j], j);
675  noSV++;
676  }
677  }
678 
679  SF::init_vector(&gv.ordered, &tmpl);
680  output_manager.register_output(gv.ordered, intra_elec_msh, 1, gv.name, gv.units);
681 
682 #ifdef WITH_PURK
683  // same procedure for Purkinje
684  if (GVs->inclPS) {
685  IF_PURK_PROC(purk) {
686  MULTI_IF* pmiif = &purk->ion;
687  for (int j = miif->N_IIF; j < nRegs; j++) {
688  gv.getsv[j] = find_SV_in_IMP(pmiif, j - miif->N_IIF, gv.imps[j],
689  gv.svNames[j], gv.svOff + j, gv.svSizes + j, gv.plugin_idx + j);
690 
691  if (gv.getsv[j] == NULL) {
692  LOG_MSG(NULL, 3, ECHO, "\tWarning: state variable \"%s\" not found in region %d\n", gv.svNames[j], j);
693  noSV++;
694  }
695  }
696  RVector_dup(purk->vm_pt, &gv.orderedPS_PS);
697  MYO_COMM(purk);
698  }
699  RVector_dup(purk->vm_pt_over, &gv.orderedPS);
700  initialize_grid_output(grid, NULL, tmo, intra_elec_msh, GRID_WRITE, 0., 1., gv.units, gv.orderedPS,
701  1, gv.GVcName, -purk->npt, param_globals::output_level);
702  }
703 #endif
704 
705  if (noSV == nRegs) {
706  log_msg(NULL, 5, ECHO, "\tError: no state variables found for global vector %d\n", i);
707  log_msg(NULL, 5, ECHO, "Run bench --imp=YourModel --imp-info to get a list of all parameters.\\n");
708  exit(1);
709  }
710  }
711 }
712 
724 {
725  for(size_t i=0; i<gvecs.vecs.size(); i++ ) {
726  sv_data & gv = gvecs.vecs[i];
727 
728  // set to the defalt value
729  gv.ordered->set(gv.bogus);
730  SF_int start, stop;
731  gv.ordered->get_ownership_range(start, stop);
732 
733  for( int n = 0; n<miif->N_IIF; n++ ) {
734  if( !gv.getsv[n] ) continue;
735 
736  SF::vector<SF_real> data (miif->N_Nodes[n]);
737  SF::vector<SF_int> indices(miif->N_Nodes[n]);
738 
739  limpet::IonIfBase* base_im = miif->IIF[n];
740  int plugin_idx = gv.plugin_idx[n];
741  limpet::IonIfBase* imp = plugin_idx > -1 ? base_im->plugins()[plugin_idx] : base_im;
742 
743  for( limpet::node_index_t j=0; j<miif->N_Nodes[n]; j++ ) {
744  indices[j] = miif->NodeLists[n][j] + start;
745  data[j] = ((limpet::SVgetfcn)(gv.getsv[n]))( *imp, j, gv.svOff[n]);
746  }
747 
748  bool add = false;
749  gv.ordered->set(indices, data, add);
750  }
751  }
752 }
753 
754 
755 } // namespace opencarp
opencarp::local_index_t mesh_int_t
Definition: SF_container.h:31
#define SF_COMM
the default SlimFem MPI communicator
Definition: SF_globals.h:25
opencarp::real_t SF_real
Global scalar type.
Definition: SF_globals.h:30
opencarp::global_index_t SF_int
Global algebraic index type.
Definition: SF_globals.h:29
#define EXIT(A)
finalize the backend, if it runs, and exit
Definition: backend.h:23
#define FLUSH
Definition: basics.h:305
#define ECHO
Definition: basics.h:302
#define NONL
Definition: basics.h:306
virtual void get_ownership_range(T &start, T &stop) const =0
virtual void set(const vector< T > &idx, const vector< S > &vals, const bool additive=false, const bool local=false)=0
Comfort class. Provides getter functions to access the mesh member variables more comfortably.
Definition: SF_fem_utils.h:689
const T & node(short nidx) const
Access the connectivity information.
Definition: SF_fem_utils.h:778
void set_elem(size_t eidx)
Set the view to a new element.
Definition: SF_fem_utils.h:716
T num_nodes() const
Getter function for the number of nodes.
Definition: SF_fem_utils.h:746
overlapping_layout< T > pl
nodal parallel layout
Definition: SF_container.h:414
size_t l_numelem
local number of elements
Definition: SF_container.h:384
std::string name
the mesh name
Definition: SF_container.h:392
size_t l_numpts
local number of points
Definition: SF_container.h:386
vector< T > & get_numbering(SF_nbr nbr_type)
Get the vector defining a certain numbering.
Definition: SF_container.h:449
vector< T > tag
element tag
Definition: SF_container.h:402
Redistributes vector data from indexing "a" to indexing "b".
A vector storing arbitrary data.
Definition: SF_vector.h:28
size_t size() const
The current size of the vector.
Definition: SF_vector.h:89
void resize(size_t n)
Resize a vector.
Definition: SF_vector.h:194
const T * end() const
Pointer to the vector's end.
Definition: SF_vector.h:113
const T * begin() const
Pointer to the vector's start.
Definition: SF_vector.h:101
T * data()
Pointer to the vector's start.
Definition: SF_vector.h:76
T & push_back(T val)
Definition: SF_vector.h:268
iterator find(const K &key)
Search for key. Return iterator.
Definition: hashmap.hpp:626
hm_int count(const K &key) const
Check if key exists.
Definition: hashmap.hpp:612
T & at(const K &key)
Data access by key.
Definition: hashmap.hpp:646
Custom unordered_set implementation.
Definition: hashmap.hpp:739
hm_int count(const K &key) const
Definition: hashmap.hpp:1067
void insert(InputIterator first, InputIterator last)
Definition: hashmap.hpp:1037
Represents the ionic model and plug-in (IMP) data structure.
Definition: ION_IF.h:168
std::vector< IonIfBase * > & plugins()
Returns a vector containing the plugins of this IMP.
Definition: ION_IF.cc:174
void compute(node_index_t start, node_index_t end, GlobalData_t **data)
Perform ionic model computation for 1 time step.
Definition: ION_IF.cc:258
ts & get_tstp()
Gets the time stepper.
Definition: ION_IF.cc:198
void for_each(const std::function< void(IonIfBase &)> &consumer)
Executes the consumer functions on this IMP and each of its plugins.
Definition: ION_IF.cc:526
bool extUpdateVm
flag indicating update function for Vm
Definition: MULTI_ION_IF.h:204
std::vector< IonIfBase * > IIF
array of IIF's
Definition: MULTI_ION_IF.h:198
opencarp::sf_vec * gdata[NUM_IMP_DATA_TYPES]
data used by all IMPs
Definition: MULTI_ION_IF.h:212
node_count_t numNode
local number of nodes
Definition: MULTI_ION_IF.h:206
int * numplugs
number of plugins for each region
Definition: MULTI_ION_IF.h:205
std::vector< Target > targets
target for each region
Definition: MULTI_ION_IF.h:209
std::vector< IonTypeList > plugtypes
plugins types for each region
Definition: MULTI_ION_IF.h:211
IonTypeList iontypes
type for each region
Definition: MULTI_ION_IF.h:208
void initialize_currents(double, int)
float restore_state(const char *, opencarp::mesh_t gid, bool)
int N_IIF
how many different IIF's
Definition: MULTI_ION_IF.h:207
void compute_ionic_current(bool flag_send=1, bool flag_receive=1)
GPU kernel to emulate the add_scaled call made to adjust the Vm values when the update to Vm is not m...
node_count_t * N_Nodes
#nodes for each IMP
Definition: MULTI_ION_IF.h:196
opencarp::FILE_SPEC logger
Definition: MULTI_ION_IF.h:213
node_index_t ** NodeLists
local partitioned node lists for each IMP stored
Definition: MULTI_ION_IF.h:197
IIF_Mask_t * IIFmask
region for each node
Definition: MULTI_ION_IF.h:210
int adjust_MIIF_variables(const char *variable, const SF::vector< SF_int > &indices, const SF::vector< SF_real > &values)
std::string name
name for MIIF region
Definition: MULTI_ION_IF.h:194
FILE_SPEC logger
The logger of the physic, each physic should have one.
Definition: physics_types.h:49
const char * name
The name of the physic, each physic should have one.
Definition: physics_types.h:47
void output_step()
Definition: ionics.cc:42
mesh_t ion_domain
Definition: ionics.h:83
generic_timing_stats comp_stats
Definition: ionics.h:85
limpet::MULTI_IF * miif
Definition: ionics.h:82
void compute_step()
Definition: ionics.cc:20
void initialize()
Definition: ionics.cc:45
void destroy()
Definition: ionics.cc:37
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
Definition: ionics.cc:543
double timer_val(const int timer_id)
figure out current value of a signal linked to a given timer
Definition: ionics.cc:535
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:2134
void setup(double inp_dt, double inp_start, double inp_end)
Initialize the timer_manager.
Definition: timer_utils.cc:21
void reset_timers()
Reset time in timer_manager and then reset registered timers.
Definition: timer_utils.h:101
Electrical ionics functions and LIMPET wrappers.
void write_data_ascii(const MPI_Comm comm, const vector< T > &idx, const vector< S > &data, std::string file, short dpn=1)
void make_global(const vector< T > &vec, vector< T > &out, MPI_Comm comm)
make a parallel vector global
Definition: SF_network.h:210
void unique_resize(vector< T > &_P)
Definition: SF_sort.h:338
void init_vector(SF::abstract_vector< T, S > **vec)
Definition: SF_init.h:127
void binary_sort(vector< T > &_V)
Definition: SF_sort.h:274
SF_nbr
Enumeration encoding the different supported numberings.
Definition: SF_container.h:185
@ NBR_PETSC
PETSc numbering of nodes.
Definition: SF_container.h:188
@ NBR_REF
The nodal numbering of the reference mesh (the one stored on HD).
Definition: SF_container.h:186
@ NBR_SUBMESH
Submesh nodal numbering: The globally ascending sorted reference indices are reindexed.
Definition: SF_container.h:187
int get_plug_flag(char *plgstr, int *out_num_plugins, IonTypeList &out_plugins)
@ AUTO
Definition: target.h:31
IonType * get_ion_type(const std::string &name)
SF_real GlobalData_t
Definition: limpet_types.h:12
GlobalData_t(* SVgetfcn)(IonIfBase &, node_index_t, int)
Definition: ion_type.h:33
constexpr T max(T a, T b)
Definition: ion_type.h:16
void update_ts(ts *ptstp)
Definition: ION_IF.cc:575
opencarp::local_index_t node_count_t
Definition: limpet_types.h:14
int read_sv(MULTI_IF *, int, const char *)
char IIF_Mask_t
Definition: ion_type.h:35
opencarp::local_index_t node_index_t
Definition: limpet_types.h:13
std::map< int, std::string > units
Definition: stimulate.cc:26
timer_manager * tm_manager
a manager for the various physics timers
Definition: main.cc:40
void compute_IIF(limpet::IonIfBase &pIF, limpet::GlobalData_t **impdata, limpet::node_index_t n)
Definition: ionics.cc:549
void region_mask(mesh_t meshspec, SF::vector< RegionSpecs > &regspec, SF::vector< int > &regionIDs, bool mask_elem, const char *reglist, FILE_SPEC logger)
classify elements/points as belonging to a region
Definition: ionics.cc:367
void * find_SV_in_IMP(limpet::MULTI_IF *miif, const int idx, const char *IMP, const char *SV, int *offset, int *sz, int *plugin_idx)
Definition: ionics.cc:571
@ iotm_console
Definition: timer_utils.h:29
sf_mesh & get_mesh(const mesh_t gt)
Get a mesh by specifying the gridID.
Definition: sf_interface.cc:18
SF::scattering * get_permutation(const int mesh_id, const int perm_id, const int dpn)
Get the PETSC to canonical permutation scattering for a given mesh and number of dpn.
void override_region_mask(mesh_t meshspec, SF::vector< int > &regionIDs, const std::string &filename, int num_regions)
directly assign specific points to a region, bypassing region_mask()'s element-tag-derived "highest t...
Definition: ionics.cc:452
SF::meshdata< mesh_int_t, mesh_real_t > sf_mesh
Definition: sf_interface.h:33
int set_dir(IO_t dest)
Definition: sim_utils.cc:896
void read_metadata(const std::string filename, std::map< std::string, std::string > &metadata, MPI_Comm comm)
Read metadata from the header.
Definition: fem_utils.cc:57
T get_global(T in, MPI_Op OP, MPI_Comm comm=SF_COMM)
Do a global reduction on a variable.
Definition: basics.h:219
void check_unassigned_tags(const SF::vector< mesh_int_t > &tags, const hashmap::unordered_map< mesh_int_t, int > &tag_to_reg, const char *gridname, const char *reglist, FILE_SPEC logger)
Abort if any element carries a tag that no region lists.
Definition: ionics.cc:333
SF::scattering * register_permutation(const int mesh_id, const int perm_id, const int dpn)
Register a permutation between two orderings for a mesh.
void register_data(sf_vec *dat, datavec_t d)
Register a data vector in the global registry.
Definition: sim_utils.cc:1371
@ OUTPUT
Definition: sim_utils.h:39
bool check_tags_in_elems(const SF::vector< mesh_int_t > &tags, SF::vector< RegionSpecs > &regspec, const char *gridname, const char *reglist, FILE_SPEC logger)
Check whether the tags in the region spec struct matches with an array of tags.
Definition: ionics.cc:293
void init_sv_gvec(gvec_data &GVs, limpet::MULTI_IF *miif, sf_vec &tmpl, igb_output_manager &output_manager)
Definition: ionics.cc:652
void assemble_sv_gvec(gvec_data &gvecs, limpet::MULTI_IF *miif)
Definition: ionics.cc:723
void dump_region_mask(mesh_t meshspec, const SF::vector< int > &regionIDs, const char *reglist)
dump a nodal region mask as produced by region_mask() to reglist+".dat"
Definition: ionics.cc:513
char * dupstr(const char *old_str)
Definition: basics.cc:27
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
Definition: basics.cc:55
mesh_t
The enum identifying the different meshes we might want to load.
Definition: sf_interface.h:44
@ intra_elec_msh
Definition: sf_interface.h:45
void alloc_gvec_data(const int nGVcs, const int nRegs, GVecs *prmGVecs, gvec_data &glob_vecs)
Definition: ionics.cc:600
void get_time(double &tm)
Definition: basics.h:430
SF::abstract_vector< SF_int, SF_real > sf_vec
Definition: sf_interface.h:35
int get_rank(MPI_Comm comm=SF_COMM)
Definition: basics.h:270
void remove_char(char *buff, const int buffsize, const char c)
Definition: basics.h:350
void read_indices_with_data(SF::vector< T > &idx, SF::vector< S > &dat, const std::string filename, const hashmap::unordered_map< mesh_int_t, mesh_int_t > &dd_map, const int dpn, MPI_Comm comm)
like read_indices, but with associated data for each index
Definition: fem_utils.h:254
V timing(V &t2, const V &t1)
Definition: basics.h:442
#define PETSC_TO_CANONICAL
Permute algebraic data from PETSC to canonical ordering.
Definition: sf_interface.h:64
File descriptor struct.
Definition: basics.h:121
void log_stats(double tm, bool cflg)
Definition: timers.cc:96
void init_logger(const char *filename)
Definition: timers.cc:80
int calls
# calls for this interval, this is incremented externally
Definition: timers.h:75
double tot_time
total time, this is incremented externally
Definition: timers.h:77
SF::vector< sv_data > vecs
store sv dump indices for global vectors
Definition: ionics.h:165
unsigned int nRegs
number of imp regions
Definition: ionics.h:163
bool inclPS
include PS if exists
Definition: ionics.h:164
float bogus
value indicating sv not in region
Definition: ionics.h:159
void ** getsv
functions to retrieve sv
Definition: ionics.h:156
char * name
Name of global composite sv vector.
Definition: ionics.h:148
int * plugin_idx
per-region plugin index in the IMP's plugin list, or -1 for the base IMP
Definition: ionics.h:154
int * svOff
sv size in bytes
Definition: ionics.h:153
char ** svNames
sv names of components forming global vector
Definition: ionics.h:150
int * svSizes
sv size in bytes
Definition: ionics.h:152
char ** imps
Name of imp to which sv belongs.
Definition: ionics.h:149
char * units
units of sv
Definition: ionics.h:158
sf_vec * ordered
vector in which to place ordered data
Definition: ionics.h:157