Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
732 changes: 294 additions & 438 deletions .basedpyright/baseline.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ jobs:
sed -i /oct2py/d .test-conda-env-py3.yml
sed -i /h5py/d .test-conda-env-py3.yml
build_py_project_in_conda_env
python -m pip install basedpyright scipy-stubs
python -m pip install basedpyright scipy-stubs optype
basedpyright

pytest3:
Expand Down
7 changes: 7 additions & 0 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@

nitpick_ignore_regex = [
["py:class", r".*VTKConnectivity"],
# NOTE: optype does not have Sphinx compatible documentation
["py:class", r"onp.*"],
# NOTE: don't want to document these
["py:class", r".*NodalAdjacencyLike"],
["py:class", r".*FacialAdjacencyLike"],
]

sphinxconfig_missing_reference_aliases = {
Expand All @@ -56,6 +61,8 @@
"ObjectArray": "class:pytools.obj_array.ObjectArray",
# modepy
"ArrayF": "obj:modepy.typing.ArrayF",
"mp.FunctionSpace": "class:modepy.FunctionSpace",
"mp.Shape": "class:modepy.Shape",
# arraycontext
"Array": "class:arraycontext.Array",
"ArrayContext": "class:arraycontext.ArrayContext",
Expand Down
2 changes: 1 addition & 1 deletion examples/mesh-to-tikz.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
FileSource("../test/blob-2d.step"), 2, order=order,
force_ambient_dim=2,
other_options=[
"-string", "Mesh.CharacteristicLengthMax = %s;" % h]
"-string", f"Mesh.CharacteristicLengthMax = {h};"]
)

print(mesh_to_tikz(mesh))
2 changes: 1 addition & 1 deletion examples/simple-dg.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ def rhs_wrapper(t, q):
assert len(fields.u) == 1
logger.info("[%05d] t %.5e / %.5e norm %.5e",
istep, t, t_final, actx_outer.to_numpy(flat_norm(fields.u, 2)))
vis.write_vtk_file("fld-wave-min-%04d.vtu" % istep, [
vis.write_vtk_file(f"fld-wave-min-{istep:04d}.vtu", [
("q", fields),
])

Expand Down
6 changes: 3 additions & 3 deletions meshmode/discretization/connection/direct.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,10 @@ def _resample_matrix(self, actx: ArrayContext, to_group_index: int,
if len(from_grp_basis_fcts) != nfrom_unit_nodes:
from meshmode.discretization import NoninterpolatoryElementGroupError
raise NoninterpolatoryElementGroupError(
"%s does not support interpolation because it is not "
"unisolvent (its unit node count does not match its "
f"{type(from_grp)} does not support interpolation because "
"it is not unisolvent (its unit node count does not match its "
"number of basis functions). Using connections requires "
"the ability to interpolate." % type(from_grp).__name__)
"the ability to interpolate.")

result = mp.resampling_matrix(
from_grp_basis_fcts,
Expand Down
4 changes: 1 addition & 3 deletions meshmode/discretization/connection/modal.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,7 @@ def __call__(self, ary):
else:
raise NotImplementedError(
"Don't know how to project from group types "
"%s to %s" % (grp.__class__.__name__,
mgrp.__class__.__name__)
)
f"{grp.__class__} to {grp.__class__}")

result_data.append(output)

Expand Down
2 changes: 1 addition & 1 deletion meshmode/discretization/connection/opposite_face.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def get_map_jacobian(unit_nodes):
niter += 1
if niter > 10:
raise RuntimeError("Gauss-Newton (for finding opposite-face reference "
"coordinates) did not converge (residual: %g)" % max_resid)
f"coordinates) did not converge (residual: {max_resid})")

raise AssertionError()

Expand Down
5 changes: 3 additions & 2 deletions meshmode/discretization/poly_element.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,8 +723,9 @@ def __call__(self, mesh_el_group: _MeshElementGroup) -> ElementGroupBase:
:attr:`order`.
"""
if not isinstance(mesh_el_group, self.mesh_group_class):
raise TypeError("only mesh element groups of type '%s' "
"are supported" % self.mesh_group_class.__name__)
raise TypeError(
f"only mesh element groups of type {self.mesh_group_class} "
"are supported")

return self.group_class(mesh_el_group, self.order)

Expand Down
51 changes: 27 additions & 24 deletions meshmode/discretization/visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import logging
from dataclasses import dataclass
from functools import singledispatch
from typing import TYPE_CHECKING, Any, TypeAlias
from typing import TYPE_CHECKING, Any

import numpy as np
from typing_extensions import TypeIs, override
Expand All @@ -56,14 +56,13 @@
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence

from numpy.typing import NDArray
import optype.numpy as onp

from meshmode.discretization import Discretization, ElementGroupBase
from meshmode.discretization.connection.direct import (
DiscretizationConnection,
)


logger = logging.getLogger(__name__)

__doc__ = """
Expand All @@ -75,13 +74,11 @@
.. autofunction:: write_nodal_adjacency_vtk_file
"""

IndexArray: TypeAlias = "NDArray[np.integer]"


# {{{ helpers

def separate_by_real_and_imag(
names_and_fields: Sequence[tuple[str, NDArray[np.inexact]]],
names_and_fields: Sequence[tuple[str, ArrayOrContainerOrScalar]],
real_only: bool,
) -> Iterator[tuple[str, ArrayOrContainerOrScalar]]:
"""
Expand Down Expand Up @@ -135,7 +132,8 @@ def _resample_to_numpy(
*,
stack: bool = False,
by_group: bool = False
) -> NDArray[Any] | ObjectArray[tuple[int, ...], NDArray[Any]]:
) -> (onp.ArrayND[np.inexact]
| ObjectArray[tuple[int, ...], onp.ArrayND[np.inexact]]):
"""
:arg stack: if *True* object arrays are stacked into a single
:class:`~numpy.ndarray`.
Expand Down Expand Up @@ -231,7 +229,7 @@ class _VisConnectivityGroup:
Starting index for subelements in :attr:`vis_connectivity`.
"""

vis_connectivity: np.ndarray
vis_connectivity: onp.Array3D[np.integer[Any]]
vtk_cell_type: int
subelement_nr_base: int

Expand Down Expand Up @@ -364,7 +362,8 @@ def tensor_cell_types(self) -> dict[int, int]:
}

def connectivity_for_element_group(
self, grp: ElementGroupBase) -> tuple[IndexArray, int]:
self, grp: ElementGroupBase
) -> tuple[onp.Array3D[np.integer[Any]], int]:
import modepy as mp

from meshmode.mesh import ModepyElementGroup
Expand All @@ -389,14 +388,14 @@ def connectivity_for_element_group(

else:
raise NotImplementedError("visualization for element groups "
"of type '%s'" % type(grp.mesh_el_group).__name__)
f"of type {type(grp.mesh_el_group)}")

assert len(node_tuples) == grp.nunit_dofs
return el_connectivity, vtk_cell_type

@property
@memoize_method
def cells(self) -> IndexArray:
def cells(self) -> onp.Array2D[np.integer[Any]]:
return np.hstack([
vgrp.vis_connectivity.reshape(-1) for vgrp in self.groups
])
Expand Down Expand Up @@ -436,7 +435,7 @@ def groups(self) -> Sequence[_VisConnectivityGroup]:

@property
@memoize_method
def cell_types(self) -> IndexArray:
def cell_types(self) -> onp.Array1D[np.integer[Any]]:
nsubelements = sum(vgrp.nsubelements for vgrp in self.groups)
cell_types = np.empty(nsubelements, dtype=np.uint8)
cell_types.fill(255)
Expand Down Expand Up @@ -482,7 +481,8 @@ def tensor_cell_types(self) -> dict[int, int]:

@override
def connectivity_for_element_group(
self, grp: ElementGroupBase) -> tuple[IndexArray, int]:
self, grp: ElementGroupBase
) -> tuple[onp.Array3D[np.integer[Any]], int]:
from meshmode.mesh import SimplexElementGroup, TensorProductElementGroup

vtk_major, vtk_minor = self.version.split(".")
Expand All @@ -495,9 +495,10 @@ def connectivity_for_element_group(

node_tuples = vtk_lagrange_simplex_node_tuples(
grp.dim, grp.order, vtk_version=vtk_version)

el_connectivity = np.array(
vtk_lagrange_simplex_node_tuples_to_permutation(node_tuples),
dtype=np.intp).reshape((1, 1, -1))
dtype=np.intp).reshape(1, 1, -1)

vtk_cell_type = self.simplex_cell_types[grp.dim]

Expand All @@ -511,20 +512,22 @@ def connectivity_for_element_group(
grp.dim, grp.order, vtk_version=vtk_version)
el_connectivity = np.array(
vtk_lagrange_quad_node_tuples_to_permutation(node_tuples),
dtype=np.intp).reshape((1, 1, -1))
dtype=np.intp).reshape(1, 1, -1)

vtk_cell_type = self.tensor_cell_types[grp.dim]

else:
raise NotImplementedError("visualization for element groups "
"of type '%s'" % type(grp.mesh_el_group).__name__)
f"of type '{type(grp.mesh_el_group)}'")

assert len(node_tuples) == grp.nunit_dofs
return el_connectivity, vtk_cell_type

@property
@memoize_method
def cells(self) -> tuple[int, IndexArray, IndexArray]:
def cells(self) -> tuple[int,
onp.Array2D[np.integer[Any]],
onp.Array1D[np.integer[Any]]]:
connectivity = np.hstack([
grp.vis_connectivity.reshape(-1)
for grp in self.groups
Expand Down Expand Up @@ -681,8 +684,8 @@ def show_scalar_in_mayavi(self, field, **kwargs):
mlab.triangular_mesh(*args, **kwargs)

else:
raise RuntimeError("meshes of bulk dimension %d are currently "
"unsupported" % self.vis_discr.dim)
raise RuntimeError(f"meshes of bulk dimension {self.vis_discr.dim} "
"are currently unsupported")

if do_show:
mlab.show()
Expand Down Expand Up @@ -1114,7 +1117,7 @@ def create_dataset(grp, name, data, *, shape, offset):
# {{{ xdmf

@memoize_method
def _xdmf_nodes_numpy(self) -> ObjectArray1D[NDArray[np.inexact]]:
def _xdmf_nodes_numpy(self) -> ObjectArray1D[onp.Array2D[np.floating]]:
actx = self.vis_discr._setup_actx
return _resample_to_numpy(
lambda x: x, self.vis_discr,
Expand Down Expand Up @@ -1359,8 +1362,8 @@ def show_scalar_in_matplotlib_3d(self, field, **kwargs):
ax.auto_scale_xyz(xt, yt, zt, had_data)

else:
raise RuntimeError("meshes of bulk dimension %d are currently "
"unsupported" % self.vis_discr.dim)
raise RuntimeError(f"meshes of bulk dimension {self.vis_discr.dim} "
"are currently unsupported")

if do_show:
plt.show()
Expand Down Expand Up @@ -1444,7 +1447,7 @@ def draw_curve(discr):
color=color[igrp])

if artist_handles:
artist_handles[0].set_label("Group %d" % igrp)
artist_handles[0].set_label(f"Group {igrp}")

# }}}

Expand Down Expand Up @@ -1496,7 +1499,7 @@ def write_nodal_adjacency_vtk_file(file_name, mesh,
if overwrite:
os.remove(file_name)
else:
raise FileExistsError("output file '%s' already exists" % file_name)
raise FileExistsError(f"output file '{file_name}' already exists")

with open(file_name, "w") as outf:
AppendedDataXMLGenerator(compressor)(grid).write(outf)
Expand Down
Loading
Loading