19 #include "opencarp_types.h"
23 #ifdef WITH_POWERCAPPING
25 #include "powercapping.h"
36 #include "openCARP_schema.hpp"
37 #include "runtime.hpp"
43 std::vector<paramschema::CitationSuggestion> active_citation_suggestions;
45 bool match_long_option(
const std::string& token,
const char* option, std::string* attached_value)
47 *attached_value = std::string();
48 if (token == option) {
52 const std::string prefix = std::string(option) +
"=";
53 if (token.size() > prefix.size() && token.compare(0, prefix.size(), prefix) == 0) {
54 *attached_value = token.substr(prefix.size());
61 bool is_help_topic_candidate(
const char* token)
63 return token != NULL && token[0] !=
'\0' && token[0] !=
'-' && token[0] !=
'+';
66 bool is_long_option_argument_error(
const std::string& token,
68 const std::string& attached_value,
71 if (attached_value.empty()) {
75 *error =
"Unexpected argument for " + std::string(option) +
" in '" + token +
"'";
79 bool normalize_runtime_args(
int argc,
81 std::vector<std::string>* normalized,
86 if (argc <= 0 || argv == NULL || argv[0] == NULL) {
87 *error =
"Missing program name";
91 normalized->push_back(argv[0]);
93 for (
int i = 1; i < argc; ++i) {
94 const std::string token = argv[i];
99 std::string attached_value;
101 if (token ==
"+Help" || match_long_option(token,
"--help", &attached_value)) {
102 std::string topic =
"PrM";
103 if (!attached_value.empty()) {
104 topic = attached_value;
105 }
else if (i + 1 < argc && is_help_topic_candidate(argv[i + 1])) {
108 normalized->push_back(
"+Help");
109 normalized->push_back(topic);
113 if (token ==
"+Doc" || match_long_option(token,
"--doc", &attached_value)) {
114 std::string topic =
"ALL";
115 if (!attached_value.empty()) {
116 topic = attached_value;
117 }
else if (i + 1 < argc && is_help_topic_candidate(argv[i + 1])) {
120 normalized->push_back(
"+Doc");
121 normalized->push_back(topic);
125 if (token ==
"+Default" || match_long_option(token,
"--default", &attached_value)) {
126 if (token !=
"+Default" && is_long_option_argument_error(token,
"--default", attached_value, error)) {
129 normalized->push_back(
"+Default");
133 if (token ==
"+Run" || match_long_option(token,
"--run", &attached_value)) {
134 if (token !=
"+Run" && is_long_option_argument_error(token,
"--run", attached_value, error)) {
137 normalized->push_back(
"+Run");
141 if (token ==
"+I" || match_long_option(token,
"--interactive", &attached_value)) {
142 if (!attached_value.empty()) {
143 *error =
"Unexpected argument for --interactive in '" + token +
"'";
145 *error =
"Unsupported option " + token +
" (interactive mode is not available)";
150 if (token ==
"+F" || match_long_option(token,
"--file", &attached_value)) {
151 std::string
filename = attached_value;
154 *error =
"Missing filename after " + token;
159 normalized->push_back(
"+F");
164 if (token ==
"+Save" || match_long_option(token,
"--save", &attached_value)) {
165 std::string
filename = attached_value;
168 *error =
"Missing argument after " + token;
173 normalized->push_back(
"+Save");
178 normalized->push_back(token);
184 void populate_arg_pointers(
const std::vector<std::string>& values, std::vector<char*>* argv)
186 argv->assign(values.size(), NULL);
187 for (std::size_t i = 0; i < values.size(); ++i) {
188 (*argv)[i] =
const_cast<char*
>(values[i].c_str());
192 void print_lines(FILE* stream,
const char* label,
const std::vector<std::string>& lines)
194 for (std::size_t i = 0; i < lines.size(); ++i) {
195 fprintf(stream,
"%s%s\n", label, lines[i].c_str());
199 void clear_active_citation_suggestions()
201 active_citation_suggestions.clear();
204 void store_active_citation_suggestions(
const std::vector<paramschema::CitationSuggestion>& suggestions)
206 active_citation_suggestions = suggestions;
209 void print_active_citation_suggestions()
211 if (active_citation_suggestions.empty() ||
get_rank() != 0) {
215 const std::vector<std::string> lines =
216 paramschema::format_citation_suggestions(active_citation_suggestions);
221 std::fprintf(stdout,
"\nIf you publish studies based on this simulation, the following references are likely relevant:\n");
222 for (std::size_t i = 0; i < lines.size(); ++i) {
223 std::fprintf(stdout,
" %s\n", lines[i].c_str());
225 std::fprintf(stdout,
" You can use https://citation.doi.org to format references in your preferred format or https://www.doi2bib.org to turn the DOIs into BibTeX format.\n");
226 std::fprintf(stdout,
"\nWe'd be happy to also see your experiment published to boost its impact and foster reproducibility.\nSee https://opencarp.org/community/upload-experiment for details.\n\n");
231 void print_parser_runtime_state(
const std::vector<std::string>& runtime_args)
233 const auto& schema = paramschema::openCARP_schema();
234 const std::string program_name =
235 runtime_args.empty() || runtime_args[0].empty() ?
"openCARP" : runtime_args[0];
237 std::string rendered;
238 std::vector<std::string> errors;
239 if (!paramschema::render_save_text(schema, program_name, &rendered, &errors)) {
240 print_lines(stderr,
"parameter parser warning: ", errors);
244 fputs(rendered.c_str(), stderr);
247 paramschema::ExecutionResult execute_parser_runtime_args(
const std::vector<std::string>& runtime_args)
249 std::vector<char*> argv;
250 populate_arg_pointers(runtime_args, &argv);
252 const auto& schema = paramschema::openCARP_schema();
254 return paramschema::execute_legacy_cli(schema,
static_cast<int>(argv.size()), argv.data());
257 bool apply_parser_runtime_args(
const std::vector<std::string>& runtime_args)
259 clear_active_citation_suggestions();
260 const paramschema::ExecutionResult executed = execute_parser_runtime_args(runtime_args);
261 print_lines(stderr,
"parameter parser warning: ", executed.warnings);
262 if (!executed.rendered_output.empty()) {
263 fputs(executed.rendered_output.c_str(), stdout);
265 if (!executed.errors.empty() || executed.status == paramschema::ExecutionStatus::Fatal) {
266 print_lines(stderr,
"parameter parser error: ", executed.errors);
270 if (param_globals::output_setup) {
271 print_parser_runtime_state(runtime_args);
274 if (executed.status == paramschema::ExecutionStatus::Help) {
278 store_active_citation_suggestions(executed.citations);
284 static char input_dir[1024],
291 void localize_gridout_nodes(
sf_mesh& mesh,
314 alg_map[nbr[local_node]] = local_node;
318 for(
int pid = 0; pid < mpi_size; pid++) {
319 if(mpi_rank == pid) {
320 recv_nodes = selected_nodes;
321 buffsize = recv_nodes.
size();
324 MPI_Bcast(&buffsize,
sizeof(
size_t), MPI_BYTE, pid, mesh.comm);
325 recv_nodes.
resize(buffsize);
326 MPI_Bcast(recv_nodes.
data(), buffsize *
sizeof(
mesh_int_t), MPI_BYTE, pid, mesh.comm);
329 auto it = alg_map.
find(node);
330 if(it != alg_map.
end())
341 for(
int pid = 0; pid < mpi_size; pid++) {
342 if(mpi_rank == pid) {
343 recv_nodes = selected_nodes;
344 buffsize = recv_nodes.
size();
347 MPI_Bcast(&buffsize,
sizeof(
size_t), MPI_BYTE, pid, mesh.comm);
348 recv_nodes.
resize(buffsize);
349 MPI_Bcast(recv_nodes.
data(), buffsize *
sizeof(
mesh_int_t), MPI_BYTE, pid, mesh.comm);
352 if(node >= start && node < stop)
362 bool mesh_has_gridout_tags(
const sf_mesh& mesh,
365 bool local_has_tag =
false;
366 for(
size_t eidx = 0; eidx < mesh.l_numelem; eidx++) {
367 if(output_tags.
count(mesh.tag[eidx]) != 0) {
368 local_has_tag =
true;
373 int local = local_has_tag ? 1 : 0;
375 MPI_Allreduce(&local, &global, 1, MPI_INT, MPI_MAX, mesh.comm);
379 void extract_gridout_tag_mesh(
const sf_mesh& mesh,
384 for(
size_t eidx = 0; eidx < mesh.l_numelem; eidx++)
385 keep_elem[eidx] = output_tags.
count(mesh.tag[eidx]) != 0;
387 out_mesh.name = mesh.name;
389 if(out_mesh.g_numelem == 0) {
390 log_msg(0, 5,
ECHO,
"gridout_tags selected no elements in \"%s\".", mesh.name.c_str());
398 std::list<sf_mesh*> meshlist;
399 meshlist.push_back(&out_mesh);
404 out_mesh.generate_par_layout();
410 void extract_gridout_surface_mesh(
const sf_mesh& mesh,
sf_mesh& out_mesh)
413 out_mesh.name = mesh.name;
421 ref_eidx.
resize(out_mesh.l_numelem);
423 long int num_local = out_mesh.l_numelem, offset = 0;
424 MPI_Exscan(&num_local, &offset, 1, MPI_LONG, MPI_SUM, out_mesh.comm);
426 for(
size_t eidx = 0; eidx < out_mesh.l_numelem; eidx++)
427 ref_eidx[eidx] = offset + eidx;
431 std::list<sf_mesh*> meshlist;
432 meshlist.push_back(&out_mesh);
437 out_mesh.generate_par_layout();
443 void write_gridout_surface(
const sf_mesh& mesh,
const std::string& basename)
446 extract_gridout_surface_mesh(mesh, surf);
452 for(
size_t i = 0; i < surf_global.con.size(); i++)
453 surf_global.con[i] = nbr[surf_global.con[i]];
462 std::vector<std::string> normalized_args;
463 std::string normalize_error;
464 if (!normalize_runtime_args(argc, argv, &normalized_args, &normalize_error)) {
465 fprintf(stderr,
"\n*** %s\n\n", normalize_error.c_str());
469 if (!apply_parser_runtime_args(normalized_args)) {
485 log_msg(NULL, 5,
ECHO,
"The EMI model was not compiled for this binary.\n");
499 log_msg(0,0,0,
"\n *** Initializing physics ***\n");
503 for (
int ii = 0; ii < param_globals::num_external_imp; ii++) {
505 assert(loading_succeeded);
508 if(param_globals::num_external_imp)
509 log_msg(NULL, 4,
ECHO,
"Loading of external LIMPET modules not enabled.\n"
510 "Recompile with DLOPEN set.\n" );
516 log_msg(NULL, 0, 0,
"Initializing %s ..", p->
name);
523 log_msg(0,0,0,
"\n *** Destroying physics ***\n");
551 for (
int i=0; i<ns; i++ ) {
559 log_msg( NULL, 1, 0,
"Extracellular stimulus %d ignored for monodomain", i );
562 log_msg( NULL, 1, 0,
"Intracellular stimulus %d converted to transmembrane", i );
597 Stimulus* s = param_globals::stimulus;
599 for(
int i=0; i < param_globals::num_stim; i++) {
607 log_msg( NULL, 4, 0,
"Elliptic system is singular!\n"
608 "Use an explicit ground:voltage (stimulus[X].stimtype=3)\n"
609 "Do not trust the elliptic solution of this simulation run!\n");
614 const char* real_precision = OPENCARP_REAL_BITS == 32 ?
"single" :
"double";
615 printf(
"\n""*** GIT tag: %s\n", GIT_COMMIT_TAG);
616 printf(
"*** GIT hash: %s\n", GIT_COMMIT_HASH);
617 printf(
"*** GIT repo: %s\n", GIT_PATH);
618 printf(
"*** local index bits: %d\n", OPENCARP_LOCAL_INDEX_BITS);
619 printf(
"*** global index bits: %d\n", OPENCARP_GLOBAL_INDEX_BITS);
620 printf(
"*** real precision: %s (%d-bit)\n", real_precision, OPENCARP_REAL_BITS);
621 printf(
"*** dependency commits: %s\n\n", SUBREPO_COMMITS);
627 param_globals::dt /= 1000.;
631 if(param_globals::mass_lumping == 0 && param_globals::parab_solve==0) {
632 log_msg(0,5,0,
"parab_solve = 0 (explicit) requires mass_lumping = 1. "
633 "Either enable mass lumping or choose an implicit parab_solve method.");
638 if(!param_globals::extracell_monodomain_stim)
647 if(param_globals::t_sentinel > 0 && param_globals::sentinel_ID < 0 ) {
648 log_msg(0,4,0,
"Warning: t_sentinel is set but no sentinel_ID has been specified; check_quiescence() behavior may not be as expected");
651 if(param_globals::num_external_imp > 0 ) {
652 for(
int ext_imp_i = 0; ext_imp_i < param_globals::num_external_imp; ext_imp_i++) {
653 if(param_globals::external_imp[ext_imp_i][0] !=
'/') {
654 log_msg(0,5,0,
"external_imp[%d] error: absolute paths must be used for .so file loading (\'%s\')",
655 ext_imp_i, param_globals::external_imp[ext_imp_i]);
661 if(param_globals::experiment ==
EXP_LAPLACE && param_globals::bidomain != 1) {
662 log_msg(0,4,0,
"Warning: Laplace experiment mode requires bidomain = 1. Setting bidomain = 1.");
663 param_globals::bidomain = 1;
666 if(param_globals::num_phys_regions == 0) {
667 log_msg(0,4,0,
"Warning: No physics region defined! Please set phys_region parameters to correctly define physics.");
670 log_msg(0,4,0,
"Intra-elec and Extra-elec domains will be derived from fibers.\n");
671 param_globals::num_phys_regions = param_globals::bidomain ? 2 : 1;
672 param_globals::phys_region = (p_region*) calloc(param_globals::num_phys_regions,
sizeof(p_region));
674 param_globals::phys_region[0].name = strdup(
"Autogenerated intracellular Electrics");
675 param_globals::phys_region[0].num_IDs = 0;
677 if(param_globals::bidomain) {
679 param_globals::phys_region[1].name = strdup(
"Autogenerated extracellular Electrics");
680 param_globals::phys_region[1].num_IDs = 0;
683 log_msg(0,4,0,
"Laplace domain will be derived from fibers.\n");
684 param_globals::num_phys_regions = 1;
685 param_globals::phys_region = (p_region*) calloc(param_globals::num_phys_regions,
sizeof(p_region));
687 param_globals::phys_region[0].name = strdup(
"Autogenerated Laplace");
688 param_globals::phys_region[0].num_IDs = 0;
693 log_msg(0,4,0,
"Warning: Laplace experiment mode requires a laplace physics regions defined.");
697 log_msg(0,4,0,
"Converting the defined extracellular-electrics-region to laplace-region.");
700 log_msg(0,4,0,
"Converting the defined intracellular-electrics-region to laplace-region.");
703 param_globals::num_phys_regions += 1;
704 param_globals::phys_region = (p_region*) realloc(param_globals::phys_region, param_globals::num_phys_regions *
sizeof(p_region));
706 param_globals::phys_region[param_globals::num_phys_regions - 1].ptype =
PHYSREG_LAPLACE;
707 param_globals::phys_region[param_globals::num_phys_regions - 1].name = strdup(
"Autogenerated Laplace");
708 param_globals::phys_region[param_globals::num_phys_regions - 1].num_IDs = 0;
712 #ifndef WITH_PARMETIS
713 if(param_globals::pstrat == 1) {
714 log_msg(0,3,0,
"openCARP was built without Parmetis support. Swithing to KDtree.");
715 param_globals::pstrat = 2;
720 bool legacy_stim_set =
false, new_stim_set =
false;
722 for(
int i=0; i<param_globals::num_stim; i++) {
723 Stimulus & legacy_stim = param_globals::stimulus[i];
724 Stim & new_stim = param_globals::stim[i];
726 if(legacy_stim.stimtype || legacy_stim.strength)
727 legacy_stim_set =
true;
729 if(new_stim.crct.type || new_stim.pulse.strength)
733 if(legacy_stim_set || new_stim_set) {
734 if(legacy_stim_set && new_stim_set) {
735 log_msg(0,4,0,
"Warning: Legacy stimuli and default stimuli are defined. Only default stimuli will be used!");
737 else if (legacy_stim_set) {
738 log_msg(0,1,0,
"Warning: Legacy stimuli defined. Please consider switching to stimulus definition \"stim[]\"!");
743 log_msg(0,4,0,
"Warning: No potential or current stimuli found!");
753 log_msg(0, 0, 0,
"LICENSE NOTICE:");
755 "This run uses openCARP components licensed under the Academic Public License v1.1.");
757 "That includes code from simulator/** and APL-licensed parts of physics/**.");
759 "Commercial use is not allowed without a separate commercial license.");
764 int flg = 0, err = 0, rank =
get_rank();
766 char *ptr = getcwd(current_dir, 1024);
767 if (ptr == NULL) err++;
768 ptr = getcwd(input_dir, 1024);
769 if (ptr == NULL) err++;
775 if (strcmp(sim_ID,
"OUTPUT_DIR")) {
776 if (mkdir(sim_ID, 0775)) {
777 if (errno == EEXIST ) {
778 log_msg(NULL, 2, 0,
"Output directory exists: %s\n", sim_ID);
780 log_msg(NULL, 5, 0,
"Unable to make output directory\n");
784 }
else if (mkdir(sim_ID, 0775) && errno != EEXIST) {
785 log_msg(NULL, 5, 0,
"Unable to make output directory\n");
793 err += chdir(sim_ID);
794 ptr = getcwd(output_dir, 1024);
795 if (ptr == NULL) err++;
800 err += chdir(output_dir);
803 if (rank == 0 && ((param_globals::experiment==
EXP_POSTPROCESS) || (param_globals::post_processing_opts &
LEADFIELD))) {
805 if (strcmp(param_globals::ppID,
"POSTPROC_DIR")) {
806 if (mkdir(param_globals::ppID, 0775)) {
807 if (errno == EEXIST ) {
808 log_msg(NULL, 2,
ECHO,
"Postprocessing directory exists: %s\n\n", param_globals::ppID);
810 log_msg(NULL, 5,
ECHO,
"Unable to make postprocessing directory\n\n");
814 }
else if (mkdir(param_globals::ppID, 0775) && errno != EEXIST) {
815 log_msg(NULL, 5,
ECHO,
"Unable to make postprocessing directory\n\n");
823 err += chdir(param_globals::ppID);
824 ptr = getcwd(postproc_dir, 1024);
825 if (ptr == NULL) err++;
826 err = chdir(output_dir);
835 bool io_node =
false;
838 if (param_globals::num_io_nodes > 0) {
841 log_msg(NULL, 5, 0,
"You cannot run with async IO on only one core.\n");
845 if (2 * param_globals::num_io_nodes >= psize) {
846 log_msg(NULL, 5, 0,
"The number of IO cores be less " "than the number of compute cores.");
850 if (param_globals::num_PS_nodes && param_globals::num_io_nodes > param_globals::num_PS_nodes) {
852 "The number of IO cores (%d) should not "
853 "exceed the number of PS compute cores (%d).\n",
854 param_globals::num_io_nodes, param_globals::num_PS_nodes);
859 io_node = prank < param_globals::num_io_nodes;
863 MPI_Comm_set_name(comm, io_node ?
"IO" :
"compute");
872 MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, io_node ? param_globals::num_io_nodes : 0,
876 log_msg(NULL, 4, 0,
"Global node %d, Comm rank %d != Intercomm rank %d\n",
880 MPI_Comm_set_name(
SF_COMM,
"compute");
885 if((io_node || !param_globals::num_io_nodes) && !prank)
893 getcwd(current_dir, 1024);
900 if (dest==
OUTPUT) err = chdir(output_dir);
901 else if (dest==
POSTPROC) err = chdir(postproc_dir);
902 else if (dest==
CURDIR) err = chdir(current_dir);
903 else err = chdir(input_dir);
911 double start_time = 0.0;
914 double end_time = param_globals::tend;
928 if(param_globals::num_tsav) {
929 std::vector<double> trig(param_globals::num_tsav);
930 for(
size_t i=0; i<trig.size(); i++) trig[i] = param_globals::tsav[i];
935 if(param_globals::chkpt_intv)
937 param_globals::chkpt_intv, 0,
iotm_chkpt_intv,
"interval checkpointing");
939 if(param_globals::num_trace)
943 #ifdef WITH_POWERCAPPING
944 void basic_powercapping_setup()
946 user_globals::pc_manager =
new powercapping_manager();
949 void basic_powercapping_cleanup()
953 delete user_globals::pc_manager; user_globals::pc_manager =
nullptr;
960 const short padding = 4;
965 if(col_width[0] <
int(strlen(buff)+padding))
966 col_width[0] = strlen(buff)+padding;
969 if(col_width[1] <
int(strlen(buff)+padding))
970 col_width[1] = strlen(buff)+padding;
973 for (
size_t tid = 0; tid < used_timer_ids.size(); tid++)
975 int timer_id = used_timer_ids[tid];
985 snprintf(buff,
sizeof buff,
"%.3lf", val);
986 if(col_width[col] <
int(strlen(buff)+padding))
987 col_width[col] = strlen(buff)+padding;
1004 const char* smpl_endl =
"\n";
1012 log_msg(0,5,0,
"Protocol file %s could not be opened for writing!\n", fname);
1025 std::vector<std::string> col_labels = {
"time",
"tick"};
1026 std::vector<std::string> col_short_labels = {
"A",
"B"};
1027 std::vector<std::string> col_unit_labels = {
"ms",
"--" };
1028 std::vector<int> col_width = {4, 4};
1030 char c_label = {
'C'};
1031 std::string label = {
""};
1032 std::string unit = {
""};
1036 std::vector<int> used_timer_ids;
1037 std::vector<int> used_stim_ids;
1047 used_stim_ids.push_back(sidx);
1057 for (
size_t tid = 0; tid < used_timer_ids.size(); tid++)
1059 int timer_id = used_timer_ids[tid];
1062 int llen = strlen(t->
name);
1063 mx_llen = llen > mx_llen ? llen : mx_llen;
1066 for (
size_t tid = 0; tid < used_timer_ids.size(); tid++)
1068 int timer_id = used_timer_ids[tid];
1071 col_labels.push_back(t->
name);
1073 col_short_labels.push_back(label);
1078 if(unit.empty()) unit =
"--";
1079 col_unit_labels.push_back(unit);
1080 col_width.push_back(4);
1088 fh <<
"# Protocol header\n#\n" <<
"# Legend:\n";
1089 for(
size_t i = 0; i<col_short_labels.size(); i++)
1091 fh <<
"#" << std::setw(2) << col_short_labels[i] <<
" = " << std::setw(mx_llen) << col_labels[i];
1092 fh <<
" [" << std::setw(10) << col_unit_labels[i] <<
"]";
1094 if(i >= 2 && used_stim_ids[i-2] > -1) {
1099 fh <<
" ground stim" << smpl_endl;
1101 fh <<
" applied: " << std::to_string(s.
pulse.
strength) << smpl_endl;
1112 for(
size_t i = 0; i<col_short_labels.size(); i++)
1113 fh << std::setw(col_width[i] - 3) << col_short_labels[i].c_str() << std::setw(3) <<
" ";
1116 fh << smpl_endl <<
"#";
1117 for(
size_t i = 0; i<col_unit_labels.size(); i++)
1118 fh <<
"[" << std::setw(col_width[i]-2) << col_unit_labels[i].c_str() <<
"]";
1121 fh << smpl_endl << std::fixed;
1129 for (
size_t tid = 0; tid < used_timer_ids.size(); tid++)
1131 int timer_id = used_timer_ids[tid];
1137 fh << std::setw(col_width[col]) << On;
1145 fh << std::setw(col_width[col]) << std::setprecision(3) << val;
1167 const char* h1_prog =
"PROG\t----- \t----\t-------\t-------|";
1168 const char* h2_prog =
"time\t%%comp\ttime\t ctime \t ETA |";
1169 const char* h1_wc =
"\tELAPS |";
1170 const char* h2_wc =
"\twc |";
1175 log_msg(NULL, 0, 0,
"%s", h1_prog );
1183 int req_hours = ((int)(time)) / 3600;
1184 int req_min = (((int)(time)) % 3600) / 60;
1185 int req_sec = (((int)(time)) % 3600) % 60;
1187 snprintf(str, str_size,
"%d:%02d:%02d", req_hours, req_min, req_sec);
1200 char elapsed_time_str[256];
1201 char req_time_str[256];
1205 log_msg( NULL, 0,
NONL,
"%.2f\t%.1f\t%.1f\t%s\t%s",
1223 if(!have_timedependent_phys) {
1224 log_msg(0,0,0,
"\n no time-dependent physics region registered, skipping simulate loop..\n");
1228 log_msg(0,0,0,
"\n *** Launching simulation ***\n");
1232 if(param_globals::dump_protocol)
1239 #ifdef WITH_POWERCAPPING
1240 basic_powercapping_setup();
1241 powercapping_manager *pc = user_globals::pc_manager;
1252 #ifdef WITH_POWERCAPPING
1253 std::vector<int> flops_per_rank;
1258 #ifdef WITH_POWERCAPPING
1259 pc->iteration_begin(flops_per_rank);
1266 it.second->output_step();
1269 #ifdef WITH_POWERCAPPING
1270 pc->sample(
"output step");
1278 #ifdef WITH_POWERCAPPING
1279 pc->sample(p->
name);
1283 #ifdef WITH_POWERCAPPING
1284 pc->iteration_end(flops_per_rank);
1292 log_msg(0,0,0,
"\n\nTimings of individual physics:");
1293 log_msg(0,0,0,
"------------------------------\n");
1300 #ifdef WITH_POWERCAPPING
1302 basic_powercapping_cleanup();
1308 if(param_globals::post_processing_opts &
RECOVER_PHIE) {
1309 log_msg(NULL,0,
ECHO,
"\nPOSTPROCESSOR: Recovering Phie ...");
1310 log_msg(NULL,0,
ECHO,
"----------------------------------\n");
1316 log_msg(NULL,0,
ECHO,
"\n-----------------------------------------");
1317 log_msg(NULL,0,
ECHO,
"POSTPROCESSOR: Successfully recoverd Phie.\n");
1321 if(param_globals::post_processing_opts &
LEADFIELD) {
1322 #ifdef WITH_LEADFIELD
1323 log_msg(NULL,0,
ECHO,
"\nPOSTPROCESSOR: Computing leadfields ...");
1324 log_msg(NULL,0,
ECHO,
"-------------------------------------\n");
1328 log_msg(NULL, 5, 0,
"Error: Leadfield requires active EP physics. Aborting.");
1332 int err = leadfield.
run(*elec);
1335 log_msg(NULL,0,
ECHO,
"\n------------------------------------------");
1336 log_msg(NULL,0,
ECHO,
"POSTPROCESSOR: Successfully computed leadfields.\n");
1339 log_msg(NULL, 5, 0,
"Error: leadfield support not compiled in. Rebuild with -DENABLE_LEADFIELD=ON.");
1352 if(error_if_missing) {
1353 log_msg(0,5,0,
"%s error: required physic is not active! Usually this is due to an inconsistent experiment configuration. Aborting!", __func__);
1377 log_msg(0,5,0,
"%s warning: trying to register already registered data vector.", __func__);
1391 auto register_new_mesh = [&] (
mesh_t mt,
int pidx) {
1392 if(!mesh_registry.count(mt)) {
1393 mesh_registry[mt] =
sf_mesh();
1394 mesh_registry[mt].name = param_globals::phys_region[pidx].name;
1396 return &mesh_registry[mt];
1400 for(
int i=0; i<param_globals::num_phys_regions; i++)
1404 switch(param_globals::phys_region[i].ptype) {
1416 curmesh = register_new_mesh(
emi_msh, i);
1421 log_msg(0,5,0,
"Unsupported mesh type %d! Aborting!", param_globals::phys_region[i].ptype);
1427 for(
int j=0; j<param_globals::phys_region[i].num_IDs; j++)
1445 if(ntr == 0)
return;
1450 for (
int i=0; i<ntr; i++) {
1459 shape.
p0.
x = tagRegs[i].p0[0];
1460 shape.
p0.
y = tagRegs[i].p0[1];
1461 shape.
p0.
z = tagRegs[i].p0[2];
1462 shape.
p1.
x = tagRegs[i].p1[0];
1463 shape.
p1.
y = tagRegs[i].p1[1];
1464 shape.
p1.
z = tagRegs[i].p1[2];
1465 shape.
radius = tagRegs[i].radius;
1472 log_msg(0,3,0,
"Tag region %d is empty", i);
1474 for(
size_t j=0; j<elem_indices.
size(); j++)
1475 mesh.
tag[elem_indices[j]] = tagRegs[i].tag;
1479 if(strlen(param_globals::retagfile))
1494 size_t renormalised_count = 0;
1500 for (
size_t i = 0; i < l_numelem; i++)
1502 const mesh_real_t f0 = fib[3*i+0], f1 = fib[3*i+1], f2 = fib[3*i+2];
1503 mesh_real_t fibre_len = sqrt(f0*f0 + f1*f1 + f2*f2);
1505 if (fibre_len && fabs(fibre_len - 1) > 1e-3) {
1506 fib[3 * i + 0] /= fibre_len;
1507 fib[3 * i + 1] /= fibre_len;
1508 fib[3 * i + 2] /= fibre_len;
1509 renormalised_count++;
1513 return renormalised_count;
1518 log_msg(0,0,0,
"\n *** Processing meshes ***\n");
1520 const std::string basename = param_globals::meshname;
1521 const int verb = param_globals::output_level;
1529 MPI_Comm comm = ref_mesh.
comm;
1532 double t1, t2, s1, s2;
1533 MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank);
1539 std::list< sf_mesh* > ptsread_list;
1542 t1 = MPI_Wtime(); s1 = t1;
1543 if(verb)
log_msg(NULL, 0, 0,
"Reading reference mesh: %s.*", basename.c_str());
1548 if (strlen(param_globals::tagfile)) {
1549 if(verb)
log_msg(NULL, 0, 0,
"Overriding element tags from: %s", param_globals::tagfile);
1554 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
1556 bool check_fibre_normality =
true;
1557 if (check_fibre_normality and ref_mesh.
fib.
size()>0) {
1563 size_t l_num_fixed_she = 0;
1567 unsigned long fixed[2] = {(
unsigned long) l_num_fixed_fib, (
unsigned long) l_num_fixed_she};
1568 MPI_Allreduce(MPI_IN_PLACE, fixed, 2, MPI_UNSIGNED_LONG, MPI_SUM, comm);
1570 if (fixed[0] + fixed[1] > 0)
1571 log_msg(NULL, 0, 0,
"Renormalised %ld longitudinal and %ld sheet-transverse fibre vectors.", fixed[0], fixed[1]);
1574 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
1577 if(param_globals::numtagreg > 0) {
1578 log_msg(0, 0, 0,
"Re-tagging reference mesh");
1582 ptsread_list.push_back(&ref_mesh);
1585 retag_elements(ref_mesh, param_globals::tagreg, param_globals::numtagreg);
1588 ptsread_list.clear();
1591 if(verb)
log_msg(NULL, 0, 0,
"Processing submeshes");
1593 bool have_emi_mesh =
false;
1594 bool have_non_emi_mesh =
false;
1596 for(
auto it = mesh_registry.begin(); it != mesh_registry.end(); ++it) {
1597 mesh_t grid_type = it->first;
1598 sf_mesh & submesh = it->second;
1602 have_emi_mesh =
true;
1604 have_non_emi_mesh =
true;
1606 if(verb > 1)
log_msg(NULL, 0, 0,
"\nSubmesh name: %s", submesh.
name.c_str());
1623 if(verb > 1)
log_msg(NULL, 0, 0,
"Extraction done in %f sec.",
float(t2 - t1));
1625 ptsread_list.push_back(&submesh);
1629 if(have_emi_mesh && have_non_emi_mesh) {
1630 log_msg(NULL, 5,
ECHO,
"EMI and non-EMI submeshes cannot be mixed during mesh setup.");
1635 if(param_globals::pstrat == 2 && have_non_emi_mesh)
1638 for(
auto it = mesh_registry.begin(); it != mesh_registry.end(); ++it)
1640 mesh_t grid_type = it->first;
1641 sf_mesh & submesh = it->second;
1643 if(verb > 2)
log_msg(NULL, 0, 0,
"\nSubmesh name: %s", submesh.
name.c_str());
1648 switch(param_globals::pstrat) {
1650 if(verb > 2)
log_msg(NULL, 0, 0,
"Using linear partitioning ..");
1653 #ifdef WITH_PARMETIS
1656 if(verb > 2)
log_msg(NULL, 0, 0,
"Using Parmetis partitioner ..");
1657 SF::parmetis_partitioner<mesh_int_t, mesh_real_t> partitioner(param_globals::pstrat_imbalance, 2);
1658 partitioner(submesh, part);
1664 if(verb > 2)
log_msg(NULL, 0, 0,
"Using KDtree partitioner ..");
1666 partitioner(submesh, part);
1671 if(verb > 2)
log_msg(NULL, 0, 0,
"Partitioning done in %f sec.",
float(t2 - t1));
1673 if(param_globals::pstrat > 0) {
1674 if(param_globals::gridout_p) {
1675 std::string out_name =
get_basename(param_globals::meshname);
1680 log_msg(0,0,0,
"Writing \"%s\" partitioning to: %s", submesh.
name.c_str(), out_name.c_str());
1687 if(verb > 2)
log_msg(NULL, 0, 0,
"Redistributing done in %f sec.",
float(t2 - t1));
1692 sm_numbering(submesh);
1694 if(verb > 2)
log_msg(NULL, 0, 0,
"Canonical numbering done in %f sec.",
float(t2 - t1));
1699 p_numbering(submesh);
1701 if(verb > 2)
log_msg(NULL, 0, 0,
"PETSc numbering done in %f sec.",
float(t2 - t1));
1706 if(have_non_emi_mesh)
1712 if(verb)
log_msg(NULL, 0, 0,
"All done in %f sec.",
float(s2 - s1));
1717 static const char* parameter_name =
"gridout_tags";
1718 const std::string spec = param_globals::gridout_tags ? param_globals::gridout_tags :
"";
1720 std::vector<int> tags;
1722 if(!paramschema::parse_idset_spec(spec, &tags, &error)) {
1723 log_msg(0, 5,
ECHO,
"Could not parse %s: %s.", parameter_name, error.c_str());
1727 output_tags.
clear();
1728 output_tags.
insert(tags.begin(), tags.end());
1730 if(output_tags.
size() == 0)
return false;
1732 log_msg(0, 0, 0,
"Restricting grid output to %zu tag(s) from %s.",
1733 output_tags.
size(), parameter_name);
1744 for(
size_t eidx = 0; eidx < mesh.
l_numelem; eidx++) {
1745 if(output_tags.
count(mesh.
tag[eidx]) == 0)
continue;
1751 localize_gridout_nodes(mesh, selected_nodes, output_idx, async);
1759 for(
mesh_t mesh_id : mesh_ids) {
1763 for(
size_t eidx = 0; eidx < mesh.
l_numelem; eidx++) {
1764 if(output_tags.
count(mesh.
tag[eidx]) != 0)
1774 for(
int tag : sorted_tags) {
1775 int local_found = local_seen.
count(tag) ? 1 : 0;
1776 int global_found = 0;
1777 MPI_Allreduce(&local_found, &global_found, 1, MPI_INT, MPI_MAX,
SF_COMM);
1778 if(global_found == 0)
1782 if(missing_tags.
size()) {
1785 std::stringstream msg;
1786 for(
size_t i = 0; i < missing_tags.
size(); i++) {
1788 msg << missing_tags[i];
1791 log_msg(0, 3,
ECHO,
"Warning: ignoring gridout_tags not present in the selected output mesh(es): %s.",
1794 for(
int tag : missing_tags)
1795 output_tags.
erase(tag);
1797 if(output_tags.
size() == 0) {
1798 log_msg(0, 5,
ECHO,
"gridout_tags did not match any tag in the selected output mesh(es).");
1817 size_t lhs = 0, rhs = 0;
1818 while(lhs < restr->size() && rhs < selected.
size()) {
1819 if((*restr)[lhs] == selected[rhs]) {
1823 }
else if((*restr)[lhs] < selected[rhs]) {
1830 *restr = intersection;
1840 std::string output_base =
get_basename(param_globals::meshname);
1842 const bool restrict_gridout =
1844 if(restrict_gridout) {
1851 if(write_intra_elec) {
1855 if(restrict_gridout) {
1856 if(!mesh_has_gridout_tags(mesh, output_tags)) {
1857 log_msg(0, 5,
ECHO,
"gridout_tags selected no intracellular grid elements.");
1860 extract_gridout_tag_mesh(mesh, output_tags, restricted_mesh);
1861 output_mesh = &restricted_mesh;
1864 if(param_globals::gridout_i & 1) {
1865 if(param_globals::output_level > 1)
1866 log_msg(0,0,0,
"Computing \"%s\" surface ..", output_mesh->
name.c_str());
1868 std::string output_file = output_base +
"_i.surf";
1869 log_msg(0,0,0,
"Writing \"%s\" surface: %s", output_mesh->
name.c_str(), output_file.c_str());
1871 if(param_globals::gridout_i & 2) {
1879 write_gridout_surface(*output_mesh, output_base +
"_i");
1882 if(param_globals::gridout_i & 2) {
1883 bool write_binary =
false;
1885 std::string output_file = output_base +
"_i";
1886 log_msg(0,0,0,
"Writing \"%s\" mesh: %s", output_mesh->
name.c_str(), output_file.c_str());
1891 if(write_extra_elec) {
1895 if(restrict_gridout) {
1896 if(!mesh_has_gridout_tags(mesh, output_tags)) {
1897 log_msg(0, 5,
ECHO,
"gridout_tags selected no extracellular grid elements.");
1900 extract_gridout_tag_mesh(mesh, output_tags, restricted_mesh);
1901 output_mesh = &restricted_mesh;
1904 if(param_globals::gridout_e & 1) {
1905 if(param_globals::output_level > 1)
1906 log_msg(0,0,0,
"Computing \"%s\" surface ..", output_mesh->
name.c_str());
1908 std::string output_file = output_base +
"_e.surf";
1909 log_msg(0,0,0,
"Writing \"%s\" surface: %s", output_mesh->
name.c_str(), output_file.c_str());
1911 if(param_globals::gridout_e & 2) {
1919 write_gridout_surface(*output_mesh, output_base +
"_e");
1922 if(param_globals::gridout_e & 2) {
1923 bool write_binary =
false;
1924 std::string output_file = output_base +
"_e";
1925 log_msg(0,0,0,
"Writing \"%s\" mesh: %s", output_mesh->
name.c_str(), output_file.c_str());
1935 print_active_citation_suggestions();
1937 const paramschema::ResetResult reset = paramschema::reset_schema_state(paramschema::openCARP_schema());
1938 print_lines(stderr,
"parameter cleanup warning: ", reset.warnings);
1939 print_lines(stderr,
"parameter cleanup error: ", reset.errors);
1951 char* filecopy =
dupstr(file);
1952 char* dir =
dupstr(dirname(filecopy));
1971 petsc_redirect_errors(NULL);
1982 for(
size_t eidx = 0; eidx < mesh.
l_numelem; eidx++) {
1985 if(mindim < cdim) mindim = cdim;
2009 mesh.
pl.algebraic_layout();
2013 for(
size_t i = 0; i < idx->
size(); i++)
2022 int gsize = inp_data->
gsize();
2028 regigb.
x(gsize / dpn);
2029 regigb.
dim_x(regigb.
x()-1);
2032 regigb.
y(1); regigb.
z(1);
2048 regigb.
inc_t(param_globals::spacedt);
2062 log_msg(0,5,0,
"%s error: Could not set up data output! Aborting!", __func__);
2069 IO.
spec = mesh_spec;
2079 buffmap[mesh_spec] = inp_copy;
2086 void igb_output_manager::register_output_async(
sf_vec* inp_data,
2114 for(
size_t i=0; i<alg_nod.
size(); i++)
2115 ioidx[i] = nbr[alg_nod[i]];
2120 for(
size_t i=0; i<idx->
size(); i++) {
2122 ioidx[i] = nbr[loc_nodal];
2142 if(param_globals::num_io_nodes == 0)
2145 register_output_async(inp_data, inp_meshid, dpn, name,
units, idx, elem_data);
2160 sc->
forward(*data_vec, *perm_vec);
2175 FILE* fd =
static_cast<FILE*
>(it.
igb.
fileptr());
2178 sf_vec* buff = fill_output_buffer(it);
2184 const int dpn = it.
spec.
v2;
2191 for(
int j = 0; j < dpn; j++)
2228 FILE* fd =
static_cast<FILE*
>(it.
igb.
fileptr());
2259 bool render_output_parameter_arguments(
int argc,
2261 std::vector<std::string>* rendered_values)
2263 rendered_values->assign(
static_cast<std::size_t
>(argc), std::string());
2265 for (
int i = 1; i < argc; ++i) {
2266 const std::string argument(argv[i]);
2267 if (argument ==
"+F" || argument.find(
"_options_file") != std::string::npos) {
2268 if (i + 1 >= argc) {
2269 std::fprintf(stderr,
"parameter file error: missing value for '%s'\n", argument.c_str());
2272 if (argument.find(
"_options_file") != std::string::npos) {
2273 std::string render_error;
2275 std::fprintf(stderr,
"parameter file error: cannot render '%s': %s\n",
2276 argument.substr(1).c_str(), render_error.c_str());
2284 if (argument.empty() || argument[0] !=
'-') {
2288 const bool prelast = (i == argc - 1);
2289 const bool parameter_follows = !prelast &&
2290 ((argv[i + 1][0] !=
'-') ||
2291 ((argv[i + 1][1] >=
'0') && (argv[i + 1][1] <=
'9')));
2292 if (!parameter_follows) {
2296 const std::string raw_value(argv[i + 1]);
2297 std::string::size_type front = 0;
2298 while (front < raw_value.size() && raw_value[front] ==
' ') {
2302 bool aggregate_value =
false;
2303 std::string value = raw_value.substr(front);
2304 if (front < raw_value.size() && raw_value[front] ==
'{') {
2305 aggregate_value =
true;
2307 while (front < raw_value.size() && raw_value[front] ==
' ') {
2311 std::string::size_type back = raw_value.size();
2312 while (back > front && raw_value[back - 1] ==
' ') {
2315 if (back > front && raw_value[back - 1] ==
'}') {
2317 value = raw_value.substr(front, back - front);
2319 value = raw_value.substr(front);
2323 std::string render_error;
2325 std::fprintf(stderr,
"parameter file error: cannot render '%s': %s\n",
2326 argv[i] + 1, render_error.c_str());
2339 const int max_line_len = 128;
2340 const char* file_sep =
"#=======================================================";
2346 std::vector<std::string> rendered_values;
2347 if (!render_output_parameter_arguments(argc, argv, &rendered_values)) {
2352 fprintf(out->
fd,
"# CARP GIT commit hash: %s\n", GIT_COMMIT_HASH);
2353 fprintf(out->
fd,
"# dependency hashes: %s\n", SUBREPO_COMMITS);
2354 fprintf(out->
fd,
"\n");
2357 char line[8196] =
"# ";
2359 for (
int j=0; j<argc; j++) {
2360 strcat(line, argv[j]);
2361 if(strlen(line) > max_line_len) {
2362 fprintf(out->
fd,
"%s\n", line);
2368 fprintf(out->
fd,
"%s\n\n", line);
2372 for (
int i=1; i<argc; i++) {
2373 std::string argument(argv[i]);
2374 if (argument ==
"+F" || argument.find(
"_options_file")!= std::string::npos) {
2376 std::string init =
"";
2377 if (argument.find(
"_options_file")!= std::string::npos) {
2378 fprintf(out->
fd,
"%s = %s\n", argument.substr(1).c_str(), rendered_values[i].c_str());
2381 fprintf(out->
fd,
"%s>>\n", file_sep);
2384 fprintf(out->
fd,
"## %s ##\n", argv[i]);
2385 FILE *in = fopen(argv[i],
"r");
2386 while (fgets(line, 8196, in))
2387 fprintf(out->
fd,
"%s%s", init.c_str(), line);
2389 fprintf(out->
fd,
"\n##END of %s\n", argv[i]);
2390 fprintf(out->
fd,
"%s<<\n\n", file_sep);
2392 else if(argv[i][0] ==
'-')
2394 bool prelast = (i==argc-1);
2395 bool paramFollows = !prelast && ((argv[i+1][0] !=
'-') ||
2396 ((argv[i+1][1] >=
'0') && (argv[i+1][1] <=
'9')));
2401 fprintf(out->
fd,
"%-40s= %s\n", argv[i]+1, rendered_values[i].c_str());
2405 fprintf(out->
fd,
"%-40s= 1\n", argv[i]);
2413 bool aggregate_value,
2414 std::string* rendered,
2417 if (aggregate_value) {
2419 if (error != NULL) {
2424 return paramschema::quote_legacy_par_value(value, rendered, error);
2436 snprintf(save_fn,
sizeof save_fn,
"exit.save.%.3f.roe", time);
2437 log_msg(NULL, 0, 0,
"savequit called at time %g\n", time);
opencarp::local_index_t mesh_int_t
#define SF_COMM
the default SlimFem MPI communicator
opencarp::real_t SF_real
Global scalar type.
Starts and stops the linear algebra backend the flavor parameter selects.
#define EXIT(A)
finalize the backend, if it runs, and exit
Basic utility structs and functions, mostly IO related.
virtual void release_ptr(S *&p)=0
virtual T gsize() const =0
size_t write_binary(FILE *fd)
Write a vector to HD in binary. File descriptor is already set up.
virtual T lsize() const =0
Comfort class. Provides getter functions to access the mesh member variables more comfortably.
void set_elem(size_t eidx)
Set the view to a new element.
void clear_data()
Clear the mesh data from memory.
overlapping_layout< T > pl
nodal parallel layout
vector< T > dsp
connectivity starting index of each element
vector< S > she
sheet direction
vector< S > fib
fiber direction
size_t l_numelem
local number of elements
std::string name
the mesh name
void generate_par_layout()
Set up the parallel layout.
MPI_Comm comm
the parallel mesh is defined on a MPI world
vector< T > & get_numbering(SF_nbr nbr_type)
Get the vector defining a certain numbering.
vector< T > tag
element tag
hashmap::unordered_set< int > extr_tag
the element tags based on which the mesh has been extracted
non_overlapping_layout< T > epl
element parallel layout
Functor class generating a numbering optimized for PETSc.
void free_scatterings()
Free the registered scatterings.
Redistributes vector data from indexing "a" to indexing "b".
void forward(abstract_vector< T, S > &in, abstract_vector< T, S > &out, bool add=false)
Forward scattering.
Functor class applying a submesh renumbering.
size_t size() const
The current size of the vector.
void resize(size_t n)
Resize a vector.
void assign(InputIterator s, InputIterator e)
Assign a memory range.
T * data()
Pointer to the vector's start.
iterator find(const K &key)
Search for key. Return iterator.
hm_int erase(const K &key)
hm_int count(const K &key) const
void insert(InputIterator first, InputIterator last)
void dump_state(char *, float, opencarp::mesh_t gid, bool, unsigned int)
The abstract physics interface we can use to trigger all physics.
int timer_idx
the timer index received from the timer manager
virtual void output_timings()
virtual void compute_step()=0
virtual void initialize()=0
const char * name
The name of the physic, each physic should have one.
SF::vector< stimulus > stimuli
the electrical stimuli
std::string timer_unit(const int timer_id)
figure out units of a signal linked to a given timer
double timer_val(const int timer_id)
figure out current value of a signal linked to a given timer
int run(Electrics &elec)
Full pipeline: construct or load Z, stream vm.igb, write ECG_*.dat.
class to store shape definitions
std::map< SF::mixed_tuple< mesh_t, int >, sf_vec * > buffmap_elem
IGBheader * get_igb_header(const sf_vec *vec)
Get the pointer to the igb header for a vector that was registered for output.
void write_data()
write registered data to disk
SF::vector< async_io_item > async_IOs
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)
std::map< SF::mixed_tuple< mesh_t, int >, sf_vec * > buffmap
map data spec -> PETSc vector buffer
void close_files_and_cleanup()
close file descriptors
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.
SF::vector< sync_io_item > sync_IOs
stim_t type
type of stimulus
int timer_id
timer for stimulus
double strength
strength of stimulus
stim_protocol ptcl
applied stimulation protocol used
stim_pulse pulse
stimulus wave form
stim_physics phys
physics of stimulus
centralize time managment and output triggering
void initialize_neq_timer(const std::vector< double > &itrig, double idur, int ID, const char *iname, const char *poolname=nullptr)
long d_time
current time instance index
bool trigger(int ID) const
void initialize_eq_timer(double istart, double iend, int ntrig, double iintv, double idur, int ID, const char *iname, const char *poolname=nullptr)
void reset_timers()
Reset time in timer_manager and then reset registered timers.
double start
initial time (nonzero when restarting)
void initialize_singlestep_timer(double tg, double idur, int ID, const char *iname, const char *poolname=nullptr)
std::vector< base_timer * > timers
vector containing individual timers
Base class for tracking progress.
Top-level header of FEM module.
Lead field ECG computation.
void extract_tagbased(const meshdata< T, S > &mesh, meshdata< T, S > &submesh)
Extract a submesh based on element tags.
void write_data_ascii(const MPI_Comm comm, const vector< T > &idx, const vector< S > &data, std::string file, short dpn=1)
void compute_surface_mesh(const meshdata< T, S > &mesh, const SF_nbr numbering, const hashmap::unordered_set< T > &tags, meshdata< T, S > &surfmesh)
Compute the surface of a given mesh.
void print_DD_info(const meshdata< T, S > &mesh)
Print some basic information on the domain decomposition of a mesh.
void read_points(const std::string basename, const MPI_Comm comm, vector< S > &pts, vector< T > &ptsidx)
Read the points and insert them into a list of meshes.
void rebalance_mesh(meshdata< T, S > &mesh)
Rebalance the parallel distribution of a mesh, if a local size is 0.
void write_surface(const meshdata< T, S > &surfmesh, std::string surffile)
void extract_mesh(const vector< bool > &keep, const meshdata< T, S > &mesh, meshdata< T, S > &submesh)
Extract a submesh from a given mesh.
void unique_resize(vector< T > &_P)
void count(const vector< T > &data, vector< S > &cnt)
Count number of occurrences of indices.
size_t root_write_ordered(FILE *fd, const vector< T > &idx, const vector< V > &vec, MPI_Comm comm)
Write index value pairs to disk in ordered permutation.
void insert_points(const vector< S > &pts, const vector< T > &ptsidx, std::list< meshdata< T, S > * > &meshlist)
Insert the points from the read-in buffers into a list of distributed meshes.
void read_element_tags(meshdata< T, S > &mesh, std::string filename)
Override element tags from an ASCII file (one int per element, global element order).
void redistribute_elements(meshdata< T, S > &mesh, meshdata< T, S > &sendbuff, vector< T > &part)
Redistribute the element data of a parallel mesh among the ranks based on a partitioning.
void write_points_parallel(const meshdata< T, S > &mesh, bool binary, std::string basename)
Write a parallel mesh to harddisk without gathering it on one rank.
T local_nodal_to_local_petsc(const meshdata< T, S > &mesh, int rank, T local_nodal)
void init_vector(SF::abstract_vector< T, S > **vec)
void binary_sort(vector< T > &_V)
void extract_myocardium(const meshdata< T, S > &mesh, meshdata< T, S > &submesh, bool require_fibers=true)
Extract the myocardium submesh.
void write_mesh_parallel(const meshdata< T, S > &mesh, bool binary, std::string basename)
void read_elements(meshdata< T, S > &mesh, std::string basename, bool require_fibers=true)
Read the element data (elements and fibers) of a CARP mesh.
@ NBR_PETSC
PETSc numbering of nodes.
@ NBR_ELEM_REF
The element numbering of the reference mesh (the one stored on HD).
@ NBR_REF
The nodal numbering of the reference mesh (the one stored on HD).
@ NBR_SUBMESH
Submesh nodal numbering: The globally ascending sorted reference indices are reindexed.
@ NBR_ELEM_SUBMESH
Submesh element numbering: The globally ascending sorted reference indices are reindexed.
int load_ionic_module(const char *)
void COMPUTE_do_output(SF_real *dat, const int lsize, const int IO_id)
int COMPUTE_register_output(const SF::vector< mesh_int_t > &idx, const int dpn, const char *name, const char *units)
std::map< int, std::string > units
MPI_Comm IO_Intercomm
Communicator between IO and compute worlds.
FILE * petsc_error_fd
file descriptor for petsc error output
timer_manager * tm_manager
a manager for the various physics timers
std::map< datavec_t, sf_vec * > datavec_reg
important solution vectors from different physics
bool using_legacy_stimuli
flag storing whether legacy stimuli are used
SF::scatter_registry scatter_reg
Registry for the different scatter objects.
std::map< mesh_t, sf_mesh > mesh_reg
Registry for the different meshes used in a multi-physics simulation.
std::map< physic_t, Basic_physic * > physics_reg
the physics
void time_to_string(float time, char *str, short str_size)
physic_t
Identifier for the different physics we want to set up.
sf_vec * get_data(datavec_t d)
Retrieve a petsc data vector from the data registry.
void initialize_physics()
Initialize all physics in the registry.
bool setup_IO(int argc, char **argv)
void retag_elements(sf_mesh &mesh, TagRegion *tagRegs, int ntr)
void parse_params_cpy(int argc, char **argv)
Initialize input parameters on a copy of the real command line parameters.
sf_mesh & get_mesh(const mesh_t gt)
Get a mesh by specifying the gridID.
int set_ignore_flags(int mode)
int get_size(MPI_Comm comm=SF_COMM)
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::meshdata< mesh_int_t, mesh_real_t > sf_mesh
datavec_t
Enum used to adress the different data vectors stored in the data registry.
void register_physics()
Register physics to the physics registry.
void post_process()
do postprocessing
void check_and_convert_params()
Here we want to put all parameter checks, conversions and modifications that have been littered throu...
short get_mesh_dim(mesh_t id)
get (lowest) dimension of the mesh used in the experiment
T get_global(T in, MPI_Op OP, MPI_Comm comm=SF_COMM)
Do a global reduction on a variable.
bool is_potential(stim_t type)
uses current for stimulation
bool phys_defined(int physreg)
function to check if certain physics are defined
void update_console_output(const timer_manager &tm, prog_stats &p)
bool output_parameter_file(const char *fname, int argc, char **argv)
void show_build_info()
show the build info, exit if -buildinfo was provided. This code runs before MPI_Init().
FILE_SPEC f_open(const char *fname, const char *mode)
Open a FILE_SPEC.
void savequit()
save state and quit simulator
bool have_permutation(const int mesh_id, const int perm_id, const int dpn)
void set_io_dirs(char *sim_ID, char *pp_ID, IO_t init)
void register_data(sf_vec *dat, datavec_t d)
Register a data vector in the global registry.
bool render_parameter_file_value(const std::string &value, bool aggregate_value, std::string *rendered, std::string *error)
void basic_timer_setup()
Here we set up the timers that we always want to have, independent of physics.
char * get_file_dir(const char *file)
IO_t
The different output (directory) types.
void get_protocol_column_widths(std::vector< int > &col_width, std::vector< int > &used_timer_ids)
int get_phys_index(int physreg)
get index in param_globals::phys_region array for a certain phys region
void intersect_output_restriction(SF::vector< mesh_int_t > *&restr, const SF::vector< mesh_int_t > &selected_idx)
Intersect an existing output restriction with another local index set.
void check_nullspace_ok()
int postproc_recover_phie()
char * dupstr(const char *old_str)
int plot_protocols(const char *fname)
plot simulation protocols (I/O timers, stimuli, boundary conditions, etc)
void indices_from_geom_shape(SF::vector< mesh_int_t > &idx, const sf_mesh &mesh, const geom_shape shape, const bool nodal)
Populate vertex data with the vertices inside a defined box shape.
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
mesh_t
The enum identifying the different meshes we might want to load.
void setup_meshes(bool require_fibers=true)
Read in the reference mesh and use its data to populate all meshes registered in the mesh registry.
void get_time(double &tm)
bool mesh_is_registered(const mesh_t gt)
check wheter a SF mesh is set
bool parse_gridout_tags(hashmap::unordered_set< int > &output_tags)
Parse the gridout_tags idset into a unique set of region IDs.
void validate_gridout_tags(hashmap::unordered_set< int > &output_tags, const SF::vector< mesh_t > &mesh_ids)
Warn about selected gridout tags that are absent from the relevant meshes.
Basic_physic * get_physics(physic_t p, bool error_if_missing)
Convinience function to get a physics.
int get_rank(MPI_Comm comm=SF_COMM)
size_t renormalise_fibres(SF::vector< mesh_real_t > &fib, size_t l_numelem)
void destroy_physics()
Destroy all physics in the registry.
void ignore_extracellular_stim(Stimulus *st, int ns, int ignore)
void init_console_output(const timer_manager &tm, prog_stats &p)
tagreg_t
tag regions types. must be in line with carp.prm
V timing(V &t2, const V &t1)
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.
std::string get_basename(const std::string &path)
void build_tagged_nodal_output_restriction(sf_mesh &mesh, const hashmap::unordered_set< int > &output_tags, SF::vector< mesh_int_t > &output_idx, bool async)
Build a local output-vector restriction from mesh element tags.
void update_cwd()
save the current working directory to curdir so that we can switch back to it if needed.
void f_close(FILE_SPEC &f)
Close a FILE_SPEC.
void setup_petsc_err_log()
set up error logs for PETSc, so that it doesnt print errors to stderr.
void simulate()
Main simulate loop.
void log_runtime_apl_notice()
log the runtime APL notice for the simulator binary.
void parse_mesh_types()
Parse the phys_type CLI parameters and set up (empty) SF::meshdata meshes.
Top-level header of physics module.
#define PHYSREG_INTRA_ELEC
#define PETSC_TO_CANONICAL
Permute algebraic data from PETSC to canonical ordering.
#define ELEM_PETSC_TO_CANONICAL
Permute algebraic element data from PETSC to canonical ordering.
#define PHYSREG_EXTRA_ELEC
Simulator-level utility execution control functions.
#define STM_IGNORE_PSEUDO_BIDM
#define STM_IGNORE_MONODOMAIN
#define STM_IGNORE_BIDOMAIN
#define Extracellular_Ground
#define Extracellular_V_OL
const SF::vector< mesh_int_t > * restr_idx
when using asyncIO, here we store the different IDs associated to the vectors we output
SF::vector< mesh_int_t > restr_petsc_idx
pointer to index vector with nodal indices we restrict to.
int IO_id
pointer to data registered for output
long d_trigger_dur
discrete duration
const char * name
timer name
bool triggered
flag indicating trigger at current time step
for display execution progress and statistical data of electrical solve
double curr
current output wallclock time
double start
output start wallclock time
double last
last output wallclock time
SF::vector< mesh_int_t > restr_global_idx
pointer to index vector used for restricting output.
bool elem_flag
igb header we use for output
IGBheader igb
global canonical indices matching restr_idx.
const SF::vector< mesh_int_t > * restr_idx
pointer to data registered for output
SF::mixed_tuple< mesh_t, int > spec
flag whether the data is elements-wise