Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f75d543586 |
No files matched your search
@@ -123,7 +123,7 @@ with CudaContext(0) as ctx, FixedPatchStepper(cfg, (8, 6, 24, 18), context=ctx,
|
||||
```
|
||||
|
||||
Scope and limits:
|
||||
- D2Q9, SRT, FP32, double buffer, unshifted, no LES or forcing; fixed 2:1 patch(es), two levels (or one nested third).
|
||||
- D2Q9, SRT, FP32, double buffer, unshifted, no LES or forcing; fixed 2:1 patches, two or three levels with separated rectangles.
|
||||
- `coarse_boundary="periodic"` (default) or `"slot_reservoir"` (bottom slot, top
|
||||
reservoir; patch needs `y0 >= 4`, `y1 <= ny-4`). Periodic mode ignores the wall/slot config fields.
|
||||
- Object centers/radii use the coarse **cell-edge** frame (cell `I` spans `[I, I+1)`),
|
||||
@@ -144,7 +144,8 @@ Scope and limits:
|
||||
not matter. `fine_objects`/`jets` work as for one patch: each circle (same
|
||||
coarse cell-edge frame) must lie wholly inside one patch's active region with
|
||||
its boundary stencil clear of transfer cells; a jet may not select links of two
|
||||
different bodies, even across patches. No wall-touching patches or nesting yet.
|
||||
different bodies, even across patches. Wall-touching patches are unsupported.
|
||||
Three-level nesting uses the explicit child coordinates described below.
|
||||
|
||||
```python
|
||||
cfg = LBMConfig(nx=32, ny=16, viscosity=.1)
|
||||
@@ -164,7 +165,10 @@ Scope and limits:
|
||||
ACTIVE cells, away from L1's ghost band and transfer footprint (checked before
|
||||
any GPU allocation). `initialize` and `download` take/return three arrays; each
|
||||
level is NaN on its non-ACTIVE (and child-covered) cells. One coarse step = 2 L1
|
||||
steps = 4 L2 steps. One L1 patch only. Optional stationary circles and Jets
|
||||
steps = 4 L2 steps. This scalar `child=` form uses one L1 patch.
|
||||
For separated L1/L2 sets, use `child_rectangles_in_parent`; see
|
||||
[coordinate frames and supported layouts](docs/fixed_three_level_multipatch.md).
|
||||
Optional stationary circles and Jets
|
||||
live on L2 via `child_objects` and `child_jets`; `fine_objects`/`jets` retain
|
||||
their L1 meaning and must be empty in this mode. All object and Jet geometry
|
||||
uses the **L0 edge frame**, not the child bounds' L1 window frame. L2 has
|
||||
@@ -192,14 +196,26 @@ Scope and limits:
|
||||
run.step(4)
|
||||
coarse_g, l1_g, l2_g = run.download() # solids/covered/nonleaves are NaN
|
||||
```
|
||||
- Manual synchronized L2 replacement: `replacement = current.remap_child(rectangles,
|
||||
child_objects=original_objects)` preserves the absolute step count and live Jet
|
||||
amplitudes. L0/L1 and whole body-containing L2 rectangles stay fixed; separated
|
||||
fluid rectangles may change. The source remains independently owned. See
|
||||
[ownership, pinning and transfer rules](docs/synchronized_leaf_remap.md).
|
||||
- Runnable three-level example: `PYTHONPATH=src python examples/multigrid_remap.py`.
|
||||
It uses two separated L1 regions, an L2 stationary Circle/Jet and an explicit
|
||||
fluid-rectangle move, retaining original root-frame body definitions. Add
|
||||
`--check-geometry` for a CPU-only check or `--verify-jet` for an optional
|
||||
next-step comparison with an explicitly driven control. No flowfiles are saved.
|
||||
- Not available: per-link surface exchange/force readout in blocked mode,
|
||||
checkpoints, moving bodies, L1 bodies/Jets in a three-level chain,
|
||||
several patches per level with nesting, dynamic refinement, `Simulation`
|
||||
integration. Validation so far is storage/operator equivalence and short runs,
|
||||
not accuracy, convergence or long-time stability. The new L2-body GPU gates
|
||||
(layouts, masks, amplitude reversal, legacy equivalence) and independent
|
||||
every-substep numerical replay remain required acceptance checks; CPU tests
|
||||
alone do not establish GPU numerical correctness.
|
||||
checkpoints, moving bodies, L1 bodies/Jets in a three-level hierarchy,
|
||||
arbitrary depth, automatic AMR or `Simulation` integration.
|
||||
Storage/operator equivalence, remap and short-run gates do not establish
|
||||
convergence or long-time physical accuracy. The earlier shear-decay result is
|
||||
a research accuracy limitation, not a demonstrated solver bug. Pinned-body
|
||||
replay conditioned on actual L1 feeds is not an independent whole-body solver.
|
||||
See [three-level validation scope](docs/fixed_three_level_multipatch.md) and
|
||||
[remap validation scope](docs/synchronized_leaf_remap.md). The new usage example
|
||||
has CPU geometry/syntax checks only until its GPU command is run on Horsea.
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
# Synchronized leaf G remap and manual continuation
|
||||
|
||||
This is a CPU state-transfer component, **not a runtime adaptive solver**.
|
||||
It changes only a separated L2 rectangle set in a three-level, body-free,
|
||||
periodic hierarchy. L0/L1 topology, relaxation parameters, direction order,
|
||||
It changes only a separated L2 rectangle set in a three-level periodic
|
||||
hierarchy, either body-free or with stationary Circles/Jets in unchanged pinned
|
||||
L2 rectangles (see below). L0/L1 topology, relaxation parameters, direction order,
|
||||
physical frame and completed time remain unchanged. Existing geometry checks
|
||||
validate child support/nesting and separation. The CPU helper itself adds no CUDA, scheduler, allocator, boundary handling,
|
||||
collision or ghost refill. A bounded runtime adapter is described below.
|
||||
@@ -29,11 +30,12 @@ origin is retained. Physical lower edges are `origin + spacing*(x,y)` on L0,
|
||||
`origin + spacing*(parent.fine_origin + (x,y)/4)` on L2.
|
||||
|
||||
Factory options `coarse_boundary` and `objects` must declare `"periodic"` and
|
||||
an empty body collection (all levels). LBMConfig's channel settings do not
|
||||
an empty L0/L1 body collection; use `child_objects`/`child_jets` for pinned L2
|
||||
bodies. LBMConfig's channel settings do not
|
||||
select this operator's boundary mode. Geometry metadata is factory-created;
|
||||
manual mutation/forging of metadata is unsupported. Caller certifies the
|
||||
actual state has no bodies/forcing, that all device work and old readers are
|
||||
quiescent, and that inputs are the **current owned-leaf postcollision G**.
|
||||
actual state has no undeclared bodies or forcing, that all device work and old
|
||||
readers are quiescent, and that inputs are the **current owned-leaf postcollision G**.
|
||||
Count/phase stamps check consistency, not freshness or active-buffer identity.
|
||||
|
||||
`current_g` is three NumPy Q-major arrays `(9,ny,nx)`. For blocked inputs,
|
||||
@@ -73,8 +75,9 @@ PYTHONPATH=src python -m unittest discover -s tests/unit -p 'test_synchronized_r
|
||||
|
||||
`replacement = current.remap_child(rectangles)` returns a new ready
|
||||
`FixedPatchStepper` at the **same absolute step_count**. It supports only
|
||||
body-free periodic three-level runs whose existing L2 uses
|
||||
`child_rectangles_in_parent`. Scalar or union L1 parents are supported; scalar
|
||||
periodic three-level runs whose existing L2 uses
|
||||
`child_rectangles_in_parent`, either body-free or under the pinned-body rules below.
|
||||
Scalar or union L1 parents are supported; scalar
|
||||
`child=` is deliberately rejected. L0/L1, relaxation and block sizes stay fixed.
|
||||
No tagger, scheduler, in-place replacement, or general rollback is provided.
|
||||
|
||||
@@ -105,9 +108,9 @@ and geometry, and candidate/source failure cleanup. GPU tests are predeclared
|
||||
in `tests/validation/multigrid/test_runtime_child_remap_gpu.py`: identity next
|
||||
step bitwise, shifted A→B→A with two intervals between changes, uniform moving
|
||||
and nonequilibrium states, exact CPU remap and overlap, both buffers reset,
|
||||
finite leaves, exact masks and absolute counts. They were not run on the CPU
|
||||
host. The separate independent FP64 capture/replay gate is max population
|
||||
error **3e-6**, with exact masks; remap mass/momentum allow FP32 roundoff.
|
||||
finite leaves, exact masks and absolute counts. These are GPU execution gates,
|
||||
not CPU-mock results. The separate body-free independent FP64 capture/replay
|
||||
gate is max population error **3e-6**, with exact masks; remap mass/momentum allow FP32 roundoff.
|
||||
Per-population conservation is not an advancement target under collision.
|
||||
|
||||
### Bounded pinned-body extension
|
||||
@@ -155,6 +158,28 @@ Multiple-body CPU coverage: `tests/unit/test_multiple_pinned_remap.py`.
|
||||
two independently updated Jets, variable fluid-region counts and add/move/remove
|
||||
immediate comparisons with CPU transfer. All nine solid-excluded area-weighted
|
||||
population integrals, exact overlap and nonleaf NaNs are checked.
|
||||
These new GPU cases have **not been run here**. They do not establish evolution
|
||||
accuracy. A 3e-6 FP32-vs-FP64 evolution gate requires a separate independent
|
||||
BFL reference; the body-free replay gate above does not establish that claim.
|
||||
These transfer/equivalence cases do not establish evolution accuracy. Historical
|
||||
pinned-body FP64 replay uses actual L1 feeds: it checks conditional L2 evolution,
|
||||
not an independent whole-body solver or whole-hierarchy accuracy. The body-free
|
||||
replay gate above does not establish that stronger claim either.
|
||||
|
||||
## Small runnable usage example
|
||||
|
||||
[`examples/multigrid_remap.py`](../examples/multigrid_remap.py) keeps the original
|
||||
root-frame Circle/Jet definitions, moves a fluid-only L2 rectangle, checks fluid
|
||||
leaves with geometry-derived masks and retires both old/new owners before their
|
||||
shared context. `--verify-jet` adds a temporary control solely to compare the
|
||||
next step against an explicitly set live amplitude; normal use needs no control.
|
||||
|
||||
```sh
|
||||
# Host-only: no CUDA import or allocation.
|
||||
PYTHONPATH=src python examples/multigrid_remap.py --check-geometry
|
||||
# Horsea: select an approved idle physical GPU; it becomes logical device 0.
|
||||
PYTHONPATH="$PWD/src" CUDA_VISIBLE_DEVICES=0 python examples/multigrid_remap.py --verify-jet
|
||||
```
|
||||
|
||||
The new example has passed host geometry and syntax/import checks only; its GPU
|
||||
run is pending Horsea. Expected scope: base counts 2 before/after remap, then 5;
|
||||
finite positive-density fluid leaves, NaN nonleaves, and exact next-step control
|
||||
agreement. This is a short public-API smoke run, not a physical accuracy test.
|
||||
No flowfiles are written.
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Three levels, separated regions and an explicit fluid-region remap.
|
||||
|
||||
Run on an approved idle GPU (logical device 0):
|
||||
PYTHONPATH=src CUDA_VISIBLE_DEVICES=0 python examples/multigrid_remap.py --verify-jet
|
||||
Host-only geometry check, without CUDA:
|
||||
PYTHONPATH=src python examples/multigrid_remap.py --check-geometry
|
||||
|
||||
A short public-API smoke example, not an accuracy/stability benchmark. No files
|
||||
are written. Edit the rectangles below; this is manual remapping, not auto AMR.
|
||||
"""
|
||||
import argparse
|
||||
from contextlib import ExitStack
|
||||
|
||||
import numpy as np
|
||||
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.jets import Jet, Parallel, Tube
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm.equilibrium import compute_feq_d2q9
|
||||
from CelerisLab.lbm.refinement import FixedPatchSet2D
|
||||
from CelerisLab.lbm.synchronized_remap import RemapTopology
|
||||
|
||||
CFG = LBMConfig(nx=48, ny=32, viscosity=.1) # D2Q9/SRT/FP32, periodic
|
||||
PARENTS = ((4, 4, 20, 28), (24, 4, 44, 28)) # L0 cell-edge rectangles
|
||||
PIN = (16, 16, 32, 24) # L1 allocated-grid indices; whole body region stays fixed
|
||||
BEFORE = (PIN, (56, 32, 72, 40))
|
||||
AFTER = (PIN, (60, 32, 76, 40)) # move only the separated fluid rectangle
|
||||
LIVE_AMPLITUDE = -.004
|
||||
|
||||
|
||||
def geometry():
|
||||
# Retain these original L0 edge-frame definitions for every remap; never
|
||||
# substitute the stepper's projected fine-local boundary objects.
|
||||
objects = (SimObject(0, geometry=CircleGeometry(12., 10., .8),
|
||||
center=(12., 10.), radius=.8),)
|
||||
jets = (Jet(Tube((10.5, 10.), 0., 3., .3), Parallel(0.), amplitude=.002),)
|
||||
parent = FixedPatchSet2D.from_config(CFG, PARENTS)
|
||||
meshes = tuple(RemapTopology.from_config(
|
||||
CFG, parent, rectangles, child_objects=objects, child_jets=jets)
|
||||
for rectangles in (BEFORE, AFTER))
|
||||
if any(mesh.pinned_rectangles != (PIN,) for mesh in meshes):
|
||||
raise RuntimeError("the body-containing rectangle must remain pinned")
|
||||
return objects, jets, meshes
|
||||
|
||||
|
||||
def diagnostics(run, mesh):
|
||||
"""Masks come from geometry, never from whether downloaded values are finite."""
|
||||
mass = 0.
|
||||
for level, (g, leaf) in enumerate(zip(run.download(), mesh.leaf_masks)):
|
||||
fluid = g[:, leaf].astype(np.float64)
|
||||
rho = fluid.sum(axis=0)
|
||||
if not np.isfinite(fluid).all() or np.any(rho <= 0):
|
||||
raise RuntimeError(f"invalid L{level} fluid populations/density")
|
||||
if not np.isnan(g[:, ~leaf]).all():
|
||||
raise RuntimeError(f"unexpected L{level} nonleaf values")
|
||||
mass += rho.sum() / 4**level # area weights: 1, 1/4, 1/16
|
||||
print(f"absolute base step {run.step_count}: finite fluid leaves, mass={mass:.9f}")
|
||||
# Driven boundary injects/extracts mass; mass need not stay constant in time.
|
||||
|
||||
|
||||
def verify_live_jet(current, objects):
|
||||
"""Optional public-API check; normal continuation needs no control solver."""
|
||||
# Identity remap copies the same state. Explicitly setting the known live
|
||||
# amplitude on the control detects a stale amplitude on the continuation.
|
||||
# No private fields or constructor-time Jet snapshots inspect the solver.
|
||||
with current.remap_child(AFTER, child_objects=objects) as control:
|
||||
control.set_jet_amplitude(0, LIVE_AMPLITUDE, level=2)
|
||||
current.step()
|
||||
control.step()
|
||||
for actual, expected in zip(current.download(), control.download()):
|
||||
if not np.array_equal(actual, expected, equal_nan=True):
|
||||
raise RuntimeError("live Jet continuation differs from explicitly set control")
|
||||
print("live Jet amplitude preserved: next step equals explicitly set control")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--check-geometry", action="store_true")
|
||||
parser.add_argument("--verify-jet", action="store_true",
|
||||
help="compare one step with an explicitly driven control")
|
||||
args = parser.parse_args()
|
||||
objects, jets, (old_mesh, new_mesh) = geometry()
|
||||
if args.check_geometry:
|
||||
print("geometry OK: three levels, two L1 regions, fixed body pin, moved fluid region")
|
||||
return
|
||||
|
||||
# Lazy imports keep --check-geometry useful on a CPU-only machine.
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
|
||||
# ExitStack owns every old/new stepper, including on failure. All are closed
|
||||
# before the shared context. remap_child never consumes/closes its source.
|
||||
with CudaContext(0) as context, ExitStack() as owned:
|
||||
old = owned.enter_context(FixedPatchStepper(
|
||||
CFG, PARENTS, context=context, base_block=(4, 4), fine_block=(4, 4),
|
||||
child_block=(4, 4), child_rectangles_in_parent=BEFORE,
|
||||
child_objects=objects, child_jets=jets))
|
||||
rest = np.asarray(compute_feq_d2q9(1., 0., 0.), np.float32)[:, None, None]
|
||||
old.initialize(*(np.broadcast_to(rest, (9, *mask.shape))
|
||||
for mask in old_mesh.leaf_masks))
|
||||
old.step(2) # one base step advances L1 twice and L2 four times
|
||||
old.set_jet_amplitude(0, LIVE_AMPLITUDE, level=2)
|
||||
diagnostics(old, old_mesh)
|
||||
count = old.step_count
|
||||
current = owned.enter_context(old.remap_child(AFTER, child_objects=objects))
|
||||
if current is old or current.step_count != count:
|
||||
raise RuntimeError("remap must return a distinct continuation at the same time")
|
||||
diagnostics(current, new_mesh)
|
||||
|
||||
if args.verify_jet:
|
||||
verify_live_jet(current, objects) # optional control; advances one step
|
||||
else:
|
||||
current.step()
|
||||
if old.step_count != count or current.step_count != count + 1:
|
||||
raise RuntimeError("old/new absolute step ownership changed")
|
||||
old.close() # retire the old state only after successful replacement
|
||||
current.step(2)
|
||||
if current.step_count != count + 3:
|
||||
raise RuntimeError("continuation lost its absolute step count")
|
||||
diagnostics(current, new_mesh)
|
||||
print("smoke example only: no accuracy or long-time stability claim")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,97 +0,0 @@
|
||||
# CelerisLab/lbm/hierarchy.py
|
||||
"""Host-only geometry of a fixed 2:1 refinement hierarchy of any depth (numpy, no CUDA).
|
||||
|
||||
Loops the existing adjacent-pair logic of refinement.py; it adds no transfer rule.
|
||||
``refinements[l]`` describes level l+1 in level-l integer cells: a scalar
|
||||
(x0, y0, x1, y1) is one FixedPatch2D window (its level keeps the window shape), a
|
||||
sequence of rectangles is a FixedPatchSet2D on the level-wide grid (origin 0).
|
||||
A scalar child is only accepted under a scalar parent. Every pair after the first
|
||||
is built by nest_patch/nest_patch_set, whose _nested_kind validates coverage,
|
||||
donors/receivers, surviving pulls and the parent's upward restriction footprint.
|
||||
"""
|
||||
from dataclasses import dataclass, replace
|
||||
from numbers import Integral
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .refinement import (ACTIVE, OUTER_GHOST, FixedPatch2D, FixedPatchSet2D,
|
||||
_middle_config, nest_patch, nest_patch_set)
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Hierarchy:
|
||||
"""configs[l]: validated LBMConfig of level l; pairs[l]: tables of (l, l+1);
|
||||
kinds[l]: composed per-cell kind (child coverage OUTER on every non-finest level)."""
|
||||
configs: tuple
|
||||
pairs: tuple
|
||||
kinds: tuple
|
||||
|
||||
@property
|
||||
def depth(self):
|
||||
return len(self.kinds)
|
||||
|
||||
|
||||
def is_rectangle(value):
|
||||
value = tuple(value)
|
||||
return len(value) == 4 and all(isinstance(v, (Integral, np.integer))
|
||||
and not isinstance(v, (bool, np.bool_)) for v in value)
|
||||
|
||||
|
||||
def build_hierarchy(cfg, refinements, *, wall_aware=False):
|
||||
"""Geometry for len(refinements) + 1 levels; wall_aware marks base rows 0 and -1 OUTER."""
|
||||
configs, pairs, kinds = [_validated(cfg)], [], []
|
||||
for level, entry in enumerate(refinements):
|
||||
scalar = is_rectangle(entry)
|
||||
if not scalar and not tuple(entry):
|
||||
raise ValueError("every refinement level needs at least one rectangle")
|
||||
if level == 0:
|
||||
pair = (FixedPatch2D if scalar else FixedPatchSet2D).from_config(configs[0], entry)
|
||||
kind = np.where(pair.covered, OUTER_GHOST, ACTIVE).astype(np.uint8)
|
||||
if wall_aware:
|
||||
kind[[0, -1]] = OUTER_GHOST
|
||||
elif scalar:
|
||||
if not isinstance(pairs[-1], FixedPatch2D):
|
||||
raise ValueError("a scalar child requires a scalar parent; use a rectangle list")
|
||||
pair, kind = nest_patch(configs[level - 1], pairs[-1], entry)
|
||||
else:
|
||||
pair, kind = nest_patch_set(configs[level - 1], pairs[-1], entry)
|
||||
kinds.append(np.asarray(kind))
|
||||
pairs.append(pair)
|
||||
configs.append(_validated(_middle_config(configs[level], pair)))
|
||||
_check_chain(configs[level], configs[level + 1], pair)
|
||||
if pairs:
|
||||
kinds.append(pairs[-1].fine_kind)
|
||||
else:
|
||||
kinds.append(np.full((cfg.ny, cfg.nx), ACTIVE, np.uint8))
|
||||
return Hierarchy(tuple(configs), tuple(pairs), tuple(kinds))
|
||||
|
||||
|
||||
def _validated(cfg):
|
||||
"""LBMConfig.omega is computed only by validate(); replace() copies it stale."""
|
||||
cfg = replace(cfg)
|
||||
cfg.validate()
|
||||
return cfg
|
||||
|
||||
|
||||
def _check_chain(coarse, fine, pair):
|
||||
if not (np.isclose(pair.tau_coarse, 1 / coarse.omega, rtol=1e-12, atol=0)
|
||||
and np.isclose(pair.tau_fine, 1 / fine.omega, rtol=1e-12, atol=0)
|
||||
and tuple(pair.fine_shape) == (fine.ny, fine.nx)):
|
||||
raise RuntimeError("level config chain is inconsistent with the pair tables")
|
||||
|
||||
|
||||
def leaf_partition(h):
|
||||
"""Base-cell fraction published as ACTIVE over all levels (exact: powers of two).
|
||||
|
||||
Window (scalar) levels are offset by their fine_level_origin first.
|
||||
"""
|
||||
base = np.zeros(h.kinds[0].shape)
|
||||
oy = ox = 0
|
||||
for level, kind in enumerate(h.kinds):
|
||||
if level:
|
||||
pair = h.pairs[level - 1]
|
||||
py, px = (pair.fine_level_origin if isinstance(pair, FixedPatch2D) else (0, 0))
|
||||
oy, ox = 2 * oy + py, 2 * ox + px
|
||||
y, x = np.nonzero(kind == ACTIVE)
|
||||
np.add.at(base, ((y + oy) >> level, (x + ox) >> level), 0.25 ** level)
|
||||
return base
|
||||
@@ -15,14 +15,37 @@ import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from ..cuda import compiler_v2 as compiler
|
||||
from .blocks import BlockLayout2D
|
||||
from ..body.jets import jet_link_velocity
|
||||
from .blocks import BlockLayout2D, blocked_link_tables
|
||||
from .curved_links import surface_link_velocity
|
||||
from ..body.jets import jet_link_shapes, jet_link_velocity
|
||||
from .block_stepper import MAX_GRID_DIM
|
||||
from .refinement import (ACTIVE, HALO, FixedPatch2D, FixedPatchSet2D,
|
||||
from .refinement import (ACTIVE, HALO, OUTER_GHOST, FixedPatch2D, FixedPatchSet2D,
|
||||
nest_patch, nest_patch_set, prepare_fine_boundary)
|
||||
from .refinement_tables import (blocked_base_tables, blocked_fine_tables, # noqa: F401 (re-export)
|
||||
blocked_kind, _prepare_blocked_boundary)
|
||||
from .descriptors import SOLID
|
||||
from .descriptors import SOLID, D2Q9_EX, D2Q9_EY
|
||||
|
||||
|
||||
def blocked_fine_tables(patch, layout, order):
|
||||
"""Remap fixed-patch fine tables to owner-core blocked storage (host only).
|
||||
|
||||
Returns (explosion target block cells, coalescence child slots in the same
|
||||
rows/child order as ``patch.coalesce_fine[order]``, per-block-cell kind with
|
||||
unused halo entries OUTER). Coarse donors/targets are unchanged.
|
||||
"""
|
||||
owner = layout.owner.ravel().astype(np.intp)
|
||||
cells = patch.fine_shape[0] * patch.fine_shape[1]
|
||||
q, cell = np.divmod(patch.coalesce_fine[order], np.uint64(cells))
|
||||
kind = blocked_kind(layout, patch.fine_kind)
|
||||
return (owner[patch.ghost_fine.astype(np.intp)].astype(np.uint64),
|
||||
layout.slot(owner[cell.astype(np.intp)], q), kind)
|
||||
|
||||
|
||||
def blocked_kind(layout, dense_kind):
|
||||
"""Per-block-cell kind; unused halo entries and unstored holes stay OUTER."""
|
||||
owner = layout.owner.ravel().astype(np.intp)
|
||||
owned = layout.owned.ravel() # sparse multipatch levels leave holes unstored
|
||||
kind = np.full(layout.nblocks * int(np.prod(layout.local_shape)), OUTER_GHOST, np.uint8)
|
||||
kind[owner[owned]] = np.asarray(dense_kind).ravel()[owned]
|
||||
return kind
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -39,6 +62,36 @@ class _Pair:
|
||||
parent_cells: int # parent block window cells (explode donor stride)
|
||||
|
||||
|
||||
def blocked_base_tables(patch, layout, order, wall_aware=False, *, composed_kind=None):
|
||||
"""Parent donor cells and receiver-local arrival slots, in transfer row order.
|
||||
|
||||
Stage arrivals only after child reads and parent halo gather, immediately
|
||||
before parent pull. Source *owner* slots are wrong at block seams.
|
||||
Nested pairs must pass composed_kind to retain inherited INNER/OUTER and
|
||||
sparse holes; donors and receivers must be owned, uncovered ACTIVE cells.
|
||||
"""
|
||||
owner = layout.owner.ravel()
|
||||
q, receiver = np.divmod(patch.coalesce_coarse[order], np.uint64(owner.size))
|
||||
if composed_kind is None:
|
||||
dense_kind = np.where(patch.covered, OUTER_GHOST, ACTIVE).astype(np.uint8)
|
||||
if wall_aware:
|
||||
dense_kind[[0, -1]] = OUTER_GHOST
|
||||
else:
|
||||
dense_kind = np.asarray(composed_kind)
|
||||
if dense_kind.shape != patch.coarse_shape:
|
||||
raise ValueError("composed parent kind has the wrong shape")
|
||||
donors = patch.ghost_coarse.astype(np.intp)
|
||||
receivers = receiver.astype(np.intp)
|
||||
legal = layout.owned.ravel() & (dense_kind.ravel() == ACTIVE) & ~patch.covered.ravel()
|
||||
if not legal[donors].all() or not legal[receivers].all():
|
||||
raise ValueError("child donors/receivers need owned uncovered parent ACTIVE cells")
|
||||
offset = (np.asarray(D2Q9_EY)[q.astype(np.intp)] * layout.local_shape[1]
|
||||
+ np.asarray(D2Q9_EX)[q.astype(np.intp)])
|
||||
source = owner[receivers].astype(np.int64) - offset
|
||||
return (owner[donors].astype(np.uint64), layout.slot(source, q),
|
||||
blocked_kind(layout, dense_kind))
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Level:
|
||||
shape: tuple
|
||||
@@ -55,6 +108,35 @@ class _Level:
|
||||
boundary: object = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _BlockedBoundary:
|
||||
"""One level's stationary BFL data and mutable Jet velocity column."""
|
||||
host: object
|
||||
tables: dict
|
||||
jets: tuple
|
||||
actuated: bool
|
||||
jet_cache: object = None
|
||||
flags: object = None
|
||||
device: object = None
|
||||
kernel: object = None
|
||||
|
||||
|
||||
def _prepare_blocked_boundary(boundary, layout, cfg, jets):
|
||||
if boundary is None or layout is None:
|
||||
return None
|
||||
fluid_idx, dirs, q, body_id, rx, ry, _, fallback = boundary.curved_host
|
||||
tables, _ = blocked_link_tables(layout, boundary.flags, fluid_idx, dirs, q, fallback)
|
||||
actuated = bool(jets) or any(o.surface_actuation is not None for o in boundary.objects)
|
||||
if actuated:
|
||||
cfg = replace(cfg)
|
||||
cfg.validate()
|
||||
tables["surface_velocity"], _ = surface_link_velocity(
|
||||
boundary.objects, cfg, boundary.flags, fluid_idx, dirs, body_id, rx, ry,
|
||||
jets=jets, hits=boundary.curved_hits)
|
||||
return _BlockedBoundary(boundary, tables, jets, actuated,
|
||||
jet_link_shapes(jets, boundary.curved_hits) if jets else None)
|
||||
|
||||
|
||||
class FixedPatchStepper:
|
||||
"""D2Q9/SRT/FP32, one unforced internal 2:1 patch in an x-periodic box.
|
||||
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
# CelerisLab/lbm/refinement_tables.py
|
||||
"""Host-only (numpy) mapping of fixed-patch transfer and boundary tables to block storage.
|
||||
|
||||
No CUDA import: CPU tests import these directly. refinement_stepper re-exports the names.
|
||||
"""
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .blocks import blocked_link_tables
|
||||
from ..body.jets import jet_link_shapes, surface_link_velocity
|
||||
from .descriptors import D2Q9_EX, D2Q9_EY
|
||||
from .refinement import ACTIVE, OUTER_GHOST
|
||||
|
||||
|
||||
def blocked_fine_tables(patch, layout, order):
|
||||
"""Remap fixed-patch fine tables to owner-core blocked storage (host only).
|
||||
|
||||
Returns (explosion target block cells, coalescence child slots in the same
|
||||
rows/child order as ``patch.coalesce_fine[order]``, per-block-cell kind with
|
||||
unused halo entries OUTER). Coarse donors/targets are unchanged.
|
||||
"""
|
||||
owner = layout.owner.ravel().astype(np.intp)
|
||||
cells = patch.fine_shape[0] * patch.fine_shape[1]
|
||||
q, cell = np.divmod(patch.coalesce_fine[order], np.uint64(cells))
|
||||
kind = blocked_kind(layout, patch.fine_kind)
|
||||
return (owner[patch.ghost_fine.astype(np.intp)].astype(np.uint64),
|
||||
layout.slot(owner[cell.astype(np.intp)], q), kind)
|
||||
|
||||
|
||||
def blocked_kind(layout, dense_kind):
|
||||
"""Per-block-cell kind; unused halo entries and unstored holes stay OUTER."""
|
||||
owner = layout.owner.ravel().astype(np.intp)
|
||||
owned = layout.owned.ravel() # sparse multipatch levels leave holes unstored
|
||||
kind = np.full(layout.nblocks * int(np.prod(layout.local_shape)), OUTER_GHOST, np.uint8)
|
||||
kind[owner[owned]] = np.asarray(dense_kind).ravel()[owned]
|
||||
return kind
|
||||
|
||||
def blocked_base_tables(patch, layout, order, wall_aware=False, *, composed_kind=None):
|
||||
"""Parent donor cells and receiver-local arrival slots, in transfer row order.
|
||||
|
||||
Stage arrivals only after child reads and parent halo gather, immediately
|
||||
before parent pull. Source *owner* slots are wrong at block seams.
|
||||
Nested pairs must pass composed_kind to retain inherited INNER/OUTER and
|
||||
sparse holes; donors and receivers must be owned, uncovered ACTIVE cells.
|
||||
"""
|
||||
owner = layout.owner.ravel()
|
||||
q, receiver = np.divmod(patch.coalesce_coarse[order], np.uint64(owner.size))
|
||||
if composed_kind is None:
|
||||
dense_kind = np.where(patch.covered, OUTER_GHOST, ACTIVE).astype(np.uint8)
|
||||
if wall_aware:
|
||||
dense_kind[[0, -1]] = OUTER_GHOST
|
||||
else:
|
||||
dense_kind = np.asarray(composed_kind)
|
||||
if dense_kind.shape != patch.coarse_shape:
|
||||
raise ValueError("composed parent kind has the wrong shape")
|
||||
donors = patch.ghost_coarse.astype(np.intp)
|
||||
receivers = receiver.astype(np.intp)
|
||||
legal = layout.owned.ravel() & (dense_kind.ravel() == ACTIVE) & ~patch.covered.ravel()
|
||||
if not legal[donors].all() or not legal[receivers].all():
|
||||
raise ValueError("child donors/receivers need owned uncovered parent ACTIVE cells")
|
||||
offset = (np.asarray(D2Q9_EY)[q.astype(np.intp)] * layout.local_shape[1]
|
||||
+ np.asarray(D2Q9_EX)[q.astype(np.intp)])
|
||||
source = owner[receivers].astype(np.int64) - offset
|
||||
return (owner[donors].astype(np.uint64), layout.slot(source, q),
|
||||
blocked_kind(layout, dense_kind))
|
||||
|
||||
|
||||
@dataclass
|
||||
class _BlockedBoundary:
|
||||
"""One level's stationary BFL data and mutable Jet velocity column."""
|
||||
host: object
|
||||
tables: dict
|
||||
jets: tuple
|
||||
actuated: bool
|
||||
jet_cache: object = None
|
||||
flags: object = None
|
||||
device: object = None
|
||||
kernel: object = None
|
||||
|
||||
|
||||
def _prepare_blocked_boundary(boundary, layout, cfg, jets):
|
||||
if boundary is None or layout is None:
|
||||
return None
|
||||
fluid_idx, dirs, q, body_id, rx, ry, _, fallback = boundary.curved_host
|
||||
tables, _ = blocked_link_tables(layout, boundary.flags, fluid_idx, dirs, q, fallback)
|
||||
actuated = bool(jets) or any(o.surface_actuation is not None for o in boundary.objects)
|
||||
if actuated:
|
||||
cfg = replace(cfg)
|
||||
cfg.validate()
|
||||
tables["surface_velocity"], _ = surface_link_velocity(
|
||||
boundary.objects, cfg, boundary.flags, fluid_idx, dirs, body_id, rx, ry,
|
||||
jets=jets, hits=boundary.curved_hits)
|
||||
return _BlockedBoundary(boundary, tables, jets, actuated,
|
||||
jet_link_shapes(jets, boundary.curved_hits) if jets else None)
|
||||
@@ -1,94 +0,0 @@
|
||||
"""CPU geometry tests for lbm.hierarchy (no CUDA). Geometry construction only, not LBM numerics."""
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm import refinement as r
|
||||
from CelerisLab.lbm.hierarchy import build_hierarchy, leaf_partition
|
||||
|
||||
CFG = LBMConfig(nx=48, ny=48, viscosity=.02)
|
||||
L1 = [(6, 6, 26, 26), (32, 30, 42, 42)] # L0 cells; L1 ACTIVE x/y 12..52 and x 64..84, y 60..84
|
||||
L2 = [(20, 20, 44, 44), (72, 68, 76, 76)] # L1 cells; L2 ACTIVE 40..88 and x 144..152, y 136..152
|
||||
L3 = [(56, 56, 72, 72)] # L2 cells
|
||||
FOUR = [L1, L2, L3]
|
||||
SMALL = LBMConfig(nx=16, ny=16, viscosity=.1)
|
||||
|
||||
|
||||
class FourLevels(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.h = build_hierarchy(CFG, FOUR)
|
||||
|
||||
def test_config_chain(self):
|
||||
self.assertEqual(self.h.depth, 4)
|
||||
for level, c in enumerate(self.h.configs):
|
||||
self.assertEqual((c.ny, c.nx), (48 << level, 48 << level))
|
||||
self.assertAlmostEqual(c.viscosity, .02 * 2 ** level, places=12)
|
||||
self.assertEqual(self.h.kinds[level].shape, (c.ny, c.nx))
|
||||
for level, p in enumerate(self.h.pairs):
|
||||
self.assertAlmostEqual(p.tau_coarse, 1 / self.h.configs[level].omega, places=12)
|
||||
self.assertAlmostEqual(p.tau_fine, 1 / self.h.configs[level + 1].omega, places=12)
|
||||
|
||||
def test_partition_and_composition(self):
|
||||
h = self.h
|
||||
np.testing.assert_array_equal(leaf_partition(h), np.ones((48, 48)))
|
||||
for level in (1, 2):
|
||||
covered, raw = h.pairs[level].covered, h.pairs[level - 1].fine_kind
|
||||
self.assertTrue((h.kinds[level][covered] == r.OUTER_GHOST).all())
|
||||
np.testing.assert_array_equal(h.kinds[level][~covered], raw[~covered])
|
||||
np.testing.assert_array_equal(h.kinds[3], h.pairs[2].fine_kind)
|
||||
|
||||
def test_depth_is_list_length(self):
|
||||
for depth in range(1, 5):
|
||||
h = build_hierarchy(CFG, FOUR[:depth - 1])
|
||||
self.assertEqual(h.depth, depth)
|
||||
np.testing.assert_array_equal(leaf_partition(h), np.ones((48, 48)))
|
||||
for level in range(depth - 1):
|
||||
np.testing.assert_array_equal(h.kinds[level], self.h.kinds[level])
|
||||
|
||||
def test_illegal_coverage_reports_first_guard(self):
|
||||
cases = [([L1, [(10, 20, 30, 44)]], "inherited ACTIVE"),
|
||||
([L1, L2[:1] + [(54, 54, 58, 58)]], "inherited ACTIVE"),
|
||||
([L1, L2, [(40, 40, 60, 60)]], "donors/receivers"),
|
||||
([L1, L2, [(41, 41, 60, 60)]], "donors/receivers"),
|
||||
([L1, L2, [(56, 56, 64, 64), (66, 56, 72, 64)]], "closer than")]
|
||||
for levels, reason in cases:
|
||||
with self.subTest(levels=levels), self.assertRaisesRegex(ValueError, reason):
|
||||
build_hierarchy(CFG, levels)
|
||||
build_hierarchy(CFG, [L1, L2, [(42, 42, 60, 60)]]) # minimal legal margin
|
||||
|
||||
|
||||
class LegacyForms(unittest.TestCase):
|
||||
def test_scalar_parent_and_child_match_existing_calls(self):
|
||||
local = r.FixedPatch2D.from_config(SMALL, (4, 4, 12, 12))
|
||||
child, kind = r.nest_patch(SMALL, local, (8, 8, 16, 16))
|
||||
h = build_hierarchy(SMALL, [(4, 4, 12, 12), (8, 8, 16, 16)])
|
||||
np.testing.assert_array_equal(h.kinds[0], np.where(local.covered, r.OUTER_GHOST, r.ACTIVE))
|
||||
np.testing.assert_array_equal(h.kinds[1], kind)
|
||||
np.testing.assert_array_equal(h.kinds[2], child.fine_kind)
|
||||
for name in ("ghost_fine", "ghost_coarse", "coalesce_coarse", "coalesce_fine"):
|
||||
np.testing.assert_array_equal(getattr(h.pairs[1], name), getattr(child, name))
|
||||
np.testing.assert_array_equal(leaf_partition(h), np.ones((16, 16)))
|
||||
|
||||
def test_set_child_under_scalar_parent(self):
|
||||
local = r.FixedPatch2D.from_config(SMALL, (4, 4, 12, 12))
|
||||
child, kind = r.nest_patch_set(SMALL, local, [(8, 8, 16, 16)])
|
||||
h = build_hierarchy(SMALL, [(4, 4, 12, 12), [(8, 8, 16, 16)]])
|
||||
np.testing.assert_array_equal(h.kinds[1], kind)
|
||||
np.testing.assert_array_equal(h.pairs[1].coalesce_fine, child.coalesce_fine)
|
||||
np.testing.assert_array_equal(leaf_partition(h), np.ones((16, 16)))
|
||||
|
||||
def test_scalar_child_under_set_parent_is_rejected(self):
|
||||
with self.assertRaisesRegex(ValueError, "scalar parent"):
|
||||
build_hierarchy(SMALL, [[(4, 4, 12, 12)], (12, 12, 20, 20)])
|
||||
|
||||
def test_wall_rows_and_single_level(self):
|
||||
h = build_hierarchy(SMALL, [(4, 4, 12, 12)], wall_aware=True)
|
||||
self.assertTrue((h.kinds[0][[0, -1]] == r.OUTER_GHOST).all())
|
||||
one = build_hierarchy(SMALL, [])
|
||||
self.assertEqual(one.depth, 1)
|
||||
self.assertTrue((one.kinds[0] == r.ACTIVE).all())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user