13 #include "petsc_utils.h"
19 #include "runtime.hpp"
27 #include <initializer_list>
29 #include <sys/resource.h>
33 #include "caliper/cali.h"
42 template<
class Assemble>
43 void assemble_with_exact_preallocation(std::initializer_list<sf_mat*> matrices, Assemble assemble)
45 bool any_supported =
false;
46 bool all_supported =
true;
47 bool saw_matrix =
false;
49 for(
sf_mat* mat : matrices) {
50 if(mat ==
nullptr)
continue;
53 const bool supported = mat->begin_exact_preallocation();
54 any_supported = any_supported || supported;
55 all_supported = all_supported && supported;
58 if(!saw_matrix)
return;
63 assert(any_supported == all_supported);
69 for(
sf_mat* mat : matrices) {
70 if(mat !=
nullptr) mat->finalize_exact_preallocation();
79 void log_emi_petsc_matrix_preallocation_report(std::initializer_list<std::pair<const char*, sf_mat*>> matrices)
82 PetscBool enabled = PETSC_FALSE;
83 PetscOptionsHasName(NULL, NULL,
"-mat_view_info", &enabled);
92 MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
94 log_msg(NULL, 0, 0,
"\nEMI PETSc matrix preallocation report");
95 log_msg(NULL, 0, 0,
"matrix alloc/used used_est allocated_est overalloc_est");
98 constexpr
double bytes_per_nz = double(
sizeof(PetscScalar) +
sizeof(PetscInt));
99 constexpr
double gib = 1024.0 * 1024.0 * 1024.0;
100 double total_used_gib = 0.0;
101 double total_allocated_gib = 0.0;
103 for(
const auto& item : matrices) {
104 auto* petsc_mat =
dynamic_cast<SF::petsc_matrix*
>(item.second);
105 if(petsc_mat ==
nullptr || petsc_mat->data ==
nullptr)
continue;
108 MatGetInfo(petsc_mat->data, MAT_GLOBAL_SUM, &info);
110 const double used =
static_cast<double>(info.nz_used);
111 const double allocated =
static_cast<double>(info.nz_allocated);
112 const double ratio = used > 0.0 ? allocated / used : 0.0;
113 const double used_gib = used * bytes_per_nz / gib;
114 const double allocated_gib = allocated * bytes_per_nz / gib;
115 const double overallocated_gib = allocated_gib - used_gib;
116 total_used_gib += used_gib;
117 total_allocated_gib += allocated_gib;
121 "%-18s alloc/used=%5.2f used_est=%6.2fG allocated_est=%6.2fG overalloc_est=%6.2fG",
122 item.first, ratio, used_gib, allocated_gib, overallocated_gib);
127 const double total_ratio = total_used_gib > 0.0 ? total_allocated_gib / total_used_gib : 0.0;
129 "%-18s alloc/used=%5.2f used_est=%6.2fG allocated_est=%6.2fG overalloc_est=%6.2fG",
130 "TOTAL:", total_ratio, total_used_gib, total_allocated_gib,
131 total_allocated_gib - total_used_gib);
135 getrusage(RUSAGE_SELF, &usage);
137 const double local_peak_rss_gib = double(usage.ru_maxrss) / gib;
139 const double local_peak_rss_gib = double(usage.ru_maxrss) * 1024.0 / gib;
141 double summed_peak_rss_gib = 0.0;
142 double max_rank_peak_rss_gib = 0.0;
143 MPI_Reduce(&local_peak_rss_gib, &summed_peak_rss_gib, 1, MPI_DOUBLE, MPI_SUM, 0, PETSC_COMM_WORLD);
144 MPI_Reduce(&local_peak_rss_gib, &max_rank_peak_rss_gib, 1, MPI_DOUBLE, MPI_MAX, 0, PETSC_COMM_WORLD);
148 "process peak RSS estimate: summed ranks=%6.2fG max rank=%6.2fG",
149 summed_peak_rss_gib, max_rank_peak_rss_gib);
151 "external peak memory from mprof --include-children is still the recommended whole-run reference.\n");
158 bool parse_emi_output_tags(
const char* tag_list,
163 static const char* parameter_name =
"gridout_tags";
164 const std::string spec = tag_list ? tag_list :
"";
166 std::vector<int> tags;
168 if(!opencarp::paramschema::parse_idset_spec(spec, &tags, &error)) {
169 log_msg(0, 5,
ECHO,
"Could not parse %s: %s.", parameter_name, error.c_str());
173 if(tags.size() == 0)
return false;
176 output_tags.
insert(tags.begin(), tags.end());
179 for(
int tag_id : output_tags) {
180 if(extra_tags.
count(tag_id) == 0 && intra_tags.
count(tag_id) == 0) {
185 if(missing_tags.
size()) {
188 std::stringstream msg;
189 for(
size_t i = 0; i < missing_tags.
size(); i++) {
191 msg << missing_tags[i];
195 "Warning: ignoring %s tag(s) not listed in the EMI extra/intra tag sets: %s.",
196 parameter_name, msg.str().c_str());
198 for(
int tag_id : missing_tags)
199 output_tags.erase(tag_id);
201 if(output_tags.size() == 0) {
202 log_msg(0, 5,
ECHO,
"%s did not match any EMI extra/intra tag.", parameter_name);
207 log_msg(0, 0, 0,
"Restricting EMI output to %zu tag(s) from %s.",
208 output_tags.size(), parameter_name);
226 struct restricted_point_record {
231 std::string gather_rank_text_root(
const std::string& local_text, MPI_Comm comm)
233 int rank = 0, size = 0;
234 MPI_Comm_rank(comm, &rank);
235 MPI_Comm_size(comm, &size);
237 std::string all_text;
239 all_text = local_text;
241 for(
int pid = 1; pid < size; pid++) {
243 size_t len = local_text.size();
244 MPI_Send(&len,
sizeof(
size_t), MPI_BYTE, 0,
SF_MPITAG, comm);
246 MPI_Send(local_text.data(),
static_cast<int>(len), MPI_CHAR, 0,
SF_MPITAG, comm);
247 }
else if(rank == 0) {
250 MPI_Recv(&len,
sizeof(
size_t), MPI_BYTE, pid,
SF_MPITAG, comm, &stat);
252 size_t offset = all_text.size();
253 all_text.resize(offset + len);
254 MPI_Recv(all_text.data() + offset,
static_cast<int>(len), MPI_CHAR, pid,
SF_MPITAG, comm, &stat);
262 struct direct_element_record {
267 std::string elem_line;
268 std::string fib_line;
271 void write_direct_restricted_mesh_text_root(
const sf_mesh& mesh,
272 const std::string& output_file,
275 MPI_Comm comm = mesh.comm;
276 int rank = 0, size = 0;
277 MPI_Comm_rank(comm, &rank);
278 MPI_Comm_size(comm, &size);
282 const bool write_fibers = mesh.fib.
size() == mesh.l_numelem * 3;
285 std::ostringstream elem_records;
287 for(
size_t eidx = 0; eidx < mesh.l_numelem; eidx++) {
288 if(!keep_elem[eidx])
continue;
290 const char* type_name = elem_type_name(mesh.type[eidx]);
291 if(type_name[0] ==
'\0') {
292 log_msg(0, 5,
ECHO,
"Unsupported element type in restricted EMI output.");
296 elem_records << elem_ref[eidx] <<
'\t' << type_name <<
'\t' << mesh.tag[eidx] <<
'\t';
297 for(
mesh_int_t j = mesh.dsp[eidx]; j < mesh.dsp[eidx + 1]; j++) {
299 elem_records << node_ref[local_node] <<
' ';
301 restricted_point_record point;
302 point.idx = node_ref[local_node];
303 point.xyz[0] = mesh.xyz[local_node * 3 + 0];
304 point.xyz[1] = mesh.xyz[local_node * 3 + 1];
305 point.xyz[2] = mesh.xyz[local_node * 3 + 2];
309 elem_records <<
'\t';
311 elem_records << mesh.fib[eidx * 3 + 0] <<
' '
312 << mesh.fib[eidx * 3 + 1] <<
' '
313 << mesh.fib[eidx * 3 + 2];
314 if(mesh.she.size() == mesh.fib.size()) {
315 elem_records <<
' ' << mesh.she[eidx * 3 + 0] <<
' '
316 << mesh.she[eidx * 3 + 1] <<
' '
317 << mesh.she[eidx * 3 + 2];
320 elem_records <<
'\n';
323 std::sort(local_points.
begin(), local_points.
end(),
324 [](
const restricted_point_record& lhs,
const restricted_point_record& rhs) {
325 return lhs.idx < rhs.idx;
327 auto unique_end = std::unique(local_points.
begin(), local_points.
end(),
328 [](
const restricted_point_record& lhs,
329 const restricted_point_record& rhs) {
330 return lhs.idx == rhs.idx;
332 local_points.
resize(unique_end - local_points.
begin());
336 all_points = local_points;
338 for(
int pid = 1; pid < size; pid++) {
340 size_t len = local_points.
size();
341 MPI_Send(&len,
sizeof(
size_t), MPI_BYTE, 0,
SF_MPITAG, comm);
343 MPI_Send(local_points.
data(),
static_cast<int>(len *
sizeof(restricted_point_record)),
345 }
else if(rank == 0) {
348 MPI_Recv(&len,
sizeof(
size_t), MPI_BYTE, pid,
SF_MPITAG, comm, &stat);
350 size_t offset = all_points.
size();
351 all_points.
resize(offset + len);
352 MPI_Recv(all_points.
data() + offset,
353 static_cast<int>(len *
sizeof(restricted_point_record)),
359 const std::string all_elem_records = gather_rank_text_root(elem_records.str(), comm);
360 if(rank != 0)
return;
362 std::sort(all_points.
begin(), all_points.
end(),
363 [](
const restricted_point_record& lhs,
const restricted_point_record& rhs) {
364 return lhs.idx < rhs.idx;
366 unique_end = std::unique(all_points.
begin(), all_points.
end(),
367 [](
const restricted_point_record& lhs,
368 const restricted_point_record& rhs) {
369 return lhs.idx == rhs.idx;
371 all_points.
resize(unique_end - all_points.
begin());
375 for(
size_t i = 0; i < all_points.
size(); i++)
376 point_map[all_points[i].idx] =
static_cast<mesh_int_t>(i);
379 std::istringstream input(all_elem_records);
381 while(std::getline(input, line)) {
382 if(line.empty())
continue;
384 std::istringstream rec(line);
385 std::string type_name;
386 direct_element_record elem;
387 rec >> elem.idx >> type_name >> elem.tag;
392 std::getline(rec, nodes,
'\t');
393 std::istringstream node_input(nodes);
395 while(node_input >> node)
396 elem.node_ref.push_back(node);
398 std::getline(rec, elem.fib_line);
402 if(elements.
size() == 0) {
403 log_msg(0, 5,
ECHO,
"Restricted EMI output mesh \"%s\" is empty.", mesh.name.c_str());
407 for(direct_element_record& elem : elements) {
408 std::ostringstream elem_line;
409 elem_line << elem_type_name(elem.type);
411 auto it = point_map.
find(ref_node);
412 if(it == point_map.
end()) {
413 log_msg(0, 5,
ECHO,
"Restricted EMI output mesh element references an unknown point.");
416 elem_line <<
' ' << it->second;
418 elem_line <<
' ' << elem.tag;
419 elem.elem_line = elem_line.str();
422 std::sort(elements.begin(), elements.end(),
423 [](
const direct_element_record& lhs,
const direct_element_record& rhs) {
424 if(lhs.idx != rhs.idx) return lhs.idx < rhs.idx;
425 if(lhs.elem_line != rhs.elem_line) return lhs.elem_line < rhs.elem_line;
426 return lhs.fib_line < rhs.fib_line;
429 FILE* pts_fd = fopen((output_file +
".pts").c_str(),
"w");
430 if(pts_fd ==
nullptr) {
431 log_msg(0, 5,
ECHO,
"Could not open restricted EMI output file %s.pts.", output_file.c_str());
434 fprintf(pts_fd,
"%zu\n", all_points.
size());
435 for(
const restricted_point_record& point : all_points)
436 fprintf(pts_fd,
"%.16g %.16g %.16g\n",
437 static_cast<double>(point.xyz[0]),
438 static_cast<double>(point.xyz[1]),
439 static_cast<double>(point.xyz[2]));
442 FILE* elem_fd = fopen((output_file +
".elem").c_str(),
"w");
443 if(elem_fd ==
nullptr) {
444 log_msg(0, 5,
ECHO,
"Could not open restricted EMI output file %s.elem.", output_file.c_str());
447 fprintf(elem_fd,
"%zu\n", elements.size());
448 for(
const direct_element_record& elem : elements) {
449 fputs(elem.elem_line.c_str(), elem_fd);
450 fputc(
'\n', elem_fd);
455 FILE* lon_fd = fopen((output_file +
".lon").c_str(),
"w");
456 if(lon_fd ==
nullptr) {
457 log_msg(0, 5,
ECHO,
"Could not open restricted EMI output file %s.lon.", output_file.c_str());
460 for(
const direct_element_record& elem : elements) {
461 fputs(elem.fib_line.c_str(), lon_fd);
468 void build_emi_volume_output_restriction(
sf_mesh& mesh,
475 for(
size_t eidx = 0; eidx < mesh.l_numelem; eidx++) {
476 if(output_tags.
count(mesh.tag[eidx]) == 0)
continue;
478 for(
mesh_int_t j = mesh.dsp[eidx]; j < mesh.dsp[eidx + 1]; j++)
479 selected_nodes.
push_back(nbr[mesh.con[j]]);
487 void build_emi_surface_output_restriction(
sf_mesh& mesh,
498 for(
size_t eidx = 0; eidx < mesh.l_numelem; eidx++) {
499 bool keep = output_tags.
count(mesh.tag[eidx]) != 0;
500 auto it = face_tags.find(eidx);
501 if(it != face_tags.end()) {
503 output_tags.
count(
static_cast<int>(it->second.first)) != 0 ||
504 output_tags.
count(
static_cast<int>(it->second.second)) != 0;
507 if(keep && nbr[eidx] >= start && nbr[eidx] < stop)
508 vm_output_idx.
push_back(nbr[eidx] - start);
516 void write_emi_output_mesh(
const sf_mesh& mesh,
518 const std::string& output_file,
519 const char* full_mesh_name,
523 for(
size_t eidx = 0; eidx < mesh.l_numelem; eidx++)
524 keep_elem[eidx] = keep(eidx);
527 write_direct_restricted_mesh_text_root(mesh, output_file, keep_elem);
532 out_mesh.
name = mesh.name;
535 if(out_mesh.g_numelem == 0) {
536 log_msg(0, 5,
ECHO,
"Restricted EMI output mesh \"%s\" is empty.", full_mesh_name);
544 std::list<sf_mesh*> meshlist;
545 meshlist.push_back(&out_mesh);
550 out_mesh.generate_par_layout();
559 struct emifld_header {
566 static_assert(
sizeof(emifld_header) == 32,
"emifld_header must be tightly packed");
568 const char EMIFLD_MAGIC[8] = {
'E',
'M',
'I',
'F',
'L',
'D',
'\0',
'\0'};
569 const uint32_t EMIFLD_VERSION = 1;
572 bool fnv1a_file(
const char* path, uint64_t& out)
574 constexpr uint64_t kFNVOffsetBasis = 0xcbf29ce484222325ULL;
575 constexpr uint64_t kFNVPrime = 0x100000001b3ULL;
576 FILE* f = fopen(path,
"rb");
577 if (!f)
return false;
578 uint64_t h = kFNVOffsetBasis;
579 unsigned char buf[1 << 16];
581 while ((n = fread(buf, 1,
sizeof buf, f)) > 0)
582 for (
size_t i = 0; i < n; i++) { h ^= buf[i]; h *= kFNVPrime; }
583 const bool ok = !ferror(f);
591 void log_mesh_local_element_ranges(
const sf_mesh& emi_mesh,
592 const sf_mesh& emi_surfmesh_w_counter_face,
593 const sf_mesh& emi_surfmesh_unique_face)
597 MPI_Comm_rank(emi_surfmesh_w_counter_face.comm, &rank);
598 MPI_Comm_size(emi_surfmesh_w_counter_face.comm, &comm_size);
600 const size_t local_emi_elems = emi_mesh.l_numelem;
601 const size_t local_both_face_elems = emi_surfmesh_w_counter_face.l_numelem;
602 const size_t local_unique_face_elems = emi_surfmesh_unique_face.l_numelem;
604 std::vector<size_t> all_emi_elems;
605 std::vector<size_t> all_both_face_elems;
606 std::vector<size_t> all_unique_face_elems;
608 all_emi_elems.resize(comm_size, 0);
609 all_both_face_elems.resize(comm_size, 0);
610 all_unique_face_elems.resize(comm_size, 0);
613 const MPI_Datatype size_mpi_t = mpi_datatype<size_t>();
614 MPI_Gather(&local_emi_elems, 1, size_mpi_t,
615 rank == 0 ? all_emi_elems.data() :
nullptr, 1, size_mpi_t,
616 0, emi_surfmesh_w_counter_face.comm);
617 MPI_Gather(&local_both_face_elems, 1, size_mpi_t,
618 rank == 0 ? all_both_face_elems.data() :
nullptr, 1, size_mpi_t,
619 0, emi_surfmesh_w_counter_face.comm);
620 MPI_Gather(&local_unique_face_elems, 1, size_mpi_t,
621 rank == 0 ? all_unique_face_elems.data() :
nullptr, 1, size_mpi_t,
622 0, emi_surfmesh_w_counter_face.comm);
624 if (rank != 0)
return;
626 const auto print_min_max = [](
const char* label,
const std::vector<size_t>& counts) {
627 if (counts.empty())
return;
629 size_t min_val = counts[0];
630 size_t max_val = counts[0];
634 for (
int r = 1; r < static_cast<int>(counts.size()); ++r) {
635 if (counts[r] < min_val) {
639 if (counts[r] > max_val) {
645 log_msg(NULL, 0, 0,
" %s: \n\t\t min=%zu on rank=%d, \n\t\t max=%zu on rank=%d\n",
646 label, min_val, min_rank, max_val, max_rank);
648 log_msg(NULL, 0, 0,
"\n**********************************");
649 log_msg(NULL, 0, 0,
"min/max number of local-element ranges:");
650 print_min_max(
"emi_mesh", all_emi_elems);
651 print_min_max(
"emi_surfmesh_w_counter_face", all_both_face_elems);
652 print_min_max(
"emi_surfmesh_unique_face", all_unique_face_elems);
653 log_msg(NULL, 0, 0,
"**********************************");
656 #ifdef EMI_DEBUG_MESH
663 if (param_globals::flavor != std::string(
"petsc"))
return;
665 auto* petsc_mat =
dynamic_cast<SF::petsc_matrix*
>(mat);
666 if (petsc_mat ==
nullptr)
return;
668 Vec x = NULL, y = NULL;
669 MatCreateVecs(petsc_mat->data, &x, &y);
671 PetscRandom rnd = NULL;
672 PetscRandomCreate(PETSC_COMM_WORLD, &rnd);
673 PetscRandomSetFromOptions(rnd);
676 MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
678 PetscReal min_q = PETSC_MAX_REAL;
679 PetscReal max_q = -PETSC_MAX_REAL;
680 PetscInt nonpos_count = 0;
682 for (
int i = 0; i < num_trials; ++i) {
683 VecSetRandom(x, rnd);
684 MatMult(petsc_mat->data, x, y);
686 PetscScalar q_scalar = 0.0;
687 VecDot(x, y, &q_scalar);
689 const PetscReal q = PetscRealPart(q_scalar);
692 if (q <= 0.0) nonpos_count++;
696 PetscPrintf(PETSC_COMM_SELF,
697 "%s: SPD probe with %d random vectors: min(x^T A x)=%g, max(x^T A x)=%g, nonpositive=%d\n",
698 stage, num_trials,
double(min_q),
double(max_q),
int(nonpos_count));
701 PetscRandomDestroy(&rnd);
706 PetscScalar emi_probe_vector_entry(
const PetscInt gid,
const int probe_id)
708 const double x =
static_cast<double>(gid + 1);
712 return std::sin(1.0e-3 * x) + 0.5 * std::cos(3.0e-3 * x);
714 return std::cos(7.0e-4 * x) - 0.35 * std::sin(2.0e-3 * x);
716 return 0.75 * std::sin(1.3e-3 * x) + 0.25 * std::cos(4.0e-3 * x);
726 if (param_globals::flavor != std::string(
"petsc"))
return;
728 auto* petsc_mat =
dynamic_cast<SF::petsc_matrix*
>(mat);
729 if (petsc_mat ==
nullptr)
return;
731 Vec x = NULL, y = NULL;
732 MatCreateVecs(petsc_mat->data, &x, &y);
734 PetscInt i_start = 0, i_end = 0;
735 VecGetOwnershipRange(x, &i_start, &i_end);
737 PetscScalar* x_arr = NULL;
739 MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
741 for (
int probe_id = 0; probe_id < num_probes; ++probe_id) {
742 VecGetArray(x, &x_arr);
743 for (PetscInt i = i_start; i < i_end; ++i) {
744 x_arr[i - i_start] = emi_probe_vector_entry(i, probe_id);
746 VecRestoreArray(x, &x_arr);
748 MatMult(petsc_mat->data, x, y);
750 PetscReal y_norm2 = 0.0;
751 PetscReal y_norminf = 0.0;
752 PetscScalar y_sum = 0.0;
753 PetscScalar xAy = 0.0;
754 VecNorm(y, NORM_2, &y_norm2);
755 VecNorm(y, NORM_INFINITY, &y_norminf);
759 PetscScalar weighted_checksum_local = 0.0;
760 const PetscScalar* y_arr = NULL;
761 VecGetArrayRead(y, &y_arr);
762 for (PetscInt i = i_start; i < i_end; ++i) {
763 const PetscScalar weight =
static_cast<PetscScalar
>(i + 1);
764 weighted_checksum_local += weight * y_arr[i - i_start];
766 VecRestoreArrayRead(y, &y_arr);
768 PetscScalar weighted_checksum = 0.0;
769 MPI_Allreduce(&weighted_checksum_local, &weighted_checksum, 1, MPIU_SCALAR, MPI_SUM, PETSC_COMM_WORLD);
772 PetscPrintf(PETSC_COMM_SELF,
773 "%s: operator probe %d ||Ax||_2=%g, ||Ax||_inf=%g, sum(Ax)=%g, x^T A x=%g, weighted_checksum=%g\n",
774 stage, probe_id + 1,
double(y_norm2),
double(y_norminf),
double(PetscRealPart(y_sum)),
775 double(PetscRealPart(xAy)),
double(PetscRealPart(weighted_checksum)));
786 if (param_globals::flavor != std::string(
"petsc"))
return;
788 auto* petsc_vec =
dynamic_cast<SF::petsc_vector*
>(vec);
789 if (petsc_vec ==
nullptr)
return;
791 PetscReal norm2 = 0.0;
792 PetscReal norminf = 0.0;
793 PetscScalar
sum = 0.0;
794 VecNorm(petsc_vec->data, NORM_2, &norm2);
795 VecNorm(petsc_vec->data, NORM_INFINITY, &norminf);
796 VecSum(petsc_vec->data, &
sum);
798 PetscInt i_start = 0, i_end = 0;
799 VecGetOwnershipRange(petsc_vec->data, &i_start, &i_end);
801 PetscScalar weighted_checksum_local = 0.0;
802 const PetscScalar* arr = NULL;
803 VecGetArrayRead(petsc_vec->data, &arr);
804 for (PetscInt i = i_start; i < i_end; ++i) {
805 const PetscScalar weight =
static_cast<PetscScalar
>(i + 1);
806 weighted_checksum_local += weight * arr[i - i_start];
808 VecRestoreArrayRead(petsc_vec->data, &arr);
810 PetscScalar weighted_checksum = 0.0;
811 MPI_Allreduce(&weighted_checksum_local, &weighted_checksum, 1, MPIU_SCALAR, MPI_SUM, PETSC_COMM_WORLD);
814 MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
816 PetscPrintf(PETSC_COMM_SELF,
817 "%s: rhs probe ||b||_2=%g, ||b||_inf=%g, sum(b)=%g, weighted_checksum=%g\n",
818 stage,
double(norm2),
double(norminf),
double(PetscRealPart(
sum)),
819 double(PetscRealPart(weighted_checksum)));
828 if (param_globals::flavor != std::string(
"petsc"))
return;
830 auto* petsc_mat =
dynamic_cast<SF::petsc_matrix*
>(mat);
831 auto* petsc_vec =
dynamic_cast<SF::petsc_vector*
>(vec);
832 if (petsc_mat ==
nullptr || petsc_vec ==
nullptr)
return;
834 Vec x = NULL, ax = NULL, residual = NULL;
835 MatCreateVecs(petsc_mat->data, &x, &ax);
836 VecDuplicate(ax, &residual);
838 PetscInt i_start = 0, i_end = 0;
839 VecGetOwnershipRange(x, &i_start, &i_end);
842 MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
844 for (
int probe_id = 0; probe_id < num_probes; ++probe_id) {
845 PetscScalar* x_arr = NULL;
846 VecGetArray(x, &x_arr);
847 for (PetscInt i = i_start; i < i_end; ++i) {
848 x_arr[i - i_start] = emi_probe_vector_entry(i, probe_id);
850 VecRestoreArray(x, &x_arr);
852 MatMult(petsc_mat->data, x, ax);
853 VecWAXPY(residual, -1.0, petsc_vec->data, ax);
855 PetscReal residual_norm2 = 0.0;
856 PetscReal residual_norminf = 0.0;
857 PetscScalar residual_sum = 0.0;
858 PetscScalar xTResidual = 0.0;
859 VecNorm(residual, NORM_2, &residual_norm2);
860 VecNorm(residual, NORM_INFINITY, &residual_norminf);
861 VecSum(residual, &residual_sum);
862 VecDot(x, residual, &xTResidual);
864 PetscScalar weighted_checksum_local = 0.0;
865 const PetscScalar* residual_arr = NULL;
866 VecGetArrayRead(residual, &residual_arr);
867 for (PetscInt i = i_start; i < i_end; ++i) {
868 const PetscScalar weight =
static_cast<PetscScalar
>(i + 1);
869 weighted_checksum_local += weight * residual_arr[i - i_start];
871 VecRestoreArrayRead(residual, &residual_arr);
873 PetscScalar weighted_checksum = 0.0;
874 MPI_Allreduce(&weighted_checksum_local, &weighted_checksum, 1, MPIU_SCALAR, MPI_SUM, PETSC_COMM_WORLD);
877 PetscPrintf(PETSC_COMM_SELF,
878 "%s: linear-system probe %d ||Ax-b||_2=%g, ||Ax-b||_inf=%g, sum(Ax-b)=%g, x^T(Ax-b)=%g, weighted_checksum=%g\n",
879 stage, probe_id + 1,
double(residual_norm2),
double(residual_norminf),
880 double(PetscRealPart(residual_sum)),
double(PetscRealPart(xTResidual)),
881 double(PetscRealPart(weighted_checksum)));
887 VecDestroy(&residual);
902 MaterialType *m = mtype;
905 m->regions.resize(param_globals::num_gregions);
907 const char* grid_name =
"emi_grid_domain";
908 log_msg(logger, 0, 0,
"Setting up %s tissue poperties for %d regions ..", grid_name,
909 param_globals::num_gregions);
912 RegionSpecs* reg = m->regions.data();
918 for (
size_t i=0; i<m->regions.size(); i++)
920 for (
int j=0;j<param_globals::gregion[i].num_IDs;j++)
922 int tag = param_globals::gregion[i].ID[j];
925 if(extra_tags_default.
find(tag) != extra_tags_default.
end())
926 extra_tags_default.
erase(tag);
928 if(intra_tags_default.
find(tag) != intra_tags_default.
end())
929 intra_tags_default.
erase(tag);
933 for (
size_t i=0; i<m->regions.size(); i++, reg++)
935 if(!strcmp(param_globals::gregion[i].name,
"")) {
936 snprintf(buf,
sizeof buf,
", gregion_%d",
int(i));
937 param_globals::gregion[i].name =
dupstr(buf);
941 reg->regname = strdup(param_globals::gregion[i].name);
945 reg->nsubregs = extra_tags_default.
size();
947 reg->nsubregs = intra_tags_default.
size();
949 reg->nsubregs = param_globals::gregion[i].num_IDs;
952 reg->subregtags = NULL;
955 reg->subregtags =
new int[reg->nsubregs];
959 for (
int tag : extra_tags_default) {
960 reg->subregtags[j] = tag;
966 for (
int tag : intra_tags_default) {
967 reg->subregtags[j] = tag;
972 for (
int j=0;j<reg->nsubregs;j++)
973 reg->subregtags[j] = param_globals::gregion[i].ID[j];
978 elecMaterial *emat =
new elecMaterial();
982 emat->InVal[0] = param_globals::gregion[i].g_bath;
983 emat->InVal[1] = param_globals::gregion[i].g_bath;
984 emat->InVal[2] = param_globals::gregion[i].g_bath;
986 emat->ExVal[0] = param_globals::gregion[i].g_bath;
987 emat->ExVal[1] = param_globals::gregion[i].g_bath;
988 emat->ExVal[2] = param_globals::gregion[i].g_bath;
990 emat->BathVal[0] = param_globals::gregion[i].g_bath;
991 emat->BathVal[1] = param_globals::gregion[i].g_bath;
992 emat->BathVal[2] = param_globals::gregion[i].g_bath;
995 for (
int j=0; j<3; j++) {
996 emat->InVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
997 emat->ExVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
998 emat->BathVal[j] *= 1e-3 * param_globals::gregion[i].g_mult;
1000 reg->material = emat;
1003 if (strlen(param_globals::gi_scale_vec))
1007 void parabolic_solver_emi::init()
1012 const int log_flag = param_globals::output_level > 1 ?
ECHO : 0;
1013 const auto log_init_timing = [&](
const char* label,
double start) {
1014 log_msg(NULL, 0, log_flag,
"EMI solver init: %s in %.5f seconds.", label,
float(MPI_Wtime() - start));
1017 double phase_t = MPI_Wtime();
1018 stats.init_logger(
"par_stats.dat");
1022 log_init_timing(
"linear solver object", phase_t);
1033 phase_t = MPI_Wtime();
1035 log_init_timing(
"maximum nodal edge counts", phase_t);
1038 MPI_Comm_rank(emi_surfmesh_w_counter_face.comm, &rank);
1048 phase_t = MPI_Wtime();
1055 SF::init_vector(&vb_both_face, emi_surfmesh_w_counter_face, dpn, alg_surface_type);
1056 SF::init_vector(&vb_unique_face, emi_surfmesh_unique_face, dpn, alg_surface_type);
1057 SF::init_vector(&Ib_both_face, emi_surfmesh_w_counter_face, dpn, alg_surface_type);
1058 SF::init_vector(&Ib_unique_face, emi_surfmesh_unique_face, dpn, alg_surface_type);
1059 log_init_timing(
"vectors", phase_t);
1065 const bool use_petsc_exact_preallocation = param_globals::flavor == std::string(
"petsc");
1066 const int petsc_initial_prealloc = 1;
1070 mesh_int_t M = emi_surfmesh_w_counter_face.g_numelem;
1072 mesh_int_t m = emi_surfmesh_w_counter_face.l_numelem;
1073 mesh_int_t m_one_side = emi_surfmesh_one_side.l_numelem;
1074 mesh_int_t M_one_side = emi_surfmesh_one_side.g_numelem;
1075 mesh_int_t m_unique_face = emi_surfmesh_unique_face.l_numelem;
1076 mesh_int_t M_unique_face = emi_surfmesh_unique_face.g_numelem;
1079 if (param_globals::output_level > 1) {
1080 log_msg(NULL, 0, 0,
"\n**********************************");
1081 log_msg(NULL, 0, 0,
"#elements of emi surfmesh unique face: %zu", emi_surfmesh_unique_face.g_numelem);
1082 log_msg(NULL, 0, 0,
"#elements of emi surfmesh one side: %zu", emi_surfmesh_one_side.g_numelem);
1083 log_msg(NULL, 0, 0,
"#elements of emi surfmesh: %zu", emi_surfmesh_w_counter_face.g_numelem);
1084 log_msg(NULL, 0, 0,
"#elements of emi mesh: %zu", emi_mesh.g_numelem);
1085 log_msg(NULL, 0, 0,
"#dofs for emi_mesh: %zu", emi_mesh.g_numpts);
1086 log_msg(NULL, 0, 0,
"#max_row_entries_emi: %zu", max_row_entries_emi);
1087 log_msg(NULL, 0, 0,
"**********************************\n");
1088 log_mesh_local_element_ranges(emi_mesh, emi_surfmesh_w_counter_face, emi_surfmesh_unique_face);
1092 SF::layout_from_count<long int>(emi_surfmesh_w_counter_face.l_numelem, layout, emi_surfmesh_w_counter_face.comm);
1094 mesh_int_t n_l = emi_mesh.pl.algebraic_layout()[rank];
1098 SF::layout_from_count<long int>(emi_surfmesh_one_side.l_numelem, layout_one_side, emi_surfmesh_one_side.comm);
1099 mesh_int_t m_one_side_l = layout_one_side[rank];
1102 SF::layout_from_count<long int>(emi_surfmesh_unique_face.l_numelem, layout_unique_face, emi_surfmesh_unique_face.comm);
1103 mesh_int_t m_unique_face_l = layout_unique_face[rank];
1111 phase_t = MPI_Wtime();
1113 B->init(M, N, m, n, m_l, use_petsc_exact_preallocation ? petsc_initial_prealloc : max_row_entries_emi*2);
1116 Bi->init(M, N, m, n, m_l, use_petsc_exact_preallocation ? petsc_initial_prealloc : max_row_entries_emi*2);
1119 BsM->init(N, M, n, m, n_l, use_petsc_exact_preallocation ? petsc_initial_prealloc : max_row_entries_emi*2);
1121 log_init_timing(
"EMI coupling matrices", phase_t);
1124 phase_t = MPI_Wtime();
1125 SF::construct_direct_unique_both_operators(operator_unique_to_both_faces,
1126 operator_both_to_unique_face,
1127 map_elem_uniqueFace_to_elem_bothface,
1128 map_elem_uniqueFace_to_elem_oneface,
1129 vec_both_to_one_face,
1130 emi_surfmesh_w_counter_face,
1131 emi_surfmesh_unique_face,
1132 max_row_entries_emi,
1135 log_init_timing(
"unique/both face transfer operators", phase_t);
1138 phase_t = MPI_Wtime();
1139 assemble_with_exact_preallocation({B, Bi, BsM}, [&]() {
1140 SF::assemble_restrict_operator(*B, *Bi, *BsM, elemTag_surface_w_counter_mesh, map_vertex_tag_to_dof_petsc, line_face, tri_face, quad_face, emi_surfmesh_w_counter_face, emi_mesh,
UM2_to_CM2);
1142 log_init_timing(
"restriction operators", phase_t);
1147 phase_t = MPI_Wtime();
1155 lhs_emi->init(emi_mesh, dpn, dpn, use_petsc_exact_preallocation ? petsc_initial_prealloc : max_row_entries_emi*3);
1156 stiffness_emi->init(emi_mesh, dpn, dpn, use_petsc_exact_preallocation ? petsc_initial_prealloc : max_row_entries_emi*2);
1157 mass_emi->init(emi_mesh, dpn, dpn, use_petsc_exact_preallocation ? petsc_initial_prealloc : max_row_entries_emi*3);
1158 mass_surf_emi->init(emi_mesh, dpn, dpn, use_petsc_exact_preallocation ? petsc_initial_prealloc : max_row_entries_emi*3);
1159 log_init_timing(
"system matrices", phase_t);
1162 #ifdef EMI_DEBUG_MESH
1165 MPI_Comm_rank(emi_mesh.comm, &local_rank);
1167 fprintf(stderr,
"RANK %d MESH SIZES: one_side=%zu, counter=%zu, unique=%zu\n",
1168 local_rank, emi_surfmesh_one_side.l_numelem,
1169 emi_surfmesh_w_counter_face.l_numelem, emi_surfmesh_unique_face.l_numelem);
1171 fprintf(stderr,
"RANK %d MAP SIZES: uniqueFace_to_oneface=%zu\n",
1172 local_rank, map_elem_uniqueFace_to_elem_oneface.size());
1177 decltype(map_elem_uniqueFace_to_elem_oneface)().swap(map_elem_uniqueFace_to_elem_oneface);
1178 decltype(map_elem_uniqueFace_to_elem_bothface)().swap(map_elem_uniqueFace_to_elem_bothface);
1184 phase_t = MPI_Wtime();
1189 if(!(vb_ptr != NULL && Ib_ptr != NULL)) {
1190 log_msg(0,5,0,
"%s error: global Vb and Ib vectors not properly set up! Ionics seem invalid! Aborting!",
1196 vb->shallow_copy(*vb_ptr);
1198 Ib->shallow_copy(*Ib_ptr);
1200 parab_tech =
static_cast<parabolic_solver_emi::parabolic_t
>(param_globals::parab_solve_emi);
1201 log_init_timing(
"ionic face vectors", phase_t);
1204 log_msg(NULL, 0, log_flag,
"EMI solver init total in %.5f seconds.",
float(dur));
1210 double start, end, period;
1213 mass_integrator mass_integ;
1214 mass_integrator mass_integ_emi;
1217 int log_flag = param_globals::output_level > 1 ?
ECHO : 0;
1218 MaterialType & mt = mtype[0];
1220 const bool use_petsc_exact_preallocation = param_globals::flavor == std::string(
"petsc");
1221 const bool reuse_petsc_fem_preallocation = use_petsc_exact_preallocation && fem_matrices_exact_preallocated;
1236 log_msg(NULL, 0, 0,
"assemble stiffness matrix");
1238 elec_stiffness_integrator stfn_integ_emi(mt);
1239 auto assemble_stiffness_emi = [&]() {
1240 stiffness_emi->zero();
1243 if(reuse_petsc_fem_preallocation) {
1244 assemble_stiffness_emi();
1246 assemble_with_exact_preallocation({stiffness_emi}, assemble_stiffness_emi);
1249 log_msg(logger,0,log_flag,
"Computed parabolic stiffness matrix in %.5f seconds.",
float(dur));
1251 log_msg(NULL, 0, 0,
"assemble mass matrix on the volumetric mesh");
1253 mass_integrator mass_integ;
1254 auto assemble_mass_emi = [&]() {
1258 auto* petsc_mass_emi = use_petsc_exact_preallocation ?
dynamic_cast<SF::petsc_matrix*
>(mass_emi) :
nullptr;
1259 auto* petsc_stiffness_emi = use_petsc_exact_preallocation ?
dynamic_cast<SF::petsc_matrix*
>(stiffness_emi) :
nullptr;
1260 if(reuse_petsc_fem_preallocation) {
1261 assemble_mass_emi();
1262 }
else if(petsc_mass_emi !=
nullptr && petsc_stiffness_emi !=
nullptr) {
1264 petsc_mass_emi->duplicate_pattern(*petsc_stiffness_emi);
1265 assemble_mass_emi();
1267 assemble_with_exact_preallocation({mass_emi}, assemble_mass_emi);
1270 log_msg(logger,0,log_flag,
"Computed volumetric mass matrix in %.5f seconds.",
float(dur));
1272 log_msg(NULL, 0, 0,
"assemble LHS matrix and mass matrix on the surface mesh");
1274 auto assemble_lhs_and_surface_mass = [&]() {
1276 mass_surf_emi->zero();
1278 SF::assemble_lhs_emi(*lhs_emi, *mass_surf_emi, mesh, emi_surfmesh_w_counter_face, map_vertex_tag_to_dof_petsc, line_face, tri_face, quad_face, stfn_integ_emi, mass_integ_emi, -1.,
UM2_to_CM2 / Dt);
1280 if(reuse_petsc_fem_preallocation) {
1281 assemble_lhs_and_surface_mass();
1283 assemble_with_exact_preallocation({lhs_emi, mass_surf_emi}, assemble_lhs_and_surface_mass);
1286 log_msg(logger,0,log_flag,
"Computed parabolic mass matrix in %.5f seconds.",
float(dur));
1290 bool same_nonzero =
false;
1294 log_msg(logger,0,log_flag,
"lhs matrix enforcing Dirichlet boundaries.");
1298 dbc =
new dbc_manager(*lhs_emi, stimuli);
1300 dbc->recompute_dbcs();
1302 dbc->enforce_dbc_lhs();
1304 log_msg(logger,0,log_flag,
"lhs matrix Dirichlet enforcing done in %.5f seconds.",
float(dur));
1307 log_msg(logger,0,
ECHO,
"without enforcing Dirichlet boundaries on the lhs matrix!");
1309 phie_mat_has_nullspace =
true;
1313 log_emi_petsc_matrix_preallocation_report({
1317 {
"unique_to_both:", operator_unique_to_both_faces},
1318 {
"both_to_unique:", operator_both_to_unique_face},
1319 {
"stiffness_emi:", stiffness_emi},
1320 {
"mass_emi:", mass_emi},
1321 {
"mass_surf_emi:", mass_surf_emi},
1322 {
"lhs_emi:", lhs_emi},
1324 if(use_petsc_exact_preallocation) fem_matrices_exact_preallocated =
true;
1326 setup_linear_solver(logger);
1328 log_msg(logger,0,log_flag,
"Initializing parabolic solver in %.5f seconds.",
float(dur));
1331 period =
timing(end, start);
1334 void parabolic_solver_emi::setup_linear_solver(
FILE_SPEC logger)
1336 tol = param_globals::cg_tol_parab;
1337 max_it = param_globals::cg_maxit_parab;
1339 std::string default_opts;
1340 std::string solver_file;
1341 solver_file = param_globals::parab_options_file;
1342 if (param_globals::flavor == std::string(
"ginkgo")) {
1343 default_opts = std::string(
1346 "type": "solver::Cg",
1348 "type": "solver::Multigrid",
1349 "min_coarse_rows": 8,
1351 "default_initial_guess": "zero",
1354 "type": "multigrid::Pgm",
1355 "deterministic": false
1358 "coarsest_solver": {
1359 "type": "preconditioner::Schwarz",
1361 "type": "preconditioner::Jacobi"
1366 "type": "Iteration",
1373 "type": "Iteration",
1377 "type": "ResidualNorm",
1378 "reduction_factor": 1e-4
1383 } else if (param_globals::flavor == std::string(
"petsc")) {
1384 default_opts = std::string(
"-ksp_type cg -pc_type gamg -options_left");
1386 lin_solver->setup_solver(*lhs_emi, tol, max_it * 100, param_globals::cg_norm_parab,
1387 "parabolic PDE", phie_mat_has_nullspace, logger, solver_file.c_str(),
1388 default_opts.c_str());
1391 void parabolic_solver_emi::solve()
1393 switch (parab_tech) {
1394 case SEMI_IMPLICIT: solve_semiImplicit();
break;
1398 void parabolic_solver_emi::solve_semiImplicit()
1405 dbc->enforce_dbc_rhs(*ui);
1413 stiffness_emi->mult(*ui, *Iij_temp);
1420 if (Iij_stim->mag() > 0.0) {
1422 mass_emi->mult(*Iij_stim, *Iij_temp);
1434 (*lin_solver)(*dui, *Irhs);
1438 if(lin_solver->reason < 0) {
1439 log_msg(0, 5, 0,
"%s solver diverged. Reason: %s.", lin_solver->name.c_str(),
1440 petsc_get_converged_reason_str(lin_solver->reason));
1446 ui_pre->add_scaled(*dui, 1.0);
1448 ui->add_scaled(*ui_pre, 1.0);
1455 dbc->enforce_dbc_rhs(*ui);
1460 stats.slvtime +=
timing(t1, t0);
1461 stats.update_iter(lin_solver->niter);
1474 hashmap::unordered_map<std::pair<mesh_int_t,mesh_int_t>, std::pair<mesh_int_t,mesh_int_t>> & map_vertex_tag_to_dof_petsc,
1475 std::vector<std::string> & tags_data)
1484 for(
size_t i=0; i<rnod.
size(); i++){
1488 for(
size_t eidx=0; eidx<emi_surfmesh_w_counter_face.l_numelem; eidx++)
1490 std::vector<mesh_int_t> elem_nodes;
1491 mesh_int_t tag = emi_surfmesh_w_counter_face.tag[eidx];
1492 for (
int n = emi_surfmesh_w_counter_face.dsp[eidx]; n < emi_surfmesh_w_counter_face.dsp[eidx+1];n++)
1494 mesh_int_t l_idx = emi_surfmesh_w_counter_face.con[n];
1496 std::pair <mesh_int_t,mesh_int_t> Index_tag_old;
1497 Index_tag_old = std::make_pair(l2g[l_idx],tags[eidx]);
1498 mesh_int_t dof = map_vertex_tag_to_dof[Index_tag_old];
1499 elem_nodes.push_back(dof);
1504 std::string result_first;
1505 std::string result_second;
1506 std::sort(elem_nodes.begin(),elem_nodes.end());
1509 if(elem_nodes.size()==2){
1512 key.
v1 = elem_nodes[0];
1513 key.
v2 = elem_nodes[1];
1514 std::pair<SF::emi_face<mesh_int_t,SF::tuple<mesh_int_t>>,
1515 SF::emi_face<mesh_int_t,SF::tuple<mesh_int_t>>> value = line_face[key];
1517 tag_first = value.first.tag;
1518 tag_second = value.second.tag;
1519 result_first = std::to_string(tag_first) +
":" + std::to_string(tag_second);
1520 result_second = std::to_string(tag_second) +
":" + std::to_string(tag_first);
1522 else if(elem_nodes.size()==3){
1524 key.
v1 = elem_nodes[0];
1525 key.
v2 = elem_nodes[1];
1526 key.
v3 = elem_nodes[2];
1527 std::pair<SF::emi_face<mesh_int_t,SF::triple<mesh_int_t>>,
1528 SF::emi_face<mesh_int_t,SF::triple<mesh_int_t>>> value = tri_face[key];
1530 tag_first = value.first.tag;
1531 tag_second = value.second.tag;
1532 result_first = std::to_string(tag_first) +
":" + std::to_string(tag_second);
1533 result_second = std::to_string(tag_second) +
":" + std::to_string(tag_first);
1535 else if(elem_nodes.size()==4){
1537 key.
v1 = elem_nodes[0];
1538 key.
v2 = elem_nodes[1];
1539 key.
v3 = elem_nodes[2];
1540 key.
v4 = elem_nodes[3];
1541 std::pair<SF::emi_face<mesh_int_t,SF::quadruple<mesh_int_t>>,
1542 SF::emi_face<mesh_int_t,SF::quadruple<mesh_int_t>>> value = quad_face[key];
1544 tag_first = value.first.tag;
1545 tag_second = value.second.tag;
1546 result_first = std::to_string(tag_first) +
":" + std::to_string(tag_second);
1547 result_second = std::to_string(tag_second) +
":" + std::to_string(tag_first);
1550 tags_data.push_back(result_first);
1551 tags_data.push_back(result_second);
1555 void EMI::initialize()
1563 logger =
f_open(
"emi.log", param_globals::experiment != 4 ?
"w" :
"r");
1564 const int verb = param_globals::output_level;
1565 const auto log_init_timing = [&](
const char* label,
double start) {
1567 log_msg(logger, 0,
ECHO,
"EMI init: %s in %.5f seconds.", label,
float(MPI_Wtime() - start));
1570 double phase_t = MPI_Wtime();
1576 log_init_timing(
"mesh setup", phase_t);
1580 phase_t = MPI_Wtime();
1582 log_init_timing(
"mesh mappings", phase_t);
1586 phase_t = MPI_Wtime();
1587 ion.logger = logger;
1589 ion.set_surface_mesh_data(parab_solver.line_face,
1590 parab_solver.tri_face,
1591 parab_solver.quad_face,
1592 parab_solver.map_vertex_tag_to_dof);
1595 std::vector<std::string> tags_data;
1596 tags_onFace(parab_solver.line_face,
1597 parab_solver.tri_face,
1598 parab_solver.quad_face,
1599 parab_solver.map_vertex_tag_to_dof,
1600 parab_solver.map_vertex_tag_to_dof_petsc,
1603 log_init_timing(
"ionic face metadata", phase_t);
1605 ion.set_tags_onFace(tags_data);
1607 ion.set_face_region_data(parab_solver.intra_tags, parab_solver.map_elem_uniqueFace_to_tags);
1608 phase_t = MPI_Wtime();
1610 log_init_timing(
"ionic model initialization", phase_t);
1612 phase_t = MPI_Wtime();
1614 set_elec_tissue_properties_emi_volume(mtype_vol, parab_solver.extra_tags, parab_solver.intra_tags, logger);
1618 region_mask(
emi_msh, mtype_vol[0].regions, mtype_vol[0].regionIDs,
true,
"gregion_vol",
false);
1623 param_globals::dt, 0,
"elec::ref_dt",
"TS");
1624 log_init_timing(
"tissue properties and timers", phase_t);
1628 phase_t = MPI_Wtime();
1629 param_globals::operator_splitting = 0;
1631 log_init_timing(
"stimuli", phase_t);
1637 phase_t = MPI_Wtime();
1639 log_init_timing(
"solver setup", phase_t);
1642 phase_t = MPI_Wtime();
1644 balance_electrodes();
1646 scale_total_stimulus_current(stimuli, *parab_solver.mass_emi, *parab_solver.mass_surf_emi, logger);
1647 log_init_timing(
"stimulus current scaling", phase_t);
1652 phase_t = MPI_Wtime();
1658 parab_solver.operator_unique_to_both_faces->mult(*parab_solver.vb, *parab_solver.vb_both_face);
1659 SF::assign_resting_potential_from_ionic_models_on_myocyte(*parab_solver.ui,
1660 parab_solver.vb_both_face,
1661 parab_solver.elemTag_emi_mesh,
1662 parab_solver.map_vertex_tag_to_dof_petsc,
1663 parab_solver.line_face, parab_solver.tri_face, parab_solver.quad_face,
1664 emi_surfmesh_w_counter_face, emi_mesh);
1669 if (strlen(param_globals::start_statef) > 0)
1670 restore_field_state(param_globals::start_statef);
1672 *parab_solver.vb_unique_face = *parab_solver.vb;
1673 log_init_timing(
"initial membrane state projection", phase_t);
1676 phase_t = MPI_Wtime();
1680 log_init_timing(
"output setup", phase_t);
1683 const double init_dur =
timing(t2, t1);
1684 this->initialize_time += init_dur;
1686 log_msg(logger, 0,
ECHO,
"EMI init total in %.5f seconds.",
float(init_dur));
1689 void EMI::setup_mappings()
1697 log_msg(logger, 0, 0,
"%s: Setting up intracellular algebraic-to-nodal scattering.", __func__);
1702 log_msg(logger, 0, 0,
"%s: Setting up intracellular PETSc to canonical permutation.", __func__);
1707 void EMI::checkpointing()
1713 char save_fnm[1024];
1716 snprintf(save_fnm,
sizeof save_fnm,
"%s.%s.roe", param_globals::write_statef, tsav_ext);
1718 ion.miif->dump_state(save_fnm, tm.time, ion.ion_domain,
false, GIT_COMMIT_COUNT);
1719 dump_field_state(save_fnm);
1724 char save_fnm[1024];
1725 snprintf(save_fnm,
sizeof save_fnm,
"checkpoint.%.1f.roe", tm.time);
1726 ion.miif->dump_state(save_fnm, tm.time, ion.ion_domain,
false, GIT_COMMIT_COUNT);
1727 dump_field_state(save_fnm);
1731 void EMI::dump_field_state(
const char* roe_fnm)
1734 std::string fnm = std::string(roe_fnm) +
".emifld";
1736 const uint64_t gsize = parab_solver.ui->gsize();
1746 memcpy(hdr.magic, EMIFLD_MAGIC,
sizeof hdr.magic);
1747 hdr.version = EMIFLD_VERSION;
1748 hdr.real_bytes =
sizeof(
SF_real);
1751 if (!fnv1a_file(roe_fnm, hdr.roe_hash)) {
1752 log_msg(logger, 5, 0,
"Cannot fingerprint ionic checkpoint %s for the EMI field file.", roe_fnm);
1754 }
else if (!(fd = fopen(fnm.c_str(),
"wb"))) {
1755 log_msg(logger, 5, 0,
"Cannot open EMI field checkpoint %s for writing.", fnm.c_str());
1759 if (
get_global(error, MPI_SUM)) EXIT(EXIT_FAILURE);
1761 log_msg(logger, 0, 0,
"Saving EMI bulk potential field in file: %s", fnm.c_str());
1767 if (rank == 0) fwrite(&hdr,
sizeof hdr, 1, fd);
1776 canon->write_binary<
SF_real>(fd);
1782 void EMI::restore_field_state(
const char* roe_fnm)
1785 std::string fnm = std::string(roe_fnm) +
".emifld";
1793 const uint64_t gsize = parab_solver.ui->gsize();
1797 fd = fopen(fnm.c_str(),
"rb");
1799 log_msg(logger, 5, 0,
"Cannot open EMI field checkpoint %s.", fnm.c_str());
1803 const long expected =
static_cast<long>(
sizeof hdr + gsize *
sizeof(
SF_real));
1804 fseek(fd, 0, SEEK_END);
1805 const long actual = ftell(fd);
1807 uint64_t roe_hash = 0;
1808 if (fread(&hdr,
sizeof hdr, 1, fd) != 1) {
1809 log_msg(logger, 5, 0,
"EMI field checkpoint %s is truncated.", fnm.c_str());
1811 }
else if (memcmp(hdr.magic, EMIFLD_MAGIC,
sizeof hdr.magic) != 0 || hdr.version != EMIFLD_VERSION) {
1812 log_msg(logger, 5, 0,
"%s is not a version-%u EMI field checkpoint.", fnm.c_str(), EMIFLD_VERSION);
1814 }
else if (hdr.real_bytes !=
sizeof(
SF_real) || hdr.gsize != gsize || actual != expected) {
1815 log_msg(logger, 5, 0,
"EMI field checkpoint %s does not match this run (wrong precision, mesh, or size).", fnm.c_str());
1817 }
else if (!fnv1a_file(roe_fnm, roe_hash) || hdr.roe_hash != roe_hash) {
1818 log_msg(logger, 5, 0,
"EMI field checkpoint %s does not belong to ionic checkpoint %s.", fnm.c_str(), roe_fnm);
1821 if (err) { fclose(fd); fd =
nullptr; }
1824 if (
get_global(err, MPI_SUM)) EXIT(EXIT_FAILURE);
1827 size_t nrd = parab_solver.ui->read_binary<
SF_real>(fd);
1829 if (nrd !=
static_cast<size_t>(gsize)) {
1830 log_msg(logger, 5, 0,
"Short read of EMI field checkpoint %s (%zu of %lu values).",
1831 fnm.c_str(), nrd,
static_cast<unsigned long>(gsize));
1837 log_msg(logger, 0, 0,
"Restored EMI bulk potential field from %s.", fnm.c_str());
1842 void EMI::compute_step()
1854 const int verb = param_globals::output_level;
1861 apply_dbc_stimulus();
1870 apply_current_stimulus();
1874 parab_solver.operator_unique_to_both_faces->mult(*parab_solver.Ib, *parab_solver.Ib_both_face);
1875 parab_solver.BsM->mult(*parab_solver.Ib_both_face, *parab_solver.Irhs);
1879 parab_solver.solve();
1882 parab_solver.B->mult(*parab_solver.ui, *parab_solver.vb_both_face);
1884 parab_solver.operator_both_to_unique_face->mult(*parab_solver.vb_both_face, *parab_solver.vb_unique_face);
1885 *parab_solver.vb = *parab_solver.vb_unique_face;
1893 this->compute_time +=
timing(t2, t1);
1900 void EMI::output_step()
1905 output_manager.write_data();
1907 double curtime =
timing(t2, t1);
1908 this->output_time += curtime;
1911 IO_stats.tot_time += curtime;
1927 output_manager.close_files_and_cleanup();
1933 void EMI::setup_stimuli()
1938 stimuli.
resize(param_globals::num_stim);
1939 for (
int i = 0; i < param_globals::num_stim; i++) {
1941 stimulus & s = stimuli[i];
1947 s.associated_intra_mesh =
emi_msh, s.associated_extra_mesh =
emi_msh;
1951 if (s.phys.type ==
Illum) {
1969 }
else if (s.phys.type ==
I_tm) {
1971 SF::restrict_to_membrane(s.electrode.vertices, dof2ptsData, mesh);
1983 if (s.electrode.dump_vtx) {
1988 if(param_globals::stim[i].pulse.dumpTrace &&
get_rank() == 0) {
1990 s.pulse.wave.write_trace(s.name+
".trc");
1996 void EMI::apply_dbc_stimulus()
1998 parabolic_solver_emi& ps = parab_solver;
2002 bool dbcs_have_updated = ps.dbc !=
nullptr && ps.dbc->dbc_update();
2005 if (dbcs_have_updated && time_not_final) {
2006 parab_solver.rebuild_matrices(mtype_vol, *ion.miif, stimuli, logger);
2010 void EMI::apply_current_stimulus()
2012 parabolic_solver_emi& ps = parab_solver;
2013 ps.Iij_stim->set(0.0);
2016 for(stimulus & s : stimuli) {
2018 switch (s.phys.type) {
2021 ps.Bi->mult(*ps.Iij_temp, *ps.Ib_both_face);
2022 ps.operator_both_to_unique_face->mult(*ps.Ib_both_face, *ps.Ib_unique_face);
2023 ps.Ib->add_scaled(*ps.Ib_unique_face, -0.5);
2037 void EMI::balance_electrodes()
2039 for (
int i = 0; i < param_globals::num_stim; i++) {
2040 if (param_globals::stim[i].crct.balance != -1) {
2041 int from = param_globals::stim[i].crct.balance;
2044 log_msg(NULL, 0, 0,
"Balancing stimulus %d with %d %s-wise.", from, to,
2045 is_current(stimuli[from].phys.type) ?
"current" :
"voltage");
2047 stimulus& s_from = stimuli[from];
2048 stimulus& s_to = stimuli[to];
2050 s_to.pulse = s_from.pulse;
2051 s_to.ptcl = s_from.ptcl;
2052 s_to.phys = s_from.phys;
2053 s_to.pulse.strength *= -1.0;
2055 if (s_from.phys.type ==
I_ex || s_from.phys.type ==
I_in) {
2059 if (!s_from.phys.total_current) {
2060 sf_mat& mass = *parab_solver.mass_emi;
2064 s_to.pulse.strength *= fabs(vol0 / vol1);
2076 for (stimulus & s : stimuli){
2077 if(
is_current(s.phys.type) && s.phys.total_current){
2078 switch (s.phys.type) {
2089 float scale = 1.e12 / vol;
2091 s.pulse.strength *= scale;
2094 "%s [Stimulus %d]: current density scaled to %.4g uA/cm^3\n",
2095 s.name.c_str(), s.idx, s.pulse.strength);
2109 s.pulse.strength /= surf;
2111 "%s [Stimulus %d]: current density scaled to %.4g uA/cm^2\n",
2112 s.name.c_str(), s.idx, s.pulse.strength);
2123 static void assign_deterministic_elem_numbering(
sf_mesh & mesh)
2125 const int KEY_SIZE = 6;
2126 int rank = 0, size = 0;
2127 MPI_Comm_rank(mesh.comm, &rank);
2128 MPI_Comm_size(mesh.comm, &size);
2130 auto make_key = [&](
size_t i) {
2131 std::array<mesh_int_t, KEY_SIZE> k;
2133 k[0] =
static_cast<mesh_int_t>(mesh.type[i]);
2137 if (mesh.type[i] ==
SF::Line) nn = 2;
2138 else if (mesh.type[i] ==
SF::Tri) nn = 3;
2139 else if (mesh.type[i] ==
SF::Quad) nn = 4;
2142 std::vector<mesh_int_t> nodes;
2144 size_t off = mesh.dsp[i];
2145 for (
int j = 0; j < nn; j++) {
2146 nodes.push_back(mesh.con[off + j]);
2148 std::sort(nodes.begin(), nodes.end());
2149 for (
int j = 0; j < (int)nodes.size(); j++) {
2150 k[2 + j] = nodes[j];
2156 std::vector<mesh_int_t> local_keys(mesh.l_numelem * KEY_SIZE, -1);
2157 for (
size_t i = 0; i < mesh.l_numelem; i++) {
2158 auto k = make_key(i);
2159 for (
int j = 0; j < KEY_SIZE; j++) local_keys[i * KEY_SIZE + j] = k[j];
2163 std::vector<int> counts(size, 0), displs(size, 0);
2164 int local_count = (int)local_keys.size();
2165 MPI_Allgather(&local_count, 1, MPI_INT, counts.data(), 1, MPI_INT, mesh.comm);
2167 for (
int r = 0; r < size; r++) {
2172 std::vector<mesh_int_t> all_keys;
2173 if (rank == 0) all_keys.resize(total, -1);
2174 const MPI_Datatype key_mpi_t = mpi_datatype<mesh_int_t>();
2175 MPI_Gatherv(local_keys.data(), local_count, key_mpi_t,
2176 rank == 0 ? all_keys.data() :
nullptr, counts.data(), displs.data(), key_mpi_t,
2180 std::vector<std::array<mesh_int_t, KEY_SIZE>> sorted_keys;
2182 const int nkeys = total / KEY_SIZE;
2183 sorted_keys.resize(nkeys);
2184 for (
int i = 0; i < nkeys; i++) {
2185 std::array<mesh_int_t, KEY_SIZE> k;
2186 for (
int j = 0; j < KEY_SIZE; j++) k[j] = all_keys[i * KEY_SIZE + j];
2189 std::sort(sorted_keys.begin(), sorted_keys.end());
2194 if (rank == 0) nkeys = (int)sorted_keys.size();
2195 MPI_Bcast(&nkeys, 1, MPI_INT, 0, mesh.comm);
2196 std::vector<mesh_int_t> flat_sorted(nkeys * KEY_SIZE, -1);
2198 for (
int i = 0; i < nkeys; i++) {
2199 for (
int j = 0; j < KEY_SIZE; j++) flat_sorted[i * KEY_SIZE + j] = sorted_keys[i][j];
2202 MPI_Bcast(flat_sorted.data(), (
int)flat_sorted.size(), key_mpi_t, 0, mesh.comm);
2206 sorted_keys.resize(nkeys);
2207 for (
int i = 0; i < nkeys; i++) {
2208 std::array<mesh_int_t, KEY_SIZE> k;
2209 for (
int j = 0; j < KEY_SIZE; j++) k[j] = flat_sorted[i * KEY_SIZE + j];
2217 nbr_ref.
resize(mesh.l_numelem);
2218 nbr_sub.
resize(mesh.l_numelem);
2219 for (
size_t i = 0; i < mesh.l_numelem; i++) {
2220 auto k = make_key(i);
2221 auto it = std::lower_bound(sorted_keys.begin(), sorted_keys.end(), k);
2222 if (it == sorted_keys.end() || *it != k) {
2223 log_msg(0, 5, 0,
"deterministic numbering failed to find key (rank %d, elem %zu)", rank, i);
2232 void EMI::setup_output()
2234 std::string output_base =
get_basename(param_globals::meshname);
2237 const bool write_binary =
2238 SF::fileExists(std::string(param_globals::meshname) +
".belem") ||
2240 const bool restrict_output =
2241 parse_emi_output_tags(param_globals::gridout_tags,
2242 parab_solver.extra_tags, parab_solver.intra_tags,
2247 const int gridout_emi = param_globals::gridout_emi;
2249 if(restrict_output && param_globals::num_io_nodes > 0) {
2250 log_msg(0, 5,
ECHO,
"Restricted EMI output with gridout_tags is not supported with async I/O.");
2256 if(restrict_output) {
2257 build_emi_volume_output_restriction(mesh, output_tags, phie_output_idx);
2258 if(
get_global(
static_cast<long int>(phie_output_idx.
size()), MPI_SUM, PETSC_COMM_WORLD) == 0) {
2259 log_msg(0, 5,
ECHO,
"Restricted EMI volume output is empty.");
2264 if(gridout_emi & 2) {
2265 std::string output_file = output_base +
"_e";
2266 log_msg(0, 0, 0,
"Writing \"%s\" mesh: %s (%s)", mesh.name.c_str(), output_file.c_str(), write_binary ?
"binary" :
"text");
2267 const double t0 = MPI_Wtime();
2268 if(restrict_output) {
2269 write_emi_output_mesh(mesh, write_binary, output_file, mesh.name.c_str(),
2270 [&](
size_t eidx) { return output_tags.count(mesh.tag[eidx]) != 0; });
2274 log_msg(0, 0, 0,
"Wrote \"%s\" mesh in %.5f seconds.", mesh.name.c_str(),
float(MPI_Wtime() - t0));
2276 else if(param_globals::output_level > 1) {
2277 log_msg(0, 0, 0,
"Skipping \"%s\" mesh output.", mesh.name.c_str());
2280 output_manager.register_output(parab_solver.ui,
emi_msh, 1, param_globals::phiefile,
"mV",
2281 restrict_output ? &phie_output_idx : NULL);
2284 mesh_m.name =
"Membrane";
2285 if(restrict_output) {
2286 build_emi_surface_output_restriction(mesh_m, output_tags, parab_solver.map_elem_uniqueFace_to_tags,
2288 if(
get_global(
static_cast<long int>(vm_output_idx.
size()), MPI_SUM, PETSC_COMM_WORLD) == 0) {
2289 log_msg(0, 5,
ECHO,
"Restricted EMI membrane output is empty.");
2294 if(gridout_emi & 1) {
2295 std::string output_file = output_base +
"_m";
2296 log_msg(0, 0, 0,
"Writing \"%s\" mesh: %s (%s)", mesh_m.name.c_str(), output_file.c_str(), write_binary ?
"binary" :
"text");
2297 const double t0 = MPI_Wtime();
2298 if(restrict_output) {
2299 write_emi_output_mesh(mesh_m, write_binary, output_file, mesh_m.name.c_str(),
2301 bool keep = output_tags.count(mesh_m.tag[eidx]) != 0;
2302 auto it = parab_solver.map_elem_uniqueFace_to_tags.find(eidx);
2303 if(it != parab_solver.map_elem_uniqueFace_to_tags.end()) {
2305 output_tags.count(static_cast<int>(it->second.first)) != 0 ||
2306 output_tags.count(static_cast<int>(it->second.second)) != 0;
2313 log_msg(0, 0, 0,
"Wrote \"%s\" mesh in %.5f seconds.", mesh_m.name.c_str(),
float(MPI_Wtime() - t0));
2315 else if(param_globals::output_level > 1) {
2316 log_msg(0, 0, 0,
"Skipping \"%s\" mesh output.", mesh_m.name.c_str());
2324 param_globals::vofile,
"mV",
2325 restrict_output ? &vm_output_idx : NULL,
true);
2327 if(param_globals::num_trace) {
2329 open_trace(ion.miif, param_globals::num_trace, param_globals::trace_node, NULL, &imesh);
2333 IO_stats.init_logger(
"IO_stats.dat");
2336 void EMI::dump_matrices()
2338 std::string bsname = param_globals::dump_basename;
2343 fn = bsname +
"_lhs.bin";
2344 parab_solver.lhs_emi->write(fn.c_str());
2346 fn = bsname +
"_K.bin";
2347 parab_solver.stiffness_emi->write(fn.c_str());
2349 fn = bsname +
"_B.bin";
2350 parab_solver.B->write(fn.c_str());
2352 fn = bsname +
"_Bi.bin";
2353 parab_solver.Bi->write(fn.c_str());
2355 fn = bsname +
"_BsM.bin";
2356 parab_solver.BsM->write(fn.c_str());
2358 fn = bsname +
"_M.bin";
2359 parab_solver.mass_emi->write(fn.c_str());
2361 fn = bsname +
"_Ms.bin";
2362 parab_solver.mass_surf_emi->write(fn.c_str());
2368 double EMI::timer_val(
const int timer_id)
2374 stimuli[sidx].value(val);
2377 val = std::nan(
"NaN");
2384 std::string EMI::timer_unit(
const int timer_id)
2391 s_unit = stimuli[sidx].pulse.wave.f_unit;
2396 void EMI::setup_solvers()
2399 const int log_flag = param_globals::output_level > 1 ?
ECHO : 0;
2400 double t0 = MPI_Wtime();
2401 parab_solver.init();
2402 log_msg(logger, 0, log_flag,
"EMI setup_solvers: parabolic solver init in %.5f seconds.",
float(MPI_Wtime() - t0));
2404 parab_solver.rebuild_matrices(mtype_vol, *ion.miif, stimuli, logger);
2405 log_msg(logger, 0, log_flag,
"EMI setup_solvers: matrix assembly and linear solver setup in %.5f seconds.",
float(MPI_Wtime() - t0));
2407 if(param_globals::dump2MatLab)
2415 MPI_Comm_size(comm, &size);
2416 MPI_Comm_rank(comm, &rank);
2429 MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank);
2430 divide(num_tags, size, num_tags_per_rank);
2433 void EMI::setup_EMI_mesh()
2435 log_msg(0,0,0,
"\n *** Processing EMI mesh ***\n");
2437 const std::string basename = param_globals::meshname;
2438 const int verb = param_globals::output_level;
2440 assert(mesh_registry.count(
emi_msh) == 1);
2449 MPI_Comm comm = emi_mesh.
comm;
2452 double t1, t2, s1, s2;
2453 const double total_setup_t0 = MPI_Wtime();
2454 MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank);
2459 if (emi_mesh.l_numelem > 0) {
2464 const char* type_name = (first_elem ==
SF::Line) ?
"1D (Line)" :
2465 (first_elem ==
SF::Tri) ?
"2D (Tri)" :
2468 log_msg(0, 5, 0,
"\n*** ERROR: EMI model requires a 3D volumetric mesh!");
2469 log_msg(0, 5, 0,
"*** Current mesh element type: %s", type_name);
2470 log_msg(0, 5, 0,
"*** EMI only supports 3D element types: Tetra, Pyramid, Prism, Hexa");
2471 log_msg(0, 5, 0,
"*** Please provide a 3D mesh with volume elements.\n");
2480 int total_num_tags = 0;
2481 if(verb)
log_msg(NULL, 0, 0,
"\nReading tags for extra and intra regions from input files");
2487 if(verb)
log_msg(NULL, 0, 0,
"Read extracellular tags");
2490 parab_solver.extra_tags.insert(tag);
2493 if(verb)
log_msg(NULL, 0, 0,
"Read intracellular tags");
2496 parab_solver.intra_tags.insert(tag);
2499 total_num_tags = parab_solver.extra_tags.size() + parab_solver.intra_tags.size();
2500 if(total_num_tags < size){
2501 log_msg(0,5,0,
"\nThe number of unique tags on EMI mesh is smaller than number of processors!");
2504 if(verb)
log_msg(NULL, 0, 0,
"\nextra_tags=%lu, intra_tags=%lu", parab_solver.extra_tags.size(), parab_solver.intra_tags.size());
2507 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2515 if(verb)
log_msg(NULL, 0, 0,
"\nReading points with data on each vertex");
2519 assert(ptsidx.
size()==ptsData.
size());
2521 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2523 std::list< sf_mesh* > meshlist;
2524 meshlist.push_back(&emi_mesh);
2529 if(verb)
log_msg(NULL, 0, 0,
"\nDistribute mesh based on tags");
2532 distribute_elements_based_tags(emi_mesh, total_num_tags);
2534 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2540 if(verb)
log_msg(NULL, 0, 0,
"\nInserting points");
2544 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2549 if(verb)
log_msg(NULL, 0, 0,
"\nCompute location of all DOFs on EMI mesh (inner DOFs, membrane, gap junction) saved into ptsData from original mesh");
2551 compute_ptsdata_from_original_mesh( emi_mesh,
2554 parab_solver.extra_tags,
2555 parab_solver.intra_tags);
2557 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2565 if(verb)
log_msg(NULL, 0, 0,
"\nExtract EMI surface mesh");
2567 extract_face_based_tags(emi_mesh,
SF::NBR_REF, vertex2ptsdata,
2568 parab_solver.line_face,
2569 parab_solver.tri_face,
2570 parab_solver.quad_face,
2571 parab_solver.extra_tags,
2572 parab_solver.intra_tags,
2573 emi_surfmesh_one_side, emi_surfmesh_w_counter_face, emi_surfmesh_unique_face,
2574 parab_solver.map_elem_uniqueFace_to_elem_oneface,
2575 unused_map_elem_oneface_to_elem_uniqueFace);
2576 meshlist.push_back(&emi_surfmesh_one_side);
2578 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2582 compute_surface_mesh_with_counter_face(emi_surfmesh_w_counter_face,
SF::NBR_REF,
2583 parab_solver.line_face,
2584 parab_solver.tri_face,
2585 parab_solver.quad_face);
2587 compute_surface_mesh_with_unique_face(emi_surfmesh_unique_face,
SF::NBR_REF,
2588 parab_solver.line_face,
2589 parab_solver.tri_face,
2590 parab_solver.quad_face,
2591 parab_solver.map_elem_uniqueFace_to_tags);
2596 SF::create_reverse_elem_mapping_between_surface_meshes(parab_solver.line_face,
2597 parab_solver.tri_face,
2598 parab_solver.quad_face,
2599 parab_solver.vec_both_to_one_face,
2602 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2607 if(verb)
log_msg(NULL, 0, 0,
"\ncompute global number of interface");
2608 size_t global_count_surf = 0;
2609 size_t numelem_surface = emi_surfmesh_one_side.l_numelem;
2610 size_t local_count_surf = numelem_surface;
2611 MPI_Reduce(&local_count_surf, &global_count_surf, 1, mpi_datatype<size_t>(), MPI_SUM, 0, MPI_COMM_WORLD);
2612 if(verb && rank==0) fprintf(stdout,
"global number of interfaces = %zu\n", global_count_surf);
2619 sub_numbering(emi_mesh);
2620 emi_mesh.generate_par_layout();
2632 if(verb)
log_msg(NULL, 0, 0,
"\ndecouple emi interfaces");
2633 if(verb)
log_msg(NULL, 0, 0,
"\tcompute map oldIdx to dof");
2634 compute_map_vertex_to_dof(emi_mesh,
SF::NBR_REF, vertex2ptsdata, parab_solver.extra_tags, parab_solver.map_vertex_tag_to_dof);
2639 if(verb)
log_msg(NULL, 0, 0,
"\tcomplete map oldIdx to dof with counter interface");
2641 complete_map_vertex_to_dof_with_counter_face(parab_solver.line_face, parab_solver.tri_face, parab_solver.quad_face, parab_solver.map_vertex_tag_to_dof);
2646 if(verb)
log_msg(NULL, 0, 0,
"\tupdate mesh with dof");
2647 update_emi_mesh_with_dofs(emi_mesh,
SF::NBR_REF, parab_solver.map_vertex_tag_to_dof, parab_solver.dof2vertex);
2649 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2655 if(verb)
log_msg(NULL, 0, 0,
"\nInitialize petsc =0 for map<oldIdx,tag> -><dof, petsc>");
2657 for(
const auto & key_value : parab_solver.map_vertex_tag_to_dof)
2659 mesh_int_t gIndex_old = key_value.first.first;
2663 std::pair <mesh_int_t,mesh_int_t> dof_petsc = std::make_pair(dof,-1);
2664 parab_solver.map_vertex_tag_to_dof_petsc.insert({key_value.first,dof_petsc});
2667 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2673 if(verb)
log_msg(NULL, 0, 0,
"Inserting points and ptsData of dofs to emi_mesh");
2674 insert_points_ptsData_to_dof(tmesh_backup_old, emi_mesh,
SF::NBR_REF, parab_solver.dof2vertex, vertex2ptsdata, dof2ptsData);
2676 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2682 if(verb)
log_msg(NULL, 0, 0,
"Generating unique PETSc numberings");
2685 sub_numbering(emi_mesh);
2686 emi_mesh.generate_par_layout();
2689 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2695 if(verb)
log_msg(NULL, 0, 0,
"Generating unique PETSc numberings");
2698 petsc_numbering(emi_mesh);
2701 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2706 if(verb)
log_msg(NULL, 0, 0,
"Updating the map between indices to PETSc numberings");
2708 update_map_indices_to_petsc(emi_mesh,
SF::NBR_REF,
SF::NBR_PETSC, parab_solver.extra_tags, parab_solver.map_vertex_tag_to_dof_petsc, parab_solver.dof2vertex, parab_solver.elemTag_emi_mesh);
2710 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2716 if(verb)
log_msg(NULL, 0, 0,
"Updating surface mesh with dof");
2717 update_faces_on_surface_mesh_after_decoupling_with_dofs(emi_surfmesh_one_side, parab_solver.map_vertex_tag_to_dof, parab_solver.line_face, parab_solver.tri_face, parab_solver.quad_face);
2719 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2725 if(verb)
log_msg(NULL, 0, 0,
"Layout for element of EMI surfmesh");
2728 SF::layout_from_count<long int>(emi_surfmesh_one_side.l_numelem, layout, emi_surfmesh_one_side.comm);
2729 size_t count = layout[rank+1] - layout[rank];
2731 for (
int i = 0; i <
count; ++i){
2732 emi_surfmesh_elem[i] = layout[rank]+i;
2738 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2744 if(verb)
log_msg(NULL, 0, 0,
"Layout for element of EMI surfmesh w counter face");
2747 SF::layout_from_count<long int>(emi_surfmesh_w_counter_face.l_numelem, layout_counter, emi_surfmesh_w_counter_face.comm);
2748 size_t count_counter = layout_counter[rank+1] - layout_counter[rank];
2749 emi_surfmesh_counter_elem.
resize(count_counter);
2750 for (
int i = 0; i < count_counter; ++i){
2751 emi_surfmesh_counter_elem[i] = layout_counter[rank]+i;
2753 emi_surfmesh_w_counter_face.localize(
SF::NBR_REF);
2756 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2763 if(verb)
log_msg(NULL, 0, 0,
"Layout for element of EMI unique-face surfmesh");
2766 SF::layout_from_count<long int>(emi_surfmesh_unique_face.l_numelem, layout_unique, emi_surfmesh_unique_face.comm);
2767 size_t count_unique = layout_unique[rank+1] - layout_unique[rank];
2768 emi_surfmesh_unique_elem.
resize(count_unique);
2769 for (
int i = 0; i < count_unique; ++i){
2770 emi_surfmesh_unique_elem[i] = layout_unique[rank]+i;
2775 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2781 if(verb)
log_msg(NULL, 0, 0,
"Inserting points to EMI surfmesh");
2782 insert_points_to_surface_mesh(tmesh_backup_old, emi_surfmesh_one_side,
SF::NBR_REF, parab_solver.dof2vertex, parab_solver.extra_tags, parab_solver.elemTag_surface_mesh);
2783 insert_points_to_surface_mesh(tmesh_backup_old, emi_surfmesh_w_counter_face,
SF::NBR_REF, parab_solver.dof2vertex, parab_solver.extra_tags, parab_solver.elemTag_surface_w_counter_mesh);
2784 insert_points_to_surface_mesh(tmesh_backup_old, emi_surfmesh_unique_face,
SF::NBR_REF, parab_solver.dof2vertex);
2786 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2792 if(verb)
log_msg(NULL, 0, 0,
"Generating submesh_numbering and PETSc numberings for surface mesh");
2795 sub_numbering(emi_surfmesh_one_side);
2796 emi_surfmesh_one_side.generate_par_layout();
2799 petsc_numbering(emi_surfmesh_one_side);
2804 sub_numbering(emi_surfmesh_w_counter_face);
2805 emi_surfmesh_w_counter_face.generate_par_layout();
2808 petsc_numbering(emi_surfmesh_w_counter_face);
2813 sub_numbering(emi_surfmesh_unique_face);
2814 emi_surfmesh_unique_face.generate_par_layout();
2817 petsc_numbering(emi_surfmesh_unique_face);
2819 assign_deterministic_elem_numbering(emi_surfmesh_unique_face);
2822 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2828 if(verb)
log_msg(NULL, 0, 0,
"assign PETSc numbering for new faces");
2829 SF::assign_petsc_on_counter_face(parab_solver.map_vertex_tag_to_dof_petsc,comm);
2832 for (it = parab_solver.map_vertex_tag_to_dof_petsc.begin(); it != parab_solver.map_vertex_tag_to_dof_petsc.end(); it++)
2834 std::pair <mesh_int_t,mesh_int_t> Index_tag_old = it->first;
2835 std::pair <mesh_int_t,mesh_int_t> dof_petsc = it->second;
2836 parab_solver.dof2petsc[dof_petsc.first] = dof_petsc.second;
2837 parab_solver.petsc2dof[dof_petsc.second] = dof_petsc.first;
2842 #ifdef EMI_DEBUG_MESH
2844 int invalid_count = 0;
2845 for (
const auto& [key, val] : parab_solver.map_vertex_tag_to_dof_petsc) {
2846 if (val.second < 0) {
2848 if (invalid_count <= 3) {
2849 fprintf(stderr,
"RANK %d INVALID: vertex=%ld tag=%ld dof=%ld petsc=%ld\n",
2850 rank, (
long)key.first, (
long)key.second, (
long)val.first, (
long)val.second);
2854 fprintf(stderr,
"RANK %d: After Step 26: %d invalid PETSc indices out of %zu total\n",
2855 rank, invalid_count, parab_solver.map_vertex_tag_to_dof_petsc.size());
2861 if(verb)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2866 added_counter_faces_to_map(parab_solver.line_face, parab_solver.tri_face, parab_solver.quad_face);
2867 const double total_setup = MPI_Wtime() - total_setup_t0;
2868 log_msg(0,0,0,
"Total setup_EMI_mesh processing time: %.5f sec.",
float(total_setup));
2870 log_msg(0,0,0,
"\n *** EMI mesh processing Done ***\n");
2876 MPI_Comm comm = mesh.
comm;
2878 double t1, t2, s1, s2;
2879 MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank);
2880 const int verb = param_globals::output_level;
2882 if(total_num_tags < size)
2884 PetscPrintf(PETSC_COMM_WORLD,
"\nThe number of processors should be less than the number of tags, size = %d & ntags = %d !!!\n",
2885 size, total_num_tags);
2889 if(verb==10)
log_msg(NULL, 0, 0,
"\ncompute the number of tags which belongs to one rank");
2893 compute_tags_per_rank(total_num_tags, ntags_per_rank);
2895 if(verb==10)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2901 partition_based_tags(total_num_tags, mesh.
tag, ntags_per_rank, part_based_Tags);
2904 permute_mesh_locally_based_on_tag_elemIdx(mesh);
2906 if(verb==10)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2911 void partition_based_tags(
int num_tags,
2916 const int verb = param_globals::output_level;
2919 MPI_Comm_size(comm, &size);
2920 MPI_Comm_rank(comm, &rank);
2926 if (!load_partitions_from_file(tags_to_rank_map, num_tags, comm)) {
2927 if(verb==10)
log_msg(NULL, 0, 0,
"\ncompute the number of unique tags");
2929 double t1 = MPI_Wtime();
2930 extract_unique_tag(unique_tags);
2931 double t2 = MPI_Wtime();
2932 if(verb==10)
log_msg(NULL, 0, 0,
"Done in %f sec.",
float(t2 - t1));
2934 if (unique_tags.
size() !=
static_cast<size_t>(num_tags)) {
2935 log_msg(0,5,0,
"\nerror: the number of tags in the EMI mesh does not match the total tags from *.extra and *.intra");
2938 map_tags_to_rank(size, unique_tags, num_tags_per_rank, tags_to_rank_map);
2941 for (
size_t i = 0; i < part.
size(); ++i) {
2942 if(tags_to_rank_map.
count(tag[i]))
2943 part[i] = tags_to_rank_map[tag[i]];
2951 for (
size_t r = 0; r < size; ++r) {
2952 for (
size_t count = 0;
count < num_tags_per_rank[r];) {
2956 tags_to_rank_map.
insert({tag, r});
2965 int expected_num_tags,
2969 MPI_Comm_size(comm, &size);
2970 MPI_Comm_rank(comm, &rank);
2973 const std::string basename = param_globals::meshname;
2974 FILE* fd = fopen((basename +
".part").c_str(),
"r");
2980 if (parts.
size() == 0)
return false;
2982 if (parts.
size() % 2 != 0) {
2983 log_msg(0,5,0,
"\nThe part file should contain 2 lines per tag, one for the tag number and the next for its associated partition number.!");
2989 for(
int i = 0; i < parts.
size(); i+=2) {
2990 min_part =
std::min(min_part, parts[i + 1]);
2991 max_part =
std::max(max_part, parts[i + 1]);
2992 tags_to_rank_map.
insert({parts[i], parts[i + 1]});
2995 if (tags_to_rank_map.
size() !=
static_cast<size_t>(expected_num_tags)) {
2996 log_msg(0,5,0,
"\nerror: the number of tags in the .part file does not match the total tags from *.extra and *.intra");
3000 if (min_part < 0 || max_part >= size) {
3002 "\nerror: EMI partition file %s.part is incompatible with this run.\n"
3003 "The file contains partition IDs in [%d, %d], but the current MPI communicator has %d rank(s).\n"
3004 "Remove/regenerate the .part file or run with a matching number of MPI tasks.",
3005 basename.c_str(), min_part, max_part, size);
3009 if (rank == 0 && max_part + 1 != size) {
3011 "Warning: EMI partition file %s.part uses %d partition ID(s), but the current run uses %d MPI rank(s).",
3012 basename.c_str(), max_part + 1, size);
opencarp::local_index_t mesh_int_t
#define SF_COMM
the default SlimFem MPI communicator
opencarp::real_t SF_real
Global scalar type.
#define SF_MPITAG
the MPI tag when communicating
#define CALI_CXX_MARK_FUNCTION
#define CALI_MARK_BEGIN(_str)
#define CALI_MARK_END(_str)
void globalize(SF_nbr nbr_type)
Localize the connectivity data w.r.t. a given numbering.
size_t l_numelem
local number of elements
std::string name
the mesh name
void localize(SF_nbr nbr_type)
Localize the connectivity data w.r.t. a given numbering.
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
Functor class generating a numbering optimized for PETSc.
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.
const T * end() const
Pointer to the vector's end.
const T * begin() const
Pointer to the vector's start.
T * data()
Pointer to the vector's start.
iterator find(const K &key)
Search for key. Return iterator.
hm_int count(const K &key) const
Check if key exists.
void insert(InputIterator first, InputIterator last)
Insert Iterator range.
iterator find(const K &key)
hm_int erase(const K &key)
hm_int count(const K &key) const
void insert(InputIterator first, InputIterator last)
long d_time
current time instance index
double time_step
global reference time step
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.
long d_end
final index in multiples of dt
EMI model based on computed current on the faces, main EMI physics class.
#define log_msg(F, L, O,...)
void init_solver(SF::abstract_linear_solver< T, S > **sol)
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 interval(vector< T > &vec, size_t start, size_t end)
Create an integer interval between start and end.
void make_global(const vector< T > &vec, vector< T > &out, MPI_Comm comm)
make a parallel vector global
void rebalance_mesh(meshdata< T, S > &mesh)
Rebalance the parallel distribution of a mesh, if a local size is 0.
void extract_mesh(const vector< bool > &keep, const meshdata< T, S > &mesh, meshdata< T, S > &submesh)
Extract a submesh from a given mesh.
void permute_mesh(const meshdata< T, S > &inmesh, meshdata< T, S > &outmesh, const vector< T > &perm)
Permute the element data of a mesh based on a given permutation.
T sum(const vector< T > &vec)
Compute sum of a vector's entries.
void unique_resize(vector< T > &_P)
void divide(const size_t gsize, const size_t num_parts, vector< T > &loc_sizes)
divide gsize into num_parts local parts with even distribution of the remainder
void count(const vector< T > &data, vector< S > &cnt)
Count number of occurrences of indices.
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 assemble_matrix(abstract_matrix< T, S > &mat, meshdata< mesh_int_t, mesh_real_t > &domain, matrix_integrator< mesh_int_t, mesh_real_t > &integrator)
Generalized matrix assembly.
int max_nodal_edgecount(const meshdata< T, S > &mesh)
Compute the maximum number of node-to-node edges for a mesh.
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 restrict_to_set(vector< T > &v, const hashmap::unordered_set< T > &set)
bool fileExists(std::string filename)
Function which checks if a given file exists.
elem_t getElemTypeID(char *eletype)
Generate element type enum from string.
void init_vector(SF::abstract_vector< T, S > **vec)
void binary_sort(vector< T > &_V)
void init_matrix(SF::abstract_matrix< T, S > **mat)
void write_mesh_parallel(const meshdata< T, S > &mesh, bool binary, std::string basename)
void binary_sort_sort_copy(vector< T > &_V, vector< T > &_W, vector< S > &_A)
@ 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.
constexpr T min(T a, T b)
constexpr T max(T a, T b)
void dump_trace(MULTI_IF *MIIF, limpet::Real time)
void open_trace(MULTI_IF *MIIF, int n_traceNodes, int *traceNodes, int *label, opencarp::sf_mesh *imesh)
Set up ionic model traces at some global node numbers.
timer_manager * tm_manager
a manager for the various physics timers
bool using_legacy_stimuli
flag storing whether legacy stimuli are used
std::map< mesh_t, sf_mesh > mesh_reg
Registry for the different meshes used in a multi-physics simulation.
int stimidx_from_timeridx(const SF::vector< stimulus > &stimuli, const int timer_id)
determine link between timer and stimulus
sf_vec * get_data(datavec_t d)
Retrieve a petsc data vector from the data registry.
SF::scattering * get_scattering(const int from, const int to, const SF::SF_nbr nbr, const int dpn)
Get a scattering from the global scatter registry.
void set_cond_type(MaterialType &m, cond_t type)
void read_el_scale_vec(const char *file, mesh_t mt, SF::vector< double > &el_scale, int &el_scale_dpn)
SF_real get_volume_from_nodes(sf_mat &mass, SF::vector< mesh_int_t > &local_idx)
sf_mesh & get_mesh(const mesh_t gt)
Get a mesh by specifying the gridID.
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 ...
cond_t
description of electrical tissue properties
SF::scattering * get_permutation(const int mesh_id, const int perm_id, const int dpn)
Get the PETSC to canonical permutation scattering for a given mesh and number of dpn.
void region_mask(mesh_t meshspec, SF::vector< RegionSpecs > ®spec, SF::vector< int > ®ionIDs, bool mask_elem, const char *reglist, bool warn_on_default_tags)
classify elements/points as belonging to a region
SF::meshdata< mesh_int_t, mesh_real_t > sf_mesh
void apply_stim_to_vector(const stimulus &s, sf_vec &vec, bool add)
void read_indices_global(SF::vector< T > &idx, const std::string filename, MPI_Comm comm)
int get_rank(MPI_Comm comm=PETSC_COMM_WORLD)
T get_global(T in, MPI_Op OP, MPI_Comm comm=PETSC_COMM_WORLD)
Do a global reduction on a variable.
void indices_from_region_tags(SF::vector< mesh_int_t > &idx, const sf_mesh &mesh, const hashmap::unordered_set< int > &tags)
Populate vertex data with the vertices of multiple tag regions.
void init_stim_info(void)
uses potential for stimulation
bool is_extra(stim_t type)
whether stimulus is on extra grid (or on intra)
FILE_SPEC f_open(const char *fname, const char *mode)
Open a FILE_SPEC.
bool have_dbc_stims(const SF::vector< stimulus > &stimuli)
return wheter any stimuli require dirichlet boundary conditions
SF::scattering * register_permutation(const int mesh_id, const int perm_id, const int dpn)
Register a permutation between two orderings for a mesh.
bool is_current(stim_t type)
uses current as stimulation
char * dupstr(const char *old_str)
void compute_restr_idx(sf_mesh &mesh, SF::vector< mesh_int_t > &inp_idx, SF::vector< mesh_int_t > &idx)
void log_msg(FILE_SPEC out, int level, unsigned char flag, const char *fmt,...)
@ emi_surface_unique_face_msh
@ emi_surface_counter_msh
void get_time(double &tm)
bool mesh_is_registered(const mesh_t gt)
check wheter a SF mesh is set
SF::abstract_vector< SF_int, SF_real > sf_vec
const char * get_tsav_ext(double time)
SF::abstract_matrix< SF_int, SF_real > sf_mat
V timing(V &t2, const V &t1)
std::string get_basename(const std::string &path)
void f_close(FILE_SPEC &f)
Close a FILE_SPEC.
#define UM2_to_CM2
convert um^2 to cm^2
#define PETSC_TO_CANONICAL
Permute algebraic data from PETSC to canonical ordering.
#define ALG_TO_NODAL
Scatter algebraic to nodal.
#define ELEM_PETSC_TO_CANONICAL
Permute algebraic element data from PETSC to canonical ordering.
Electrical stimulation functions.