"""What a geometry file holds: :func:`summarize` measures it, :func:`format_summary` prints it."""
from pathlib import Path
from typing import Any
from mpi4py import MPI
import dolfinx
import numpy as np
import ufl
from . import check as _check
from .geometry import IO_BACKEND_SUFFIXES, Geometry
from .standard import FIBER_NAMES
UNIT_TO_CM = {"m": 1e2, "cm": 1.0, "mm": 1e-1}
def _owned_entities(mesh: dolfinx.mesh.Mesh, dim: int) -> int:
mesh.topology.create_entities(dim)
return int(mesh.comm.allreduce(mesh.topology.index_map(dim).size_local))
def _tag_counts(
geometry: Geometry, tags: dolfinx.mesh.MeshTags | None, dim: int
) -> dict[str, dict[str, int]]:
"""``{name: {"tag", "count"}}`` of the markers of dimension `dim`; counts are global."""
mesh = geometry.mesh
mesh.topology.create_entities(dim)
n_owned = mesh.topology.index_map(dim).size_local
# Any integer dtype: dolfinx nightly types MeshTags.values wider than int32
values: np.ndarray = np.empty(0, dtype=np.int32)
if tags is not None:
values = tags.values[tags.indices < n_owned]
out = {}
for name, (tag, d) in geometry.markers.items():
if int(d) == dim:
count = int(mesh.comm.allreduce(int(np.sum(values == int(tag)))))
out[name] = {"tag": int(tag), "count": count}
return out
def _field(comm: MPI.Comm, data: Any, info: dict[str, Any]) -> dict[str, Any]:
entry: dict[str, Any] = {"element": _check.describe_data(data), **info}
if isinstance(data, dolfinx.fem.Function):
x = _check._owned(data).ravel()
entry["min"] = float(comm.allreduce(float(x.min()) if x.size else np.inf, op=MPI.MIN))
entry["max"] = float(comm.allreduce(float(x.max()) if x.size else -np.inf, op=MPI.MAX))
values = info.get("values")
if values:
counts = {}
for name, value in values.items():
n = int(np.sum(np.abs(x - float(value)) <= _check.VALUE_TOL))
counts[name] = int(comm.allreduce(n))
entry["counts"] = counts
return entry
def _degree(mesh: dolfinx.mesh.Mesh) -> int:
domain = mesh.ufl_domain()
assert domain is not None
return int(domain.ufl_coordinate_element().degree)
[docs]
def summarize(geometry: Geometry, path: Path | None = None) -> dict[str, Any]:
"""Measure `geometry`. Every count is global; every rank must call it."""
mesh = geometry.mesh
comm = mesh.comm
tdim = mesh.topology.dim
info = dict(geometry.info or {})
volume = float(
comm.allreduce(
dolfinx.fem.assemble_scalar(
dolfinx.fem.form(dolfinx.fem.Constant(mesh, 1.0) * ufl.dx(domain=mesh))
)
)
)
x = mesh.geometry.x[:, :tdim]
lo_local = x.min(axis=0) if len(x) else np.full(tdim, np.inf)
hi_local = x.max(axis=0) if len(x) else np.full(tdim, -np.inf)
lo = np.min(comm.allgather(lo_local.tolist()), axis=0).tolist()
hi = np.max(comm.allgather(hi_local.tolist()), axis=0).tolist()
fibres: dict[str, Any] = {}
arrays = {n: getattr(geometry, n) for n in FIBER_NAMES}
arrays = {n: u for n, u in arrays.items() if u is not None}
owned = {n: _check._owned(u) for n, u in arrays.items()}
names = list(owned)
for n in names:
other = [m for m in names if m != n]
dots = [
_check.max_dot(comm, owned[n], owned[m])
for m in other
if owned[n].shape == owned[m].shape
]
fibres[n] = {
"element": _check.describe_data(arrays[n]),
"max_norm_error": _check.max_norm_error(comm, owned[n]),
"max_dot": max(dots) if dots else None,
}
total, untagged = _check._untagged_exterior_facets(geometry)
fields = {
name: _field(comm, data, geometry.additional_data_info.get(name, {}))
for name, data in geometry.additional_data.items()
}
suffix = Path(path).suffix if path is not None else None
backend = {v: k for k, v in IO_BACKEND_SUFFIXES.items()}.get(suffix) if suffix else None
return {
"path": None if path is None else str(path),
"backend": backend,
"format": geometry.file_format,
"unit": geometry.unit,
"written_by": info.get("cardiac_geometry_version"),
"mesh": {
"cell_type": mesh.topology.cell_type.name,
"degree": _degree(mesh),
"cells": _owned_entities(mesh, tdim),
"vertices": _owned_entities(mesh, 0),
"volume": volume,
"bounds": [lo, hi],
},
"facets": _tag_counts(geometry, geometry.ffun, tdim - 1),
"cells": _tag_counts(geometry, geometry.cfun, tdim),
"exterior_facets": total,
"untagged_exterior_facets": untagged,
"fibres": fibres,
"fields": fields,
"info": info,
"problems": [
{"code": p.code, "severity": p.severity, "message": p.message}
for p in _check.check(geometry)
],
}
def _number(x: float) -> str:
"""`x` to four significant digits."""
return f"{x:.4g}"
def _tags(entries: dict[str, dict[str, int]]) -> list[str]:
return [f"{n} {e['tag']}: {e['count']}" for n, e in entries.items()]
def _labelled_rows(label: str, cells: list[str], per_row: int = 4) -> list[str]:
"""`cells` in rows of `per_row`, the first row headed by `label`."""
if not cells:
return [f"{label:<8} none"]
lines = []
for i in range(0, len(cells), per_row):
head = label if i == 0 else ""
lines.append(f"{head:<8} " + " ".join(cells[i : i + per_row]))
return lines