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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ examples/*.pdf

*.vtu
*.vts
*.png
*.gif

.cache

Expand Down
13 changes: 7 additions & 6 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
}

nitpick_ignore_regex = [
["py:class", r".*_ProxyNeighborEvaluationResult"],
# Sphinx started complaining about these in 8.2.1(-ish)
# -AK, 2025-02-24
["py:class", r"TypeAliasForwardRef"],
Expand Down Expand Up @@ -70,13 +71,13 @@
"cl_array.Array": "obj:pyopencl.array.Array",
# pymbolic
"ArithmeticExpression": "obj:pymbolic.ArithmeticExpression",
"ArithmeticExpressionContainerTc":
"obj:pymbolic.typing.ArithmeticExpressionContainerTc",
"Expression": "obj:pymbolic.typing.Expression",
"MultiVector": "obj:pymbolic.geometric_algebra.MultiVector",
"Variable": "class:pymbolic.primitives.Variable",
"prim.Subscript": "class:pymbolic.primitives.Subscript",
"prim.Variable": "class:pymbolic.primitives.Variable",
"ArithmeticExpressionContainerTc":
"obj:pymbolic.typing.ArithmeticExpressionContainerTc",
# arraycontext
"ArrayContainer": "obj:arraycontext.ArrayContainer",
"ArrayOrContainerOrScalar": "obj:arraycontext.ArrayOrContainerOrScalar",
Expand All @@ -91,6 +92,7 @@
# boxtree
"FromSepSmallerCrit": "obj:boxtree.traversal.FromSepSmallerCrit",
"TimingResult": "class:boxtree.timing.TimingResult",
"Tree": "obj:boxtree.tree.Tree",
"TreeKind": "obj:boxtree.tree_build.TreeKind",
# sumpy
"ExpansionBase": "class:sumpy.expansion.ExpansionBase",
Expand All @@ -114,11 +116,10 @@
"Side": "obj:pytential.symbolic.primitives.Side",
"TargetOrDiscretization": "obj:pytential.target.TargetOrDiscretization",
"VectorExpression": "obj:pytential.symbolic.pde.scalar.VectorExpression",
"pytential.symbolic.dof_desc.DOFDescriptorLike":
"data:pytential.symbolic.dof_desc.DOFDescriptorLike",
"pytential.symbolic.primitives.ExpressionNode":
"class:pytential.symbolic.primitives.ExpressionNode",
"pytential.symbolic.dof_desc.DOFDescriptorLike": "data:pytential.symbolic.dof_desc.DOFDescriptorLike", # noqa: E501
"pytential.symbolic.primitives.ExpressionNode": "class:pytential.symbolic.primitives.ExpressionNode", # noqa: E501
"sym.DOFDescriptor": "class:pytential.symbolic.dof_desc.DOFDescriptor",
"sym.DOFDescriptorLike": "obj:pytential.symbolic.dof_desc.DOFDescriptorLike",
"sym.IntG": "class:pytential.symbolic.primitives.IntG",
"sym.var": "obj:pytential.symbolic.primitives.var",
}
Expand Down
1 change: 1 addition & 0 deletions doc/linalg.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Low-level Functionality
All the classes and routines in this module are experimental and the
API can change at any point.

.. automodule:: pytential.linalg.cluster
.. automodule:: pytential.linalg.proxy
.. automodule:: pytential.linalg.skeletonization

Expand Down
199 changes: 199 additions & 0 deletions examples/scaling-study-hmatrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
__copyright__ = "Copyright (C) 2022 Alexandru Fikl"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import logging
from dataclasses import dataclass

import numpy as np

from meshmode.array_context import PyOpenCLArrayContext
from pytools.convergence import EOCRecorder

from pytential import GeometryCollection, sym


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


@dataclass(frozen=True)
class Timings:
build: float
matvec: float


def run_hmatrix_matvec(
actx: PyOpenCLArrayContext,
places: GeometryCollection, *,
dofdesc: sym.DOFDescriptor) -> None:
from sumpy.kernel import LaplaceKernel
kernel = LaplaceKernel(places.ambient_dim)
sym_u = sym.var("u")
sym_op = -0.5 * sym_u + sym.D(kernel, sym_u, qbx_forced_limit="avg")

density_discr = places.get_discretization(dofdesc.geometry, dofdesc.discr_stage)
u = actx.thaw(density_discr.nodes()[0])

def build_hmat():
from pytential.linalg.hmatrix import build_hmatrix_by_proxy
return build_hmatrix_by_proxy(
actx, places, sym_op, sym_u,
domains=[dofdesc],
context={},
auto_where=dofdesc,
id_eps=1.0e-10,
_tree_kind="adaptive-level-restricted",
_approx_nproxy=64,
_proxy_radius_factor=1.15).get_forward()

# warmup
from pytools import ProcessTimer
with ProcessTimer() as pt:
hmat = build_hmat()
actx.queue.finish()

logger.info("build(warmup): %s", pt)

# build
with ProcessTimer() as pt:
hmat = build_hmat()
actx.queue.finish()

t_build = pt.wall_elapsed
logger.info("build: %s", pt)

# matvec
with ProcessTimer() as pt:
du = hmat @ u
assert du is not None
actx.queue.finish()

t_matvec = pt.wall_elapsed
logger.info("matvec: %s", pt)

return Timings(t_build, t_matvec)

Check failure on line 93 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Argument of type "float | None" cannot be assigned to parameter "matvec" of type "float" in function "__init__"   Type "float | None" is not assignable to type "float"     "None" is not assignable to "float" (reportArgumentType)

Check failure on line 93 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Argument of type "float | None" cannot be assigned to parameter "build" of type "float" in function "__init__"   Type "float | None" is not assignable to type "float"     "None" is not assignable to "float" (reportArgumentType)

Check failure on line 93 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Type "Timings" is not assignable to return type "None"   "Timings" is not assignable to "None" (reportReturnType)


def run_scaling_study(
ambient_dim: int, *,
target_order: int = 4,
source_ovsmp: int = 4,
qbx_order: int = 4,
) -> None:
dd = sym.DOFDescriptor(f"d{ambient_dim}", discr_stage=sym.QBX_SOURCE_STAGE2)

import pyopencl as cl
ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)
actx = PyOpenCLArrayContext(queue)

eoc_build = EOCRecorder()
eoc_matvec = EOCRecorder()

import meshmode.discretization.poly_element as mpoly
import meshmode.mesh.generation as mgen

resolutions = [64, 128, 256, 512, 1024, 1536, 2048, 2560, 3072]

for n in resolutions:
mesh = mgen.make_curve_mesh(
mgen.NArmedStarfish(5, 0.25),
np.linspace(0, 1, n),
order=target_order)

from meshmode.discretization import Discretization
pre_density_discr = Discretization(actx, mesh,
mpoly.InterpolatoryQuadratureGroupFactory(target_order))

from pytential.qbx import QBXLayerPotentialSource
qbx = QBXLayerPotentialSource(
pre_density_discr,
fine_order=source_ovsmp * target_order,
qbx_order=qbx_order,
fmm_order=False, fmm_backend=None,

Check failure on line 132 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Argument of type "None" cannot be assigned to parameter "fmm_backend" of type "FMMBackend" in function "__init__"   Type "None" is not assignable to type "FMMBackend"     "None" is not assignable to "Literal['sumpy']"     "None" is not assignable to "Literal['fmmlib']" (reportArgumentType)
)
places = GeometryCollection(qbx, auto_where=dd.geometry)
density_discr = places.get_discretization(dd.geometry, dd.discr_stage)

logger.info("ndofs: %d", density_discr.ndofs)
logger.info("nelements: %d", density_discr.mesh.nelements)

timings = run_hmatrix_matvec(actx, places, dofdesc=dd)
eoc_build.add_data_point(density_discr.ndofs, timings.build)

Check failure on line 141 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Cannot access attribute "build" for class "None"   Attribute "build" is unknown (reportAttributeAccessIssue)

Check warning on line 141 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Argument type is unknown   Argument corresponds to parameter "error" in function "add_data_point" (reportUnknownArgumentType)

Check warning on line 141 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Type of "build" is unknown (reportUnknownMemberType)
eoc_matvec.add_data_point(density_discr.ndofs, timings.matvec)

Check failure on line 142 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Cannot access attribute "matvec" for class "None"   Attribute "matvec" is unknown (reportAttributeAccessIssue)

Check warning on line 142 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Argument type is unknown   Argument corresponds to parameter "error" in function "add_data_point" (reportUnknownArgumentType)

Check warning on line 142 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Type of "matvec" is unknown (reportUnknownMemberType)

for name, eoc in [("build", eoc_build), ("matvec", eoc_matvec)]:
logger.info("%s\n%s",
name, eoc.pretty_print(
abscissa_label="dofs",
error_label=f"{name} (s)",
abscissa_format="%d",
error_format="%.3fs",
eoc_format="%.2f",
)
)
visualize_eoc(f"scaling-study-hmatrix-{name}", eoc, 1)


def visualize_eoc(
filename: str, eoc: EOCRecorder, order: int,
overwrite: bool = False) -> None:
try:
import matplotlib.pyplot as plt
except ImportError:
logger.info("matplotlib not available for plotting")
return

fig = plt.figure(figsize=(10, 10), dpi=300)

Check warning on line 166 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Type of "figure" is partially unknown   Type of "figure" is "(num: int | str | Figure | SubFigure | None = None, figsize: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None, dpi: float | None = None, *, facecolor: tuple[float, float, float] | str | tuple[float, float, float, float] | tuple[tuple[float, float, float] | str, float] | tuple[tuple[float, float, float, float], float] | None = None, edgecolor: tuple[float, float, float] | str | tuple[float, float, float, float] | tuple[tuple[float, float, float] | str, float] | tuple[tuple[float, float, float, float], float] | None = None, frameon: bool = True, FigureClass: type[Figure] = Figure, clear: bool = False, **kwargs: Unknown) -> Figure" (reportUnknownMemberType)
ax = fig.gca()

h, error = np.array(eoc.history).T # type: ignore[no-untyped-call]

Check warning on line 169 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Type of "T" is unknown (reportUnknownMemberType)

Check warning on line 169 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Type of "error" is unknown (reportUnknownVariableType)

Check warning on line 169 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Type of "h" is unknown (reportUnknownVariableType)
ax.loglog(h, error, "o-")

max_h = np.max(h)
min_e = np.min(error)
max_e = np.max(error)
min_h = np.exp(np.log(max_h) + np.log(min_e / max_e) / order)

ax.loglog(
[max_h, min_h], [max_e, min_e], "k-", label=rf"$\mathcal{{O}}(h^{order})$"
)

# }}}

ax.grid(True, which="major", linestyle="-", alpha=0.75)
ax.grid(True, which="minor", linestyle="--", alpha=0.5)

ax.set_xlabel("$N$")
ax.set_ylabel("$T~(s)$")

import pathlib
filename = pathlib.Path(filename)

Check failure on line 190 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Type "Path" is not assignable to declared type "str"   "Path" is not assignable to "str" (reportAssignmentType)
if not overwrite and filename.exists():

Check failure on line 191 in examples/scaling-study-hmatrix.py

View workflow job for this annotation

GitHub Actions / basedpyright

Cannot access attribute "exists" for class "str"   Attribute "exists" is unknown (reportAttributeAccessIssue)
raise FileExistsError(f"output file '{filename}' already exists")

fig.savefig(filename)
plt.close(fig)


if __name__ == "__main__":
run_scaling_study(ambient_dim=2)
Loading
Loading