# # Converting a geometry
#
# Geometries made before format 1 are an io4dolfinx file with JSON files beside it, and sometimes
# the fields of a simulation in a file of their own. `geox convert` turns such a case into one
# self-describing file, with a TOML mapping that says what the old names and tags mean. Here we do
# it for a small case that has the layout of the Rodero BiV that
# [physcardems](https://github.com/finsberg/physcardems) uses: old facet names (`LV`, `RV`), cell
# tags 1 and 2 for the walls and 7 to 10 for the valve regions, fibers on DG0, and a cell type and
# an activation time in a separate file, `ep_node_fields.bp`. The page
# [geometry file](../docs/geometry_file.md) describes the standard.
#
# The conversion reads files and runs on one process.

import json
import shutil
from pathlib import Path

import dolfinx
import io4dolfinx
import numpy as np
from mpi4py import MPI

import cardiac_geometries as cg
from cardiac_geometries import check, convert, export, summary

comm = MPI.COMM_WORLD
folder = Path("convert_demo")
if comm.rank == 0:
    shutil.rmtree(folder, ignore_errors=True)
    folder.mkdir()
comm.barrier()

# ## A case in the old layout
#
# We start from a coarse BiV ellipsoid and tag its cells. The cells above a certain height are the
# valve regions: they are split in four by the plane through the mean of their midpoints, and the
# rest of the cells are the LV wall (the left half, 1) and the RV wall (the right half, 2).

geo = cg.mesh.biv_ellipsoid(folder / "generated", char_length=1.0)
mesh = geo.mesh
tdim = mesh.topology.dim
ncells = mesh.topology.index_map(tdim).size_local
midpoints = dolfinx.mesh.compute_midpoints(mesh, tdim, np.arange(ncells, dtype=np.int32))

tags = np.where(midpoints[:, 0] < 0, 1, 2).astype(np.int32)
top = midpoints[:, 2] >= midpoints[:, 2].max() - 0.3
x0, y0 = midpoints[top, 0].mean(), midpoints[top, 1].mean()
quadrant = {(True, True): 7, (False, True): 8, (True, False): 9, (False, False): 10}
for i in np.flatnonzero(top):
    tags[i] = quadrant[(bool(midpoints[i, 0] < x0), bool(midpoints[i, 1] < y0))]
cfun = dolfinx.mesh.meshtags(mesh, tdim, np.arange(ncells, dtype=np.int32), tags)

# The facets get the tags of the old case, 10 to 40, under the old names `LV` and `RV`

markers = {"LV": (30, 2), "RV": (20, 2), "EPI": (40, 2), "BASE": (10, 2)}
retag = {geo.markers[name][0]: tag for name, (tag, _) in markers.items()}
ffun = dolfinx.mesh.meshtags(
    mesh,
    tdim - 1,
    geo.ffun.indices,
    np.array([retag[v] for v in geo.ffun.values], dtype=np.int32),
)

# The fibers are constant: along x, y and z. They are orthonormal, so `check` accepts them.


def direction(name, axis):
    u = dolfinx.fem.Function(dolfinx.fem.functionspace(mesh, ("DG", 0, (3,))), name=name)
    u.x.array.reshape(-1, 3)[:, axis] = 1.0
    return u


fibers = {name: direction(name, axis) for axis, name in enumerate(("f0", "s0", "n0"))}

# Now we write the old layout: an adios2 file, `geometry.bp`, and beside it `markers.json` (and
# the JSON files that describe the fibers and the additional data). There is no unit.

path = folder / "geometry.bp"
io4dolfinx.write_mesh(mesh=mesh, filename=path, backend="adios2")
for meshtags, name in ((cfun, "Cell tags"), (ffun, "Facet tags")):
    io4dolfinx.write_meshtags(
        meshtags=meshtags, mesh=mesh, filename=path, meshtag_name=name, backend="adios2"
    )
for u in fibers.values():
    io4dolfinx.write_function(u=u, filename=path, name=u.name, backend="adios2")
if comm.rank == 0:
    microstructure = {
        name: cg.utils.element2array(u.ufl_element())[:4] for name, u in fibers.items()
    }
    for prefix, content in (("markers", markers), ("microstructure", microstructure)):
        (folder / f"{prefix}_geometry.json").write_text(json.dumps(content, default=cg.utils.json_serial))
    (folder / "additional_data_geometry.json").write_text("{}")
    (folder / "markers.json").write_text(json.dumps(markers))
    (folder / "info.json").write_text(json.dumps({"mesh_type": "rodero_like"}))
comm.barrier()

# The cell type and the activation time are P1 fields in a file of their own. The activation time is
# called `lat_ms` there. (We avoid names that end in `_time` in a `.bp` file, since io4dolfinx's
# adios2 backend cannot read them back.)

V = dolfinx.fem.functionspace(mesh, ("P", 1))
celltype = dolfinx.fem.Function(V, name="celltype")
lat = dolfinx.fem.Function(V, name="lat_ms")
celltype.x.array[:] = np.arange(len(celltype.x.array)) % 3
lat.interpolate(lambda x: 130.0 + 10.0 * x[2])
for u in (celltype, lat):
    io4dolfinx.write_function(
        u=u, filename=folder / "ep_node_fields.bp", name=u.name, backend="adios2"
    )

# This geometry is not in the standard. It has no unit, and it uses old facet names, and
# `check` says so. A format-0 file reads, but its errors are reported.

old = cg.geometry.Geometry.from_file(comm, path)
for problem in check.check(old):
    print(problem)

# ## The mapping
#
# The mapping gives what is missing: the unit (this BiV is in centimetres), the new names of the
# facets, a name for each cell tag, and where each field is. It is a TOML file for the command line,
# `geox convert SOURCE OUT.h5 --mapping rodero_like.toml`, and here the same as a dictionary.

mapping = {
    "unit": "cm",
    "facets": {"LV": "LV_ENDO", "RV": "RV_ENDO"},
    "cells": {
        1: "LV_WALL",
        2: "RV_WALL",
        7: "MITRAL_VALVE",
        8: "TRICUSPID_VALVE",
        9: "AORTIC_VALVE",
        10: "PULMONARY_VALVE",
    },
    "fields": {
        "celltype": {
            "file": "ep_node_fields.bp",
            "name": "celltype",
            "element": "P_1",
            "values": {"endo": 0, "epi": 1, "mid": 2},
        },
        "activation_time": {
            "file": "ep_node_fields.bp",
            "name": "lat_ms",
            "element": "P_1",
            "unit": "ms",
        },
    },
    "info": {"source": "rodero_like"},
}

# ## Convert, check and inspect
#
# `convert` checks the result before it writes anything, and raises `ValueError` for an error.

converted = convert.convert(folder, folder / "converted.h5", mapping)

# The new file stands alone. We read it back and check it: no problems.

geo = cg.geometry.Geometry.from_file(comm, folder / "converted.h5")
problems = check.check(geo)
print(problems or "no problems")

# `inspect` prints what the file holds. This is `geox inspect converted.h5`.

print(summary.format_summary(summary.summarize(geo, folder / "converted.h5")))

# ## Export
#
# `export` writes VTU files for ParaView, which the generators do from the command line:
# the mesh with the tags and the fields, the tagged facets, and the legend of the tags.
# It needs pyvista.

try:
    import pyvista  # noqa: F401
except ImportError:
    print("pyvista is not installed, so we do not export")
else:
    for written in export.export(geo, folder / "viz"):
        print(written.name)
