# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH
"""Geometry/mesh generation entrypoint for `jcmsuite`."""
from __future__ import annotations
import asyncio
import math
import shutil
from collections.abc import Coroutine, Mapping
from pathlib import Path
from typing import Literal, overload
from ..context import SolverContext, resolve_context
from ..context.subprocess_tools import _call_binary
from ..exceptions import (
ConfigMappingError,
InvalidConfigurationError,
RuntimeContextError,
)
from ..internal.diagnostics import parse_source_position
from ..templates import jcmt2jcm
@overload
def geo(
project_dir: str | Path = ".",
*,
keys: Mapping[str, object] | None = None,
working_dir: str | Path | None = None,
jcmt_pattern: str | None = None,
show: bool = False,
show_duration: float = float("inf"),
context: SolverContext | None = None,
asynchronous: Literal[False] = False,
) -> None: ...
@overload
def geo(
project_dir: str | Path = ".",
*,
keys: Mapping[str, object] | None = None,
working_dir: str | Path | None = None,
jcmt_pattern: str | None = None,
show: bool = False,
show_duration: float = float("inf"),
context: SolverContext | None = None,
asynchronous: Literal[True],
) -> Coroutine[object, object, None]: ...
[docs]
def geo(
project_dir: str | Path = ".",
*,
keys: Mapping[str, object] | None = None,
working_dir: str | Path | None = None,
jcmt_pattern: str | None = None,
show: bool = False,
show_duration: float = float("inf"),
context: SolverContext | None = None,
asynchronous: bool = False,
) -> None | Coroutine[object, object, None]:
"""Create the mesh for a project with `JCMgeo`.
Parameters
----------
project_dir : str | Path, optional
project directory that contains `layout.jcm` or `layout.jcmt`.
keys : Mapping[str, object] | None, optional
project keys for `.jcmt` input files.
working_dir : str | Path | None, optional
Directory in which `JCMgeo` creates the mesh. If omitted, use
`project_dir`.
jcmt_pattern : str | None, optional
JCMT pattern that selects `layout.<suffix>.jcm` or
`layout.<suffix>.jcmt` before the unsuffixed file.
show : bool, optional
If `True`, show the generated mesh with `JCMgeo`.
show_duration : float, optional
Number of seconds to show the mesh if `show=True`. Use
`float("inf")` to keep the mesh window open.
context : SolverContext | None, optional
JCMsuite settings to use. If omitted, use the active context or the
default context.
asynchronous : bool, optional
If `True`, return a value that you must use with `await`.
Returns
-------
None | Coroutine[object, object, None]
`None` after the mesh is created. If `asynchronous` is `True`, returns
a coroutine that creates the mesh.
Raises
------
InvalidConfigurationError
If a project directory or working directory is not valid.
ConfigMappingError
If `JCMgeo` reports an error at a position in an input file.
RuntimeContextError
If `JCMgeo` is not available.
RuntimeError
If `JCMgeo` fails. This error also occurs if asynchronous code calls
the function without `asynchronous=True`.
TypeError
If `show` is not a Boolean value or `show_duration` is not a number.
ValueError
If `show=True` and `show_duration` is not positive.
"""
if asynchronous:
return _geo_impl(
project_dir=project_dir,
keys=keys,
working_dir=working_dir,
jcmt_pattern=jcmt_pattern,
show=show,
show_duration=show_duration,
context=context,
)
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(
_geo_impl(
project_dir=project_dir,
keys=keys,
working_dir=working_dir,
jcmt_pattern=jcmt_pattern,
show=show,
show_duration=show_duration,
context=context,
)
)
raise RuntimeError(
"geo() called from a running event loop; use `await geo(..., asynchronous=True)`."
)
async def _geo_impl(
*,
project_dir: str | Path,
keys: Mapping[str, object] | None,
working_dir: str | Path | None,
jcmt_pattern: str | None,
show: bool,
show_duration: float,
context: SolverContext | None,
) -> None:
"""Internal geo implementation shared by sync and async wrappers."""
resolved_context: SolverContext = resolve_context(context)
await resolved_context.startup()
geo_binary_path: Path | None = resolved_context.jcm_geo
if geo_binary_path is None or not geo_binary_path.is_file():
raise RuntimeContextError("JCMgeo binary is not available in the context.")
project_path: Path = Path(project_dir).expanduser().resolve()
if not project_path.is_dir():
raise InvalidConfigurationError(
f"project_dir must point to an existing directory: {project_path}"
)
resolved_working_dir: Path
if working_dir is None:
resolved_working_dir = project_path
else:
candidate_working_dir: Path = Path(working_dir).expanduser()
if not candidate_working_dir.is_absolute():
candidate_working_dir = (project_path / candidate_working_dir).resolve()
resolved_working_dir = candidate_working_dir.resolve()
resolved_working_dir.mkdir(parents=True, exist_ok=True)
if keys is not None or jcmt_pattern is not None:
_prepare_geo_input_files(
project_path=project_path,
working_dir_path=resolved_working_dir,
keys={} if keys is None else keys,
jcmt_pattern=jcmt_pattern,
)
geo_args: list[str] = [str(resolved_working_dir)]
if not isinstance(show, bool):
raise TypeError("show -> boolean value expected.")
if not isinstance(show_duration, (int, float)) or isinstance(show_duration, bool):
raise TypeError("show_duration -> float value expected.")
if show:
if math.isinf(float(show_duration)) and show_duration > 0:
geo_args.append("--show")
elif math.isfinite(float(show_duration)) and show_duration > 0.0:
geo_args.extend(["--show", str(float(show_duration))])
else:
raise ValueError("show_duration must be positive or infinity.")
_stdout_text: str
stderr_text: str
return_code: int | None
_stdout_text, stderr_text, return_code = await _call_binary(
geo_binary_path,
args=geo_args,
)
if return_code not in (0, None):
source_path: Path | None
line: int | None
column: int | None
source_path, line, column = parse_source_position(
stderr_text,
base_dir=resolved_working_dir,
)
if source_path is not None:
raise ConfigMappingError(
"*** JCMgeo failed.",
source=source_path,
line=line,
column=column,
)
raise RuntimeError(f"*** JCMgeo failed. ==>\n\n{stderr_text}")
grid_path: Path = resolved_working_dir / "grid.jcm"
if not grid_path.is_file():
raise RuntimeError("*** JCMgeo failed.")
def _prepare_geo_input_files(
*,
project_path: Path,
working_dir_path: Path,
keys: Mapping[str, object],
jcmt_pattern: str | None,
) -> None:
"""Prepare `layout` input files in the working directory."""
selected_any: bool = False
for jcm_file_name in ("layout.jcm",):
selected_template_path, selected_jcm_path = _select_geo_source_file(
project_path=project_path,
jcm_file_name=jcm_file_name,
jcmt_pattern=jcmt_pattern,
)
if selected_template_path is None and selected_jcm_path is None:
continue
selected_any = True
target_jcm_path: Path = working_dir_path / jcm_file_name
if selected_template_path is not None:
jcmt2jcm(
selected_template_path,
keys=keys,
outputfile=target_jcm_path,
)
continue
if (
selected_jcm_path is not None
and selected_jcm_path.is_file()
and selected_jcm_path.resolve() != target_jcm_path.resolve()
):
shutil.copyfile(selected_jcm_path, target_jcm_path)
if jcmt_pattern is not None and not selected_any:
raise InvalidConfigurationError(
f"No layout input matched JCMT pattern {jcmt_pattern!r} in {project_path}."
)
def _select_geo_source_file(
*,
project_path: Path,
jcm_file_name: str,
jcmt_pattern: str | None,
) -> tuple[Path | None, Path | None]:
"""Select preferred template/jcm source file for geo input preparation."""
candidate_paths: list[Path] = []
if jcmt_pattern is not None:
pattern_jcm_name: str = jcm_file_name.replace(".jcm", f".{jcmt_pattern}.jcm")
candidate_paths.extend(
[
project_path / f"{pattern_jcm_name}t",
project_path / pattern_jcm_name,
]
)
candidate_paths.extend(
[
project_path / f"{jcm_file_name}t",
project_path / jcm_file_name,
]
)
for candidate_path in candidate_paths:
if candidate_path.is_file():
if candidate_path.suffix in (".jcmt", ".jcmpt"):
return candidate_path.resolve(), None
return None, candidate_path.resolve()
return None, None