Compare commits
75
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbf6f1d122 | ||
|
|
1e8e2c9a69 | ||
|
|
c750493b07 | ||
|
|
21bcb8a141 | ||
|
|
8fa9ac0253 | ||
|
|
c11b138a09 | ||
|
|
7ecb179a41 | ||
|
|
edce582a2d | ||
|
|
baba5e02d9 | ||
|
|
eeb90ace9a | ||
|
|
77c034a29a | ||
|
|
60ad6b8b0d | ||
|
|
864a220dbe | ||
|
|
6a7e9226db | ||
|
|
766658185f | ||
|
|
999d3a0e94 | ||
|
|
a24e6d2742 | ||
|
|
20fb16ded5 | ||
|
|
64665319a4 | ||
|
|
f1dcf329ff | ||
|
|
dd9a4dc4b8 | ||
|
|
76555de4b8 | ||
|
|
6301887093 | ||
|
|
0397b6ebb7 | ||
|
|
4c8240ea13 | ||
|
|
93d1cddd27 | ||
|
|
68ecaf9e81 | ||
|
|
cc64abcafe | ||
|
|
aecee19c19 | ||
|
|
fa7fd9097a | ||
|
|
c397e08565 | ||
|
|
99ddb5fc27 | ||
|
|
bf0adda45f | ||
|
|
64d54ab23e | ||
|
|
f1e03423f3 | ||
|
|
e67799812e | ||
|
|
19bd3088ef | ||
|
|
063508d1a3 | ||
|
|
508d412e43 | ||
|
|
aebef52345 | ||
|
|
f26410f94a | ||
|
|
038a759ff1 | ||
|
|
f7753be0e4 | ||
|
|
62c525e735 | ||
|
|
906e0d9a0e | ||
|
|
da8bfb0d4a | ||
|
|
b1cd555b0f | ||
|
|
932702f779 | ||
|
|
611a64c54a | ||
|
|
ca5a145107 | ||
|
|
23ac099475 | ||
|
|
749f103ea8 | ||
|
|
5304525e39 | ||
|
|
5c37d75dc4 | ||
|
|
1a274817cd | ||
|
|
7bf6101460 | ||
|
|
2bbf82121e | ||
|
|
59921a0181 | ||
|
|
dc5850c198 | ||
|
|
3e44e90ca5 | ||
|
|
eeda651626 | ||
|
|
1a2d58312d | ||
|
|
865bb0d6e0 | ||
|
|
7071ed32a6 | ||
|
|
7281d91fd6 | ||
|
|
4645e48a2c | ||
|
|
99c86e441c | ||
|
|
a0a13402f3 | ||
|
|
4029a0b27e | ||
|
|
103f144404 | ||
|
|
d27d344f43 | ||
|
|
118635aebd | ||
|
|
2a68d7e7c7 | ||
|
|
2aadffe183 | ||
|
|
a64af5bece |
No files matched your search
@@ -90,6 +90,116 @@ sim.run(100, stream=stream, upload_act=False, sync_obs=False)
|
||||
# Later: sync and read
|
||||
stream.synchronize()
|
||||
obs = sim.read_bodies(stream=stream) # sync already done, just read pinned buffer
|
||||
```
|
||||
|
||||
### Fixed 2:1 refinement patch (experimental backend)
|
||||
|
||||
`FixedPatchStepper` advances one fixed 2:1 refinement patch inside a coarse
|
||||
grid, optionally with stationary circles in the fine region and a prescribed
|
||||
normal surface velocity (blowing/suction). It is a standalone backend, not part
|
||||
of `Simulation`. Runnable demo (blocked fine storage; omit `--fine-block`
|
||||
for dense): `PYTHONPATH="$PWD/src" python examples/fixed_patch_circle.py --fine-block 16 20`.
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject, SurfaceActuation
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
from CelerisLab.lbm.equilibrium import compute_feq_d2q9
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
|
||||
cfg = LBMConfig(nx=32, ny=24, viscosity=.1)
|
||||
body = SimObject(0, geometry=CircleGeometry(16.0, 12.0, 2.15), center=(16.0, 12.0), radius=2.15,
|
||||
surface_actuation=SurfaceActuation(0.7, 0.85, 0.002)) # angle, half-width, speed
|
||||
with CudaContext(0) as ctx, FixedPatchStepper(cfg, (8, 6, 24, 18), context=ctx,
|
||||
fine_objects=[body], fine_block=(16, 20)) as run:
|
||||
rest = np.asarray(compute_feq_d2q9(1.0, 0.0, 0.0), np.float32)[:, None, None]
|
||||
# (9, ny, nx) postcollision populations per level; non-leaf cells are discarded.
|
||||
run.initialize(np.broadcast_to(rest, (9, *run.patch.coarse_shape)),
|
||||
np.broadcast_to(rest, (9, *run.patch.fine_shape)))
|
||||
run.step(128) # coarse steps; fine level takes two per step
|
||||
coarse_g, fine_g = run.download() # NaN on covered, ghost and solid cells
|
||||
```
|
||||
|
||||
Scope and limits:
|
||||
- D2Q9, SRT, FP32, double buffer, unshifted, no LES or forcing; fixed 2:1 patch(es), two levels (or one nested third).
|
||||
- `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)`),
|
||||
unlike `Simulation`'s integer-node frame. Surface speeds are in coarse lattice units.
|
||||
- Bodies must be stationary circles whose whole boundary stencil lies in the fine
|
||||
active region, clear of the coarse/fine transfer cells; violations are rejected
|
||||
before any GPU allocation.
|
||||
- `fine_block=(by, bx)` stores the fine level in fixed-size blocks; `by`/`bx` must
|
||||
divide the WHOLE fine allocation, i.e. `2*(y1-y0)+8` by `2*(x1-x0)+8` including the
|
||||
four-cell ghost band. It gives results identical to dense storage and is
|
||||
infrastructure for future block AMR, not a speedup.
|
||||
- Several separated patches: pass a sequence of `(x0, y0, x1, y1)`
|
||||
rectangles as `bounds`, at least 4 coarse cells apart, with both `fine_block`
|
||||
and `base_block`. The fine level is then one level-wide grid `(2*ny, 2*nx)`:
|
||||
`run.patch.fine_shape` gives it, `initialize`/`download` use it, and only the
|
||||
patch windows (active region plus 4-cell ghost band, origin `(2*y0-4, 2*x0-4)`)
|
||||
are stored; each window must align with `fine_block`. Order of rectangles does
|
||||
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.
|
||||
|
||||
```python
|
||||
cfg = LBMConfig(nx=32, ny=16, viscosity=.1)
|
||||
rest = np.asarray(compute_feq_d2q9(1.0, 0.0, 0.0), np.float32)[:, None, None]
|
||||
with CudaContext(0) as ctx, FixedPatchStepper(
|
||||
cfg, ((4, 4, 12, 12), (16, 4, 24, 12)), context=ctx,
|
||||
fine_block=(4, 4), base_block=(4, 4)) as run:
|
||||
run.initialize(np.broadcast_to(rest, (9, *run.patch.coarse_shape)),
|
||||
np.broadcast_to(rest, (9, *run.patch.fine_shape))) # (9, 32, 64)
|
||||
run.step(32)
|
||||
coarse_g, fine_g = run.download() # coarse: NaN on every covered cell;
|
||||
# fine: NaN on every non-ACTIVE cell
|
||||
```
|
||||
- Three levels (one nested chain): add `child=(x0, y0, x1, y1)` in
|
||||
**L1 window cells** (the patch's fine grid including its 4-cell ghost band) and
|
||||
`child_block`, with `fine_block` and `base_block`. L2 must sit inside L1's
|
||||
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
|
||||
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
|
||||
dx=dt=0.25, so prescribed lattice velocity is unchanged. Each whole body and
|
||||
its BFL stencil must be inside L2 ACTIVE cells, outside the transfer footprint.
|
||||
A Jet may select one physical body across multiple blocks, never two bodies.
|
||||
|
||||
```python
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.body.jets import Jet, Tube, Parallel
|
||||
|
||||
cfg = LBMConfig(nx=16, ny=16, viscosity=.1)
|
||||
body = SimObject(0, geometry=CircleGeometry(8., 8., .8), center=(8., 8.), radius=.8)
|
||||
jet = Jet(Tube((6.5, 8.), 0., 3., .3), Parallel(0.), amplitude=.002)
|
||||
rest = np.asarray(compute_feq_d2q9(1.0, 0.0, 0.0), np.float32)[:, None, None]
|
||||
with CudaContext(0) as ctx, FixedPatchStepper(
|
||||
cfg, (4, 4, 12, 12), context=ctx, fine_block=(4, 4), base_block=(4, 4),
|
||||
child=(8, 8, 16, 16), child_block=(4, 4),
|
||||
child_objects=[body], child_jets=[jet]) as run:
|
||||
shapes = (run.patch.coarse_shape, run.patch.fine_shape, run.child_patch.fine_shape)
|
||||
run.initialize(*(np.broadcast_to(rest, (9, *s)) for s in shapes)) # 16², 24², 24²
|
||||
run.step(4)
|
||||
run.set_jet_amplitude(0, -.002, level=2) # default level=1 still addresses L1
|
||||
run.step(4)
|
||||
coarse_g, l1_g, l2_g = run.download() # solids/covered/nonleaves are NaN
|
||||
```
|
||||
- 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.
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Raw multilevel boundary exchange (opt-in candidate)
|
||||
|
||||
Use `FixedPatchStepper(..., observe_raw_exchange=True)` and, after a successful
|
||||
base step, `read_raw_exchange(body_id, level=l, window="last_base_step")`.
|
||||
The alternative window is `"last_substep"`. Body IDs are object positions within
|
||||
the named level, not the object's original user label. The torque reference is
|
||||
that circle's geometry.center (the center used to construct BFL arms), reported
|
||||
in the root edge frame. A differing SimObject.center does not change this reference. Current geometry
|
||||
restrictions are unchanged: fixed complete bodies on the finest level, isolated
|
||||
from the transfer footprint. New observation currently requires blocked body
|
||||
storage; dense-body configurations raise before device allocation. Existing
|
||||
dense diagnostics are unchanged.
|
||||
|
||||
Each result contains `wall`, `aperture`, `total`, with `force`, `torque`,
|
||||
`impulse`, `angular_impulse`, `mass_into_fluid`, and `mass_rate`. These are raw
|
||||
boundary momentum reaction, not validated stress or whole-nozzle mechanical
|
||||
load. No GI/advective correction or guessed thrust is added. Apertures retain
|
||||
their geometric classification when their prescribed velocity is zero.
|
||||
|
||||
All results are base-lattice units per unit out-of-plane depth. For local
|
||||
spacing and timestep h=dt, raw `(jx,jy,tz,dm)` converts to impulse
|
||||
`(h*dt*jx,h*dt*jy,h*h*dt*tz)` and mass `h*h*dm`.
|
||||
The accumulator intentionally accepts h and dt separately to make the spatial
|
||||
and temporal conversion explicit; the current acoustic hierarchy supplies dt=h.
|
||||
The stored rx/ry arms run from geometry.center to the actual wall hit, not to
|
||||
the fluid node. For this raw exchange j=c_i(a+b), moving the arm from the fluid
|
||||
node to the hit adds q*c_i, whose cross product with j is zero. Thus either arm
|
||||
gives the same raw torque (up to floating-point rounding); this equivalence
|
||||
must not be assumed for a future nonparallel stress/advective correction.
|
||||
|
||||
Force/torque are impulse/angular impulse divided by the reported window length.
|
||||
`dm=b-a` is positive into the exterior fluid, while j is the opposite of the
|
||||
fluid's momentum change across that cut link. Interpolated BFL can introduce
|
||||
mass drift; dm is an observation, not an assertion of impermeability.
|
||||
|
||||
`last_base_step` means [t-1,t] even after step(n); `last_substep` means [t-h,t]
|
||||
and is not a common instantaneous sample across levels. A Jet amplitude set
|
||||
before step(1) applies to all its substeps. Reads are repeatable; step(0) leaves
|
||||
them unchanged. Initialization and a remap candidate invalidate observation.
|
||||
Only successful stream synchronization publishes a window; failed instances
|
||||
reject reads rather than returning partially advanced measurements.
|
||||
|
||||
Storage is one FP32 [N,4] raw array and one FP64 [N,4] integral per measured
|
||||
level, plus row metadata. No substep history is stored. Same-stream sequencing
|
||||
is halo/restriction -> BFL -> independent row accumulation -> step. There are
|
||||
no accumulation atomics or body obs offsets (blocked n_objects remains zero).
|
||||
Disabled observation allocates neither observation buffer and launches no
|
||||
accumulation kernel. The standalone periodic block caller passes explicit
|
||||
null optional arguments.
|
||||
|
||||
## Gates
|
||||
|
||||
CPU (standard library unittest, plus existing NumPy dependency):
|
||||
|
||||
PYTHONPATH=src python -m unittest discover -s tests/unit -p test_raw_exchange.py -v
|
||||
|
||||
GPU, explicitly on a CUDA host with the existing environment:
|
||||
|
||||
PYTHONPATH=src python -m unittest discover -s tests/validation/multigrid -p test_raw_exchange_gpu.py -v
|
||||
|
||||
The GPU suite includes an independent actual-population cut-link census and
|
||||
ACTIVE-fluid momentum/mass ledger with non-body boundary flux, observation
|
||||
on/off population equivalence, dense/blocked row comparison, three block
|
||||
partitions, zero/step/reversed/disabled Jet amplitudes, depth-four eight-sample
|
||||
accumulation, and a short-time whole-domain uniform-fine comparison with the
|
||||
same physical geometry, viscosity and Jet velocity. The uniform reference
|
||||
uses a test-only adapter to the standalone kernel's optional inputs.
|
||||
|
||||
These are implementation checks. They do not establish physical Jet/stress
|
||||
accuracy, long-time AMR error, or convergence order. Resolution/long-time
|
||||
studies and independently validated continuum load benchmarks remain separate.
|
||||
GPU gates were prepared but not run in the authoring environment (no CUDA,
|
||||
PyCUDA or nvcc); run them before merging this candidate.
|
||||
@@ -0,0 +1,76 @@
|
||||
# Fixed three-level separated patches
|
||||
|
||||
`FixedPatchStepper` supports exactly three static, blocked levels with separated
|
||||
rectangle sets on either adjacent pair. This is not general AMR: there is no
|
||||
per-region timestep, moving geometry, dynamic refinement or L1 body support.
|
||||
All regions share one current/spare buffer pair per level. The existing schedule
|
||||
advances L0 once, L1 twice and L2 four times per base step, with aggregate transfers.
|
||||
No CUDA kernel changes are involved.
|
||||
|
||||
## Explicit coordinate frames
|
||||
|
||||
Keep the existing scalar `child=(x0,y0,x1,y1)` for a single scalar parent patch.
|
||||
Its coordinates retain their original meaning: half-open integer indices in the
|
||||
allocated L1 window, including its ghost band.
|
||||
|
||||
The new keyword `child_rectangles_in_parent=[...]` is mutually exclusive with
|
||||
`child`. It accepts a scalar or a set parent and interprets every rectangle in
|
||||
the actual allocated L1 array, including ghost bands and holes. It never infers
|
||||
region-local coordinates. The physical root cell edge corresponding to an L1
|
||||
index `(x,y)` is `parent.fine_origin + (x,y)/2`:
|
||||
|
||||
- A scalar L1 parent has a shifted window origin.
|
||||
- A set L1 parent has origin `(0,0)` and public shape `(2*ny,2*nx)`.
|
||||
- A child set has public shape twice the allocated L1 shape. Its root origin is
|
||||
the L1 allocated origin, even when the parent is a scalar window.
|
||||
|
||||
For a 16x16 root, scalar parent `(4,4,12,12)` and scalar child `(8,8,16,16)`
|
||||
are physically equivalent to parent set `[(4,4,12,12)]` with child set
|
||||
`[(12,12,20,20)]`. A child set on the *scalar* parent instead uses
|
||||
`[(8,8,16,16)]`. Reusing the same numbers after changing the parent frame can
|
||||
move the physical region.
|
||||
|
||||
Both adjacent pairs require a Chebyshev gap of at least four in their own
|
||||
parent-cell units. The whole child union must preserve inherited ACTIVE
|
||||
coverage, uncovered ACTIVE donors/receivers, surviving pulls, and the upstream
|
||||
restriction footprint. Sparse holes remain unowned; inherited INNER remains
|
||||
stream-only and OUTER remains invalid. Block sizes must align with every
|
||||
support edge, including its four-cell ghost band.
|
||||
|
||||
## Example
|
||||
|
||||
```python
|
||||
run = FixedPatchStepper(
|
||||
cfg, [(4, 4, 20, 28), (24, 4, 44, 28)], context=ctx,
|
||||
base_block=(4, 4), fine_block=(4, 4), child_block=(4, 4),
|
||||
child_rectangles_in_parent=[(16, 16, 32, 40), (56, 16, 80, 40)],
|
||||
)
|
||||
```
|
||||
|
||||
This example uses a 48x32 root. `initialize` and `download` use three Q-major
|
||||
dense arrays. Public arrays and masks still scale with the full allocated
|
||||
extent; sparse device buffers do not remove that host-memory limit.
|
||||
|
||||
Stationary whole-circle `child_objects` and `child_jets` use root edge
|
||||
coordinates and a single L2 boundary object. Body IDs are physical object-list
|
||||
positions, not region IDs or caller `obj_id`. Complete boundary stencils must
|
||||
avoid the transfer footprint. Change a child Jet with
|
||||
`set_jet_amplitude(index, value, level=2)`; L1 bodies/Jets remain unsupported.
|
||||
|
||||
## Verification
|
||||
|
||||
CPU geometry, table, pre-CUDA rejection, schedule and cleanup tests:
|
||||
|
||||
```sh
|
||||
PYTHONPATH=src python -m unittest discover -s tests/unit -p 'test_refinement*.py' -v
|
||||
```
|
||||
|
||||
Explicit GPU gates are in
|
||||
`tests/validation/multigrid/test_refinement_three_level_multipatch_gpu.py`.
|
||||
They cover physical-frame equivalence, twins, asymmetric refinement, multiple
|
||||
children, reversed order, independently varied aligned layouts, public/raw
|
||||
masks and two L2 bodies with static/zero/driven/switched Jets. Snapshots are
|
||||
0/1/2/8. CPU mocks do not execute CUDA and do not establish numerical accuracy.
|
||||
GPU equivalence gates supplement the separately frozen independent dense
|
||||
three-level numerical replay; passing either alone is not a conservation,
|
||||
performance or physical-accuracy claim.
|
||||
@@ -0,0 +1,160 @@
|
||||
# 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,
|
||||
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.
|
||||
|
||||
```python
|
||||
from CelerisLab.lbm.refinement import FixedPatchSet2D
|
||||
from CelerisLab.lbm.synchronized_remap import RemapTopology, remap_synchronized
|
||||
|
||||
# cfg: D2Q9/SRT/FP32/unshifted/double_buffer, nz=1, no LES
|
||||
parent = FixedPatchSet2D.from_config(cfg, [(4, 4, 20, 28), (24, 4, 44, 28)])
|
||||
old = RemapTopology.from_config(cfg, parent, [(16, 16, 32, 40)])
|
||||
new = RemapTopology.from_config(cfg, parent, [(20, 16, 36, 40)])
|
||||
candidate = remap_synchronized(
|
||||
old, new, current_g, base_count=7, level_steps=(7, 14, 28),
|
||||
phase="postcollision_g", origin=(0., 0.), spacing=1.,
|
||||
)
|
||||
```
|
||||
|
||||
The example has a 48×32 root; both child supports allow 4×4 blocks.
|
||||
Child bounds use the parent's allocated L1 coordinates, not rectangle-local
|
||||
indices. A scalar FixedPatch2D parent is also supported: its shifted L1 window
|
||||
origin is retained. Physical lower edges are `origin + spacing*(x,y)` on L0,
|
||||
`origin + spacing*(parent.fine_origin + (x,y)/2)` on L1 and
|
||||
`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
|
||||
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**.
|
||||
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,
|
||||
pass `layouts=(base_layout, fine_layout, child_layout)`; each optional `None`
|
||||
entry denotes dense input. Every leaf must have an owner. Only owner cores
|
||||
are read, never redundant block halos. Mixed precision is rejected. FP64 is
|
||||
accepted for CPU reference tests; this does not enable FP64 runtime storage.
|
||||
Outputs `candidate.g` are separate dense arrays regardless of input layout.
|
||||
Memory scales with public grid extents, not only sparse allocated blocks.
|
||||
|
||||
Same-level leaf overlap is copied bitwise in physical coordinates. Newly
|
||||
refined L2 copies all nine values from its valid old L1 parent. Newly exposed
|
||||
L1 receives the complete four-child mean, including q0. Covered parents,
|
||||
ghosts and holes never serve as donors; NaN/Inf outside leaves is ignored,
|
||||
while nonfinite required leaves or nonpositive density reject the operation.
|
||||
Restriction uses FP64 quarter-weight accumulation and rounds to the input
|
||||
dtype. New nonleaves are NaN. Source arrays/metadata are not changed.
|
||||
|
||||
`candidate` retains `base_count`, `level_steps`, `phase`, `origin`, `spacing`
|
||||
and new `topology.leaf_masks`. Existing `FixedPatchStepper.initialize` resets
|
||||
the counter: using it is **not** a continuation adapter. This component neither
|
||||
publishes a candidate nor retires old state. Runtime table rebuild/halo refill
|
||||
and correct first-step scheduling are handled only by the explicit adapter below.
|
||||
|
||||
Tests accumulate leaf-area integrals in FP64 for each population, mass and
|
||||
momentum. The declared absolute tolerance is `2e-13 * sum(abs(old population
|
||||
integrals))` for FP64, `2e-7 * scale` for FP32, accounting for reduction and
|
||||
restriction rounding (not a solver accuracy bound). Coarse→fine→coarse copy
|
||||
round-trips preserve state; coarsening arbitrary fine structure loses it and
|
||||
is not invertible. No kinetic accuracy or stability claim follows.
|
||||
|
||||
```sh
|
||||
PYTHONPATH=src python -m unittest discover -s tests/unit -p 'test_synchronized_remap.py' -v
|
||||
```
|
||||
|
||||
## Explicit runtime continuation
|
||||
|
||||
`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
|
||||
`child=` is deliberately rejected. L0/L1, relaxation and block sizes stay fixed.
|
||||
No tagger, scheduler, in-place replacement, or general rollback is provided.
|
||||
|
||||
The method holds the stepper lock, validates geometry, synchronizes its stream,
|
||||
and downloads the actual current owned leaves. It certifies postcollision G
|
||||
and completed 1:2:4 counts internally, applies the CPU helper, rebuilds all
|
||||
geometry/transfer/kind/halo buffers, and uploads both current and spare buffers.
|
||||
No old halo is reused. The regular step schedule fills transit ghosts/halos
|
||||
before use. `initialize` itself still resets the count to zero.
|
||||
|
||||
The old stepper remains ready, unchanged and independently usable. The caller
|
||||
owns **both** objects and must close both before closing their shared CUDA
|
||||
context. Candidate construction or upload failure releases only candidate
|
||||
resources; an actual old-device synchronization/read failure marks the old
|
||||
stepper failed, consistent with its existing failure semantics.
|
||||
|
||||
```python
|
||||
replacement = current.remap_child([(20, 16, 36, 40)])
|
||||
# Explicitly choose the returned continuation only after success.
|
||||
current.close()
|
||||
current = replacement
|
||||
current.step() # advances the preserved absolute count by one
|
||||
```
|
||||
|
||||
CPU lifecycle mocks cover fresh current-buffer reads, exact transfer, separate
|
||||
ownership, time preservation, ordinary initialization reset, unsupported states
|
||||
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.
|
||||
Per-population conservation is not an advancement target under collision.
|
||||
|
||||
### Bounded pinned-body extension
|
||||
|
||||
`replacement = current.remap_child(rectangles, child_objects=original_objects)`
|
||||
also accepts stationary Circles in separated L2 rectangles. Every body’s
|
||||
**complete containing rectangle must remain identical**. Several bodies may
|
||||
share one pinned rectangle; there need not be any fluid-only rectangles.
|
||||
Separated fluid-only rectangles may be added, removed or moved. Existing
|
||||
nesting, four-cell gap, full-circle containment, reverse cut-link coverage and two-hop BFL
|
||||
transfer-footprint checks still apply. This is manual remapping, not adaptive
|
||||
body tracking or runtime body editing.
|
||||
|
||||
Supply all original root edge-frame definitions in their construction order.
|
||||
Do not pass `current.child_boundary.objects`: those are projected fine-local copies.
|
||||
There is no retained mutable original-object registry. Before reading device
|
||||
state, remapping reprojects the supplied definition onto the old topology and
|
||||
compares exact ordered circle centers/radii, flags, physical cut links, body
|
||||
IDs, q, lever arms, hits, BFL support,
|
||||
legacy SurfaceActuation specification and current per-link velocity against
|
||||
the existing boundary. Omission, changed geometry/actuation and changed body
|
||||
rectangle fail without device reads or allocations; reordered bodies fail
|
||||
too. Root object IDs are still assigned by list position, as in the constructor.
|
||||
|
||||
Jets are taken from the live L2 boundary, including the most recent successful
|
||||
`set_jet_amplitude(..., level=2)`. There is no replacement-Jets argument or
|
||||
constructor-time Jet snapshot. New blocked addresses may differ; the physical
|
||||
boundary and velocities must match exactly.
|
||||
|
||||
`RemapTopology.from_config(..., child_objects=..., child_jets=...)` prepares a
|
||||
typed `FineBoundary2D`; it derives L2 fluid leaves as ACTIVE minus SOLID. No
|
||||
caller mask is accepted. Solids, ghosts and holes are never donors and remain
|
||||
NaN, physical-fluid overlap is exact, and exposed L1 still restricts all four
|
||||
old fluid children. The helper checks the old/new body pins and boundary too.
|
||||
Its immutable `pinned_rectangles` is a canonical, deduplicated tuple, empty for body-free layouts; rectangle input
|
||||
order does not affect it. Scalar-parent window offsets remain part of the
|
||||
coordinate conversion.
|
||||
|
||||
Focused CPU mocks: `tests/unit/test_pinned_body_remap.py`. GPU declarations:
|
||||
`tests/validation/multigrid/test_pinned_body_remap_gpu.py`, covering no-op
|
||||
next-step bitwise identity, moved-fluid A→B→A, current-amplitude preservation,
|
||||
physical boundary/velocity equality, source independence and absolute counts.
|
||||
Multiple-body CPU coverage: `tests/unit/test_multiple_pinned_remap.py`.
|
||||
`tests/validation/multigrid/test_multiple_pinned_remap_gpu.py` adds two pins,
|
||||
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.
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Public API demo: fixed 2:1 patch with a stationary, optionally actuated circle.
|
||||
|
||||
From this checkout, after checking the selected physical GPU is idle:
|
||||
PYTHONPATH="$PWD/src" CUDA_VISIBLE_DEVICES=0 python examples/fixed_patch_circle.py --fine-block 16 20
|
||||
... --speed -0.002 --fine-block 16 20 --mode slot_reservoir
|
||||
Omit --fine-block for the (equivalent) dense fine storage.
|
||||
|
||||
A short smoke run (default 128 coarse steps): it shows setup, stepping and
|
||||
fluid-only diagnostics, not a developed flow, accuracy or long-time stability.
|
||||
Normal blowing/suction injects/extracts mass, so leaf mass is expected to change.
|
||||
No files, plots or checkpoints are written.
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
import CelerisLab
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject, SurfaceActuation
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
from CelerisLab.lbm.descriptors import D2Q9_EX, D2Q9_EY, SOLID
|
||||
from CelerisLab.lbm.equilibrium import compute_feq_d2q9
|
||||
from CelerisLab.lbm.refinement import ACTIVE
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
|
||||
NX, NY, BOUNDS = 32, 24, (8, 6, 24, 18) # coarse cells; patch is half-open (x0, y0, x1, y1)
|
||||
CENTER, RADIUS = (16.0, 12.0), 2.15 # coarse CELL-EDGE frame: cell I spans [I, I+1)
|
||||
|
||||
|
||||
def config(mode):
|
||||
if mode == "periodic": # x and y periodic coarse level
|
||||
return LBMConfig(nx=NX, ny=NY, viscosity=.1)
|
||||
# Bottom on-site velocity slot, top fixed-density reservoir, x periodic.
|
||||
return LBMConfig(nx=NX, ny=NY, viscosity=.1, velocity=0, wall_normal_velocity=.001,
|
||||
wall_slot_width=8, y_wall_bc="on_site_velocity", top_wall_bc="reservoir")
|
||||
|
||||
|
||||
def leaf_masks(run, mode):
|
||||
"""Known fluid leaves: uncovered coarse cells (minus wall rows in slot mode)
|
||||
and fine ACTIVE cells outside the body."""
|
||||
p = run.patch
|
||||
x0, y0, x1, y1 = p.bounds
|
||||
coarse = np.ones(p.coarse_shape, bool)
|
||||
coarse[y0:y1, x0:x1] = False
|
||||
if mode == "slot_reservoir":
|
||||
coarse[[0, -1]] = False
|
||||
solid = (run.fine_boundary.flags.reshape(p.fine_shape) & SOLID) != 0
|
||||
return coarse, (p.fine_kind == ACTIVE) & ~solid
|
||||
|
||||
|
||||
def leaf_diagnostics(coarse, fine, masks):
|
||||
"""Fluid leaves only; a non-finite population or rho <= 0 there is an error.
|
||||
|
||||
Mass counts a fine cell as 1/4 of a coarse cell (2D, 2:1)."""
|
||||
out = {}
|
||||
for name, g, leaf, area in (("coarse", coarse, masks[0], 1.0), ("fine", fine, masks[1], .25)):
|
||||
f = g[:, leaf].astype(np.float64)
|
||||
rho = f.sum(axis=0)
|
||||
if not np.isfinite(f).all() or (rho <= 0).any():
|
||||
raise RuntimeError(f"non-finite population or non-positive density on a {name} fluid leaf")
|
||||
ux = (np.array(D2Q9_EX)[:, None] * f).sum(axis=0) / rho
|
||||
uy = (np.array(D2Q9_EY)[:, None] * f).sum(axis=0) / rho
|
||||
out[name] = (area * rho.sum(), rho.min(), rho.max(), np.hypot(ux, uy).max())
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--mode", choices=("periodic", "slot_reservoir"), default="periodic")
|
||||
parser.add_argument("--speed", type=float, default=.002,
|
||||
help="normal surface velocity, coarse lattice units (+ blows, - sucks, 0 passive)")
|
||||
parser.add_argument("--fine-block", type=int, nargs=2, metavar=("BY", "BX"),
|
||||
help="blocked fine storage; must divide the whole fine allocation (32 x 40 here)")
|
||||
parser.add_argument("--steps", type=int, default=128)
|
||||
args = parser.parse_args()
|
||||
if args.steps < 0:
|
||||
parser.error("--steps must be nonnegative")
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
if Path(CelerisLab.__file__).resolve() != root / "src/CelerisLab/__init__.py":
|
||||
raise RuntimeError(f"Set PYTHONPATH to {root / 'src'}")
|
||||
|
||||
# Aperture centred at angle 0.7 rad, half-width 0.85 rad (the tested fixture).
|
||||
spec = SurfaceActuation(0.7, 0.85, args.speed) if args.speed else None
|
||||
body = SimObject(0, geometry=CircleGeometry(*CENTER, RADIUS), center=CENTER, radius=RADIUS,
|
||||
surface_actuation=spec)
|
||||
cfg = config(args.mode)
|
||||
fine_block = tuple(args.fine_block) if args.fine_block else None
|
||||
# The caller owns the CUDA context; the stepper must be closed first (the
|
||||
# nested with-statement does that).
|
||||
with CudaContext(0) as context, FixedPatchStepper(
|
||||
cfg, BOUNDS, context=context, coarse_boundary=args.mode,
|
||||
fine_objects=[body], fine_block=fine_block) as run:
|
||||
p = run.patch
|
||||
# Rest equilibrium is already postcollision G, so no initial collision is
|
||||
# needed. Non-leaf entries (covered, ghost, solid) are discarded by initialize.
|
||||
rest = np.asarray(compute_feq_d2q9(1.0, 0.0, 0.0), np.float32)[:, None, None]
|
||||
run.initialize(np.broadcast_to(rest, (9, *p.coarse_shape)),
|
||||
np.broadcast_to(rest, (9, *p.fine_shape)))
|
||||
storage = f"blocked {fine_block}" if fine_block else "dense"
|
||||
print(f"mode={args.mode} fine storage={storage} speed={args.speed:+g} "
|
||||
f"(fine allocation {p.fine_shape[0]}x{p.fine_shape[1]}, fine origin {p.fine_origin})")
|
||||
masks = leaf_masks(run, args.mode)
|
||||
start = leaf_diagnostics(*run.download(), masks)
|
||||
for _ in range(0, args.steps, 32):
|
||||
run.step(min(32, args.steps - run.step_count))
|
||||
coarse, fine = run.download() # synchronized postcollision G, NaN on non-leaves
|
||||
d = leaf_diagnostics(coarse, fine, masks)
|
||||
mass = d["coarse"][0] + d["fine"][0]
|
||||
rho_lo = min(d["coarse"][1], d["fine"][1])
|
||||
rho_hi = max(d["coarse"][2], d["fine"][2])
|
||||
speed = max(d["coarse"][3], d["fine"][3])
|
||||
print(f"coarse step {run.step_count:4d}: leaf mass {mass:.9f} "
|
||||
f"(change {mass - start['coarse'][0] - start['fine'][0]:+.3e}) "
|
||||
f"rho [{rho_lo:.6f}, {rho_hi:.6f}] max |u| {speed:.3e}")
|
||||
print("smoke run only: storage/stepping demonstration, not accuracy or stability evidence")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,70 @@
|
||||
# One measured-strain refinement example
|
||||
|
||||
Research only: one completed base-time observation, one possible growth-only
|
||||
fluid L2 enlargement, then two more base steps. L0/L1 and the Circle-containing
|
||||
L2 rectangle stay fixed. No scheduler, coarsening, packing, CUDA changes, or
|
||||
claim of accuracy, stable long-time adaptation, or optimal mesh selection.
|
||||
|
||||
The periodic initial shear wave is evolved for two base steps. The downloaded
|
||||
postcollision G moments supply actual L1 velocity, at dx=.5 and the parent's
|
||||
physical origin. The tagger measures |S|=sqrt(2 S:S), not vorticity. We use
|
||||
s*=|S|/0.05, cutoff .001, no wall band/history/buffer. This deliberately small
|
||||
cutoff exercises the mechanism; it is not an error estimator or calibrated
|
||||
physical criterion. A high cutoff yields no change with the same observation.
|
||||
|
||||
The eligible corridor is L1 indices [72,76) x [20,36), immediately right of the
|
||||
fluid child. Only L1 fluid leaves are valid gradient donors and owned voters;
|
||||
covered cells, holes and ghosts cannot supply gradients. L1 has no physical
|
||||
solid cells: the Circle is entirely in the fixed L2 patch. The cropped sparse
|
||||
arrays are never treated as a full periodic domain. One-sided derivatives may
|
||||
be used at missing-neighbor edges. Unknown gradients, unavailable corridor
|
||||
cells, and tags outside the corridor are reported separately. Ignored tags do
|
||||
not certify adequate resolution elsewhere. Old coverage is always retained.
|
||||
|
||||
`grow_rectangle` knows only a rectangle, boolean requests, alignment and area
|
||||
cap. It returns an unchanged/enlarged tuple or raises ValueError before any
|
||||
solver mutation. The caller validates the entire proposed mesh with the
|
||||
existing RemapTopology and sparse-layout guards; remap_child repeats its full
|
||||
runtime checks. This example targets exactly the original mesh once, not a
|
||||
reusable adaptation loop. A rejection propagates explicitly; no partial
|
||||
proposal is installed. All solver instances are independently closed.
|
||||
|
||||
## Run
|
||||
|
||||
From repository root, with dependencies already available:
|
||||
|
||||
PYTHONPATH=src:. python -m unittest discover -s tests/unit -p test_shear_refinement_example.py -v
|
||||
|
||||
Only on an approved idle CUDA device:
|
||||
|
||||
PYTHONPATH=src:. python -m research.shear_refinement.example
|
||||
PYTHONPATH=src:.:tests/validation/multigrid python -m unittest discover -s tests/validation/multigrid -p test_shear_refinement_example_gpu.py -v
|
||||
|
||||
The GPU gate compares automatic selection to an explicitly identical manual
|
||||
rectangle after short continuation, requires finite leaves, exact NaN masks,
|
||||
and an unchanged source. It does not replace independent numerical replay.
|
||||
GPU execution has not been performed in the implementation cloud environment.
|
||||
|
||||
## Tagger provenance and license
|
||||
|
||||
`boundary_shear_tagging.py` is the unchanged accepted Grok standalone v0.2
|
||||
preparation (2026-10-16), SHA256
|
||||
`12bc70ab989953501a752a2dc23e3712b6e69bfd47e67664c1771ff2dfa4da0b`.
|
||||
The delivered `README_boundary_shear_tagging_v0.2.md` identifies it as original
|
||||
code under MIT, the same license as CelerisLab (see repository LICENSE), with
|
||||
nothing copied from upstream examples. Its source ledger/review is in the
|
||||
preparation/grok_amr_review/v0.2 handoff. Vendoring keeps this example runnable
|
||||
without external preparation paths; it is not installed as production API.
|
||||
The separate reviewed level-request policy v0.2.1 is intentionally not copied:
|
||||
this example observes only L1 and can request only the existing L2 level.
|
||||
|
||||
## Local implementation checks (2026-10-16)
|
||||
|
||||
Seven focused example tests passed. The combined CPU suite below passed all
|
||||
60 tests, including existing topology, pinned-body and synchronized remap gates:
|
||||
|
||||
PYTHONPATH=src:. python -m unittest tests.unit.test_refinement tests.unit.test_refinement_three_level_multipatch tests.unit.test_pinned_body_remap tests.unit.test_runtime_child_remap tests.unit.test_synchronized_remap tests.unit.test_shear_refinement_example -q
|
||||
|
||||
Broad unit discovery was also attempted; 14 legacy module imports failed
|
||||
because PyCUDA is absent. That broad run is not a pass. No installation or GPU
|
||||
execution was attempted. The example uses a passive Circle, with no Jet drive.
|
||||
@@ -0,0 +1,285 @@
|
||||
"""Boundary-proximity + physically scaled shear tagging with hysteresis (CPU prototype), v0.2.
|
||||
|
||||
Status: standalone preparation for CelerisLab AMR (baseline dev 93d1cdd). Original code, not
|
||||
copied from any project. It only *proposes* cells for refinement: it returns masks and
|
||||
diagnostics and never builds patches, regrids, applies a max_level, or touches solver state.
|
||||
Not a block/AMR integration: callers must still legalise/align proposals and run the existing
|
||||
BlockLayout2D / FixedPatch2D / prepare_fine_boundary guards.
|
||||
|
||||
v0.2 changes (2026-10-16 review): explicit periodic axes for distance AND dilation (minimum
|
||||
image); three separate masks (physical solid / valid stencil samples / owned cells); core tags
|
||||
only on owned-eligible fluid; hold previous core where the strain is unevaluable.
|
||||
|
||||
Masks (all bool, shape (ny, nx)):
|
||||
* solid - physical solid geometry. The ONLY source of walls. Never fill holes with it.
|
||||
* valid - cells holding a usable, finite macroscopic velocity sample (may include ghosts).
|
||||
Derivative stencils read only valid cells. Default: ~solid. Must not overlap solid.
|
||||
Cells that are neither solid nor valid are "absent" (sparse holes): never walls,
|
||||
never derivative donors, never tagged; their velocity is never read.
|
||||
* owned - cells this caller owns and may propose (e.g. ACTIVE fine cells, owned blocks).
|
||||
Default: all True. eligible = owned & ~solid, and must be a subset of valid.
|
||||
Core tags exist only on eligible cells; the buffer is clipped to owned cells.
|
||||
|
||||
Units (match CelerisLab refinement.py: coarse dx = dt = 1, level l has dx = dt = 2**-l):
|
||||
* Lengths (origin, wall distance, L_ref, periods) are in COARSE cells.
|
||||
* Velocities are lattice velocities; under acoustic scaling these equal coarse units.
|
||||
* Strain rate |S| = sqrt(2 S_ij S_ij) in 1/coarse-time-step; u = (g*y, 0) gives |S| = |g|.
|
||||
* Shear indicator s* = |S| * L_ref / U_ref: dimensionless; the physical definition is
|
||||
level-independent (its finite-difference estimate is exactly level-invariant only for
|
||||
affine fields; otherwise it changes by truncation error).
|
||||
* cell_strain = |S| * dx_level / U_ref: an analogous dx-scaled STRAIN diagnostic, returned
|
||||
but not used to tag. It is not the quantity waLBerla/AMReX threshold: those use
|
||||
vorticity-related indicators (rigid rotation: zero strain, nonzero vorticity). We borrow
|
||||
only their level-scaling pattern. A dx-scaled indicator is resolution-sensitive; it is not
|
||||
an accuracy certificate and not a substitute for a hard max_level in the policy layer.
|
||||
* Velocity must be MACROSCOPIC (moments of one consistent population phase).
|
||||
|
||||
Tag rule per call, on eligible cells:
|
||||
wall: d <= band_on or (prev and d <= band_off) band_off >= band_on (units L_ref)
|
||||
shear: where evaluable: s* >= shear_on or (prev and s* >= shear_off)
|
||||
where unevaluable (no valid stencil): HOLD prev (never switches a tag off)
|
||||
core = wall | shear; tagged = core dilated n_buffer cells (Chebyshev, periodic-aware) & owned.
|
||||
Feed ``core`` (never ``tagged``) back as ``prev_core``. prev_core outside eligible cells is
|
||||
rejected; buffered history on an all-fluid grid cannot be detected, so the contract stays
|
||||
core-only. History is only meaningful on unchanged topology: reset or remap after a regrid.
|
||||
An untagged unevaluable cell (reported in ``unevaluable``) is NOT evidence that it may coarsen.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from numbers import Integral, Real
|
||||
|
||||
import numpy as np
|
||||
|
||||
WALL, SHEAR, HELD = 1, 2, 4 # bits in TagResult.reason (HELD: shear state held, unevaluable)
|
||||
_CHUNK = 4096
|
||||
|
||||
|
||||
def _ro(a):
|
||||
a = np.ascontiguousarray(a)
|
||||
a.setflags(write=False)
|
||||
return a
|
||||
|
||||
|
||||
def _num(name, v, *, positive=False, nonneg=False):
|
||||
if isinstance(v, (bool, np.bool_)) or not isinstance(v, Real) or not np.isfinite(v):
|
||||
raise ValueError(f"{name} must be a finite real number")
|
||||
v = float(v)
|
||||
if positive and v <= 0:
|
||||
raise ValueError(f"{name} must be > 0")
|
||||
if nonneg and v < 0:
|
||||
raise ValueError(f"{name} must be >= 0")
|
||||
return v
|
||||
|
||||
|
||||
def _periodic(periodic):
|
||||
if (not isinstance(periodic, (tuple, list)) or len(periodic) != 2
|
||||
or not all(isinstance(p, (bool, np.bool_)) for p in periodic)):
|
||||
raise ValueError("periodic must be two bools (x, y)")
|
||||
return bool(periodic[0]), bool(periodic[1])
|
||||
|
||||
|
||||
def _mask(name, m, shape, default):
|
||||
if m is None:
|
||||
return default
|
||||
m = np.asarray(m)
|
||||
if m.dtype != np.bool_ or m.shape != shape:
|
||||
raise ValueError(f"{name} must be a bool array of the grid shape")
|
||||
return m
|
||||
|
||||
|
||||
def _neighbour_or(m, periodic):
|
||||
"""OR over the 3x3 Chebyshev neighbourhood; wraps on periodic axes, False-pads others."""
|
||||
px, py = periodic
|
||||
p = np.pad(m, ((0 if py else 1,) * 2, (0 if px else 1,) * 2), constant_values=False)
|
||||
out = np.zeros(m.shape, bool)
|
||||
ny, nx = m.shape
|
||||
for dy in (-1, 0, 1):
|
||||
for dx in (-1, 0, 1):
|
||||
if px or py:
|
||||
s = np.roll(p, (-dy if py else 0, -dx if px else 0), axis=(0, 1))
|
||||
else:
|
||||
s = p
|
||||
oy = 0 if py else 1 + dy
|
||||
ox = 0 if px else 1 + dx
|
||||
out |= s[oy:oy + ny, ox:ox + nx]
|
||||
return out
|
||||
|
||||
|
||||
def dilate(mask, n, periodic=(False, False)):
|
||||
"""Chebyshev dilation by n cells; wraps across periodic axes only."""
|
||||
periodic = _periodic(periodic)
|
||||
m = np.asarray(mask, bool).copy()
|
||||
for _ in range(int(n)):
|
||||
m = _neighbour_or(m, periodic)
|
||||
return m
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class TagResult:
|
||||
core: np.ndarray # bool: hysteresis state on eligible cells; feed back as prev_core
|
||||
tagged: np.ndarray # bool: core + buffer, clipped to owned; proposal for a regridder
|
||||
reason: np.ndarray # uint8 bits WALL|SHEAR|HELD on core cells
|
||||
strain_star: np.ndarray # float64 s*; NaN where unevaluable or not valid
|
||||
cell_strain: np.ndarray # float64 |S| dx_level / U_ref (diagnostic only)
|
||||
wall_distance: np.ndarray # float64 coarse cells from non-solid centres; inf if no wall / solid
|
||||
unevaluable: np.ndarray # bool: eligible cells with no usable gradient stencil
|
||||
eligible: np.ndarray # bool: owned & ~solid (the only cells that can hold core tags)
|
||||
n_unevaluable_fluid: int # count of `unevaluable`
|
||||
|
||||
|
||||
def strain_rate(ux, uy, fluid, dx_level, periodic=(False, False)):
|
||||
"""|S| = sqrt(2 S:S) in 1/coarse-time-step on `fluid` (= valid sample) cells; NaN elsewhere.
|
||||
|
||||
Each derivative uses a central difference when both neighbours are valid (inside the
|
||||
domain or across a periodic seam), else a one-sided difference (first order) to one valid
|
||||
neighbour, else NaN. Values in non-valid cells are never read.
|
||||
"""
|
||||
fluid = np.asarray(fluid, bool)
|
||||
px, py = _periodic(periodic)
|
||||
|
||||
def ddir(f, axis, per):
|
||||
n = f.shape[axis]
|
||||
idx = np.arange(n)
|
||||
ip, im = idx + 1, idx - 1
|
||||
okp, okm = ip < n, im >= 0
|
||||
if per:
|
||||
ip, im = ip % n, im % n
|
||||
okp = okm = np.ones(n, bool)
|
||||
ip, im = np.clip(ip, 0, n - 1), np.clip(im, 0, n - 1)
|
||||
take = lambda a, i: np.take(a, i, axis=axis)
|
||||
shape = [1, 1]; shape[axis] = n
|
||||
fp = take(fluid, ip) & okp.reshape(shape)
|
||||
fm = take(fluid, im) & okm.reshape(shape)
|
||||
fz = np.where(fluid, f, 0.0)
|
||||
vp, vm = take(fz, ip), take(fz, im)
|
||||
out = np.full(f.shape, np.nan)
|
||||
c = fluid & fp & fm
|
||||
out[c] = 0.5 * (vp - vm)[c]
|
||||
o = fluid & fp & ~fm
|
||||
out[o] = (vp - fz)[o]
|
||||
o = fluid & ~fp & fm
|
||||
out[o] = (fz - vm)[o]
|
||||
return out / dx_level
|
||||
|
||||
dudx, dudy = ddir(ux, 1, px), ddir(ux, 0, py)
|
||||
dvdx, dvdy = ddir(uy, 1, px), ddir(uy, 0, py)
|
||||
sxy = 0.5 * (dudy + dvdx)
|
||||
return np.sqrt(2.0 * (dudx**2 + dvdy**2 + 2.0 * sxy**2))
|
||||
|
||||
|
||||
def wall_distance(fluid, dx_level, origin=(0.0, 0.0), distance_fn=None,
|
||||
periodic=(False, False), solid=None):
|
||||
"""Distance (coarse cells) from each non-solid cell centre to the wall; inf if no wall.
|
||||
|
||||
`solid` (default ~fluid) is the physical geometry; only solid cells with a non-solid
|
||||
Chebyshev neighbour (seam-aware) are wall cells, so absent cells are never walls.
|
||||
distance_fn(x, y) -> signed distance (coarse units, negative inside bodies) is preferred
|
||||
when geometry is known; it is evaluated at cell centres as given, so for periodic axes it
|
||||
must itself return the minimum-image distance. Otherwise a raster HEURISTIC is used:
|
||||
distance to the nearest wall-cell centre (minimum image on periodic axes) minus dx/2.
|
||||
It is exact only for a planar wall lying on cell faces; it has no general error bound
|
||||
(a physical wall off the cell face, curved, sub-cell or off-patch bodies differ).
|
||||
"""
|
||||
fluid = np.asarray(fluid, bool)
|
||||
solid = ~fluid if solid is None else np.asarray(solid, bool)
|
||||
px, py = _periodic(periodic)
|
||||
ny, nx = fluid.shape
|
||||
x = origin[0] + (np.arange(nx) + 0.5) * dx_level
|
||||
y = origin[1] + (np.arange(ny) + 0.5) * dx_level
|
||||
X, Y = np.meshgrid(x, y)
|
||||
target = ~solid
|
||||
d = np.full(fluid.shape, np.inf)
|
||||
if distance_fn is not None:
|
||||
dv = np.asarray(distance_fn(X, Y), dtype=np.float64)
|
||||
if dv.shape != fluid.shape or not np.all(np.isfinite(dv[target])):
|
||||
raise ValueError("distance_fn must return finite values of the grid shape")
|
||||
d[target] = np.maximum(dv[target], 0.0)
|
||||
return d
|
||||
wall = solid & _neighbour_or(~solid, (px, py))
|
||||
if not wall.any() or not target.any():
|
||||
return d
|
||||
Lx, Ly = nx * dx_level, ny * dx_level
|
||||
wx, wy = X[wall], Y[wall]
|
||||
fx, fy = X[target], Y[target]
|
||||
best = np.empty(fx.size)
|
||||
for s in range(0, fx.size, _CHUNK):
|
||||
ex, ey = np.abs(fx[s:s + _CHUNK, None] - wx), np.abs(fy[s:s + _CHUNK, None] - wy)
|
||||
if px:
|
||||
ex = np.minimum(ex, Lx - ex)
|
||||
if py:
|
||||
ey = np.minimum(ey, Ly - ey)
|
||||
best[s:s + _CHUNK] = np.sqrt((ex * ex + ey * ey).min(axis=1))
|
||||
d[target] = np.maximum(best - 0.5 * dx_level, 0.0)
|
||||
return d
|
||||
|
||||
|
||||
def tag_cells(ux, uy, solid, *, dx_level, U_ref, L_ref, shear_on, shear_off,
|
||||
band_on, band_off, n_buffer=2, prev_core=None, origin=(0.0, 0.0),
|
||||
periodic=(False, False), distance_fn=None, valid=None, owned=None):
|
||||
"""Propose refinement tags for one level. Pure function: inputs are not modified.
|
||||
|
||||
band_on/band_off are in units of L_ref. See module docstring for the three masks.
|
||||
"""
|
||||
solid = np.asarray(solid)
|
||||
if solid.dtype != np.bool_ or solid.ndim != 2 or min(solid.shape) < 3:
|
||||
raise ValueError("solid must be a 2-D bool array with both sides >= 3")
|
||||
shape = solid.shape
|
||||
ux = np.asarray(ux, dtype=np.float64)
|
||||
uy = np.asarray(uy, dtype=np.float64)
|
||||
if ux.shape != shape or uy.shape != shape:
|
||||
raise ValueError("ux, uy and solid must have the same (ny, nx) shape")
|
||||
valid = _mask("valid", valid, shape, ~solid)
|
||||
owned = _mask("owned", owned, shape, np.ones(shape, bool))
|
||||
if np.any(valid & solid):
|
||||
raise ValueError("valid must not overlap solid (solid cells are not velocity samples)")
|
||||
eligible = owned & ~solid
|
||||
if np.any(eligible & ~valid):
|
||||
raise ValueError("owned non-solid cells must be valid (have a velocity sample)")
|
||||
if not (np.all(np.isfinite(ux[valid])) and np.all(np.isfinite(uy[valid]))):
|
||||
raise ValueError("velocity must be finite on every valid cell")
|
||||
dx_level = _num("dx_level", dx_level, positive=True)
|
||||
lvl = -np.log2(dx_level)
|
||||
if abs(lvl - round(lvl)) > 1e-12 or round(lvl) < 0:
|
||||
raise ValueError("dx_level must be 2**-level coarse cells (1, 0.5, 0.25, ...)")
|
||||
U_ref = _num("U_ref", U_ref, positive=True)
|
||||
L_ref = _num("L_ref", L_ref, positive=True)
|
||||
shear_on = _num("shear_on", shear_on, positive=True)
|
||||
shear_off = _num("shear_off", shear_off, nonneg=True)
|
||||
if not shear_off < shear_on:
|
||||
raise ValueError("hysteresis needs shear_off < shear_on")
|
||||
band_on = _num("band_on", band_on, nonneg=True)
|
||||
band_off = _num("band_off", band_off, nonneg=True)
|
||||
if not band_off >= band_on:
|
||||
raise ValueError("hysteresis needs band_off >= band_on")
|
||||
if isinstance(n_buffer, (bool, np.bool_)) or not isinstance(n_buffer, Integral) or n_buffer < 0:
|
||||
raise ValueError("n_buffer must be a non-negative integer")
|
||||
if len(origin) != 2:
|
||||
raise ValueError("origin must be (x0, y0) in coarse units")
|
||||
origin = (_num("origin[0]", origin[0]), _num("origin[1]", origin[1]))
|
||||
periodic = _periodic(periodic)
|
||||
if prev_core is None:
|
||||
prev = np.zeros(shape, bool)
|
||||
else:
|
||||
prev = np.asarray(prev_core)
|
||||
if prev.dtype != np.bool_ or prev.shape != shape:
|
||||
raise ValueError("prev_core must be a bool array of the grid shape")
|
||||
if np.any(prev & ~eligible):
|
||||
raise ValueError("prev_core marks solid/unowned cells: pass TagResult.core, not tagged")
|
||||
|
||||
S = strain_rate(ux, uy, valid, dx_level, periodic)
|
||||
s_star = S * L_ref / U_ref
|
||||
cell_strain = S * dx_level / U_ref
|
||||
d = wall_distance(~solid, dx_level, origin, distance_fn, periodic, solid=solid)
|
||||
dn = d / L_ref
|
||||
|
||||
ok = np.isfinite(s_star)
|
||||
sv = np.where(ok, s_star, -np.inf)
|
||||
unevaluable = eligible & ~ok
|
||||
held = unevaluable & prev
|
||||
shear = eligible & (((sv >= shear_on) | (prev & (sv >= shear_off))) | held)
|
||||
wall = eligible & ((dn <= band_on) | (prev & (dn <= band_off)))
|
||||
core = shear | wall
|
||||
reason = (wall * WALL + shear * SHEAR + held * HELD).astype(np.uint8)
|
||||
tagged = dilate(core, n_buffer, periodic) & owned
|
||||
return TagResult(_ro(core), _ro(tagged), _ro(reason), _ro(s_star), _ro(cell_strain),
|
||||
_ro(d), _ro(unevaluable), _ro(eligible),
|
||||
int(np.count_nonzero(unevaluable)))
|
||||
@@ -0,0 +1,140 @@
|
||||
"""One measured L1 strain observation, one growth-only L2 remap, no scheduler.
|
||||
|
||||
Run from the repository root: PYTHONPATH=src:. python -m research.shear_refinement.example
|
||||
Requires CUDA; CPU helpers and tests never import CUDA.
|
||||
"""
|
||||
from contextlib import ExitStack
|
||||
from numbers import Integral
|
||||
import numpy as np
|
||||
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.lbm.descriptors import D2Q9_EX, D2Q9_EY
|
||||
from CelerisLab.lbm.refinement import FixedPatchSet2D
|
||||
from CelerisLab.lbm.synchronized_remap import RemapTopology
|
||||
from .boundary_shear_tagging import tag_cells
|
||||
|
||||
CFG = LBMConfig(nx=48, ny=32, viscosity=.1)
|
||||
PARENTS = ((4, 4, 20, 28), (24, 4, 44, 28))
|
||||
CHILDREN = ((16, 16, 32, 40), (56, 16, 72, 40))
|
||||
CORRIDOR = (72, 20, 76, 36) # L1 allocated indices; bounded to right of fluid L2
|
||||
|
||||
|
||||
def grow_rectangle(current, request, *, alignment=4, area_cap=480):
|
||||
"""Bounding-box growth only, in request-array cell-edge coordinates.
|
||||
|
||||
No body or solver knowledge. Reject invalid/budget-exceeding proposals with
|
||||
ValueError; never clip a request, shrink old coverage or mutate an input.
|
||||
Alignment is edge divisibility, not a substitute for full topology guards.
|
||||
"""
|
||||
request = np.asarray(request)
|
||||
if request.dtype != bool or request.ndim != 2:
|
||||
raise ValueError('request must be a 2D boolean mask')
|
||||
values = (*current, alignment, area_cap)
|
||||
if len(current) != 4 or any(isinstance(v, (bool, np.bool_)) or not isinstance(v, Integral) for v in values):
|
||||
raise ValueError('rectangle, alignment and area cap must be integers')
|
||||
x0, y0, x1, y1 = current
|
||||
ny, nx = request.shape
|
||||
if alignment <= 0 or area_cap <= 0 or not (0 <= x0 < x1 <= nx and 0 <= y0 < y1 <= ny):
|
||||
raise ValueError('invalid rectangle, alignment or area cap')
|
||||
if any(v % alignment for v in current):
|
||||
raise ValueError('current rectangle must be aligned')
|
||||
y, x = np.nonzero(request)
|
||||
if x.size:
|
||||
x0, y0 = min(x0, int(x.min())), min(y0, int(y.min()))
|
||||
x1, y1 = max(x1, int(x.max())+1), max(y1, int(y.max())+1)
|
||||
a = alignment
|
||||
result = (x0//a*a, y0//a*a, (x1+a-1)//a*a, (y1+a-1)//a*a)
|
||||
if result[2] > nx or result[3] > ny:
|
||||
raise ValueError('aligned growth exceeds observation frame')
|
||||
if (result[2]-result[0])*(result[3]-result[1]) > area_cap:
|
||||
raise ValueError('growth exceeds area cap')
|
||||
return result
|
||||
|
||||
|
||||
def objects():
|
||||
return (SimObject(71, geometry=CircleGeometry(12., 14., .8),
|
||||
center=(12., 14.), radius=.8),)
|
||||
|
||||
|
||||
def topology(rectangles=CHILDREN):
|
||||
return RemapTopology.from_config(CFG, FixedPatchSet2D.from_config(CFG, PARENTS),
|
||||
rectangles, child_objects=objects())
|
||||
|
||||
|
||||
def observe(g, mesh, *, shear_on=.001):
|
||||
"""Moments of completed-time postcollision G; only real L1 fluid leaves.
|
||||
|
||||
No reconstructed covered values, ghosts or holes are derivative donors.
|
||||
solid is independent geometry (empty on L1: the body is pinned at L2).
|
||||
The array is cropped/sparse, so neither derivative axis wraps.
|
||||
"""
|
||||
valid = mesh.leaf_masks[1]
|
||||
f = g[:, valid].astype(np.float64)
|
||||
rho = f.sum(axis=0)
|
||||
if not np.isfinite(f).all() or np.any(rho <= 0):
|
||||
raise ValueError('invalid completed-time L1 fluid populations')
|
||||
ux, uy = (np.full(valid.shape, np.nan) for _ in range(2))
|
||||
ux[valid] = (np.asarray(D2Q9_EX)[:, None]*f).sum(axis=0)/rho
|
||||
uy[valid] = (np.asarray(D2Q9_EY)[:, None]*f).sum(axis=0)/rho
|
||||
tags = tag_cells(ux, uy, np.zeros(valid.shape, bool), valid=valid, owned=valid,
|
||||
dx_level=.5, origin=mesh.parent.fine_origin, periodic=(False, False),
|
||||
U_ref=.05, L_ref=1., shear_on=shear_on, shear_off=0.,
|
||||
band_on=0., band_off=0., n_buffer=0)
|
||||
corridor = np.zeros(valid.shape, bool)
|
||||
x0, y0, x1, y1 = CORRIDOR
|
||||
corridor[y0:y1, x0:x1] = True
|
||||
request = tags.tagged & corridor
|
||||
proposed = (CHILDREN[0], grow_rectangle(CHILDREN[1], request))
|
||||
# Host guards cover nesting, donor footprints, complete body and separation.
|
||||
candidate = topology(proposed)
|
||||
candidate.child.fine_layout((4, 4))
|
||||
report = dict(requested=int(request.sum()), unknown=int(tags.unevaluable.sum()),
|
||||
corridor_unknown=int((tags.unevaluable & corridor).sum()),
|
||||
corridor_unavailable=int((corridor & ~valid).sum()),
|
||||
out_of_scope=int((tags.tagged & ~corridor).sum()), rectangles=proposed)
|
||||
return proposed, report
|
||||
|
||||
|
||||
def initial_fields(mesh):
|
||||
"""Smooth periodic shear wave, sampled in each level's physical frame."""
|
||||
from CelerisLab.lbm.equilibrium import compute_feq_d2q9
|
||||
frames = ((np.zeros(2), 1.), (np.asarray(mesh.parent.fine_origin), .5),
|
||||
(np.asarray(mesh.parent.fine_origin)+.5*np.asarray(mesh.child.fine_origin), .25))
|
||||
arrays = []
|
||||
for leaf, (origin, dx) in zip(mesh.leaf_masks, frames):
|
||||
y = origin[1]+dx*(np.arange(leaf.shape[0])+.5)
|
||||
ux = .01*np.sin(2*np.pi*y/CFG.ny)
|
||||
rows = np.stack([compute_feq_d2q9(1., u, 0.) for u in ux], axis=1)
|
||||
arrays.append(np.broadcast_to(rows[:, :, None], (9, *leaf.shape)).copy())
|
||||
return tuple(arrays)
|
||||
|
||||
|
||||
def initialize(run):
|
||||
run.initialize(*initial_fields(topology()))
|
||||
|
||||
|
||||
def make(context):
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
return FixedPatchStepper(CFG, PARENTS, context=context, base_block=(4, 4),
|
||||
fine_block=(4, 4), child_block=(4, 4),
|
||||
child_rectangles_in_parent=CHILDREN, child_objects=objects())
|
||||
|
||||
|
||||
def main():
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
with CudaContext(0) as ctx, ExitStack() as owned:
|
||||
run = owned.enter_context(make(ctx))
|
||||
initialize(run)
|
||||
run.step(2) # Returns only at completed synchronized base time.
|
||||
proposed, report = observe(run.download()[1], topology())
|
||||
print(report)
|
||||
if proposed != CHILDREN:
|
||||
run = owned.enter_context(run.remap_child(proposed, child_objects=objects()))
|
||||
run.step(2)
|
||||
print(f'completed base step {run.step_count}; body rectangle {run.child_patch.bounds[0]}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -9,6 +9,7 @@ from .sync_plan import BodySyncPlan
|
||||
from .geometry.base import CutLink, SensorCell, Geometry
|
||||
from .geometry.circle import CircleGeometry
|
||||
from .coupling.soa_packer import pack_cut_links_to_soa, pack_sensor_to_soa
|
||||
from .jets import Jet, Sector, Tube, Radial, Parallel
|
||||
|
||||
__all__ = [
|
||||
"SimObject", "ObjectState", "ObjectControl", "SurfaceActuation",
|
||||
@@ -18,6 +19,7 @@ __all__ = [
|
||||
"CutLink", "SensorCell", "Geometry",
|
||||
"CircleGeometry",
|
||||
"pack_cut_links_to_soa", "pack_sensor_to_soa",
|
||||
"Jet", "Sector", "Tube", "Radial", "Parallel",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
# CelerisLab/body/jets.py
|
||||
"""Body-independent jets: spatial region + direction field + profile + amplitude.
|
||||
|
||||
A Jet selects cut links purely by the true wall hit point (FP64, before SoA
|
||||
packing), over every link in the scene; it carries no body association.
|
||||
Per-link velocity = amplitude * profile(s) * field(hit), where ``s`` in [-1, 1]
|
||||
is the region's lateral coordinate. Velocities are lattice units of the level
|
||||
whose links are evaluated; callers convert frames/units before evaluation.
|
||||
One physical link (receiver, direction) may be driven by at most one jet, and
|
||||
one jet may drive the links of only one body (checked at assignment, any amplitude).
|
||||
|
||||
``condition`` names the prescribed boundary type. Only ``"velocity"`` (the
|
||||
default: amplitude is a signed lattice velocity, not a flow rate) is
|
||||
implemented; ``"pressure"`` is reserved and rejected at construction, before
|
||||
any amplitude validation, so it never reaches assignment or a kernel.
|
||||
|
||||
Edge rule: the lateral bound |s| < 1 is exclusive (the profile vanishes
|
||||
there for parabolic/quartic); Sector r_min/r_max and Tube 0 <= along <= length
|
||||
are inclusive. Jets are immutable; an amplitude change replaces the Jet.
|
||||
|
||||
``surface_link_velocity`` is the single host-only assignment/validation point
|
||||
for legacy apertures plus jets (no PyCUDA import), shared by dense and fine
|
||||
levels.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
import numpy as np
|
||||
|
||||
CONDITIONS = ("velocity",)
|
||||
RESERVED_CONDITIONS = ("pressure",)
|
||||
|
||||
PROFILES = {
|
||||
"uniform": lambda s: np.ones_like(s),
|
||||
"parabolic": lambda s: 1 - s*s,
|
||||
"quartic": lambda s: (1 - s*s)**2,
|
||||
}
|
||||
|
||||
|
||||
def _finite(*values):
|
||||
if not all(math.isfinite(v) for v in values):
|
||||
raise ValueError("Jet parameters must be finite")
|
||||
|
||||
|
||||
def _freeze_origin(spec):
|
||||
"""Store ``origin`` as a validated float 2-tuple (no caller-owned list/array)."""
|
||||
origin = tuple(float(v) for v in spec.origin)
|
||||
if len(origin) != 2:
|
||||
raise ValueError("Jet origin must be a 2D point")
|
||||
_finite(*origin)
|
||||
object.__setattr__(spec, "origin", origin)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Sector:
|
||||
"""Annular sector about ``origin``: |angle offset| < half_width, r_min <= r <= r_max."""
|
||||
origin: tuple
|
||||
angle: float
|
||||
half_width: float
|
||||
r_max: float
|
||||
r_min: float = 0.0
|
||||
|
||||
def __post_init__(self):
|
||||
_freeze_origin(self)
|
||||
_finite(self.angle, self.half_width, self.r_max, self.r_min)
|
||||
if not (0 < self.half_width <= math.pi and 0 <= self.r_min <= self.r_max):
|
||||
raise ValueError("Sector requires 0 < half_width <= pi and 0 <= r_min <= r_max")
|
||||
|
||||
def select(self, hits):
|
||||
d = hits - np.asarray(self.origin, np.float64)
|
||||
r = np.hypot(d[:, 0], d[:, 1])
|
||||
delta = np.angle(np.exp(1j*(np.arctan2(d[:, 1], d[:, 0]) - self.angle)))
|
||||
return (np.abs(delta) < self.half_width) & (r >= self.r_min) & (r <= self.r_max), \
|
||||
delta/self.half_width
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Tube:
|
||||
"""Rectangle from ``origin`` along ``axis_angle`` for ``length``, |lateral| < half_width."""
|
||||
origin: tuple
|
||||
axis_angle: float
|
||||
length: float
|
||||
half_width: float
|
||||
|
||||
def __post_init__(self):
|
||||
_freeze_origin(self)
|
||||
_finite(self.axis_angle, self.length, self.half_width)
|
||||
if self.length <= 0 or self.half_width <= 0:
|
||||
raise ValueError("Tube requires positive length and half_width")
|
||||
|
||||
def select(self, hits):
|
||||
d = hits - np.asarray(self.origin, np.float64)
|
||||
c, s = math.cos(self.axis_angle), math.sin(self.axis_angle)
|
||||
along, lateral = d[:, 0]*c + d[:, 1]*s, -d[:, 0]*s + d[:, 1]*c
|
||||
return (along >= 0) & (along <= self.length) & (np.abs(lateral) < self.half_width), \
|
||||
lateral/self.half_width
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Radial:
|
||||
"""Unit vector along hit - origin (outward) or its reverse (inward)."""
|
||||
origin: tuple
|
||||
inward: bool = True
|
||||
|
||||
def __post_init__(self):
|
||||
_freeze_origin(self)
|
||||
|
||||
def direction(self, hits):
|
||||
d = hits - np.asarray(self.origin, np.float64)
|
||||
r = np.hypot(d[:, 0], d[:, 1])[:, None]
|
||||
if np.any(r <= 0):
|
||||
raise ValueError("Radial field undefined at its origin")
|
||||
return (-d if self.inward else d)/r
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Parallel:
|
||||
"""Uniform unit vector at ``angle`` (radians, counterclockwise from +x)."""
|
||||
angle: float
|
||||
|
||||
def __post_init__(self):
|
||||
_finite(self.angle)
|
||||
|
||||
def direction(self, hits):
|
||||
return np.broadcast_to([math.cos(self.angle), math.sin(self.angle)], hits.shape)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Jet:
|
||||
"""Region (Sector|Tube), field (Radial|Parallel), profile name, signed amplitude,
|
||||
prescribed boundary condition (velocity only; pressure reserved).
|
||||
|
||||
Frozen: change amplitude with ``with_amplitude`` (validated, new object);
|
||||
the cached per-link shapes stay valid because region/field/profile cannot change.
|
||||
"""
|
||||
region: object
|
||||
field: object
|
||||
profile: str = "uniform"
|
||||
amplitude: float = 0.0
|
||||
condition: str = "velocity"
|
||||
|
||||
def __post_init__(self):
|
||||
# The condition decides what amplitude and field mean: check it first.
|
||||
if self.condition in RESERVED_CONDITIONS:
|
||||
raise NotImplementedError(f"{self.condition} jets are reserved but not implemented")
|
||||
if self.condition not in CONDITIONS:
|
||||
raise ValueError(f"Jet condition must be one of {CONDITIONS + RESERVED_CONDITIONS}")
|
||||
if self.profile not in PROFILES:
|
||||
raise ValueError(f"Jet profile must be one of {sorted(PROFILES)}")
|
||||
_finite(self.amplitude)
|
||||
if abs(self.amplitude) >= 1:
|
||||
raise ValueError("Jet amplitude must satisfy abs(amplitude) < 1 (lattice units)")
|
||||
|
||||
def with_amplitude(self, amplitude):
|
||||
return replace(self, amplitude=float(amplitude))
|
||||
|
||||
|
||||
def jet_link_shapes(jets, hits):
|
||||
"""Unit-amplitude per-link vectors (n, 2) FP64 and jet index (n,) int32 (-1 = none).
|
||||
|
||||
``hits`` are true FP64 wall hit points (n, 2) row-aligned with the packed
|
||||
links. Raises if a jet selects nothing or two jets select the same link.
|
||||
"""
|
||||
hits = np.asarray(hits, np.float64).reshape(-1, 2)
|
||||
if not np.isfinite(hits).all():
|
||||
raise ValueError("Jet hit points must be finite")
|
||||
shape = np.zeros_like(hits)
|
||||
jet_id = np.full(len(hits), -1, np.int32)
|
||||
for j, jet in enumerate(jets):
|
||||
selected, s = jet.region.select(hits)
|
||||
if not selected.any():
|
||||
raise ValueError(f"Jet {j} selects no resolved cut links")
|
||||
if np.any(jet_id[selected] >= 0):
|
||||
raise ValueError(f"Jet {j} overlaps links already driven by another jet")
|
||||
jet_id[selected] = j
|
||||
shape[selected] = (PROFILES[jet.profile](s[selected])[:, None]
|
||||
* jet.field.direction(hits[selected]))
|
||||
return shape, jet_id
|
||||
|
||||
|
||||
def jet_link_velocity(jets, shape, jet_id):
|
||||
"""FP32 (n, 2) velocity = amplitude[jet_id] * shape; O(n), no geometry work."""
|
||||
amplitude = np.array([jet.amplitude for jet in jets] + [0.0], np.float64)
|
||||
return (amplitude[jet_id][:, None]*shape).astype(np.float32)
|
||||
|
||||
|
||||
# Two coarse-unit frames coexist (see FixedPatchStepper docs): the patch
|
||||
# cell-edge frame puts coarse cell I's center at I + 1/2, while Simulation
|
||||
# geometry uses the integer-node frame with that center at I. Jets are
|
||||
# evaluated in the frame their region/field were written in; convert hits
|
||||
# explicitly, never by relabelling.
|
||||
|
||||
def fine_hits_to_edge_frame(hits_local, fine_origin, dx):
|
||||
"""Fine-local cell-index hits -> coarse cell-edge frame: origin + dx*(hit + 1/2)."""
|
||||
return np.asarray(fine_origin, np.float64) + dx*(np.asarray(hits_local, np.float64) + .5)
|
||||
|
||||
|
||||
def edge_to_node_frame(points):
|
||||
"""Coarse cell-edge frame -> Simulation integer-node frame (shift by -1/2)."""
|
||||
return np.asarray(points, np.float64) - .5
|
||||
|
||||
|
||||
def surface_link_velocity(objects, cfg, flags, fluid_idx, dir, body_id, rx, ry,
|
||||
jets=(), hits=None):
|
||||
"""Per-link prescribed surface velocity (n, 2) FP32 and aperture mask.
|
||||
|
||||
Host-only and storage-neutral: rows follow the given physical cut-link
|
||||
order. Returns (None, None) when neither an object carries surface
|
||||
actuation nor a jet is given. Jets need true FP64 ``hits`` (n, 2) and may
|
||||
not share a link with each other or with a legacy aperture.
|
||||
"""
|
||||
enabled = [obj for obj in objects if obj.surface_actuation is not None]
|
||||
if not enabled and not jets:
|
||||
return None, None
|
||||
from ..lbm.descriptors import FLUID, SOLID
|
||||
if np.any((flags[fluid_idx] & FLUID) == 0) or np.any(flags[fluid_idx] & SOLID):
|
||||
raise ValueError("Surface cut links must have active fluid receivers")
|
||||
if len(np.unique(fluid_idx.astype(np.uint64)*cfg.nq+dir)) != len(dir):
|
||||
raise ValueError("Surface boundary requires unique cut-link writers")
|
||||
surface_velocity = np.zeros((len(dir), 2), np.float32)
|
||||
surface_aperture = np.zeros(len(dir), bool)
|
||||
for obj in enabled:
|
||||
obj.validate_surface_actuation(cfg)
|
||||
selected = body_id == obj.obj_id
|
||||
velocity, aperture = obj.surface_actuation.project(rx[selected], ry[selected])
|
||||
if not aperture.any():
|
||||
raise ValueError("Surface aperture hits no resolved cut links")
|
||||
surface_velocity[selected] = velocity
|
||||
surface_aperture[selected] = aperture
|
||||
if jets:
|
||||
if hits is None or len(hits) != len(dir):
|
||||
raise ValueError("Jets require true hit points row-aligned with the cut links")
|
||||
if (cfg is None or not cfg.is_d2q9 or cfg.store_precision != "FP32"
|
||||
or cfg.streaming != "double_buffer" or cfg.ddf_shifting):
|
||||
raise ValueError("Jets require D2Q9/FP32/unshifted/double_buffer")
|
||||
shape, jet_id = jet_link_shapes(jets, hits)
|
||||
driven = jet_id >= 0
|
||||
for j in range(len(jets)): # scene-wide body identity, independent of storage blocks
|
||||
bodies = np.unique(body_id[jet_id == j])
|
||||
if len(bodies) > 1:
|
||||
raise ValueError(f"Jet {j} selects cut links of bodies {bodies.tolist()}; "
|
||||
"one jet may drive only one body")
|
||||
owners = {obj.obj_id: obj for obj in objects}
|
||||
for bid in np.unique(body_id[driven]):
|
||||
state = vars(owners[int(bid)].state)
|
||||
if any(state.get(k, 0.) != 0 for k in ("vx", "vy", "omega")):
|
||||
raise ValueError("Jets may only drive links of stationary bodies")
|
||||
if np.any(surface_aperture & driven):
|
||||
raise ValueError("Jet overlaps a SurfaceActuation aperture")
|
||||
surface_velocity[driven] = jet_link_velocity(jets, shape, jet_id)[driven]
|
||||
surface_aperture |= driven
|
||||
return surface_velocity, surface_aperture
|
||||
@@ -70,6 +70,7 @@ class ObjectManager:
|
||||
self.nq = nq
|
||||
self.cfg = cfg
|
||||
self._registry = BodyRegistry()
|
||||
self.jets: list = [] # scene-level Jets; selection is spatial, not per body
|
||||
|
||||
self.action_gpu: Optional[cuda.DeviceAllocation] = None
|
||||
self.obs_gpu: Optional[cuda.DeviceAllocation] = None
|
||||
@@ -247,6 +248,7 @@ class ObjectManager:
|
||||
|
||||
# Build compact lists for new object set
|
||||
new_sensor_counts = np.zeros(max(next_count, 1), dtype=np.int32)
|
||||
hits = []
|
||||
(
|
||||
cl_fluid_idx, cl_dir, cl_q, cl_body_id,
|
||||
cl_rx, cl_ry, cl_rz, cl_fallback_class,
|
||||
@@ -254,7 +256,7 @@ class ObjectManager:
|
||||
fr_cells, fr_obj_id,
|
||||
) = self.build_compact_lists_for(
|
||||
next_objects, domain_flags=next_flags,
|
||||
sensor_cell_counts_out=new_sensor_counts,
|
||||
sensor_cell_counts_out=new_sensor_counts, hits_out=hits,
|
||||
)
|
||||
|
||||
# Compute change masks
|
||||
@@ -277,6 +279,7 @@ class ObjectManager:
|
||||
added_solid_mask=added_solid_mask,
|
||||
released_fluid_mask=released_fluid_mask,
|
||||
new_sensor_counts=new_sensor_counts,
|
||||
curved_hits=hits[0],
|
||||
)
|
||||
|
||||
def commit_pending(self, next_objects: List[SimObject],
|
||||
@@ -309,7 +312,8 @@ class ObjectManager:
|
||||
|
||||
cl_host = plan.curved_host
|
||||
field.curved.assign_host(*cl_host)
|
||||
field.curved.assign_surface(plan.next_objects, self.cfg, plan.next_flags)
|
||||
field.curved.assign_surface(plan.next_objects, self.cfg, plan.next_flags,
|
||||
jets=self.jets, hits=plan.curved_hits)
|
||||
s_cells, s_ids = plan.sensor_host
|
||||
field.sensors.assign_host(s_cells, s_ids)
|
||||
fr_cells, fr_ids = plan.force_region_host
|
||||
@@ -344,13 +348,13 @@ class ObjectManager:
|
||||
return merge_flag_masks(base_flags, masks)
|
||||
|
||||
# -- Compact list building -----------------------------------------------
|
||||
def build_compact_lists(self, domain_flags: np.ndarray | None = None):
|
||||
def build_compact_lists(self, domain_flags: np.ndarray | None = None, *, hits_out=None):
|
||||
"""Build cut-link SoA columns, sensor lists, and force-region lists
|
||||
from the formal registry objects.
|
||||
"""
|
||||
return self.build_compact_lists_for(
|
||||
self._registry.objects, domain_flags,
|
||||
sensor_cell_counts_out=self.sensor_cell_counts,
|
||||
sensor_cell_counts_out=self.sensor_cell_counts, hits_out=hits_out,
|
||||
)
|
||||
|
||||
def build_compact_lists_for(
|
||||
@@ -359,6 +363,7 @@ class ObjectManager:
|
||||
domain_flags: np.ndarray | None = None,
|
||||
*,
|
||||
sensor_cell_counts_out: np.ndarray | None = None,
|
||||
hits_out: list | None = None,
|
||||
):
|
||||
"""Build cut-link SoA columns, sensor lists, and force-region lists.
|
||||
|
||||
@@ -367,6 +372,8 @@ class ObjectManager:
|
||||
domain_flags: Optional uint16 flags for donor-cell classification.
|
||||
sensor_cell_counts_out: Int array to fill with per-object sensor
|
||||
cell counts. If provided, ``fill(0)`` is called first.
|
||||
hits_out: List that receives one FP64 (n, 2) array of true hit
|
||||
points row-aligned with the cut-link columns (for Jets).
|
||||
|
||||
Returns:
|
||||
cl_fluid_idx, cl_dir, cl_q, cl_body_id, cl_rx, cl_ry, cl_rz,
|
||||
@@ -376,6 +383,7 @@ class ObjectManager:
|
||||
"""
|
||||
cl_idx, cl_dir, cl_q, cl_bid = [], [], [], []
|
||||
cl_rx, cl_ry, cl_rz, cl_fallback = [], [], [], []
|
||||
cl_hit = []
|
||||
s_cells, s_ids = [], []
|
||||
fr_cells, fr_ids = [], []
|
||||
if domain_flags is None:
|
||||
@@ -404,7 +412,7 @@ class ObjectManager:
|
||||
) = obj.get_curved_list(
|
||||
self.nx, self.ny, self.nq,
|
||||
nz=self.nz, ex=ex, ey=ey, ez=ez,
|
||||
domain_flags=domain_flags,
|
||||
domain_flags=domain_flags, hits_out=cl_hit,
|
||||
)
|
||||
if len(fluid_idx) > 0:
|
||||
cl_idx.append(fluid_idx)
|
||||
@@ -452,12 +460,15 @@ class ObjectManager:
|
||||
r_fr_cells = np.concatenate(fr_cells) if fr_cells else np.zeros(0, dtype=np.uint32)
|
||||
r_fr_ids = np.concatenate(fr_ids) if fr_ids else np.zeros(0, dtype=np.int32)
|
||||
|
||||
if any(obj.surface_actuation is not None for obj in objects):
|
||||
r_hit = np.concatenate(cl_hit) if cl_hit else np.zeros((0, 2))
|
||||
if hits_out is not None:
|
||||
hits_out.append(r_hit)
|
||||
if self.jets or any(obj.surface_actuation is not None for obj in objects):
|
||||
# Reject unresolved apertures/ownership before sync or restart mutates state.
|
||||
from ..lbm.curved_links import CurvedLinkSoA
|
||||
links = CurvedLinkSoA()
|
||||
links.assign_host(r_idx, r_dir, r_q, r_bid, r_rx, r_ry, r_rz, r_fallback)
|
||||
links.assign_surface(objects, self.cfg, domain_flags)
|
||||
links.assign_surface(objects, self.cfg, domain_flags, jets=self.jets, hits=r_hit)
|
||||
|
||||
return (
|
||||
r_idx, r_dir, r_q, r_bid,
|
||||
@@ -479,13 +490,14 @@ class ObjectManager:
|
||||
self._telemetry_field = field
|
||||
|
||||
next_flags = self.build_flags(field.build_channel_flags()) if rebuild_flags else field.flag
|
||||
hits = []
|
||||
|
||||
(
|
||||
cl_fluid_idx, cl_dir, cl_q, cl_body_id,
|
||||
cl_rx, cl_ry, cl_rz, cl_fallback_class,
|
||||
sensor_cells, sensor_obj_id,
|
||||
fr_cells, fr_obj_id,
|
||||
) = self.build_compact_lists(domain_flags=next_flags)
|
||||
) = self.build_compact_lists(domain_flags=next_flags, hits_out=hits)
|
||||
|
||||
if rebuild_flags:
|
||||
field.flag = next_flags
|
||||
@@ -495,7 +507,8 @@ class ObjectManager:
|
||||
cl_fluid_idx, cl_dir, cl_q, cl_body_id,
|
||||
cl_rx, cl_ry, cl_rz, cl_fallback_class,
|
||||
)
|
||||
field.curved.assign_surface(self.objects, self.cfg, field.flag)
|
||||
field.curved.assign_surface(self.objects, self.cfg, field.flag,
|
||||
jets=self.jets, hits=hits[0])
|
||||
field.sensors.assign_host(sensor_cells, sensor_obj_id)
|
||||
field.force_regions.assign_host(fr_cells, fr_obj_id)
|
||||
|
||||
@@ -609,11 +622,19 @@ class ObjectManager:
|
||||
cuda.memcpy_dtoh_async(self.obs_pinned, self.obs_gpu, stream)
|
||||
|
||||
def _upload_action_async(self, stream: cuda.Stream) -> None:
|
||||
"""Async H2D of host action array to action_gpu."""
|
||||
"""Async H2D of host action array to action_gpu.
|
||||
|
||||
Single gate for every action path (setters or direct ``action`` edits):
|
||||
surface-actuated and Jet-driven bodies must keep zero motion slots.
|
||||
"""
|
||||
slot = 3*(self.cfg.dim if self.cfg else 2)
|
||||
for obj in self.objects:
|
||||
obj.validate_surface_actuation(self.cfg)
|
||||
if obj.surface_actuation is not None and self.action[(obj.obj_id+1)*3*self.cfg.dim-1] != 0:
|
||||
base = obj.obj_id*slot
|
||||
if obj.surface_actuation is not None and self.action[base+slot-1] != 0:
|
||||
raise ValueError("Surface actuation cannot share the rotation action")
|
||||
self.validate_jet_motion(obj.obj_id, {"vx": self.action[base], "vy": self.action[base+1],
|
||||
"omega": self.action[base+slot-1]})
|
||||
if self.action_gpu is None or self.action.size == 0:
|
||||
return
|
||||
if self._action_pinned is None or self._action_pinned.size != self.action.size:
|
||||
@@ -725,6 +746,18 @@ class ObjectManager:
|
||||
assert self.obs_pinned is not None
|
||||
return self.obs_pinned.copy()
|
||||
|
||||
def validate_jet_motion(self, body_id: int, state: dict) -> None:
|
||||
"""Reject motion of a body whose synced cut links are Jet-driven.
|
||||
|
||||
Before the first sync no links exist; sync-time checks cover that case.
|
||||
"""
|
||||
field = self._telemetry_field
|
||||
cl = field.curved if field is not None else None
|
||||
if (cl is not None and cl.jet_id is not None
|
||||
and np.any(cl.body_id[cl.jet_id >= 0] == body_id)
|
||||
and any(state.get(k, 0.) != 0 for k in ("vx", "vy", "omega"))):
|
||||
raise ValueError("Jet-driven bodies must stay stationary")
|
||||
|
||||
def set_body_state(self, body_id: int, omega: float = 0.0) -> None:
|
||||
"""Set runtime body state (host action array only, no H2D).
|
||||
|
||||
@@ -732,7 +765,9 @@ class ObjectManager:
|
||||
"""
|
||||
self._validate_body_id(body_id)
|
||||
obj = self.get(body_id)
|
||||
obj.validate_surface_actuation(self.cfg, dict(vars(obj.state), omega=omega))
|
||||
proposed = dict(vars(obj.state), omega=float(omega))
|
||||
obj.validate_surface_actuation(self.cfg, proposed)
|
||||
self.validate_jet_motion(body_id, proposed)
|
||||
dim = self.cfg.dim if self.cfg else 2
|
||||
slot = 3 * dim
|
||||
base = body_id * slot
|
||||
|
||||
@@ -84,6 +84,18 @@ class SurfaceActuation:
|
||||
speed = self.normal_velocity*np.maximum(0., 1-(delta/self.half_width)**2)**2
|
||||
return np.stack((speed*rx/radius, speed*ry/radius), axis=-1).astype(np.float32), aperture
|
||||
|
||||
def as_jet(self, center, radius, tol=1e-6):
|
||||
"""Legacy adapter: equivalent body-independent Jet on a circle of ``radius``.
|
||||
|
||||
The thin annulus replaces the old body filter; equality with ``project``
|
||||
holds up to FP32 lever-arm rounding (measured in tests, not assumed).
|
||||
"""
|
||||
from .jets import Jet, Radial, Sector
|
||||
band = tol*max(1.0, radius)
|
||||
return Jet(Sector(tuple(center), self.angle, self.half_width, radius + band,
|
||||
max(0.0, radius - band)),
|
||||
Radial(tuple(center), inward=False), "quartic", self.normal_velocity)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SimObject container
|
||||
@@ -183,12 +195,13 @@ class SimObject:
|
||||
def get_curved_list(
|
||||
self, nx: int, ny: int, nq: int,
|
||||
nz: int = 1, ex=None, ey=None, ez=None,
|
||||
domain_flags=None,
|
||||
domain_flags=None, hits_out=None,
|
||||
):
|
||||
"""Return 8-column SoA arrays for curved-boundary kernel.
|
||||
|
||||
Delegates to the geometry object for cut-link enumeration and
|
||||
to ``pack_cut_links_to_soa`` for SoA packing.
|
||||
to ``pack_cut_links_to_soa`` for SoA packing. If ``hits_out`` is a
|
||||
list, the true FP64 hit points (n, 2) are appended row-aligned.
|
||||
|
||||
Returns:
|
||||
8-tuple matching CurvedLinkSoA.assign_host().
|
||||
@@ -198,6 +211,9 @@ class SimObject:
|
||||
links = self.geometry.build_cut_links(nx, ny, domain_flags=domain_flags)
|
||||
for cl in links:
|
||||
cl.body_id = self.obj_id
|
||||
if hits_out is not None:
|
||||
hits_out.append(np.array([(cl.hit_x, cl.hit_y) for cl in links],
|
||||
np.float64).reshape(-1, 2))
|
||||
return pack_cut_links_to_soa(links)
|
||||
|
||||
def get_sensor_list(self, nx: int, ny: int, nz: int = 1):
|
||||
|
||||
@@ -40,6 +40,7 @@ class BodySyncPlan:
|
||||
added_solid_mask: Bool array -- True where ``old_fluid -> new_solid``.
|
||||
released_fluid_mask: Bool array -- True where ``old_obstacle -> new_fluid``.
|
||||
new_sensor_counts: Int array of sensor cell counts per object.
|
||||
curved_hits: FP64 (n, 2) true hit points row-aligned with curved_host.
|
||||
"""
|
||||
next_objects: List[SimObject]
|
||||
next_count: int
|
||||
@@ -50,3 +51,4 @@ class BodySyncPlan:
|
||||
added_solid_mask: np.ndarray
|
||||
released_fluid_mask: np.ndarray
|
||||
new_sensor_counts: np.ndarray
|
||||
curved_hits: np.ndarray | None = None
|
||||
@@ -0,0 +1,273 @@
|
||||
# CelerisLab/lbm/block_stepper.py
|
||||
"""Opt-in periodic backend for one BlockLayout2D level, optional static circles.
|
||||
|
||||
D2Q9/SRT/FP32 unforced double buffers. Each step refreshes every halo from
|
||||
its owner core, then pulls/collides core cells into the spare buffer, then
|
||||
swaps. Only halo pair tables are uploaded; dense ownership stays on the host.
|
||||
The caller owns the CudaContext and must close this backend before it.
|
||||
Optional ``objects`` are stationary passive circles (static linear BFL via
|
||||
receiver-local staging: halo refresh -> cut links -> pull, no copy between).
|
||||
No force/actuation readout, motion, walls, refinement, checkpoint or runtime
|
||||
parameter mutation; wall/slot/inlet fields in cfg are ignored.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
from numbers import Integral
|
||||
import struct
|
||||
from threading import RLock
|
||||
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from ..cuda import compiler_v2 as compiler
|
||||
from .blocks import NQ, BlockLayout2D, blocked_link_tables
|
||||
from .descriptors import D2Q9_EX, D2Q9_EY, FLUID, SOLID
|
||||
|
||||
MAX_GRID_DIM = 65535 # CUDA gridDim.y/z limit (rows, blocks)
|
||||
|
||||
|
||||
def _static_circles(layout, objects):
|
||||
"""Host tables for stationary circles; rejects before any CUDA work.
|
||||
|
||||
Every periodic neighbor of every fluid core is inspected, including domain
|
||||
edges that CircleGeometry does not enumerate, so clipped or incomplete
|
||||
geometry cannot pass. Each physical link has one receiver-owning block.
|
||||
"""
|
||||
from ..body.geometry.circle import CircleGeometry
|
||||
|
||||
ny, nx = layout.shape
|
||||
flags = np.full(ny * nx, FLUID, np.uint16)
|
||||
for obj in objects:
|
||||
if (type(obj.geometry) is not CircleGeometry or obj.is_sensor or obj.is_force_region
|
||||
or obj.surface_actuation is not None
|
||||
or any(getattr(obj.state, name) != 0 for name in ("vx", "vy", "omega"))
|
||||
or any(vars(obj.control).values())):
|
||||
raise ValueError("Block bodies must be stationary passive circles")
|
||||
cx, cy = obj.geometry.center
|
||||
radius = obj.geometry._radius
|
||||
if not np.isfinite([cx, cy, radius]).all() or radius <= 0:
|
||||
raise ValueError("Block circle center/radius must be finite with radius > 0")
|
||||
mask = obj.geometry.build_flag_mask(nx, ny)
|
||||
solid = (mask & SOLID) != 0
|
||||
if not solid.any() or np.any(flags[solid] & SOLID):
|
||||
raise ValueError("Block circles must be resolved and disjoint")
|
||||
flags[solid] = mask[solid]
|
||||
solid = ((flags & SOLID) != 0).reshape(ny, nx)
|
||||
if solid[[0, -1]].any() or solid[:, [0, -1]].any():
|
||||
raise ValueError("Block circles must not touch the domain edge")
|
||||
links = [link for obj in objects
|
||||
for link in obj.geometry.build_cut_links(nx, ny, domain_flags=flags)]
|
||||
def source(r, q):
|
||||
y, x = divmod(r, nx)
|
||||
return (y + D2Q9_EY[q]) % ny, (x + D2Q9_EX[q]) % nx
|
||||
receivers = {(int(link.fluid_idx), int(link.dir)) for link in links}
|
||||
required = {(int(r), q) for r in np.flatnonzero(~solid.ravel())
|
||||
for q in range(1, NQ) if solid[source(r, q)]}
|
||||
if len(receivers) != len(links) or receivers != required:
|
||||
raise ValueError("Cut links must cover every fluid pull from a solid exactly once")
|
||||
tables, _ = blocked_link_tables(
|
||||
layout, flags, np.array([link.fluid_idx for link in links], np.uint32),
|
||||
np.array([link.dir for link in links], np.uint8),
|
||||
np.array([link.q for link in links], np.float32),
|
||||
np.array([link.fallback for link in links], np.uint8))
|
||||
return dict(solid=solid, **tables)
|
||||
|
||||
|
||||
class PeriodicBlockStepper:
|
||||
"""G->G stepping of Q-major (9, ny, nx) postcollision populations.
|
||||
|
||||
On a device/launch failure the instance becomes unusable: close and
|
||||
recreate it rather than assuming a partially advanced buffer rolled back.
|
||||
"""
|
||||
def __init__(self, cfg, layout, *, context, objects=()):
|
||||
if not isinstance(layout, BlockLayout2D) or layout.periodic != (True, True):
|
||||
raise ValueError("PeriodicBlockStepper requires a doubly periodic BlockLayout2D")
|
||||
checked = replace(cfg)
|
||||
checked.validate()
|
||||
if (not checked.is_d2q9 or checked.collision != "SRT"
|
||||
or checked.streaming != "double_buffer" or checked.store_precision != "FP32"
|
||||
or checked.ddf_shifting or checked.les_enabled
|
||||
or (checked.ny, checked.nx) != layout.shape):
|
||||
raise ValueError("PeriodicBlockStepper requires matching D2Q9/SRT/FP32/"
|
||||
"unshifted/double_buffer config without LES")
|
||||
ly, lx = layout.local_shape
|
||||
pairs = len(layout.halo_dst)
|
||||
tpb = checked.threads_per_block
|
||||
if layout.nblocks > MAX_GRID_DIM or ly > MAX_GRID_DIM or not 0 < pairs < 2**31:
|
||||
raise ValueError("block count, block rows or halo pairs exceed launch limits")
|
||||
objects = tuple(objects) # an empty iterable takes the body-free path
|
||||
self.boundary = _static_circles(layout, objects) if objects else None
|
||||
links = 0 if self.boundary is None else len(self.boundary["cell"])
|
||||
if links >= 2**31:
|
||||
raise ValueError("cut links exceed launch limits")
|
||||
self.layout = layout
|
||||
self.ctx = context
|
||||
self._links = links
|
||||
self._link_grid = ((links + tpb - 1) // tpb, 1)
|
||||
# Wall/slot fields are not applied; neutralize them like the fine patch level.
|
||||
self._local_cfg = replace(checked, nx=lx, ny=ly, y_wall_bc="bounce_back", top_wall_bc="velocity",
|
||||
wall_slot_width=0, wall_normal_velocity=0.0, velocity=0.0)
|
||||
self._block = (tpb, 1, 1)
|
||||
self._grid = ((lx + tpb - 1) // tpb, ly, layout.nblocks)
|
||||
self._copy_grid = ((pairs + tpb - 1) // tpb, 1)
|
||||
self._bytes = int(np.prod(layout.blocked_shape)) * 4
|
||||
self._lock = RLock()
|
||||
self._status = "new"
|
||||
self._step_count = 0
|
||||
self._allocations = []
|
||||
self._stream = self._module = self._copy = self._step = self._curved = None
|
||||
self._tables = {}
|
||||
with self.ctx.activate():
|
||||
try:
|
||||
free, _ = cuda.mem_get_info()
|
||||
tables = sum(a.nbytes for k, a in (self.boundary or {}).items() if k != "solid")
|
||||
if 2 * self._bytes + layout.halo_dst.nbytes + layout.halo_src.nbytes + tables > free:
|
||||
raise MemoryError("blocked buffers exceed free device memory")
|
||||
self._stream = cuda.Stream()
|
||||
config = self._local_cfg
|
||||
config.validate()
|
||||
if not np.isclose(config.omega, 1 / (3 * checked.viscosity + .5), rtol=1e-14, atol=0):
|
||||
raise RuntimeError("block omega/tau mismatch")
|
||||
build = compiler.generate_config(config)
|
||||
try:
|
||||
ptx = compiler.compile_kernel(self.ctx.sm_arch, source="blocks.cu", build_dir=build)
|
||||
module = compiler.load_module(ptx)
|
||||
finally:
|
||||
compiler.cleanup_build_dir(build)
|
||||
ptr, size = module.get_global("d_params")
|
||||
if size != struct.calcsize("=ffffI"):
|
||||
raise RuntimeError("LBMParams host/device layout mismatch")
|
||||
cuda.memcpy_htod(ptr, struct.pack("=ffffI", config.omega, 0, 0, 0, 0))
|
||||
self._module = module
|
||||
self._current = self._allocate(self._bytes)
|
||||
self._spare = self._allocate(self._bytes)
|
||||
self._dst = self._upload(layout.halo_dst)
|
||||
self._src = self._upload(layout.halo_src)
|
||||
self._copy = module.get_function("BlockHaloCopy")
|
||||
self._step = module.get_function("BlockStep")
|
||||
if self.boundary is not None:
|
||||
self._tables = {k: self._upload(a) for k, a in self.boundary.items() if k != "solid"}
|
||||
self._curved = module.get_function("BlockCurvedBoundary")
|
||||
except BaseException:
|
||||
try:
|
||||
self.close()
|
||||
except Exception:
|
||||
pass # Preserve the original construction failure.
|
||||
raise
|
||||
|
||||
def _allocate(self, size):
|
||||
pointer = cuda.mem_alloc(size)
|
||||
self._allocations.append(pointer)
|
||||
return pointer
|
||||
|
||||
def _upload(self, array):
|
||||
array = np.ascontiguousarray(array)
|
||||
pointer = self._allocate(array.nbytes)
|
||||
cuda.memcpy_htod(pointer, array)
|
||||
return pointer
|
||||
|
||||
def _require(self, *states):
|
||||
if self._status not in states:
|
||||
raise RuntimeError(f"Block stepper is {self._status}; expected {' or '.join(states)}")
|
||||
|
||||
@property
|
||||
def step_count(self):
|
||||
return self._step_count
|
||||
|
||||
def initialize(self, g):
|
||||
"""Upload dense G_0; the spare buffer starts NaN so stale halos cannot hide."""
|
||||
with self._lock, self.ctx.activate():
|
||||
self._require("new", "ready")
|
||||
dense = np.array(g, dtype=np.float32, order="C", copy=True)
|
||||
if dense.shape != (NQ, *self.layout.shape):
|
||||
raise ValueError("Expected a Q-major (9, ny, nx) array")
|
||||
fluid = np.ones(self.layout.shape, bool) if self.boundary is None else ~self.boundary["solid"]
|
||||
if not np.isfinite(dense[:, fluid]).all() or (dense[:, fluid].sum(axis=0) <= 0).any():
|
||||
raise ValueError("Fluid populations must be finite with positive density")
|
||||
dense[:, ~fluid] = np.nan # Solid cores are deliberately invalid.
|
||||
blocked = self.layout.to_blocked(dense)
|
||||
spare = np.full_like(blocked, np.nan)
|
||||
try:
|
||||
cuda.memcpy_htod(self._current, blocked)
|
||||
cuda.memcpy_htod(self._spare, spare)
|
||||
self._step_count = 0
|
||||
self._status = "ready"
|
||||
except BaseException:
|
||||
self._status = "failed"
|
||||
raise
|
||||
|
||||
def step(self, n=1):
|
||||
"""Advance n steps: halo refresh, then core pull/collide, per step."""
|
||||
if isinstance(n, bool) or not isinstance(n, Integral) or n < 0:
|
||||
raise ValueError("n must be a nonnegative integer")
|
||||
with self._lock, self.ctx.activate():
|
||||
self._require("ready")
|
||||
kw = dict(block=self._block, stream=self._stream)
|
||||
try:
|
||||
self._status = "advancing"
|
||||
for _ in range(n):
|
||||
self._copy(self._current, self._dst, self._src,
|
||||
np.uint32(len(self.layout.halo_dst)), grid=self._copy_grid, **kw)
|
||||
if self._curved is not None:
|
||||
t = self._tables
|
||||
self._curved(self._current, t["block"], t["cell"], t["dir"], t["q"],
|
||||
t["fallback"], np.uint32(self._links), np.uintp(0), # no actuation
|
||||
np.uintp(0), np.uintp(0), np.uintp(0), # no observation
|
||||
grid=self._link_grid, **kw)
|
||||
self._step(self._current, self._spare, np.uint32(self.layout.halo),
|
||||
self._tables.get("flags", np.uintp(0)), np.uintp(0), # no kind
|
||||
grid=self._grid, **kw)
|
||||
self._stream.synchronize()
|
||||
self._current, self._spare = self._spare, self._current
|
||||
self._step_count += 1
|
||||
self._status = "ready"
|
||||
except BaseException:
|
||||
self._status = "failed"
|
||||
raise
|
||||
|
||||
def download(self):
|
||||
"""Return dense (9, ny, nx) FP32 core populations; no host cache."""
|
||||
with self._lock, self.ctx.activate():
|
||||
self._require("ready")
|
||||
blocked = np.empty(self.layout.blocked_shape, np.float32)
|
||||
try:
|
||||
cuda.memcpy_dtoh(blocked, self._current)
|
||||
except BaseException:
|
||||
self._status = "failed"
|
||||
raise
|
||||
return self.layout.to_dense(blocked)
|
||||
|
||||
def close(self):
|
||||
"""Release owned resources; retain them for retry if context activation fails."""
|
||||
with self._lock:
|
||||
if self._status == "closed":
|
||||
return
|
||||
self._status = "failed"
|
||||
with self.ctx.activate():
|
||||
self._status = "closed"
|
||||
error = None
|
||||
try:
|
||||
if self._stream is not None:
|
||||
self._stream.synchronize()
|
||||
except Exception as exc:
|
||||
error = exc
|
||||
self._copy = self._step = self._curved = self._module = None
|
||||
self._tables = {}
|
||||
for pointer in self._allocations:
|
||||
try:
|
||||
pointer.free()
|
||||
except Exception as exc:
|
||||
error = error or exc
|
||||
self._allocations.clear()
|
||||
self._stream = None
|
||||
if error is not None:
|
||||
raise error
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
try:
|
||||
self.close()
|
||||
except Exception:
|
||||
if exc[0] is None:
|
||||
raise
|
||||
@@ -0,0 +1,375 @@
|
||||
# CelerisLab/lbm/blocks.py
|
||||
"""CPU layout for fixed-size 2D blocks: core ownership, halo pairs and packing.
|
||||
|
||||
Dense arrays are Q-major (q, y, x) with cell y*nx+x, as in core/layout.cuh.
|
||||
Blocked storage is block-contiguous and Q-major inside each block:
|
||||
(nblocks, q, by+2*halo, bx+2*halo). A full layout stores every grid block,
|
||||
block b = jy*nbx + jx with core origin (jy*by, jx*bx), so every dense cell,
|
||||
fluid or solid, has exactly one core owner. A sparse layout stores only the
|
||||
selected grid-aligned blocks (row-major order, b = position in that list);
|
||||
cells of absent blocks are HOLES: owner = layout.hole (one past the last
|
||||
block cell, so any unguarded use fails instead of wrapping like -1), no halo
|
||||
pair reads them, packing ignores them and unpacking returns NaN there. This
|
||||
is physical-block storage, not arbitrary cell refinement.
|
||||
|
||||
A "block cell" id is b*L + c with L=(by+2h)*(bx+2h) and c the local row-major
|
||||
cell; its population q lives at flat slot b*NQ*L + q*L + c. Halo pairs copy
|
||||
all NQ populations from an owner core cell into another block's halo cell.
|
||||
Periodicity is explicit per axis. Across a non-periodic exterior, halo cells
|
||||
have no pair and stay invalid (NaN after packing): no wrap, no implied BC.
|
||||
|
||||
Preparation only: no CUDA, no boundary conditions, no refinement levels.
|
||||
The one-cell same-level halo here is unrelated to the four-cell fine halo of
|
||||
the fixed refinement patch (refinement.py), whose semantics are unchanged.
|
||||
|
||||
Static cut links (map_cut_links) use RECEIVER-LOCAL staging: each physical
|
||||
link belongs once to the block whose core holds its fluid receiver. Order per
|
||||
step: gather halos -> BFL writes the reflected source population into that
|
||||
block's own core/halo copy of the solid cell -> pull/collide core cells, with
|
||||
NO halo copy between BFL and pull. Reflected populations are temporary,
|
||||
receiver-local boundary values: the solid's owner-core copy of that slot may
|
||||
be stale, which is distinct from the unique core ownership of stored state.
|
||||
No moving geometry is implied.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from numbers import Integral
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .descriptors import D2Q9_EX, D2Q9_EY
|
||||
|
||||
NQ = 9
|
||||
FACE, CORNER = 0, 1
|
||||
|
||||
|
||||
def _readonly(values, dtype):
|
||||
array = np.ascontiguousarray(values, dtype=dtype)
|
||||
array.setflags(write=False)
|
||||
return array
|
||||
|
||||
|
||||
def _index(value, upper, name, lower=0):
|
||||
"""Integer index or index array in [lower, upper); rejects bools and floats."""
|
||||
array = np.asarray(value)
|
||||
if array.dtype.kind not in "iu" or (array.size and (array.min() < lower or array.max() >= upper)):
|
||||
raise ValueError(f"{name} must be integer index(es) in [{lower}, {upper})")
|
||||
return array
|
||||
|
||||
|
||||
def _positive_int(value, name):
|
||||
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral) or value <= 0:
|
||||
raise ValueError(f"{name} must be a positive integer")
|
||||
return int(value)
|
||||
|
||||
|
||||
def _selected_blocks(origins, ny, nx, by, bx):
|
||||
"""Row-major grid block indices of explicit (y0, x0) origins, validated."""
|
||||
array = np.asarray(origins)
|
||||
if array.dtype.kind not in "iu" or array.ndim != 2 or array.shape[1] != 2 or not len(array):
|
||||
raise ValueError("origins must be a non-empty integer (n, 2) array of (y0, x0)")
|
||||
y0, x0 = array[:, 0].astype(np.int64), array[:, 1].astype(np.int64)
|
||||
if (y0 % by).any() or (x0 % bx).any():
|
||||
raise ValueError("origins must be multiples of the block size")
|
||||
if (y0 < 0).any() or (y0 >= ny).any() or (x0 < 0).any() or (x0 >= nx).any():
|
||||
raise ValueError("origins must lie inside the grid")
|
||||
index = (y0 // by) * (nx // bx) + x0 // bx
|
||||
if (np.diff(index) == 0).any():
|
||||
raise ValueError("origins must be unique")
|
||||
if (np.diff(index) < 0).any():
|
||||
raise ValueError("origins must be in row-major order")
|
||||
return index
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class BlockCutLinks:
|
||||
"""One row per input link, in input order (so force is counted once).
|
||||
|
||||
``block`` owns the receiver core cell; ``receiver`` and ``donor`` are block
|
||||
cell ids in that block (donor = NO_DONOR unless q<.5 with a legal donor);
|
||||
``write`` is the flat blocked slot of the reflected population.
|
||||
"""
|
||||
block: np.ndarray
|
||||
receiver: np.ndarray
|
||||
donor: np.ndarray
|
||||
write: np.ndarray
|
||||
|
||||
|
||||
NO_DONOR = np.iinfo(np.uint64).max
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class BlockLayout2D:
|
||||
"""Fixed-size block partition of an (ny, nx) grid; construct with build().
|
||||
|
||||
``origins`` rows are (y0, x0) core origins. ``owner`` maps each dense cell
|
||||
to its owning block cell id, or ``hole`` if its block is absent.
|
||||
``halo_dst``/``halo_src`` are block cell ids (destination halo cell,
|
||||
source owner core cell) sorted by destination;
|
||||
``halo_kind`` marks FACE or CORNER pairs. Sources are never halo cells, so
|
||||
one gather in any order fills every valid halo cell.
|
||||
"""
|
||||
shape: tuple[int, int]
|
||||
block: tuple[int, int]
|
||||
halo: int
|
||||
periodic: tuple[bool, bool]
|
||||
origins: np.ndarray
|
||||
owner: np.ndarray
|
||||
halo_dst: np.ndarray
|
||||
halo_src: np.ndarray
|
||||
halo_kind: np.ndarray
|
||||
|
||||
@classmethod
|
||||
def build(cls, ny, nx, by, bx, *, halo=1, periodic=(True, True), origins=None) -> "BlockLayout2D":
|
||||
"""``periodic`` is (periodic_x, periodic_y); block sizes must divide the grid.
|
||||
|
||||
``origins`` (optional) selects stored blocks by (y0, x0) core origin:
|
||||
integer multiples of (by, bx) inside the grid, at least one, unique
|
||||
and strictly increasing in row-major order (no silent reordering).
|
||||
None stores all blocks; passing every origin gives the same layout.
|
||||
"""
|
||||
ny, nx, by, bx, halo = (_positive_int(v, n) for v, n in
|
||||
((ny, "ny"), (nx, "nx"), (by, "by"), (bx, "bx"), (halo, "halo")))
|
||||
if ny % by or nx % bx:
|
||||
raise ValueError("block sizes must divide the grid")
|
||||
if halo > min(by, bx):
|
||||
raise ValueError("halo may not exceed the block size")
|
||||
if len(periodic) != 2 or not all(isinstance(p, (bool, np.bool_)) for p in periodic):
|
||||
raise ValueError("periodic must be two booleans (x, y)")
|
||||
px, py = map(bool, periodic)
|
||||
nby, nbx = ny // by, nx // bx
|
||||
ly, lx = by + 2 * halo, bx + 2 * halo
|
||||
cells = ly * lx
|
||||
if origins is not None:
|
||||
selected = _selected_blocks(origins, ny, nx, by, bx)
|
||||
origins = np.array(origins, dtype=np.int64).reshape(-1, 2) # own copy, never caller storage
|
||||
# Capacity from arithmetic before any grid-sized allocation; hole =
|
||||
# nblocks * cells is below this bound too.
|
||||
if (nby * nbx if origins is None else len(origins)) * NQ * cells > np.iinfo(np.int64).max // 2:
|
||||
raise ValueError("blocked storage exceeds 64-bit indexing")
|
||||
if origins is None:
|
||||
selected = np.arange(nby * nbx)
|
||||
jy, jx = np.divmod(selected, nbx)
|
||||
origins = np.stack([jy * by, jx * bx], axis=1)
|
||||
|
||||
# Grid block -> stored block, or len(origins) for an absent block, so
|
||||
# absent cells land exactly on hole = nblocks * cells.
|
||||
stored = np.full(nby * nbx, len(origins), dtype=np.int64)
|
||||
stored[selected] = np.arange(len(origins))
|
||||
gy, gx = np.mgrid[0:ny, 0:nx]
|
||||
gb = stored[(gy // by) * nbx + gx // bx]
|
||||
hole = len(origins) * cells
|
||||
owner = np.where(gb < len(origins),
|
||||
gb * cells + (gy % by + halo) * lx + gx % bx + halo, hole)
|
||||
|
||||
# Halo cells of one block in local row-major order, then all blocks.
|
||||
hy, hx = np.mgrid[0:ly, 0:lx]
|
||||
out_y = (hy < halo) | (hy >= by + halo)
|
||||
out_x = (hx < halo) | (hx >= bx + halo)
|
||||
ring = out_y | out_x
|
||||
hy, hx, kind = hy[ring], hx[ring], np.where(out_y[ring] & out_x[ring], CORNER, FACE)
|
||||
dst, src, kinds = [], [], []
|
||||
for b, (y0, x0) in enumerate(origins):
|
||||
sy, sx = y0 + hy - halo, x0 + hx - halo
|
||||
if py:
|
||||
sy %= ny
|
||||
if px:
|
||||
sx %= nx
|
||||
keep = (sy >= 0) & (sy < ny) & (sx >= 0) & (sx < nx)
|
||||
keep[keep] = owner[sy[keep], sx[keep]] != hole
|
||||
dst.append(b * cells + hy[keep] * lx + hx[keep])
|
||||
src.append(owner[sy[keep], sx[keep]])
|
||||
kinds.append(kind[keep])
|
||||
return cls((ny, nx), (by, bx), halo, (px, py),
|
||||
_readonly(origins, np.int64), _readonly(owner, np.uint64),
|
||||
_readonly(np.concatenate(dst), np.uint64),
|
||||
_readonly(np.concatenate(src), np.uint64),
|
||||
_readonly(np.concatenate(kinds), np.uint8))
|
||||
|
||||
@property
|
||||
def nblocks(self) -> int:
|
||||
return len(self.origins)
|
||||
|
||||
@property
|
||||
def hole(self) -> int:
|
||||
"""Owner value of cells in absent blocks: one past the last block cell."""
|
||||
return self.nblocks * int(np.prod(self.local_shape))
|
||||
|
||||
@property
|
||||
def owned(self) -> np.ndarray:
|
||||
"""Dense (ny, nx) mask of cells stored in some block core."""
|
||||
return self.owner != self.hole
|
||||
|
||||
@property
|
||||
def local_shape(self) -> tuple[int, int]:
|
||||
return self.block[0] + 2 * self.halo, self.block[1] + 2 * self.halo
|
||||
|
||||
@property
|
||||
def blocked_shape(self) -> tuple[int, int, int, int]:
|
||||
return (self.nblocks, NQ, *self.local_shape)
|
||||
|
||||
def slot(self, block_cell, q):
|
||||
"""Flat blocked population slot of block cell id(s) for direction q."""
|
||||
cells = int(np.prod(self.local_shape))
|
||||
block_cell = _index(block_cell, self.nblocks * cells, "block_cell").astype(np.uint64)
|
||||
q = _index(q, NQ, "q").astype(np.uint64)
|
||||
b, c = np.divmod(block_cell, np.uint64(cells))
|
||||
return (b * np.uint64(NQ) + q) * np.uint64(cells) + c
|
||||
|
||||
def block_cell(self, block, y, x):
|
||||
"""Address of in-grid cell (y, x) in ``block``'s own storage, core or halo.
|
||||
|
||||
Periodic axes resolve to the image inside the block's halo window;
|
||||
if two images fit, the core-side one is returned (use local offsets,
|
||||
not this lookup, when a stencil must follow a specific image).
|
||||
Raises if the cell is not represented there or lies across an exterior.
|
||||
In a sparse layout a represented halo cell whose source is a hole has
|
||||
no pair and stays invalid (NaN after packing).
|
||||
"""
|
||||
by, bx = self.block
|
||||
ly, lx = self.local_shape
|
||||
ny, nx = self.shape
|
||||
block = int(_index(block, self.nblocks, "block"))
|
||||
y, x = int(_index(y, ny, "y")), int(_index(x, nx, "x"))
|
||||
y0, x0 = self.origins[block]
|
||||
ry, rx = y - int(y0) + self.halo, x - int(x0) + self.halo
|
||||
if self.periodic[1] and not 0 <= ry < ly:
|
||||
ry = next((r for r in (ry - ny, ry + ny) if 0 <= r < ly), ry)
|
||||
if self.periodic[0] and not 0 <= rx < lx:
|
||||
rx = next((r for r in (rx - nx, rx + nx) if 0 <= r < lx), rx)
|
||||
if not (0 <= ry < ly and 0 <= rx < lx):
|
||||
raise ValueError("cell is not represented in this block's storage")
|
||||
return block * ly * lx + ry * lx + rx
|
||||
|
||||
def _neighbor(self, y, x, dy, dx):
|
||||
ny, nx = self.shape
|
||||
y, x = y + dy, x + dx
|
||||
if self.periodic[1]:
|
||||
y %= ny
|
||||
if self.periodic[0]:
|
||||
x %= nx
|
||||
if not (0 <= y < ny and 0 <= x < nx):
|
||||
raise ValueError("cut-link stencil crosses a non-periodic exterior")
|
||||
if self.owner[y, x] == self.hole:
|
||||
raise ValueError("cut-link stencil touches an absent block")
|
||||
return y, x
|
||||
|
||||
def map_cut_links(self, links) -> BlockCutLinks:
|
||||
"""Map dense static cut links (fluid_idx, dir, q, fallback) to blocks.
|
||||
|
||||
Rejects repeated physical links and repeated local writers. Addresses
|
||||
are geometry-free: q, fallback and BFL math stay as built on the dense
|
||||
grid. Halo must be at least one cell (always true here). In a sparse
|
||||
layout the receiver, its solid neighbor and any q<.5 donor must all lie
|
||||
in stored blocks.
|
||||
"""
|
||||
ny, nx = self.shape
|
||||
lx = self.local_shape[1]
|
||||
cells = int(np.prod(self.local_shape))
|
||||
rows, seen, writers = [], set(), set()
|
||||
for link in links:
|
||||
r = int(_index(link.fluid_idx, ny * nx, "fluid_idx"))
|
||||
q = int(_index(link.dir, NQ, "dir", lower=1))
|
||||
if (r, q) in seen:
|
||||
raise ValueError("cut link is repeated")
|
||||
seen.add((r, q))
|
||||
y, x = divmod(r, nx)
|
||||
receiver = int(self.owner[y, x])
|
||||
if receiver == self.hole:
|
||||
raise ValueError("cut-link receiver lies in an absent block")
|
||||
block = receiver // cells
|
||||
# Local stencil offsets from the core receiver: the window image the
|
||||
# next local pull reads, even where a periodic seam wraps physically.
|
||||
# Physical neighbors are formed only to reject non-periodic exteriors.
|
||||
step = D2Q9_EY[q] * lx + D2Q9_EX[q]
|
||||
self._neighbor(y, x, D2Q9_EY[q], D2Q9_EX[q])
|
||||
opp = q + 1 if q % 2 else q - 1
|
||||
write = int(self.slot(receiver + step, opp))
|
||||
if write in writers:
|
||||
raise ValueError("duplicate local boundary writer")
|
||||
writers.add(write)
|
||||
donor = NO_DONOR
|
||||
if float(link.q) < .5 and int(link.fallback) == 0:
|
||||
self._neighbor(y, x, -D2Q9_EY[q], -D2Q9_EX[q])
|
||||
donor = receiver - step
|
||||
rows.append((block, receiver, donor, write))
|
||||
table = np.array(rows, dtype=np.uint64).reshape(-1, 4)
|
||||
return BlockCutLinks(_readonly(table[:, 0], np.uint32),
|
||||
*(_readonly(table[:, i], np.uint64) for i in (1, 2, 3)))
|
||||
|
||||
def exchange(self, blocked) -> None:
|
||||
"""Fill every valid halo cell in place from its owner's core."""
|
||||
blocked = self._check_blocked(blocked)
|
||||
flat = blocked.reshape(self.nblocks, NQ, -1)
|
||||
cells = flat.shape[2]
|
||||
db, dc = np.divmod(self.halo_dst.astype(np.intp), cells)
|
||||
sb, sc = np.divmod(self.halo_src.astype(np.intp), cells)
|
||||
flat[db, :, dc] = flat[sb, :, sc]
|
||||
|
||||
def to_blocked(self, dense):
|
||||
"""Pack (NQ, ny, nx) floats; halo cells without a pair stay NaN.
|
||||
|
||||
Values at holes (absent blocks) are ignored.
|
||||
"""
|
||||
dense = np.asarray(dense)
|
||||
if dense.shape != (NQ, *self.shape) or not np.issubdtype(dense.dtype, np.floating):
|
||||
raise ValueError(f"expected floating (NQ, ny, nx) = {(NQ, *self.shape)}")
|
||||
blocked = np.full(self.blocked_shape, np.nan, dtype=dense.dtype)
|
||||
flat = blocked.reshape(self.nblocks, NQ, -1)
|
||||
owned = self.owned.ravel()
|
||||
ob, oc = np.divmod(self.owner.ravel()[owned].astype(np.intp), flat.shape[2])
|
||||
flat[ob, :, oc] = dense.reshape(NQ, -1)[:, owned].T
|
||||
self.exchange(blocked)
|
||||
return blocked
|
||||
|
||||
def to_dense(self, blocked):
|
||||
"""Unpack owner cores only; halo contents are ignored, holes are NaN.
|
||||
|
||||
Full layouts accept any dtype; layouts with holes require floats.
|
||||
"""
|
||||
blocked = self._check_blocked(blocked)
|
||||
flat = blocked.reshape(self.nblocks, NQ, -1)
|
||||
owned = self.owned.ravel()
|
||||
if not owned.all() and not np.issubdtype(blocked.dtype, np.floating):
|
||||
raise ValueError("a layout with holes unpacks floating arrays only (holes are NaN)")
|
||||
ob, oc = np.divmod(self.owner.ravel()[owned].astype(np.intp), flat.shape[2])
|
||||
dense = np.empty((NQ, owned.size), dtype=blocked.dtype)
|
||||
if not owned.all(): # even an empty NaN assignment fails for integer dtypes
|
||||
dense[:, ~owned] = np.nan
|
||||
dense[:, owned] = flat[ob, :, oc].T
|
||||
return dense.reshape(NQ, *self.shape)
|
||||
|
||||
def _check_blocked(self, blocked):
|
||||
if not isinstance(blocked, np.ndarray) or blocked.shape != self.blocked_shape \
|
||||
or not blocked.flags.c_contiguous:
|
||||
raise ValueError(f"expected C-contiguous blocked array {self.blocked_shape}")
|
||||
return blocked
|
||||
|
||||
|
||||
def blocked_link_tables(layout, flags, fluid_idx, dir, q, fallback):
|
||||
"""Storage adapter: dense static cut-link SoA + dense flags -> blocked tables.
|
||||
|
||||
Legality (geometry, coverage, transfer isolation) stays with the caller's
|
||||
own builder; this only maps storage via map_cut_links (unique receiver
|
||||
owner and local writer, input row order kept). Returns (tables, mapped):
|
||||
tables holds device-ready arrays, with flags sized nblocks*L (unused halo
|
||||
entries 0) and cell = the receiver's local core cell. Flags at holes
|
||||
(absent blocks) are not stored.
|
||||
"""
|
||||
flags = np.asarray(flags)
|
||||
if flags.shape != (int(np.prod(layout.shape)),) or flags.dtype != np.uint16:
|
||||
raise ValueError("flags must be dense uint16 with one entry per grid cell")
|
||||
columns = [np.asarray(fluid_idx), np.asarray(dir), np.asarray(q), np.asarray(fallback)]
|
||||
if len({len(c) for c in columns}) != 1:
|
||||
raise ValueError("cut-link columns must have equal length")
|
||||
mapped = layout.map_cut_links(SimpleNamespace(fluid_idx=r, dir=d, q=v, fallback=f)
|
||||
for r, d, v, f in zip(*columns))
|
||||
cells = int(np.prod(layout.local_shape))
|
||||
blocked_flags = np.zeros(layout.nblocks * cells, np.uint16)
|
||||
owned = layout.owned.ravel()
|
||||
blocked_flags[layout.owner.ravel()[owned].astype(np.intp)] = flags[owned]
|
||||
tables = dict(flags=blocked_flags, block=mapped.block,
|
||||
cell=(mapped.receiver % cells).astype(np.uint32),
|
||||
dir=columns[1].astype(np.uint8), q=columns[2].astype(np.float32),
|
||||
fallback=columns[3].astype(np.uint8))
|
||||
return tables, mapped
|
||||
@@ -17,6 +17,8 @@ from typing import Optional
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from ..body.jets import surface_link_velocity # host-only; re-exported for callers
|
||||
|
||||
|
||||
def _free_alloc(ptr: Optional[cuda.DeviceAllocation]) -> None:
|
||||
if ptr is not None:
|
||||
@@ -80,28 +82,40 @@ class CurvedLinkSoA:
|
||||
aperture: Optional[np.ndarray] = None
|
||||
surface_velocity_gpu: Optional[cuda.DeviceAllocation] = None
|
||||
link_exchange_gpu: Optional[cuda.DeviceAllocation] = None
|
||||
# Host-only jet cache (never uploaded or checkpointed).
|
||||
jets: tuple = ()
|
||||
jet_shape: Optional[np.ndarray] = None
|
||||
jet_id: Optional[np.ndarray] = None
|
||||
|
||||
def assign_surface(self, objects, cfg, flags):
|
||||
"""Keep the original eight-column geometry/checkpoint contract unchanged."""
|
||||
enabled = [obj for obj in objects if obj.surface_actuation is not None]
|
||||
def assign_surface(self, objects, cfg, flags, jets=(), hits=None):
|
||||
"""Keep the original eight-column geometry/checkpoint contract unchanged.
|
||||
|
||||
Jet shapes are cached host-side so amplitude changes skip geometry work.
|
||||
"""
|
||||
self.surface_velocity = self.aperture = None
|
||||
if not enabled:
|
||||
return
|
||||
from .descriptors import FLUID, SOLID
|
||||
if np.any((flags[self.fluid_idx] & FLUID) == 0) or np.any(flags[self.fluid_idx] & SOLID):
|
||||
raise ValueError("Surface cut links must have active fluid receivers")
|
||||
if len(np.unique(self.fluid_idx.astype(np.uint64)*cfg.nq+self.dir)) != len(self.dir):
|
||||
raise ValueError("Surface boundary requires unique cut-link writers")
|
||||
self.surface_velocity = np.zeros((len(self.dir), 2), np.float32)
|
||||
self.aperture = np.zeros(len(self.dir), bool)
|
||||
for obj in enabled:
|
||||
obj.validate_surface_actuation(cfg)
|
||||
selected = self.body_id == obj.obj_id
|
||||
velocity, aperture = obj.surface_actuation.project(self.rx[selected], self.ry[selected])
|
||||
if not aperture.any():
|
||||
raise ValueError("Surface aperture hits no resolved cut links")
|
||||
self.surface_velocity[selected] = velocity
|
||||
self.aperture[selected] = aperture
|
||||
self.jets, self.jet_shape, self.jet_id = tuple(jets), None, None
|
||||
self.surface_velocity, self.aperture = surface_link_velocity(
|
||||
objects, cfg, flags, self.fluid_idx, self.dir, self.body_id, self.rx, self.ry,
|
||||
jets=self.jets, hits=hits)
|
||||
if self.jets:
|
||||
from ..body.jets import jet_link_shapes
|
||||
self.jet_shape, self.jet_id = jet_link_shapes(self.jets, hits)
|
||||
|
||||
def set_jet_amplitude(self, index, amplitude, stream=None):
|
||||
"""Rewrite jet rows from cached shapes; re-upload only the velocity column.
|
||||
|
||||
Host state is committed only after the upload returns; on a device error
|
||||
the host keeps the previous amplitude (device contents are then unknown).
|
||||
"""
|
||||
from ..body.jets import jet_link_velocity
|
||||
jets = list(self.jets)
|
||||
jets[index] = jets[index].with_amplitude(amplitude) # validates before any change
|
||||
velocity = self.surface_velocity.copy()
|
||||
driven = self.jet_id >= 0
|
||||
velocity[driven] = jet_link_velocity(jets, self.jet_shape, self.jet_id)[driven]
|
||||
if self.surface_velocity_gpu is not None:
|
||||
_upload_columns([(self.surface_velocity_gpu, velocity)], stream)
|
||||
self.jets, self.surface_velocity = tuple(jets), velocity
|
||||
|
||||
def surface_exchange(self, body_id):
|
||||
"""Latest boundary step's (Fx,Fy,Tz), split by aperture; not nozzle thrust.
|
||||
@@ -187,6 +201,7 @@ class CurvedLinkSoA:
|
||||
"CurvedLinkSoA column 'fallback_class' must use classes {0, 1}"
|
||||
)
|
||||
self.surface_velocity = self.aperture = None
|
||||
self.jets, self.jet_shape, self.jet_id = (), None, None
|
||||
|
||||
def upload(self, stream: Optional[cuda.Stream] = None) -> None:
|
||||
"""Upload host columns to GPU with capacity-based allocation reuse.
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# 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:
|
||||
kind = np.full((cfg.ny, cfg.nx), ACTIVE, np.uint8)
|
||||
if wall_aware:
|
||||
kind[[0, -1]] = OUTER_GHOST
|
||||
kinds.append(kind)
|
||||
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
|
||||
@@ -0,0 +1,151 @@
|
||||
// CelerisLab/lbm/kernels/blocks.cu
|
||||
// One periodic level of fixed-size blocks (lbm/blocks.py layout). Separate
|
||||
// compilation entry: NX, NY are the block window including halo, so index_f
|
||||
// and linear_index address one block; blockIdx.z selects the block, whose
|
||||
// populations start at b*NQ*TOTAL_CELLS (block-contiguous, Q-major inside).
|
||||
#include <stdint.h>
|
||||
#include <math.h>
|
||||
#include "config.h"
|
||||
#include "core/precision.cuh"
|
||||
#include "core/descriptors.cuh"
|
||||
#include "core/layout.cuh"
|
||||
#include "core/params.cuh"
|
||||
#include "core/flags.cuh"
|
||||
#include "core/obs.cuh"
|
||||
#include "operators/macro.cuh"
|
||||
#include "operators/collision_srt.cuh"
|
||||
#include "streaming/pull_double_buffer.cuh"
|
||||
#include "boundary/curved_boundary.cuh"
|
||||
#include "boundary/planar_velocity.cuh"
|
||||
|
||||
#if DIM != 2 || NQ != 9 || COLLISION_MODEL != 0 || STORE_PRECISION != 0 || USE_DDF_SHIFTING || USE_LES || STREAMING_MODEL != 0
|
||||
#error "Blocks require unshifted FP32 D2Q9 SRT double buffers without LES"
|
||||
#endif
|
||||
|
||||
// Fixed-patch cell kinds, matching refinement.py ACTIVE/INNER_GHOST/OUTER_GHOST.
|
||||
constexpr unsigned char KIND_ACTIVE = 0u, KIND_INNER = 1u, KIND_OUTER = 2u;
|
||||
|
||||
// Zero-initialized for ordinary blocks/fine levels. Set only for parent walls;
|
||||
// NX/NY remain local storage strides, never physical wall coordinates.
|
||||
struct BlockWall { unsigned int nx, ny, slot_width; float amplitude; };
|
||||
extern "C" { __constant__ BlockWall d_block_wall; }
|
||||
|
||||
// Halo refresh: block cell ids b*TOTAL_CELLS+c, sources are always core cells.
|
||||
extern "C" __global__ void BlockHaloCopy(
|
||||
fpxx* f, const uint64_t* dst, const uint64_t* src, unsigned int count)
|
||||
{
|
||||
unsigned int row = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (row >= count) return;
|
||||
const uint64_t d = dst[row], s = src[row];
|
||||
fpxx* to = f + (d / TOTAL_CELLS) * NQ * TOTAL_CELLS;
|
||||
const fpxx* from = f + (s / TOTAL_CELLS) * NQ * TOTAL_CELLS;
|
||||
for (unsigned int q = 0; q < NQ; ++q)
|
||||
to[index_f(d % TOTAL_CELLS, q)] = from[index_f(s % TOTAL_CELLS, q)];
|
||||
}
|
||||
|
||||
// Fixed-patch explosion into blocked fine storage: target = owner block cell
|
||||
// id of a patch-ghost cell; donors are parent block cell ids. Dense parent
|
||||
// storage is the one-window case with coarse_cells = full domain size.
|
||||
extern "C" __global__ void BlockExplode(
|
||||
const fpxx* coarse, fpxx* fine, const uint64_t* target, const uint64_t* donor,
|
||||
unsigned int count, unsigned long coarse_cells)
|
||||
{
|
||||
unsigned int row = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (row >= count) return;
|
||||
const uint64_t t = target[row];
|
||||
fpxx* to = fine + (t / TOTAL_CELLS) * NQ * TOTAL_CELLS;
|
||||
const uint64_t d = donor[row];
|
||||
const fpxx* from = coarse + (d / coarse_cells) * NQ * coarse_cells;
|
||||
for (unsigned int q = 0; q < NQ; ++q)
|
||||
to[index_f(t % TOTAL_CELLS, q)] = from[q * coarse_cells + d % coarse_cells];
|
||||
}
|
||||
|
||||
// Targets are receiver-local SOURCE slots for the immediately following pull.
|
||||
// Keep child summation order identical to PatchCoarseStep; no collision here.
|
||||
extern "C" __global__ void BlockCoalesce(
|
||||
const fpxx* fine, fpxx* coarse, const uint64_t* target, const uint64_t* children,
|
||||
unsigned int count)
|
||||
{
|
||||
unsigned int row = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (row >= count) return;
|
||||
const uint64_t* s = children + 4ul * row;
|
||||
coarse[target[row]] = 0.25f * (fine[s[0]] + fine[s[1]] + fine[s[2]] + fine[s[3]]);
|
||||
}
|
||||
|
||||
// Static cut links, receiver-local staging: cell is the receiver's local core
|
||||
// cell, so the existing BFL writes the solid-source window image that this
|
||||
// block's next pull reads (no halo copy between this kernel and BlockStep).
|
||||
// surface_velocity (nullable, 2 floats per link): prescribed fluid velocity on
|
||||
// fixed geometry, same convention as CurvedBoundaryKernel. Optional raw rows
|
||||
// (jx,jy,torque,dm) are unique physical links, never body-observation slots.
|
||||
extern "C" __global__ void BlockCurvedBoundary(
|
||||
fpxx* f, const uint32_t* block, const uint32_t* cell, const unsigned char* dir,
|
||||
const float* q, const unsigned char* fallback, unsigned int count,
|
||||
const float* surface_velocity, const float* rx, const float* ry, float* raw)
|
||||
{
|
||||
unsigned int row = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (row >= count) return;
|
||||
float Uw = 0.0f, Vw = 0.0f;
|
||||
if (surface_velocity != nullptr) {
|
||||
const float u = surface_velocity[2 * row], v = surface_velocity[2 * row + 1];
|
||||
if (u != 0.0f || v != 0.0f) { Uw = u; Vw = v; }
|
||||
}
|
||||
apply_bouzidi_link(dir[row], q[row], cell[row], f + (unsigned long)block[row] * NQ * TOTAL_CELLS,
|
||||
Uw, Vw, rx ? rx[row] : 0.0f, ry ? ry[row] : 0.0f,
|
||||
fallback[row], nullptr, -1, raw ? raw + 4ul * row : nullptr,
|
||||
raw ? raw + 4ul * row + 3 : nullptr);
|
||||
}
|
||||
|
||||
// Same-stream BFL -> this row-owned accumulation -> pull step. No atomics,
|
||||
// no cross-row reduction and no history allocation proportional to substeps.
|
||||
extern "C" __global__ void BlockAccumulateExchange(
|
||||
const float* raw, double* integral, unsigned int count, double h, double dt)
|
||||
{
|
||||
unsigned int row = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (row >= count) return;
|
||||
const unsigned long k = 4ul * row;
|
||||
const double impulse = h * dt;
|
||||
integral[k] += impulse * (double)raw[k];
|
||||
integral[k + 1] += impulse * (double)raw[k + 1];
|
||||
integral[k + 2] += h * impulse * (double)raw[k + 2];
|
||||
integral[k + 3] += h * h * (double)raw[k + 3];
|
||||
}
|
||||
|
||||
// Pull/collide/store core cells only; halo cells of out are left untouched.
|
||||
// flags (block cell ids, nullable): solid cores store NaN and never collide.
|
||||
// kind (block cell ids, nullable = all ACTIVE): OUTER skips the pull and
|
||||
// stores NaN, INNER pulls without collision, ACTIVE pulls and collides.
|
||||
extern "C" __global__ void BlockStep(const fpxx* in, fpxx* out, unsigned int halo,
|
||||
const uint16_t* flags, const unsigned char* kind) {
|
||||
unsigned int x, y; unsigned long k;
|
||||
index_from_thread(x, y, k);
|
||||
if (x < halo || y < halo || x >= NX - halo || y >= NY - halo) return;
|
||||
const unsigned long base = (unsigned long)blockIdx.z * NQ * TOTAL_CELLS;
|
||||
const unsigned long cell = (unsigned long)blockIdx.z * TOTAL_CELLS + k;
|
||||
const unsigned char cell_kind = kind != nullptr ? kind[cell] : KIND_ACTIVE;
|
||||
float f[NQ];
|
||||
if (cell_kind == KIND_OUTER || (flags != nullptr && is_solid(flags[cell]))) {
|
||||
for (int q = 0; q < NQ; ++q) f[q] = NAN;
|
||||
} else {
|
||||
unsigned long j[NQ];
|
||||
compute_neighbors(x, y, j); // Core neighbors stay inside the window: no wrap.
|
||||
stream_pull_load(k, f, in + base, j);
|
||||
if (cell_kind == KIND_ACTIVE) {
|
||||
if (d_block_wall.nx != 0) {
|
||||
const unsigned int bx = NX - 2 * halo, by = NY - 2 * halo;
|
||||
const unsigned int nbx = d_block_wall.nx / bx;
|
||||
const unsigned int gx = (blockIdx.z % nbx) * bx + x - halo;
|
||||
const unsigned int gy = (blockIdx.z / nbx) * by + y - halo;
|
||||
if (gy == 1)
|
||||
reconstruct_bottom_velocity(f, 0.0f, bottom_wall_normal_velocity(
|
||||
gx, d_block_wall.nx, d_block_wall.slot_width, d_block_wall.amplitude));
|
||||
else if (gy == d_block_wall.ny - 2) reconstruct_top_reservoir(f, RHO);
|
||||
}
|
||||
float rho, ux, uy, feq[NQ];
|
||||
compute_rho_u(f, rho, ux, uy);
|
||||
compute_feq(rho, ux, uy, feq);
|
||||
collide_srt_no_force(f, feq, d_params.omega);
|
||||
}
|
||||
}
|
||||
stream_pull_store(k, f, out + base);
|
||||
}
|
||||
@@ -82,7 +82,8 @@ __device__ inline void apply_bouzidi_link(
|
||||
float Uw, float Vw,
|
||||
float rx, float ry,
|
||||
unsigned char fallback_class,
|
||||
float* __restrict__ obs, int body_id, float* link_exchange = nullptr)
|
||||
float* __restrict__ obs, int body_id, float* link_exchange = nullptr,
|
||||
float* link_mass = nullptr)
|
||||
{
|
||||
const unsigned int dir_opp = (unsigned int)opp_dir((int)dir);
|
||||
|
||||
@@ -120,6 +121,10 @@ __device__ inline void apply_bouzidi_link(
|
||||
// corrected incoming population into the adjacent fluid node.
|
||||
store_ddf(fi, index_f(k_s, dir_opp), f_reflected);
|
||||
|
||||
// Equal opposite weights cancel even with shifted DDFs.
|
||||
if (link_mass != nullptr)
|
||||
*link_mass = f_reflected - f_toward;
|
||||
|
||||
if (obs != nullptr || link_exchange != nullptr) {
|
||||
#if USE_DDF_SHIFTING
|
||||
const float w_i = (float)d_w[dir];
|
||||
|
||||
@@ -3,16 +3,26 @@
|
||||
// the caller owns collision/store. No force, shifting or off-lattice walls.
|
||||
#ifndef CELERIS_BOUNDARY_PLANAR_VELOCITY_CUH
|
||||
#define CELERIS_BOUNDARY_PLANAR_VELOCITY_CUH
|
||||
#include <math.h>
|
||||
|
||||
__device__ __forceinline__ float bottom_wall_normal_velocity(
|
||||
unsigned int x, unsigned int width, unsigned int slot_width, float amplitude)
|
||||
{
|
||||
// Width is the physical domain width, even when NX is a block window.
|
||||
if (slot_width > 0 && slot_width < width) {
|
||||
const float s = (2.0f*(float)x-(float)(width-1))/(float)slot_width;
|
||||
const float w = fmaxf(0.0f, 1.0f-s*s);
|
||||
return amplitude*w*w;
|
||||
}
|
||||
return amplitude; // Disabled or explicitly uniform full width.
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float bottom_wall_normal_velocity(unsigned int x)
|
||||
{
|
||||
#if WALL_SLOT_WIDTH > 0 && WALL_SLOT_WIDTH < NX
|
||||
// C1 compact profile centered at (NX-1)/2; amplitude is its continuous peak.
|
||||
const float s = (2.0f*(float)x-(float)(NX-1))/(float)WALL_SLOT_WIDTH;
|
||||
const float w = fmaxf(0.0f, 1.0f-s*s);
|
||||
return WALL_NORMAL_VELOCITY*w*w;
|
||||
return bottom_wall_normal_velocity(x, NX, WALL_SLOT_WIDTH, WALL_NORMAL_VELOCITY);
|
||||
#else
|
||||
return WALL_NORMAL_VELOCITY; // Disabled or explicitly uniform full width.
|
||||
return WALL_NORMAL_VELOCITY;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Host-only reduction of raw cut-link observations; no stress/GI correction.
|
||||
|
||||
Rows are unique physical links. All quantities are 2D, per unit out-of-plane
|
||||
thickness; centers are in the root edge frame, torque is about the named body.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
|
||||
def summarize_exchange(rows, body_ids, aperture, *, body_id, level, h,
|
||||
time_end, window, reference_center):
|
||||
"""Reduce FP64 interval integrals or convert FP32 last-substep raw rows.
|
||||
|
||||
dt_l=h_l under acoustic 2:1 refinement. Local momentum j -> base force
|
||||
h*j -> impulse h*dt*j; torque adds one h; mass is h**2*dm.
|
||||
"""
|
||||
if window not in ("last_base_step", "last_substep"):
|
||||
raise ValueError("unknown exchange window")
|
||||
values = np.array(rows, dtype=np.float64, copy=True)
|
||||
duration = 1.0 if window == "last_base_step" else h
|
||||
if window == "last_substep":
|
||||
values *= np.array([h*h, h*h, h*h*h, h*h])
|
||||
selected = np.asarray(body_ids) == body_id
|
||||
aperture = np.asarray(aperture, bool)
|
||||
|
||||
def reduce(mask):
|
||||
integral = values[mask].sum(axis=0, dtype=np.float64)
|
||||
return dict(impulse=integral[:2].copy(), angular_impulse=float(integral[2]),
|
||||
mass_into_fluid=float(integral[3]), force=integral[:2] / duration,
|
||||
torque=float(integral[2] / duration), mass_rate=float(integral[3] / duration))
|
||||
|
||||
return dict(wall=reduce(selected & ~aperture), aperture=reduce(selected & aperture),
|
||||
total=reduce(selected), body_id=int(body_id), level=int(level),
|
||||
time_start=time_end-duration, time_end=time_end, dt=h,
|
||||
sample_count=round(1/h) if window == "last_base_step" else 1,
|
||||
window=window, units="base_lattice_per_unit_depth",
|
||||
definition="raw_boundary_exchange", reference_center=tuple(reference_center), valid=True)
|
||||
@@ -114,6 +114,19 @@ class FixedPatch2D:
|
||||
def fine_origin(self) -> tuple[float, float]:
|
||||
return self.bounds[0] - HALO / 2, self.bounds[1] - HALO / 2
|
||||
|
||||
@property
|
||||
def fine_level_origin(self) -> tuple[int, int]:
|
||||
"""(y, x) of this window's first cell on the level-wide 2:1 fine grid."""
|
||||
return 2 * self.bounds[1] - HALO, 2 * self.bounds[0] - HALO
|
||||
|
||||
@property
|
||||
def covered(self) -> np.ndarray:
|
||||
"""Dense coarse mask of cells replaced by the patch (not leaves)."""
|
||||
x0, y0, x1, y1 = self.bounds
|
||||
mask = np.zeros(self.coarse_shape, bool)
|
||||
mask[y0:y1, x0:x1] = True
|
||||
return mask
|
||||
|
||||
@property
|
||||
def table_bytes(self) -> int:
|
||||
return sum(a.nbytes for a in (self.fine_kind, self.ghost_fine,
|
||||
@@ -138,6 +151,113 @@ class FixedPatch2D:
|
||||
raise ValueError("levels are not synchronized: fine_steps must equal 2*coarse_steps")
|
||||
|
||||
|
||||
MIN_PATCH_GAP = 4 # coarse cells: the full 4-fine-cell supports stay disjoint
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class FixedPatchSet2D:
|
||||
"""Several separated FixedPatch2D rectangles sharing one 2:1 fine level.
|
||||
|
||||
The fine level is the whole (2*ny, 2*nx) grid in level coordinates; only
|
||||
the patch supports (active region + HALO ghost band) are stored, by a
|
||||
sparse BlockLayout2D from fine_layout(). Tables have FixedPatch2D meaning
|
||||
and row/child order, re-addressed to level cells: ghost_fine are level
|
||||
fine cells, coalesce_fine are q*N+cell level slots; coarse ids unchanged.
|
||||
Patches are kept in canonical (y0, x0) order, so input order is irrelevant.
|
||||
Active regions must be >= MIN_PATCH_GAP coarse cells apart (Chebyshev).
|
||||
"""
|
||||
coarse_shape: tuple[int, int]
|
||||
patches: tuple
|
||||
tau_coarse: float
|
||||
tau_fine: float
|
||||
fine_kind: np.ndarray
|
||||
ghost_fine: np.ndarray
|
||||
ghost_coarse: np.ndarray
|
||||
coalesce_coarse: np.ndarray
|
||||
coalesce_fine: np.ndarray
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, cfg: LBMConfig, rectangles) -> "FixedPatchSet2D":
|
||||
rectangles = tuple(rectangles)
|
||||
if not rectangles:
|
||||
raise ValueError("at least one patch rectangle is required")
|
||||
patches = sorted((FixedPatch2D.from_config(cfg, r) for r in rectangles),
|
||||
key=lambda p: (p.bounds[1], p.bounds[0]))
|
||||
for i, a in enumerate(patches):
|
||||
for b in patches[i + 1:]:
|
||||
(ax0, ay0, ax1, ay1), (bx0, by0, bx1, by1) = a.bounds, b.bounds
|
||||
if max(ay0 - by1, by0 - ay1, ax0 - bx1, bx0 - ax1) < MIN_PATCH_GAP:
|
||||
raise ValueError(f"patches {a.bounds} and {b.bounds} are closer "
|
||||
f"than {MIN_PATCH_GAP} coarse cells")
|
||||
ny, nx = patches[0].coarse_shape
|
||||
fy, fx = 2 * ny, 2 * nx
|
||||
if fy * fx * 9 > np.iinfo(np.uint64).max // 2:
|
||||
raise ValueError("fine level exceeds 64-bit indexing")
|
||||
kind = np.full((fy, fx), OUTER_GHOST, np.uint8)
|
||||
ghost_fine, coalesce_fine = [], []
|
||||
for p in patches:
|
||||
y0, x0 = p.fine_level_origin
|
||||
ly, lx = p.fine_shape
|
||||
kind[y0:y0 + ly, x0:x0 + lx] = p.fine_kind
|
||||
gy, gx = np.divmod(p.ghost_fine.astype(np.int64), lx)
|
||||
ghost_fine.append((gy + y0) * fx + gx + x0)
|
||||
q, cell = np.divmod(p.coalesce_fine.astype(np.int64), ly * lx)
|
||||
cy, cx = np.divmod(cell, lx)
|
||||
coalesce_fine.append(q * fy * fx + (cy + y0) * fx + cx + x0)
|
||||
ghost_coarse = np.concatenate([p.ghost_coarse for p in patches])
|
||||
coalesce_coarse = np.concatenate([p.coalesce_coarse for p in patches])
|
||||
covered = np.zeros((ny, nx), bool)
|
||||
for p in patches:
|
||||
covered |= p.covered
|
||||
cells = ny * nx
|
||||
if (covered.ravel()[ghost_coarse].any()
|
||||
or covered.ravel()[coalesce_coarse % np.uint64(cells)].any()
|
||||
or len(np.unique(coalesce_coarse)) != len(coalesce_coarse)):
|
||||
raise ValueError("patch transfers overlap another patch")
|
||||
return cls((ny, nx), tuple(patches), patches[0].tau_coarse, patches[0].tau_fine,
|
||||
_readonly(kind, np.uint8), _readonly(np.concatenate(ghost_fine), np.uint64),
|
||||
_readonly(ghost_coarse, np.uint32), _readonly(coalesce_coarse, np.uint64),
|
||||
_readonly(np.concatenate(coalesce_fine), np.uint64).reshape(-1, 4))
|
||||
|
||||
@property
|
||||
def fine_shape(self) -> tuple[int, int]:
|
||||
return self.fine_kind.shape
|
||||
|
||||
@property
|
||||
def bounds(self) -> tuple:
|
||||
return tuple(p.bounds for p in self.patches)
|
||||
|
||||
@property
|
||||
def fine_origin(self) -> tuple[float, float]:
|
||||
"""Lower edge of the level-wide fine grid in coarse physical units."""
|
||||
return 0.0, 0.0
|
||||
|
||||
@property
|
||||
def covered(self) -> np.ndarray:
|
||||
mask = np.zeros(self.coarse_shape, bool)
|
||||
for p in self.patches:
|
||||
mask |= p.covered
|
||||
return mask
|
||||
|
||||
def fine_layout(self, block):
|
||||
"""Sparse non-periodic layout storing exactly the patch supports."""
|
||||
from .blocks import BlockLayout2D
|
||||
block = tuple(block)
|
||||
if len(block) != 2 or any(isinstance(v, (bool, np.bool_)) or not isinstance(v, Integral)
|
||||
or v <= 0 for v in block):
|
||||
raise ValueError("fine block must be two positive integers (by, bx)")
|
||||
by, bx = map(int, block)
|
||||
origins = set()
|
||||
for p in self.patches:
|
||||
y0, x0 = p.fine_level_origin
|
||||
ly, lx = p.fine_shape
|
||||
if y0 % by or x0 % bx or ly % by or lx % bx:
|
||||
raise ValueError(f"patch {p.bounds} support is not aligned to fine blocks {block}")
|
||||
origins.update((y, x) for y in range(y0, y0 + ly, by) for x in range(x0, x0 + lx, bx))
|
||||
return BlockLayout2D.build(*self.fine_shape, by, bx, periodic=(False, False),
|
||||
origins=sorted(origins))
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class FineBoundary2D:
|
||||
"""Fixed local projection plus auditable, finite transfer dependency sets.
|
||||
@@ -153,6 +273,7 @@ class FineBoundary2D:
|
||||
transfer_fine_cells: np.ndarray
|
||||
transfer_coarse_cells: np.ndarray
|
||||
transfer_reads: np.ndarray
|
||||
curved_hits: np.ndarray | None = None # FP64 cell-edge-frame hits, row-aligned
|
||||
|
||||
|
||||
def _transfer_footprint(patch):
|
||||
@@ -183,15 +304,101 @@ def _transfer_footprint(patch):
|
||||
return fine, coarse, _readonly(sorted(reads), np.int64)
|
||||
|
||||
|
||||
def prepare_fine_boundary(cfg, patch, objects, *, wall_aware=False):
|
||||
def nest_patch(cfg, parent, child_bounds):
|
||||
"""Child FixedPatch2D inside a fine patch window, plus the composed middle kind.
|
||||
|
||||
``cfg`` is the base (L0) configuration and ``parent`` the L0->L1
|
||||
FixedPatch2D; ``child_bounds`` (x0, y0, x1, y1) are in L1 window cells
|
||||
(its dense fine grid, ghost band included). Returns (child, kind): the
|
||||
L1->L2 FixedPatch2D (viscosity 2*nu on L1) and the L1 kind array with
|
||||
inherited INNER/OUTER kept and only the child-covered ACTIVE cells made
|
||||
OUTER (invalid). Rejects, from the actual tables before any allocation:
|
||||
coverage outside inherited ACTIVE; explosion donors or coalescence
|
||||
receivers that are not uncovered ACTIVE; any surviving ACTIVE pull that
|
||||
would read a covered or OUTER cell without a child-supplied arrival; and
|
||||
child coverage of L1's own two-hop restriction footprint toward L0.
|
||||
"""
|
||||
child = FixedPatch2D.from_config(_middle_config(cfg, parent), child_bounds)
|
||||
return child, _nested_kind(parent, child)
|
||||
|
||||
|
||||
def nest_patch_set(cfg, parent, child_rectangles_in_parent):
|
||||
"""Separated child union in the parent's allocated L1 array coordinates.
|
||||
|
||||
The root edge coordinate of L1 index (x, y) is
|
||||
``parent.fine_origin + (x, y)/2``. For a set parent its origin is zero;
|
||||
a scalar parent's window includes its ghost band and has a shifted origin.
|
||||
The child set allocates a dense public extent twice that L1 array, while
|
||||
its blocked storage omits holes. Both adjacent pairs retain gap >= 4 in
|
||||
their respective parent-cell units. Validate support over the whole union.
|
||||
"""
|
||||
child = FixedPatchSet2D.from_config(
|
||||
_middle_config(cfg, parent), child_rectangles_in_parent)
|
||||
return child, _nested_kind(parent, child)
|
||||
|
||||
|
||||
def _middle_config(cfg, parent):
|
||||
fy, fx = parent.fine_shape
|
||||
return replace(cfg, nx=fx, ny=fy, viscosity=2 * cfg.viscosity, y_wall_bc="bounce_back",
|
||||
top_wall_bc="velocity", wall_slot_width=0, wall_normal_velocity=0.0,
|
||||
velocity=0.0)
|
||||
|
||||
|
||||
def _nested_kind(parent, child):
|
||||
"""Validate composed transfer support and preserve inherited ghost kinds."""
|
||||
fy, fx = parent.fine_shape
|
||||
kind = parent.fine_kind
|
||||
covered = child.covered
|
||||
active = (kind == ACTIVE) & ~covered
|
||||
if not (kind[covered] == ACTIVE).all():
|
||||
raise ValueError("child must cover only inherited ACTIVE cells")
|
||||
cells = fx * fy
|
||||
receivers = child.coalesce_coarse % np.uint64(cells)
|
||||
if (not active.ravel()[child.ghost_coarse].all()
|
||||
or not active.ravel()[receivers.astype(np.intp)].all()):
|
||||
raise ValueError("child donors/receivers must be uncovered parent ACTIVE cells")
|
||||
supplied = set(map(int, child.coalesce_coarse))
|
||||
invalid = covered | (kind == OUTER_GHOST)
|
||||
for y, x in zip(*np.nonzero(active)):
|
||||
for q in range(1, 9):
|
||||
sy, sx = y - D2Q9_EY[q], x - D2Q9_EX[q]
|
||||
inside = 0 <= sy < fy and 0 <= sx < fx
|
||||
if (not inside or invalid[sy, sx]) and q * cells + y * fx + x not in supplied:
|
||||
raise ValueError("a surviving parent ACTIVE pull would read an invalid cell")
|
||||
footprint, _, _ = _transfer_footprint(parent)
|
||||
if covered.ravel()[sorted(footprint)].any():
|
||||
raise ValueError("child covers the parent's restriction footprint")
|
||||
composed = kind.copy()
|
||||
composed[covered] = OUTER_GHOST
|
||||
return _readonly(composed, np.uint8)
|
||||
|
||||
|
||||
def prepare_fine_boundary(cfg, patch, objects, *, wall_aware=False, jets=(),
|
||||
parent_origin=(0., 0.), parent_spacing=1.):
|
||||
"""Project fixed circles and reject boundary/transfer overlap before CUDA.
|
||||
|
||||
Input centers/radii are in coarse physical coordinates (dx=dt=1).
|
||||
Input centers/radii and Jets are in the root edge frame. ``parent_origin``
|
||||
and ``parent_spacing`` map this patch's parent grid into that frame; the
|
||||
default preserves the L0->L1 convention. cfg must describe the parent grid.
|
||||
SurfaceActuation retains its lattice-velocity meaning: input coarse units
|
||||
are converted into independent fine-local objects with dx=dt=.5.
|
||||
are converted into independent fine-local objects with
|
||||
dx=dt=parent_spacing/2.
|
||||
Original objects are not retained or mutated. No runtime geometry updates.
|
||||
``patch`` may be a FixedPatchSet2D: objects are then projected once onto
|
||||
the level-wide fine grid (fine_origin (0, 0)); each circle must lie inside
|
||||
one patch, body ids are the positions in ``objects`` (never patch ids), and
|
||||
jets and the (receiver, dir) writer checks run once over the whole level.
|
||||
``jets`` use the same coarse cell-edge frame as the objects; their
|
||||
selection is checked against true fine hits here. Jet amplitudes need no
|
||||
rescaling (lattice velocity scales by dt/dx = 1 under acoustic 2:1).
|
||||
"""
|
||||
origin = np.asarray(parent_origin, dtype=np.float64)
|
||||
if (origin.shape != (2,) or not np.isfinite(origin).all()
|
||||
or not np.isfinite(parent_spacing) or parent_spacing <= 0):
|
||||
raise ValueError("Parent frame must have a finite origin and positive spacing")
|
||||
if not objects:
|
||||
if jets:
|
||||
raise ValueError("Fine jets need fine boundary objects")
|
||||
return None
|
||||
checked = replace(cfg)
|
||||
checked.validate()
|
||||
@@ -209,8 +416,10 @@ def prepare_fine_boundary(cfg, patch, objects, *, wall_aware=False):
|
||||
flags = np.full(nx * ny, FLUID, np.uint16)
|
||||
active = patch.fine_kind.ravel() == ACTIVE
|
||||
local, links = [], []
|
||||
x0, y0, x1, y1 = patch.bounds
|
||||
dx = dt = .5
|
||||
rects = patch.bounds if isinstance(patch, FixedPatchSet2D) else (patch.bounds,)
|
||||
covered = patch.covered
|
||||
dx = dt = .5 * parent_spacing
|
||||
fine_origin = origin + parent_spacing * np.asarray(patch.fine_origin)
|
||||
for bid, obj in enumerate(objects):
|
||||
if (type(obj.geometry) is not CircleGeometry or obj.is_sensor or obj.is_force_region
|
||||
or any(getattr(obj.state, name) != 0 for name in ("vx", "vy", "omega"))
|
||||
@@ -218,10 +427,13 @@ def prepare_fine_boundary(cfg, patch, objects, *, wall_aware=False):
|
||||
raise ValueError("Fine boundaries require stationary circles without other roles")
|
||||
cx, cy = obj.geometry.center
|
||||
radius = obj.geometry._radius
|
||||
px, py = (np.asarray((cx, cy)) - origin) / parent_spacing
|
||||
pr = radius / parent_spacing
|
||||
if (not np.isfinite([cx, cy, radius]).all() or radius <= 0
|
||||
or cx-radius < x0 or cx+radius > x1 or cy-radius < y0 or cy+radius > y1):
|
||||
raise ValueError("Entire fine circle must lie inside the physical patch")
|
||||
center = tuple((v-o)/dx-.5 for v, o in zip((cx, cy), patch.fine_origin))
|
||||
or not any(x0 <= px-pr and px+pr <= x1 and y0 <= py-pr
|
||||
and py+pr <= y1 for x0, y0, x1, y1 in rects)):
|
||||
raise ValueError("Entire fine circle must lie inside one physical patch")
|
||||
center = tuple((v-o)/dx-.5 for v, o in zip((cx, cy), fine_origin))
|
||||
spec = obj.surface_actuation
|
||||
if spec is not None:
|
||||
spec = replace(spec, normal_velocity=spec.normal_velocity * dt / dx)
|
||||
@@ -280,13 +492,27 @@ def prepare_fine_boundary(cfg, patch, objects, *, wall_aware=False):
|
||||
raise ValueError("Boundary stencil overlaps the two-hop transfer footprint")
|
||||
for k in coarse:
|
||||
y, x = divmod(k, cfg.nx)
|
||||
if x0 <= x < x1 and y0 <= y < y1:
|
||||
if covered[y, x]:
|
||||
raise ValueError("Transfer coarse donor/target is not an uncovered bulk cell")
|
||||
# Coarse reconstruction targets y=1,ny-2 pull from y=0..2,ny-3..ny-1.
|
||||
if wall_aware and (y <= 2 or y >= cfg.ny-3):
|
||||
# Rows 0/ny-1 are never computed and rows 1/ny-2 are reconstructed after
|
||||
# coalescence; rows 2/ny-3 are ordinary bulk cells only read as donors.
|
||||
if wall_aware and (y <= 1 or y >= cfg.ny-2):
|
||||
raise ValueError("Transfer footprint touches the coarse wall reconstruction stencil")
|
||||
from ..body.jets import fine_hits_to_edge_frame, surface_link_velocity
|
||||
hits = fine_hits_to_edge_frame([(link.hit_x, link.hit_y) for link in links],
|
||||
fine_origin, dx)
|
||||
packed = pack_cut_links_to_soa(links)
|
||||
if jets:
|
||||
# Same assignment checks as the stepper: empty/overlapping jets and
|
||||
# jet-vs-SurfaceActuation overlap are rejected before CUDA.
|
||||
jet_cfg = replace(fine_cfg)
|
||||
jet_cfg.validate()
|
||||
fluid_idx, dirs, _, body_id, rx, ry, _, _ = packed
|
||||
surface_link_velocity(local, jet_cfg, flags, fluid_idx, dirs, body_id, rx, ry,
|
||||
jets=jets, hits=hits)
|
||||
return FineBoundary2D(tuple(local), _readonly(flags, np.uint16),
|
||||
tuple(_readonly(a, a.dtype) for a in pack_cut_links_to_soa(links)),
|
||||
tuple(_readonly(a, a.dtype) for a in packed),
|
||||
_readonly(sorted(boundary), np.uint32),
|
||||
_readonly(sorted(fine), np.uint32),
|
||||
_readonly(sorted(coarse), np.uint32), reads)
|
||||
_readonly(sorted(coarse), np.uint32), reads,
|
||||
_readonly(hits, np.float64))
|
||||
@@ -3,7 +3,8 @@
|
||||
|
||||
The caller owns the CudaContext and must close this backend before that context.
|
||||
Only synchronized postcollision_g leaf populations are public. No checkpoint,
|
||||
snapshot, forcing, runtime parameter mutation or dynamic refinement is offered.
|
||||
forcing or runtime parameter mutation is offered. Bounded manual periodic
|
||||
L2 set replacement is available at completed base intervals via remap_child.
|
||||
"""
|
||||
from dataclasses import dataclass, replace
|
||||
from numbers import Integral
|
||||
@@ -14,8 +15,30 @@ import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from ..cuda import compiler_v2 as compiler
|
||||
from .refinement import ACTIVE, HALO, FixedPatch2D, prepare_fine_boundary
|
||||
from .blocks import BlockLayout2D
|
||||
from ..body.jets import jet_link_velocity
|
||||
from .block_stepper import MAX_GRID_DIM
|
||||
from .hierarchy import build_hierarchy, is_rectangle
|
||||
from .refinement import ACTIVE, HALO, FixedPatch2D, FixedPatchSet2D, prepare_fine_boundary
|
||||
from .refinement_tables import (blocked_base_tables, blocked_fine_tables, # noqa: F401 (re-export)
|
||||
blocked_kind, _prepare_blocked_boundary,
|
||||
BLOCKED_BOUNDARY_DEVICE_COLUMNS)
|
||||
from .descriptors import SOLID
|
||||
from .raw_exchange import summarize_exchange
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Pair:
|
||||
"""Device transfer tables of one nested parent->child relationship."""
|
||||
explode: object # BlockExplode from the CHILD module (child TOTAL_CELLS)
|
||||
coalesce: object
|
||||
ghosts: object
|
||||
donors: object
|
||||
targets: object # receiver-local staged parent slots
|
||||
children: object
|
||||
n_ghosts: int
|
||||
n_rows: int
|
||||
parent_cells: int # parent block window cells (explode donor stride)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -26,6 +49,84 @@ class _Level:
|
||||
spare: object
|
||||
kernel: object
|
||||
grid: tuple
|
||||
layout: object = None
|
||||
kind: object = None
|
||||
halo_copy: object = None
|
||||
halo_dst: object = None
|
||||
halo_src: object = None
|
||||
boundary: object = None
|
||||
|
||||
|
||||
def _level_name(level):
|
||||
return ("base", "fine", "child")[level] if level < 3 else f"level {level}"
|
||||
|
||||
|
||||
def _legacy_levels(bounds, *, fine_block, base_block, child, child_block, child_rectangles_in_parent,
|
||||
fine_objects, jets, child_objects, child_jets):
|
||||
"""Normalise the original two/three-level keywords to per-level lists (original errors)."""
|
||||
if child is not None and child_rectangles_in_parent is not None:
|
||||
raise ValueError("child and child_rectangles_in_parent are mutually exclusive")
|
||||
nested = child is not None or child_rectangles_in_parent is not None
|
||||
bounds = tuple(bounds)
|
||||
if not is_rectangle(bounds) and (fine_block is None or base_block is None):
|
||||
raise ValueError("several patches require fine_block and base_block")
|
||||
fine_objects, jets = tuple(fine_objects), tuple(jets)
|
||||
child_objects, child_jets = tuple(child_objects), tuple(child_jets)
|
||||
if not nested and (child_objects or child_jets):
|
||||
raise ValueError("child_objects/child_jets require a nested child")
|
||||
if base_block is not None and fine_block is None:
|
||||
raise ValueError("base_block requires fine_block")
|
||||
refinements, blocks = [bounds], [base_block, fine_block]
|
||||
objects, level_jets = [(), fine_objects], [(), jets]
|
||||
if nested:
|
||||
if child is not None and not is_rectangle(bounds):
|
||||
raise ValueError("scalar child requires one parent patch; use child_rectangles_in_parent")
|
||||
if fine_block is None or base_block is None or child_block is None:
|
||||
raise ValueError("a nested child needs fine_block, base_block and child_block")
|
||||
if fine_objects or jets:
|
||||
raise ValueError("a nested child supports bodies/Jets only on L2; use child_objects/child_jets")
|
||||
refinements.append(tuple(child) if child is not None else tuple(child_rectangles_in_parent))
|
||||
blocks.append(child_block)
|
||||
objects.append(child_objects)
|
||||
level_jets.append(child_jets)
|
||||
return refinements, blocks, objects, level_jets
|
||||
|
||||
|
||||
def _initial_levels(level_g, coarse_g, fine_g, child_g):
|
||||
"""One tuple of per-level arrays from initialize()'s positional or legacy named form."""
|
||||
if coarse_g is None and fine_g is None:
|
||||
if child_g is not None and len(level_g) != 2:
|
||||
raise TypeError("child_g needs exactly the coarse and fine arrays before it")
|
||||
return tuple(level_g) + (() if child_g is None else (child_g,))
|
||||
if level_g:
|
||||
raise TypeError("pass level arrays positionally or as coarse_g/fine_g/child_g, not both")
|
||||
if coarse_g is None or fine_g is None:
|
||||
raise TypeError("coarse_g and fine_g are both required in the named form")
|
||||
return (coarse_g, fine_g) + (() if child_g is None else (child_g,))
|
||||
|
||||
|
||||
def _check_levels(refinements, blocks, objects, jets):
|
||||
"""Candidate limits shared by the list and the legacy entry points."""
|
||||
depth = len(refinements) + 1
|
||||
if depth < 2:
|
||||
raise ValueError("at least one refinement level is required")
|
||||
for name, values in (("level_blocks", blocks), ("level_objects", objects), ("level_jets", jets)):
|
||||
if len(values) != depth:
|
||||
raise ValueError(f"{name} needs one entry per level ({depth})")
|
||||
for level, block in enumerate(blocks):
|
||||
if block is not None and len(block) != 2:
|
||||
raise ValueError(f"{_level_name(level)}_block must be (by, bx)")
|
||||
if objects[0] or jets[0]:
|
||||
raise ValueError("base-level bodies/Jets are not supported")
|
||||
if any(blocks[level - 1] is not None and blocks[level] is None for level in range(1, depth)):
|
||||
raise ValueError("a blocked level requires blocked refined levels below it")
|
||||
if not is_rectangle(refinements[0]) and (blocks[0] is None or blocks[1] is None):
|
||||
raise ValueError("several patches require fine_block and base_block")
|
||||
if depth > 2:
|
||||
if any(block is None for block in blocks):
|
||||
raise ValueError("three or more levels must all be blocked")
|
||||
if any(objects[level] or jets[level] for level in range(1, depth - 1)):
|
||||
raise ValueError("bodies/Jets are supported only on the finest level of a nested hierarchy")
|
||||
|
||||
|
||||
class FixedPatchStepper:
|
||||
@@ -46,82 +147,218 @@ class FixedPatchStepper:
|
||||
Every ``step()`` publishes only after both levels complete on one stream.
|
||||
On a device/launch failure the instance becomes unusable: close and recreate
|
||||
it, rather than pretending the partially advanced fine buffer rolled back.
|
||||
|
||||
``fine_block=(by, bx)`` (opt-in) stores the fine level in
|
||||
blocks.cu storage: the ENTIRE fine_shape, including the four-cell patch
|
||||
ghost band, is partitioned by a non-periodic BlockLayout2D with one-cell
|
||||
same-level halos. Patch kinds stay per cell (OUTER invalid, INNER stream
|
||||
only, ACTIVE collide); halos are gathered before each fine hop. Public
|
||||
arrays keep the dense (9, ny, nx) fine shape; only the allocation differs.
|
||||
Blocked fine_objects are stationary circles, optionally surface-actuated:
|
||||
prepare_fine_boundary decides legality on the dense fine grid, then cut
|
||||
links are staged receiver-local per hop: halo -> BFL -> step, same buffer.
|
||||
``base_block=(by, bx)`` also blocks the parent; it requires ``fine_block``.
|
||||
Parent halos precede receiver-local coalescence staging and pull/collision;
|
||||
covered cells are explicitly poisoned on every step. Public shapes stay dense.
|
||||
``observe_raw_exchange=True`` records blocked physical cut-link exchange
|
||||
without changing populations. read_raw_exchange reports the last complete
|
||||
base interval or last substep in base-lattice units per unit depth. This
|
||||
is boundary momentum reaction, not a validated nozzle/stress load. Dense
|
||||
body layouts are not supported by this new diagnostic in this candidate.
|
||||
``jets`` (body.jets.Jet) use the same edge frame as ``fine_objects`` and
|
||||
drive fine cut links selected at their true hits; ``set_jet_amplitude``
|
||||
re-uploads the per-link velocity column only.
|
||||
|
||||
Several patches: pass ``bounds`` as a sequence of (x0, y0, x1, y1)
|
||||
rectangles (FixedPatchSet2D, >= 4 coarse cells apart). This requires
|
||||
fine_block and base_block; fine_objects/jets are projected once onto the
|
||||
level-wide fine grid (each circle inside one patch, body ids = object
|
||||
positions, jet and writer checks level-wide), and
|
||||
uses one level-wide fine grid (2*ny, 2*nx): public fine arrays have that
|
||||
shape, NaN outside the patches' ACTIVE cells. The step sequence is the
|
||||
blocked one above, with every patch's transfers in one launch each.
|
||||
|
||||
Three-level separated unions: ``child_rectangles_in_parent=[...]`` is
|
||||
mutually exclusive with scalar ``child`` and accepts either parent form.
|
||||
Coordinates index the allocated L1 array, including ghost bands and holes:
|
||||
root edge = patch.fine_origin + L1 index / 2. A parent set has origin zero;
|
||||
a scalar parent retains its shifted window origin. The child set's public
|
||||
extent is twice the allocated L1 shape, even though storage is sparse.
|
||||
Each pair requires gap >= 4 in its own parent-cell units. All regions share
|
||||
one buffer pair per level and the fixed 1:2:4 schedule; L2-only bodies/Jets
|
||||
below apply unchanged, with object IDs assigned over the whole level.
|
||||
|
||||
Three-level single chain: ``child`` bounds use L1 window cells; all three
|
||||
levels must be blocked. ``child_objects`` and ``child_jets`` use the L0
|
||||
edge frame, with L2 dx=dt=.25 and unchanged lattice velocity. L1 bodies
|
||||
and Jets remain unsupported in a chain. Every whole circle and its BFL
|
||||
stencil must fit strictly away from the L2 transfer footprint. L2 runs
|
||||
halo -> BFL -> step four times per base step. Runtime child Jet changes
|
||||
require ``set_jet_amplitude(index, amplitude, level=2)``.
|
||||
|
||||
Level lists (any depth): ``refinements[l]`` gives level l+1 in level-l
|
||||
integer cells (scalar window or rectangle list, see lbm.hierarchy);
|
||||
``level_blocks``/``level_objects``/``level_jets`` hold one entry per level,
|
||||
L0 included. They are mutually exclusive with the legacy keywords above,
|
||||
which are normalised to the same lists. One recursive hop advances every
|
||||
level: a child explodes from its parent's current hop source, takes two
|
||||
hops, then the parent gathers halos, stages restriction, applies BFL and
|
||||
steps. Depth >= 3 must be fully blocked with bodies/Jets on the finest level.
|
||||
"""
|
||||
def __init__(self, cfg, bounds, *, context, coarse_boundary="periodic", fine_objects=()):
|
||||
def __init__(self, cfg, bounds=None, *, context, coarse_boundary="periodic", fine_objects=(),
|
||||
fine_block=None, base_block=None, jets=(), child=None, child_block=None,
|
||||
child_objects=(), child_jets=(), child_rectangles_in_parent=None,
|
||||
refinements=None, level_blocks=None, level_objects=None, level_jets=None,
|
||||
observe_raw_exchange=False):
|
||||
if HALO != 4:
|
||||
raise RuntimeError("refinement.cu requires a four-cell fine halo")
|
||||
if coarse_boundary not in ("periodic", "slot_reservoir"):
|
||||
raise ValueError("coarse_boundary must be periodic or slot_reservoir")
|
||||
self.patch = FixedPatch2D.from_config(cfg, bounds)
|
||||
if refinements is None:
|
||||
if bounds is None:
|
||||
raise ValueError("bounds or refinements is required")
|
||||
if level_blocks is not None or level_objects is not None or level_jets is not None:
|
||||
raise ValueError("level_blocks/level_objects/level_jets require refinements")
|
||||
refinements, level_blocks, level_objects, level_jets = _legacy_levels(
|
||||
bounds, fine_block=fine_block, base_block=base_block, child=child,
|
||||
child_block=child_block, child_rectangles_in_parent=child_rectangles_in_parent,
|
||||
fine_objects=fine_objects, jets=jets, child_objects=child_objects,
|
||||
child_jets=child_jets)
|
||||
else:
|
||||
if (bounds is not None or child is not None or child_rectangles_in_parent is not None
|
||||
or fine_block is not None or base_block is not None or child_block is not None
|
||||
or tuple(fine_objects) or tuple(jets) or tuple(child_objects) or tuple(child_jets)):
|
||||
raise ValueError("refinements and the legacy patch keywords are mutually exclusive")
|
||||
depth = len(refinements) + 1
|
||||
level_blocks = [None] * depth if level_blocks is None else list(level_blocks)
|
||||
level_objects = [()] * depth if level_objects is None else list(level_objects)
|
||||
level_jets = [()] * depth if level_jets is None else list(level_jets)
|
||||
level_objects = [tuple(o) for o in level_objects]
|
||||
level_jets = [tuple(j) for j in level_jets]
|
||||
level_blocks = [None if b is None else tuple(b) for b in level_blocks]
|
||||
_check_levels(refinements, level_blocks, level_objects, level_jets)
|
||||
depth = len(refinements) + 1
|
||||
self._wall_aware = coarse_boundary == "slot_reservoir"
|
||||
if self._wall_aware and (cfg.y_wall_bc != "on_site_velocity" or cfg.top_wall_bc != "reservoir"
|
||||
or cfg.velocity != 0 or not 2 <= cfg.wall_slot_width < cfg.nx):
|
||||
raise ValueError("slot_reservoir requires on_site_velocity, reservoir, "
|
||||
"velocity=0 and 2 <= wall_slot_width < nx")
|
||||
self.hierarchy = build_hierarchy(cfg, refinements, wall_aware=self._wall_aware)
|
||||
pairs = self.hierarchy.pairs
|
||||
if self._wall_aware:
|
||||
if (cfg.y_wall_bc != "on_site_velocity" or cfg.top_wall_bc != "reservoir"
|
||||
or cfg.velocity != 0 or not 2 <= cfg.wall_slot_width < cfg.nx):
|
||||
raise ValueError("slot_reservoir requires on_site_velocity, reservoir, "
|
||||
"velocity=0 and 2 <= wall_slot_width < nx")
|
||||
if self.patch.bounds[1] < 4 or self.patch.bounds[3] > cfg.ny - 4:
|
||||
rects = (pairs[0].bounds,) if isinstance(pairs[0], FixedPatch2D) else pairs[0].bounds
|
||||
if any(r[1] < 4 or r[3] > cfg.ny - 4 for r in rects):
|
||||
raise ValueError("slot_reservoir requires y0 >= 4 and y1 <= ny-4")
|
||||
self.fine_boundary = prepare_fine_boundary(
|
||||
cfg, self.patch, tuple(fine_objects), wall_aware=self._wall_aware)
|
||||
self._fine_leaf = self.patch.fine_kind == ACTIVE
|
||||
if self.fine_boundary is not None:
|
||||
self._fine_leaf &= (self.fine_boundary.flags.reshape(self.patch.fine_shape) & SOLID) == 0
|
||||
self._layouts = []
|
||||
for level, block in enumerate(level_blocks):
|
||||
layout = None
|
||||
if block is not None:
|
||||
if level == 0:
|
||||
layout = BlockLayout2D.build(cfg.ny, cfg.nx, *block,
|
||||
periodic=(True, not self._wall_aware))
|
||||
elif isinstance(pairs[level - 1], FixedPatchSet2D):
|
||||
layout = pairs[level - 1].fine_layout(block)
|
||||
else:
|
||||
layout = BlockLayout2D.build(*pairs[level - 1].fine_shape, *block,
|
||||
periodic=(False, False))
|
||||
if layout.nblocks > MAX_GRID_DIM or layout.local_shape[0] > MAX_GRID_DIM:
|
||||
raise ValueError(f"{_level_name(level)} blocks exceed launch limits")
|
||||
self._layouts.append(layout)
|
||||
# Kernel configurations per level (geometry configs live in self.hierarchy).
|
||||
fine_cfg = replace(cfg, nx=pairs[0].fine_shape[1], ny=pairs[0].fine_shape[0],
|
||||
viscosity=2 * cfg.viscosity)
|
||||
if self._wall_aware:
|
||||
fine_cfg = replace(fine_cfg, y_wall_bc="bounce_back", top_wall_bc="velocity",
|
||||
wall_slot_width=0, wall_normal_velocity=0.0, velocity=0.0)
|
||||
self._level_cfgs = [replace(cfg), fine_cfg]
|
||||
for pair in pairs[1:]:
|
||||
parent = self._level_cfgs[-1]
|
||||
self._level_cfgs.append(replace(parent, nx=pair.fine_shape[1], ny=pair.fine_shape[0],
|
||||
viscosity=2 * parent.viscosity))
|
||||
# Per-level boundary geometry in the root edge frame (level l spacing 2**-l).
|
||||
self._boundary_hosts = [None]
|
||||
origin, spacing = (0.0, 0.0), 1.0
|
||||
spacings = [spacing]
|
||||
for level in range(1, depth):
|
||||
pair = pairs[level - 1]
|
||||
if level == 1:
|
||||
host = prepare_fine_boundary(cfg, pair, level_objects[1],
|
||||
wall_aware=self._wall_aware, jets=level_jets[1])
|
||||
else:
|
||||
host = prepare_fine_boundary(self._level_cfgs[level - 1], pair, level_objects[level],
|
||||
jets=level_jets[level], parent_origin=origin,
|
||||
parent_spacing=spacing)
|
||||
self._boundary_hosts.append(host)
|
||||
origin = tuple(o + spacing * f for o, f in zip(origin, pair.fine_origin))
|
||||
spacing /= 2
|
||||
spacings.append(spacing)
|
||||
if not isinstance(observe_raw_exchange, bool):
|
||||
raise ValueError("observe_raw_exchange must be bool")
|
||||
if observe_raw_exchange and any(b is not None and layout is None
|
||||
for b, layout in zip(self._boundary_hosts, self._layouts)):
|
||||
raise ValueError("raw exchange currently requires blocked body levels")
|
||||
self._observe_raw_exchange = observe_raw_exchange
|
||||
self._exchange_valid = False
|
||||
self._exchange_spacing = tuple(spacings)
|
||||
self._exchange_centers = tuple(tuple(tuple(o.geometry.center) for o in objects)
|
||||
for objects in level_objects)
|
||||
self._level_jets = level_jets
|
||||
self._level_boundaries = [None] + [
|
||||
_prepare_blocked_boundary(self._boundary_hosts[level], self._layouts[level],
|
||||
self._level_cfgs[level], level_jets[level])
|
||||
for level in range(1, depth)]
|
||||
self._leaf = [kind == ACTIVE for kind in self.hierarchy.kinds]
|
||||
for level in range(1, depth):
|
||||
host = self._boundary_hosts[level]
|
||||
if host is not None:
|
||||
self._leaf[level] &= (host.flags.reshape(pairs[level - 1].fine_shape) & SOLID) == 0
|
||||
# Private constructor inputs for the bounded manual L2 continuation.
|
||||
self._remap_cfg = replace(cfg)
|
||||
self._level_blocks = level_blocks
|
||||
self.ctx = context
|
||||
self._lock = RLock()
|
||||
self._status = "new"
|
||||
self._step_count = 0
|
||||
self._allocations = []
|
||||
self._levels = []
|
||||
self._levels, self._pairs = [], []
|
||||
self._stream = None
|
||||
self._fine_flags = self._fine_curved = self._curved = None
|
||||
self._link_tables = {}
|
||||
self._block = (cfg.threads_per_block, 1, 1)
|
||||
fine_cfg = replace(cfg, nx=self.patch.fine_shape[1], ny=self.patch.fine_shape[0],
|
||||
viscosity=2 * cfg.viscosity)
|
||||
if self._wall_aware:
|
||||
fine_cfg = replace(fine_cfg, y_wall_bc="bounce_back", top_wall_bc="velocity",
|
||||
wall_slot_width=0, wall_normal_velocity=0.0, velocity=0.0)
|
||||
with self.ctx.activate():
|
||||
try:
|
||||
self._stream = cuda.Stream()
|
||||
for config, name, tau in ((replace(cfg), "PatchCoarseStep", self.patch.tau_coarse),
|
||||
(fine_cfg, "PatchFineStep", self.patch.tau_fine)):
|
||||
config.validate()
|
||||
if not np.isclose(config.omega, 1 / tau, rtol=1e-14, atol=0):
|
||||
raise RuntimeError("level omega/tau mismatch")
|
||||
n_objects = (len(self.fine_boundary.objects)
|
||||
if name == "PatchFineStep" and self.fine_boundary is not None else 0)
|
||||
build = compiler.generate_config(config, n_objects=n_objects)
|
||||
try:
|
||||
ptx = compiler.compile_kernel(self.ctx.sm_arch, source="refinement.cu",
|
||||
build_dir=build)
|
||||
module = compiler.load_module(ptx)
|
||||
finally:
|
||||
compiler.cleanup_build_dir(build)
|
||||
ptr, size = module.get_global("d_params")
|
||||
if size != struct.calcsize("=ffffI"):
|
||||
raise RuntimeError("LBMParams host/device layout mismatch")
|
||||
cuda.memcpy_htod(ptr, struct.pack("=ffffI", config.omega, 0, 0, 0, n_objects))
|
||||
shape = (9, config.ny, config.nx)
|
||||
size = int(np.prod(shape)) * 4
|
||||
self._levels.append(_Level(shape, module, self._allocate(size),
|
||||
self._allocate(size), module.get_function(name),
|
||||
((config.nx + self._block[0] - 1) // self._block[0],
|
||||
config.ny, 1)))
|
||||
p = self.patch
|
||||
order = np.argsort(p.coalesce_coarse)
|
||||
self._ghosts = self._upload(p.ghost_fine)
|
||||
self._donors = self._upload(p.ghost_coarse)
|
||||
self._targets = self._upload(p.coalesce_coarse[order])
|
||||
self._children = self._upload(p.coalesce_fine[order])
|
||||
self._explode = self._levels[1].module.get_function("PatchExplode")
|
||||
if self.fine_boundary is not None:
|
||||
for level in range(depth):
|
||||
self._levels.append(self._build_level(level))
|
||||
for index, pair in enumerate(pairs):
|
||||
self._pairs.append(self._build_pair(index, pair))
|
||||
for level in self._levels:
|
||||
b = level.boundary
|
||||
if b is not None:
|
||||
b.flags = self._upload(b.tables["flags"])
|
||||
b.device = {k: self._upload(v) for k, v in b.tables.items()
|
||||
if k in BLOCKED_BOUNDARY_DEVICE_COLUMNS}
|
||||
if self._observe_raw_exchange:
|
||||
b.device.update(rx=self._upload(b.tables["rx"]),
|
||||
ry=self._upload(b.tables["ry"]))
|
||||
count = len(b.tables["cell"])
|
||||
b.last_raw = self._allocate(count * 4 * 4)
|
||||
b.interval_integral = self._allocate(count * 4 * 8)
|
||||
b.accumulate = level.module.get_function("BlockAccumulateExchange")
|
||||
b.kernel = level.module.get_function("BlockCurvedBoundary")
|
||||
if self._level_boundaries[1] is not None:
|
||||
b = self._level_boundaries[1]
|
||||
self._fine_flags, self._link_tables, self._curved = b.flags, b.device, b.kernel
|
||||
elif self._boundary_hosts[1] is not None:
|
||||
from .curved_links import CurvedLinkSoA
|
||||
boundary = self.fine_boundary
|
||||
boundary = self._boundary_hosts[1]
|
||||
self._fine_flags = self._upload(boundary.flags)
|
||||
# SoA owns its allocations; never also register them in _allocations.
|
||||
self._fine_curved = CurvedLinkSoA()
|
||||
self._fine_curved.assign_host(*boundary.curved_host)
|
||||
self._fine_curved.assign_surface(boundary.objects, fine_cfg, boundary.flags)
|
||||
self._fine_curved.assign_surface(boundary.objects, fine_cfg, boundary.flags,
|
||||
jets=self._level_jets[1],
|
||||
hits=boundary.curved_hits)
|
||||
self._fine_curved.upload()
|
||||
self._curved = self._levels[1].module.get_function("CurvedBoundaryKernel")
|
||||
except BaseException:
|
||||
@@ -131,6 +368,84 @@ class FixedPatchStepper:
|
||||
pass # Preserve the original construction failure.
|
||||
raise
|
||||
|
||||
def _build_level(self, index):
|
||||
"""Compile one level's step module and allocate its two G buffers."""
|
||||
layout, config = self._layouts[index], self._level_cfgs[index]
|
||||
pairs = self.hierarchy.pairs
|
||||
tau = pairs[0].tau_coarse if index == 0 else pairs[index - 1].tau_fine
|
||||
name, source = ("PatchCoarseStep" if index == 0 else "PatchFineStep"), "refinement.cu"
|
||||
if layout is not None:
|
||||
config = replace(config, nx=layout.local_shape[1], ny=layout.local_shape[0],
|
||||
y_wall_bc="bounce_back", top_wall_bc="velocity",
|
||||
wall_slot_width=0, wall_normal_velocity=0.0, velocity=0.0)
|
||||
name, source = "BlockStep", "blocks.cu"
|
||||
config.validate()
|
||||
if not np.isclose(config.omega, 1 / tau, rtol=1e-14, atol=0):
|
||||
raise RuntimeError("level omega/tau mismatch")
|
||||
host = self._boundary_hosts[index]
|
||||
n_objects = len(host.objects) if name == "PatchFineStep" and host is not None else 0
|
||||
build = compiler.generate_config(config, n_objects=n_objects)
|
||||
try:
|
||||
ptx = compiler.compile_kernel(self.ctx.sm_arch, source=source, build_dir=build)
|
||||
module = compiler.load_module(ptx)
|
||||
finally:
|
||||
compiler.cleanup_build_dir(build)
|
||||
ptr, size = module.get_global("d_params")
|
||||
if size != struct.calcsize("=ffffI"):
|
||||
raise RuntimeError("LBMParams host/device layout mismatch")
|
||||
cuda.memcpy_htod(ptr, struct.pack("=ffffI", config.omega, 0, 0, 0, n_objects))
|
||||
shape = (9, *self.hierarchy.kinds[index].shape)
|
||||
size = int(np.prod(shape if layout is None else layout.blocked_shape)) * 4
|
||||
grid = ((config.nx + self._block[0] - 1) // self._block[0], config.ny,
|
||||
1 if layout is None else layout.nblocks)
|
||||
level = _Level(shape, module, self._allocate(size), self._allocate(size),
|
||||
module.get_function(name), grid, layout)
|
||||
level.boundary = self._level_boundaries[index]
|
||||
if layout is not None:
|
||||
level.halo_copy = module.get_function("BlockHaloCopy")
|
||||
if len(layout.halo_dst):
|
||||
level.halo_dst = self._upload(layout.halo_dst)
|
||||
level.halo_src = self._upload(layout.halo_src)
|
||||
if index == 0 and self._wall_aware:
|
||||
cfg = self._remap_cfg
|
||||
ptr, size = module.get_global("d_block_wall")
|
||||
if size != struct.calcsize("=IIIf"):
|
||||
raise RuntimeError("Block wall host/device layout mismatch")
|
||||
cuda.memcpy_htod(ptr, struct.pack("=IIIf", cfg.nx, cfg.ny,
|
||||
cfg.wall_slot_width, cfg.wall_normal_velocity))
|
||||
return level
|
||||
|
||||
def _build_pair(self, index, pair):
|
||||
"""Upload the transfer tables of levels (index, index+1) and the child's block kinds."""
|
||||
parent, child = self._levels[index], self._levels[index + 1]
|
||||
order = np.argsort(pair.coalesce_coarse)
|
||||
fine = None if child.layout is None else blocked_fine_tables(pair, child.layout, order)
|
||||
base = None
|
||||
if parent.layout is not None:
|
||||
if index == 0:
|
||||
base = blocked_base_tables(pair, parent.layout, order, self._wall_aware)
|
||||
else:
|
||||
# Nested pairs keep inherited INNER/OUTER and sparse holes of the parent.
|
||||
base = blocked_base_tables(pair, parent.layout, order,
|
||||
composed_kind=self.hierarchy.kinds[index])
|
||||
ghosts = pair.ghost_fine if fine is None else fine[0]
|
||||
donors = pair.ghost_coarse if base is None else base[0]
|
||||
if fine is not None:
|
||||
donors = donors.astype(np.uint64)
|
||||
targets = pair.coalesce_coarse[order] if base is None else base[1]
|
||||
children = pair.coalesce_fine[order] if fine is None else fine[1]
|
||||
result = _Pair(child.module.get_function("PatchExplode" if fine is None else "BlockExplode"),
|
||||
None if parent.layout is None else parent.module.get_function("BlockCoalesce"),
|
||||
self._upload(ghosts), self._upload(donors), self._upload(targets),
|
||||
self._upload(children), len(ghosts), len(targets),
|
||||
int(np.prod(pair.coarse_shape if parent.layout is None
|
||||
else parent.layout.local_shape)))
|
||||
if child.layout is not None:
|
||||
child.kind = self._upload(blocked_kind(child.layout, self.hierarchy.kinds[index + 1]))
|
||||
if index == 0 and base is not None:
|
||||
parent.kind = self._upload(base[2])
|
||||
return result
|
||||
|
||||
def _allocate(self, size):
|
||||
pointer = cuda.mem_alloc(size)
|
||||
self._allocations.append(pointer)
|
||||
@@ -150,30 +465,30 @@ class FixedPatchStepper:
|
||||
def step_count(self):
|
||||
return self._step_count
|
||||
|
||||
def _mask_nonleaves(self, coarse, fine):
|
||||
x0, y0, x1, y1 = self.patch.bounds
|
||||
coarse[:, y0:y1, x0:x1] = np.nan
|
||||
if self._wall_aware:
|
||||
coarse[:, (0, -1), :] = np.nan
|
||||
fine[:, ~self._fine_leaf] = np.nan
|
||||
def _mask_nonleaves(self, *arrays):
|
||||
for array, leaf in zip(arrays, self._leaf):
|
||||
array[:, ~leaf] = np.nan
|
||||
|
||||
def initialize(self, coarse_g, fine_g):
|
||||
"""Upload an explicit G_0; invalid non-leaves are discarded."""
|
||||
def initialize(self, *level_g, coarse_g=None, fine_g=None, child_g=None):
|
||||
"""Upload an explicit G_0, one Q-major array per level; non-leaves are discarded.
|
||||
|
||||
Pass the level arrays positionally (L0 first), or use the original
|
||||
two/three-level names coarse_g, fine_g[, child_g]; mixing is rejected.
|
||||
"""
|
||||
given = _initial_levels(level_g, coarse_g, fine_g, child_g)
|
||||
with self._lock, self.ctx.activate():
|
||||
self._require("new", "ready")
|
||||
arrays = [np.array(a, dtype=np.float32, order="C", copy=True)
|
||||
for a in (coarse_g, fine_g)]
|
||||
if len(given) != len(self._levels):
|
||||
raise ValueError("Expected one Q-major array per level")
|
||||
arrays = [np.array(a, dtype=np.float32, order="C", copy=True) for a in given]
|
||||
if any(a.shape != level.shape for a, level in zip(arrays, self._levels)):
|
||||
raise ValueError("Expected Q-major (9,ny,nx) arrays for both levels")
|
||||
x0, y0, x1, y1 = self.patch.bounds
|
||||
leaf = np.ones(self.patch.coarse_shape, dtype=bool)
|
||||
leaf[y0:y1, x0:x1] = False
|
||||
if self._wall_aware:
|
||||
leaf[[0, -1]] = False
|
||||
for array, mask in zip(arrays, (leaf, self._fine_leaf)):
|
||||
raise ValueError("Expected Q-major (9,ny,nx) arrays for every level")
|
||||
for array, mask in zip(arrays, self._leaf):
|
||||
if not np.isfinite(array[:, mask]).all() or (array[:, mask].sum(axis=0) <= 0).any():
|
||||
raise ValueError("Leaf populations must be finite with positive density")
|
||||
self._mask_nonleaves(*arrays)
|
||||
arrays = [a if level.layout is None else level.layout.to_blocked(a)
|
||||
for a, level in zip(arrays, self._levels)]
|
||||
try:
|
||||
for level, array in zip(self._levels, arrays):
|
||||
cuda.memcpy_htod(level.current, array)
|
||||
@@ -181,21 +496,105 @@ class FixedPatchStepper:
|
||||
if self._fine_curved is not None and self._fine_curved.link_exchange_gpu is not None:
|
||||
cuda.memset_d8(self._fine_curved.link_exchange_gpu, 0, self._fine_curved.count * 12)
|
||||
self._step_count = 0
|
||||
self._exchange_valid = False
|
||||
self._status = "ready"
|
||||
except BaseException:
|
||||
self._status = "failed"
|
||||
raise
|
||||
|
||||
def remap_child(self, rectangles, *, child_objects=()):
|
||||
"""Return a NEW ready stepper with an L2 set replaced at this base time.
|
||||
|
||||
Periodic three-level set children only; L0/L1 and block sizes stay fixed.
|
||||
A body run requires its original root-edge-frame ``child_objects``:
|
||||
stationary circles pinned in unchanged complete L2 rectangles.
|
||||
Separated fluid-only rectangles may be added, moved or removed.
|
||||
Current L2 Jets (including updated amplitudes)
|
||||
are preserved. Local projected boundary objects are not valid inputs.
|
||||
The lock and stream synchronization certify
|
||||
current postcollision G and the completed 1:2:4 counts internally.
|
||||
Both objects remain independently owned: the caller must close each,
|
||||
and chooses when to stop using the unchanged old instance. Candidate
|
||||
construction/upload errors never invalidate the old instance; failure
|
||||
to synchronize/read its device state does, as with step/download.
|
||||
"""
|
||||
from .synchronized_remap import (RemapTopology, remap_synchronized,
|
||||
same_physical_boundary, boundary_velocity)
|
||||
|
||||
with self._lock:
|
||||
self._require("ready")
|
||||
pairs = self.hierarchy.pairs
|
||||
if (self._wall_aware or self.hierarchy.depth != 3
|
||||
or not isinstance(pairs[1], FixedPatchSet2D)
|
||||
or self._boundary_hosts[1] is not None
|
||||
or any(b is not None for b in self._level_boundaries[:2])):
|
||||
raise ValueError("remap_child requires periodic three-level L2 sets with no L0/L1 bodies")
|
||||
cfg = self._remap_cfg
|
||||
child_objects = tuple(child_objects)
|
||||
actual = self._level_boundaries[2]
|
||||
jets = () if actual is None else actual.jets
|
||||
old = RemapTopology.from_config(cfg, pairs[0], pairs[1].bounds,
|
||||
child_objects=child_objects, child_jets=jets)
|
||||
if (not same_physical_boundary(old.boundary, self._boundary_hosts[2])
|
||||
or (self._boundary_hosts[2] is not None and actual is None)):
|
||||
raise ValueError("child_objects must reproduce the original root-edge-frame boundary")
|
||||
if actual is not None:
|
||||
velocity = actual.tables.get("surface_velocity")
|
||||
if velocity is None:
|
||||
velocity = boundary_velocity(cfg, pairs[1], actual.host, jets)
|
||||
if (not same_physical_boundary(old.boundary, actual.host)
|
||||
or not np.array_equal(old.surface_velocity, velocity)):
|
||||
raise ValueError("child_objects changed boundary ownership or surface velocity")
|
||||
new = RemapTopology.from_config(cfg, pairs[0], rectangles,
|
||||
child_objects=child_objects, child_jets=jets)
|
||||
if (old.pinned_rectangles != new.pinned_rectangles
|
||||
or not same_physical_boundary(old.boundary, new.boundary)
|
||||
or not np.array_equal(old.surface_velocity, new.surface_velocity)):
|
||||
raise ValueError("remap requires the identical pinned body rectangles and boundary")
|
||||
base_block, fine_block, child_block = self._level_blocks
|
||||
# Check sparse block alignment/launch size before any device read/allocation.
|
||||
layout = new.child.fine_layout(child_block)
|
||||
if layout.nblocks > MAX_GRID_DIM or layout.local_shape[0] > MAX_GRID_DIM:
|
||||
raise ValueError("child blocks exceed launch limits")
|
||||
with self.ctx.activate():
|
||||
try:
|
||||
self._stream.synchronize()
|
||||
source = self.download()
|
||||
except BaseException:
|
||||
self._status = "failed"
|
||||
raise
|
||||
count = self._step_count
|
||||
transferred = remap_synchronized(
|
||||
old, new, source, base_count=count, level_steps=(count, 2*count, 4*count),
|
||||
phase="postcollision_g")
|
||||
candidate = type(self)(
|
||||
cfg, pairs[0].bounds, context=self.ctx, base_block=base_block,
|
||||
fine_block=fine_block, child_block=child_block,
|
||||
child_rectangles_in_parent=new.child.bounds,
|
||||
child_objects=child_objects, child_jets=jets,
|
||||
observe_raw_exchange=self._observe_raw_exchange)
|
||||
try:
|
||||
candidate.initialize(*transferred.g)
|
||||
candidate._step_count = count
|
||||
except BaseException:
|
||||
try:
|
||||
candidate.close()
|
||||
except Exception:
|
||||
pass # Preserve the original candidate initialization failure.
|
||||
raise
|
||||
return candidate
|
||||
|
||||
def _apply_fine_boundary(self, buffer, **kw):
|
||||
"""Stage solid source slots; exchange buffer holds this fine substep only."""
|
||||
cl = self._fine_curved
|
||||
if cl is None:
|
||||
if self.fine_boundary is not None:
|
||||
if self._boundary_hosts[1] is not None:
|
||||
raise RuntimeError("Fine boundary device buffers are missing")
|
||||
return
|
||||
if self._curved is None or cl.fluid_idx_gpu is None:
|
||||
raise RuntimeError("Fine boundary device buffers are missing")
|
||||
driven = any(obj.surface_actuation is not None for obj in self.fine_boundary.objects)
|
||||
driven = bool(self._level_jets[1]) or any(
|
||||
obj.surface_actuation is not None for obj in self._boundary_hosts[1].objects)
|
||||
if driven and (cl.surface_velocity_gpu is None or cl.link_exchange_gpu is None):
|
||||
raise RuntimeError("Surface boundary device buffers are missing")
|
||||
self._curved(buffer, cl.fluid_idx_gpu, cl.dir_gpu, cl.q_gpu,
|
||||
@@ -205,52 +604,188 @@ class FixedPatchStepper:
|
||||
cl.link_exchange_gpu if cl.link_exchange_gpu is not None else np.uintp(0),
|
||||
grid=((cl.count + self._block[0] - 1) // self._block[0], 1), **kw)
|
||||
|
||||
def set_jet_amplitude(self, index, amplitude, *, level=1):
|
||||
"""Replace one jet's amplitude between steps; no geometry/table rebuild.
|
||||
|
||||
``level=1`` preserves the L1 default; use ``level=2`` for child_jets.
|
||||
Invalid input raises before any change. A device/sync error marks the
|
||||
instance failed (as step/initialize do); host state commits only after
|
||||
a successful upload.
|
||||
"""
|
||||
with self._lock, self.ctx.activate():
|
||||
self._require("new", "ready")
|
||||
if (isinstance(level, bool) or not isinstance(level, Integral)
|
||||
or not 1 <= level < self.hierarchy.depth):
|
||||
raise ValueError("Jet level must name an existing refined level (1 = first)")
|
||||
boundary = self._level_boundaries[level]
|
||||
jets = list(self._level_jets[level])
|
||||
jets[index] = jets[index].with_amplitude(amplitude) # validates first
|
||||
velocity = None
|
||||
if boundary is not None and boundary.jet_cache is not None:
|
||||
shape, jet_id = boundary.jet_cache
|
||||
velocity = boundary.tables["surface_velocity"].copy()
|
||||
driven = jet_id >= 0
|
||||
velocity[driven] = jet_link_velocity(jets, shape, jet_id)[driven]
|
||||
try:
|
||||
if level == 1 and self._fine_curved is not None:
|
||||
self._fine_curved.set_jet_amplitude(index, amplitude, self._stream)
|
||||
elif velocity is not None:
|
||||
self._stream.synchronize() # no in-flight step reads the column
|
||||
cuda.memcpy_htod(boundary.device["surface_velocity"], velocity)
|
||||
except BaseException:
|
||||
self._status = "failed"
|
||||
raise
|
||||
if velocity is not None:
|
||||
boundary.tables["surface_velocity"] = velocity
|
||||
if boundary is not None:
|
||||
boundary.jets = tuple(jets)
|
||||
self._level_jets[level] = tuple(jets)
|
||||
|
||||
def _blocked_boundary(self, level, buffer, **kw):
|
||||
b = level.boundary
|
||||
if b is None:
|
||||
return
|
||||
if b.kernel is None or b.flags is None:
|
||||
raise RuntimeError("Boundary device buffers are missing")
|
||||
t, count = b.device, len(b.tables["cell"])
|
||||
velocity = t.get("surface_velocity")
|
||||
if b.actuated and velocity is None:
|
||||
raise RuntimeError("Surface velocity device buffer is missing")
|
||||
b.kernel(buffer, t["block"], t["cell"], t["dir"], t["q"], t["fallback"],
|
||||
np.uint32(count), velocity if velocity is not None else np.uintp(0),
|
||||
t.get("rx", np.uintp(0)), t.get("ry", np.uintp(0)),
|
||||
b.last_raw if b.last_raw is not None else np.uintp(0),
|
||||
grid=((count + self._block[0] - 1) // self._block[0], 1), **kw)
|
||||
|
||||
def _advance(self, index, parent_buffer, **kw):
|
||||
"""Explode from the given parent buffer, then two hops of level ``index``."""
|
||||
pair, level = self._pairs[index - 1], self._levels[index]
|
||||
pair.explode(parent_buffer, level.current, pair.ghosts, pair.donors, np.uint32(pair.n_ghosts),
|
||||
np.uint64(pair.parent_cells),
|
||||
grid=((pair.n_ghosts + self._block[0] - 1) // self._block[0], 1), **kw)
|
||||
self._hop(index, level.current, level.spare, **kw)
|
||||
self._hop(index, level.spare, level.current, **kw)
|
||||
|
||||
def _hop(self, index, src, dst, **kw):
|
||||
"""One interval of level ``index``: a child reads ``src`` (fresh at the midpoint) and
|
||||
advances twice; then halo -> receiver-local restriction -> BFL -> step on ``src``."""
|
||||
level = self._levels[index]
|
||||
nested = index + 1 < len(self._levels)
|
||||
if nested:
|
||||
self._advance(index + 1, src, **kw)
|
||||
if level.layout is None:
|
||||
if index == 0: # dense root: PatchCoarseStep fuses restriction and collision
|
||||
pair = self._pairs[0]
|
||||
level.kernel(src, dst, self._levels[1].current, pair.targets, pair.children,
|
||||
np.uint32(pair.n_rows), *(np.uint32(v) for v in self.hierarchy.pairs[0].bounds),
|
||||
np.uint32(self._wall_aware), grid=level.grid, **kw)
|
||||
return
|
||||
if self._boundary_hosts[index] is not None and self._fine_flags is None:
|
||||
raise RuntimeError("Fine boundary flags are missing")
|
||||
self._apply_fine_boundary(src, **kw)
|
||||
flags = self._fine_flags if self._fine_flags is not None else np.uintp(0)
|
||||
level.kernel(src, dst, flags, grid=level.grid, **kw)
|
||||
return
|
||||
# Child donors were read above; no halo gather may overwrite staged arrivals below.
|
||||
self._gather_halo(level, src, **kw)
|
||||
if nested:
|
||||
pair = self._pairs[index]
|
||||
pair.coalesce(self._levels[index + 1].current, src, pair.targets, pair.children,
|
||||
np.uint32(pair.n_rows),
|
||||
grid=((pair.n_rows + self._block[0] - 1) // self._block[0], 1), **kw)
|
||||
self._blocked_boundary(level, src, **kw)
|
||||
b = level.boundary
|
||||
if b is not None and b.last_raw is not None:
|
||||
count = len(b.tables["cell"])
|
||||
h = self._exchange_spacing[index] # acoustic scaling: dt_l = h_l
|
||||
b.accumulate(b.last_raw, b.interval_integral, np.uint32(count),
|
||||
np.float64(h), np.float64(h),
|
||||
grid=((count + self._block[0] - 1) // self._block[0], 1), **kw)
|
||||
flags = np.uintp(0) if level.boundary is None else level.boundary.flags
|
||||
level.kernel(src, dst, np.uint32(level.layout.halo), flags, level.kind, grid=level.grid, **kw)
|
||||
|
||||
def _gather_halo(self, level, buffer, **kw):
|
||||
pairs = len(level.layout.halo_dst)
|
||||
if pairs:
|
||||
level.halo_copy(buffer, level.halo_dst, level.halo_src, np.uint32(pairs),
|
||||
grid=((pairs + self._block[0] - 1) // self._block[0], 1), **kw)
|
||||
|
||||
def step(self, n=1):
|
||||
"""Advance G→G: one explosion, two fine collisions, one coarse collision."""
|
||||
"""Advance G→G by n base intervals: level l takes 2**l hops per interval."""
|
||||
if isinstance(n, bool) or not isinstance(n, Integral) or n < 0:
|
||||
raise ValueError("n must be a nonnegative integer")
|
||||
with self._lock, self.ctx.activate():
|
||||
self._require("ready")
|
||||
c, f = self._levels
|
||||
p = self.patch
|
||||
root = self._levels[0]
|
||||
kw = dict(block=self._block, stream=self._stream)
|
||||
try:
|
||||
self._status = "advancing"
|
||||
for _ in range(n):
|
||||
self._explode(c.current, f.current, self._ghosts, self._donors,
|
||||
np.uint32(len(p.ghost_fine)), np.uint64(np.prod(p.coarse_shape)),
|
||||
grid=((len(p.ghost_fine) + self._block[0] - 1) // self._block[0], 1),
|
||||
**kw)
|
||||
flags = self._fine_flags if self._fine_flags is not None else np.uintp(0)
|
||||
if self.fine_boundary is not None and self._fine_flags is None:
|
||||
raise RuntimeError("Fine boundary flags are missing")
|
||||
self._apply_fine_boundary(f.current, **kw)
|
||||
f.kernel(f.current, f.spare, flags, grid=f.grid, **kw)
|
||||
self._apply_fine_boundary(f.spare, **kw)
|
||||
f.kernel(f.spare, f.current, flags, grid=f.grid, **kw)
|
||||
c.kernel(c.current, c.spare, f.current, self._targets, self._children,
|
||||
np.uint32(len(p.coalesce_coarse)),
|
||||
*(np.uint32(v) for v in p.bounds), np.uint32(self._wall_aware),
|
||||
grid=c.grid, **kw)
|
||||
if self._observe_raw_exchange:
|
||||
self._exchange_valid = False
|
||||
for b in self._level_boundaries:
|
||||
if b is not None:
|
||||
cuda.memset_d8_async(b.interval_integral, 0,
|
||||
len(b.tables["cell"]) * 32, self._stream)
|
||||
self._hop(0, root.current, root.spare, **kw)
|
||||
self._stream.synchronize()
|
||||
c.current, c.spare = c.spare, c.current
|
||||
root.current, root.spare = root.spare, root.current
|
||||
self._step_count += 1
|
||||
self._exchange_valid = self._observe_raw_exchange
|
||||
self._status = "ready"
|
||||
except BaseException:
|
||||
self._status = "failed"
|
||||
raise
|
||||
|
||||
def download(self):
|
||||
"""Return two synchronized G arrays, NaN on all non-leaves; no host cache."""
|
||||
def read_raw_exchange(self, body_id, *, level=1, window="last_base_step"):
|
||||
"""Read raw boundary reaction about its geometric center in the root edge frame.
|
||||
|
||||
Repeated reads and step(0) preserve the window. last_substep samples
|
||||
[t-h,t], not a common instantaneous time across refinement levels.
|
||||
step(n) retains only the final complete base interval [t-1,t].
|
||||
Wall/aperture splitting is geometric, including zero-amplitude Jets.
|
||||
"""
|
||||
with self._lock, self.ctx.activate():
|
||||
self._require("ready")
|
||||
arrays = [np.empty(level.shape, np.float32) for level in self._levels]
|
||||
if not self._observe_raw_exchange:
|
||||
raise RuntimeError("raw exchange observation is disabled")
|
||||
if not self._exchange_valid:
|
||||
raise RuntimeError("raw exchange requires a completed base interval")
|
||||
if (isinstance(level, bool) or not isinstance(level, Integral)
|
||||
or not 0 <= level < len(self._levels)):
|
||||
raise ValueError("level must name an existing level")
|
||||
b = self._level_boundaries[level]
|
||||
if (b is None or isinstance(body_id, bool) or not isinstance(body_id, Integral)
|
||||
or not 0 <= body_id < len(b.host.objects)):
|
||||
raise ValueError("body_id must name a body on this level")
|
||||
if window not in ("last_base_step", "last_substep"):
|
||||
raise ValueError("window must be last_base_step or last_substep")
|
||||
count = len(b.tables["cell"])
|
||||
rows = np.empty((count, 4), np.float64 if window == "last_base_step" else np.float32)
|
||||
try:
|
||||
cuda.memcpy_dtoh(rows, b.interval_integral if window == "last_base_step" else b.last_raw)
|
||||
except BaseException:
|
||||
self._status = "failed"
|
||||
raise
|
||||
return summarize_exchange(rows, b.tables["body_id"], b.tables["aperture"],
|
||||
body_id=body_id, level=level, h=self._exchange_spacing[level],
|
||||
time_end=self._step_count, window=window,
|
||||
reference_center=self._exchange_centers[level][body_id])
|
||||
|
||||
def download(self):
|
||||
"""Return synchronized G arrays (one per level), NaN on all non-leaves; no host cache."""
|
||||
with self._lock, self.ctx.activate():
|
||||
self._require("ready")
|
||||
arrays = [np.empty(level.shape if level.layout is None else level.layout.blocked_shape,
|
||||
np.float32) for level in self._levels]
|
||||
try:
|
||||
for level, array in zip(self._levels, arrays):
|
||||
cuda.memcpy_dtoh(array, level.current)
|
||||
except BaseException:
|
||||
self._status = "failed"
|
||||
raise
|
||||
arrays = [a if level.layout is None else level.layout.to_dense(a)
|
||||
for a, level in zip(arrays, self._levels)]
|
||||
self._mask_nonleaves(*arrays)
|
||||
return tuple(arrays)
|
||||
|
||||
@@ -268,8 +803,12 @@ class FixedPatchStepper:
|
||||
self._stream.synchronize()
|
||||
except Exception as exc:
|
||||
error = exc
|
||||
for b in getattr(self, "_level_boundaries", ()):
|
||||
if b is not None:
|
||||
b.flags = b.device = b.kernel = None
|
||||
b.last_raw = b.interval_integral = b.accumulate = None
|
||||
self._levels.clear()
|
||||
self._explode = None
|
||||
self._pairs = []
|
||||
if getattr(self, "_fine_curved", None) is not None:
|
||||
try:
|
||||
self._fine_curved.free()
|
||||
@@ -277,6 +816,7 @@ class FixedPatchStepper:
|
||||
error = error or exc
|
||||
self._fine_curved = None
|
||||
self._curved = self._fine_flags = None
|
||||
self._link_tables = {}
|
||||
for pointer in self._allocations:
|
||||
try:
|
||||
pointer.free()
|
||||
@@ -297,6 +837,28 @@ class FixedPatchStepper:
|
||||
if exc[0] is None:
|
||||
raise
|
||||
|
||||
# Read-only compatibility views over the level lists. Internal code must not use them;
|
||||
# REMOVE AFTER the existing tests/docs migrate to hierarchy/_layouts/_level_* lists.
|
||||
patch = property(lambda self: self.hierarchy.pairs[0])
|
||||
child_patch = property(lambda self: self.hierarchy.pairs[1] if self.hierarchy.depth > 2 else None)
|
||||
base_layout = property(lambda self: self._layouts[0])
|
||||
fine_layout = property(lambda self: self._layouts[1])
|
||||
child_layout = property(lambda self: self._layouts[2] if len(self._layouts) > 2 else None)
|
||||
fine_boundary = property(lambda self: self._boundary_hosts[1])
|
||||
child_boundary = property(lambda self: self._boundary_hosts[2] if len(self._boundary_hosts) > 2
|
||||
else None)
|
||||
_jets = property(lambda self: self._level_jets[1])
|
||||
_boundaries = property(lambda self: {i: b for i, b in enumerate(self._level_boundaries) if i})
|
||||
_fine_tables = property(lambda self: None if self._level_boundaries[1] is None
|
||||
else self._level_boundaries[1].tables)
|
||||
_actuated = property(lambda self: self._level_boundaries[1] is not None
|
||||
and self._level_boundaries[1].actuated)
|
||||
_jet_cache = property(lambda self: None if self._level_boundaries[1] is None
|
||||
else self._level_boundaries[1].jet_cache)
|
||||
_fine_leaf = property(lambda self: self._leaf[1])
|
||||
_child_leaf = property(lambda self: self._leaf[2] if len(self._leaf) > 2 else None)
|
||||
_middle_kind = property(lambda self: self.hierarchy.kinds[1] if self.hierarchy.depth > 2 else None)
|
||||
|
||||
|
||||
# Preserve the original entry point and its periodic default.
|
||||
PeriodicPatchStepper = FixedPatchStepper
|
||||
@@ -0,0 +1,107 @@
|
||||
# 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))
|
||||
|
||||
|
||||
# Required device columns plus optional actuation; observation arms are uploaded
|
||||
# separately only when enabled. body_id/aperture remain host reduction metadata.
|
||||
BLOCKED_BOUNDARY_DEVICE_COLUMNS = ("block", "cell", "dir", "q", "fallback", "surface_velocity")
|
||||
|
||||
|
||||
@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
|
||||
last_raw: object = None
|
||||
interval_integral: object = None
|
||||
accumulate: 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)
|
||||
# blocked_link_tables/map_cut_links already rejects repeated (fluid_idx, dir),
|
||||
# independently of body_id, and repeated local writers.
|
||||
tables.update(body_id=np.asarray(body_id, np.int32), rx=np.asarray(rx, np.float32),
|
||||
ry=np.asarray(ry, np.float32), aperture=np.zeros(len(dirs), bool))
|
||||
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"], tables["aperture"] = 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)
|
||||
@@ -0,0 +1,213 @@
|
||||
"""CPU-only whole-volume G transfer, not a runtime adaptive solver.
|
||||
|
||||
Periodic three-level grids with fixed L0/L1 topology are supported, including
|
||||
stationary circles pinned inside unchanged L2 rectangles. The caller
|
||||
certifies that current owned leaves are quiescent,
|
||||
unshifted D2Q9 postcollision G at the supplied completed base interval.
|
||||
No device buffers, device boundary state, ghosts, collision or time advance
|
||||
occur; boundary preparation is host-only.
|
||||
"""
|
||||
from dataclasses import dataclass, replace
|
||||
from numbers import Integral
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .refinement import (ACTIVE, FixedPatch2D, FixedPatchSet2D, FineBoundary2D,
|
||||
nest_patch_set, prepare_fine_boundary)
|
||||
from .descriptors import SOLID
|
||||
from ..body.jets import surface_link_velocity
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class RemapTopology:
|
||||
"""Validated fixed parent and separated L2 set; use ``from_config``.
|
||||
|
||||
Child rectangles are in the parent's allocated L1 coordinates, including
|
||||
its window offset/halo when the parent is a scalar patch. Dense masks are
|
||||
rebuilt from geometry, never inferred from finite values in input arrays.
|
||||
``pinned_rectangles`` canonically lists each body-containing rectangle once;
|
||||
fluid-only layouts have no pins.
|
||||
"""
|
||||
parent: object
|
||||
child: FixedPatchSet2D
|
||||
leaf_masks: tuple
|
||||
boundary: FineBoundary2D | None = None
|
||||
pinned_rectangles: tuple = ()
|
||||
surface_velocity: np.ndarray | None = None
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, cfg, parent, child_rectangles, *, coarse_boundary="periodic", objects=(),
|
||||
child_objects=(), child_jets=()):
|
||||
if coarse_boundary != "periodic" or tuple(objects) or cfg.nz != 1:
|
||||
raise ValueError("remap requires periodic 2D state; use child_objects for a pinned L2 body")
|
||||
if type(parent) not in (FixedPatch2D, FixedPatchSet2D):
|
||||
raise ValueError("parent must be a fixed patch or fixed patch set")
|
||||
parent = type(parent).from_config(cfg, parent.bounds)
|
||||
child, middle_kind = nest_patch_set(cfg, parent, child_rectangles)
|
||||
child_objects, child_jets = tuple(child_objects), tuple(child_jets)
|
||||
fine_cfg = replace(cfg, nx=parent.fine_shape[1], ny=parent.fine_shape[0],
|
||||
viscosity=2 * cfg.viscosity)
|
||||
boundary = prepare_fine_boundary(
|
||||
fine_cfg, child, child_objects, jets=child_jets,
|
||||
parent_origin=parent.fine_origin, parent_spacing=.5)
|
||||
pinned, velocity = (), None
|
||||
child_leaf = child.fine_kind == ACTIVE
|
||||
if boundary is not None:
|
||||
child_leaf &= (boundary.flags.reshape(child.fine_shape) & SOLID) == 0
|
||||
# Whole circle containment, not merely the resolved solid cells.
|
||||
containing = set()
|
||||
for obj in child_objects:
|
||||
cx, cy = (np.asarray(obj.geometry.center) - parent.fine_origin) * 2
|
||||
radius = obj.geometry._radius * 2
|
||||
containing.add(next(r for r in child.bounds if
|
||||
r[0] <= cx-radius and cx+radius <= r[2] and
|
||||
r[1] <= cy-radius and cy+radius <= r[3]))
|
||||
pinned = tuple(sorted(containing))
|
||||
velocity = boundary_velocity(cfg, child, boundary, child_jets)
|
||||
if velocity is not None:
|
||||
velocity.setflags(write=False)
|
||||
masks = (~parent.covered, middle_kind == ACTIVE, child_leaf)
|
||||
for mask in masks:
|
||||
mask.setflags(write=False)
|
||||
return cls(parent, child, masks, boundary, pinned, velocity)
|
||||
|
||||
|
||||
def boundary_velocity(cfg, child, boundary, jets=()):
|
||||
"""Physical cut-link order; never blocked addresses or stale Jet snapshots."""
|
||||
local_cfg = replace(cfg, nx=child.fine_shape[1], ny=child.fine_shape[0],
|
||||
viscosity=4 * cfg.viscosity)
|
||||
local_cfg.validate()
|
||||
fluid, dirs, _, ids, rx, ry, _, _ = boundary.curved_host
|
||||
velocity, _ = surface_link_velocity(
|
||||
boundary.objects, local_cfg, boundary.flags, fluid, dirs, ids, rx, ry,
|
||||
jets=jets, hits=boundary.curved_hits)
|
||||
return velocity
|
||||
|
||||
|
||||
def same_physical_boundary(a, b):
|
||||
"""Compare geometry, ownership, hits and the entire BFL support stencil."""
|
||||
if a is None or b is None:
|
||||
return a is b
|
||||
if not isinstance(a, FineBoundary2D) or not isinstance(b, FineBoundary2D):
|
||||
return False
|
||||
# Exact ordered geometry also catches changes hidden by cut-table rounding.
|
||||
def signatures(boundary):
|
||||
return tuple((o.geometry.center, o.geometry._radius, o.surface_actuation)
|
||||
for o in boundary.objects)
|
||||
if signatures(a) != signatures(b):
|
||||
return False
|
||||
return all(np.array_equal(x, y) for x, y in zip(
|
||||
(a.flags, a.boundary_cells, a.curved_hits, *a.curved_host),
|
||||
(b.flags, b.boundary_cells, b.curved_hits, *b.curved_host)))
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class RemapCandidate:
|
||||
"""Separate dense arrays plus explicit synchronization/frame metadata.
|
||||
|
||||
Passing these arrays to the existing stepper.initialize resets its count;
|
||||
this candidate is deliberately NOT an installed runtime continuation.
|
||||
"""
|
||||
topology: RemapTopology
|
||||
g: tuple
|
||||
base_count: int
|
||||
level_steps: tuple
|
||||
phase: str
|
||||
origin: tuple
|
||||
spacing: float
|
||||
|
||||
|
||||
def _same_parent(a, b):
|
||||
return (type(a) is type(b) and a.bounds == b.bounds
|
||||
and a.coarse_shape == b.coarse_shape
|
||||
and a.tau_coarse == b.tau_coarse and a.tau_fine == b.tau_fine)
|
||||
|
||||
|
||||
def _read_leaves(topology, arrays, layouts):
|
||||
"""Unpack only owned cores; nonleaf values are not evidence of validity."""
|
||||
if len(arrays) != 3 or len(layouts) != 3:
|
||||
raise ValueError("expected three G arrays and three layouts")
|
||||
result = []
|
||||
for a, layout, leaf in zip(arrays, layouts, topology.leaf_masks):
|
||||
if not isinstance(a, np.ndarray) or a.dtype not in (np.dtype('float32'), np.dtype('float64')):
|
||||
raise ValueError("G arrays must be FP32 or FP64 NumPy arrays")
|
||||
if layout is not None:
|
||||
if layout.shape != leaf.shape or not layout.owned[leaf].all():
|
||||
raise ValueError("layout must own every required leaf donor")
|
||||
a = layout.to_dense(a)
|
||||
if a.shape != (9, *leaf.shape):
|
||||
raise ValueError("G must have Q-major (9, ny, nx) shape")
|
||||
values = a[:, leaf]
|
||||
if not np.isfinite(values).all() or (values.sum(axis=0, dtype=np.float64) <= 0).any():
|
||||
raise ValueError("required leaf donors must be finite with positive density")
|
||||
result.append(a)
|
||||
if len({a.dtype for a in result}) != 1:
|
||||
raise ValueError("all levels must use the same population dtype")
|
||||
return result
|
||||
|
||||
|
||||
def remap_synchronized(old, new, old_g, *, base_count, level_steps, phase,
|
||||
origin=(0., 0.), spacing=1., layouts=None):
|
||||
"""Return a non-mutating candidate at the SAME physical time and frame.
|
||||
|
||||
``old``/``new`` are RemapTopology.from_config results. L0/L1 geometry and
|
||||
relaxation parameters must match; only the L2 rectangle set may change.
|
||||
``old_g`` contains current owned-leaf G, dense or (with ``layouts``) blocked.
|
||||
``level_steps`` must equal (base_count, 2*base_count, 4*base_count), and
|
||||
``phase`` must be 'postcollision_g'. These stamps are caller assertions,
|
||||
not proof of device quiescence or active-buffer freshness.
|
||||
|
||||
Preserve same-level leaf overlap bitwise. Copy all nine parent G values
|
||||
to newly refined children; average ALL four old children (including q0)
|
||||
for newly exposed L1. Restriction accumulates in FP64, then rounds once to
|
||||
the source dtype. No equilibrium reconstruction or nonequilibrium scaling.
|
||||
All destination nonleaves are NaN. Inputs and their write flags are intact.
|
||||
"""
|
||||
if (not isinstance(old, RemapTopology) or not isinstance(new, RemapTopology)
|
||||
or not _same_parent(old.parent, new.parent)
|
||||
or old.child.tau_fine != new.child.tau_fine):
|
||||
raise ValueError("remap requires unchanged L0/L1 geometry and relaxation")
|
||||
if (old.pinned_rectangles != new.pinned_rectangles
|
||||
or not same_physical_boundary(old.boundary, new.boundary)
|
||||
or not np.array_equal(old.surface_velocity, new.surface_velocity)):
|
||||
raise ValueError("remap requires the identical pinned body rectangles and physical boundary")
|
||||
if not isinstance(level_steps, (tuple, list)):
|
||||
raise ValueError("level_steps must be three completed integer counts")
|
||||
counts = (base_count, *level_steps)
|
||||
if (len(counts) != 4 or any(isinstance(n, (bool, np.bool_))
|
||||
or not isinstance(n, Integral) or n < 0 for n in counts)
|
||||
or tuple(level_steps) != (base_count, 2*base_count, 4*base_count)
|
||||
or phase != 'postcollision_g'):
|
||||
raise ValueError("requires synchronized completed counts and postcollision_g")
|
||||
try:
|
||||
frame = np.asarray(origin, dtype=np.float64)
|
||||
spacing = float(spacing)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("frame needs a finite (x,y) origin and positive spacing") from None
|
||||
if (frame.shape != (2,) or not np.isfinite(frame).all()
|
||||
or not np.isscalar(spacing) or not np.isfinite(spacing) or spacing <= 0):
|
||||
raise ValueError("frame needs a finite (x,y) origin and positive spacing")
|
||||
source = _read_leaves(old, old_g, (None,)*3 if layouts is None else layouts)
|
||||
candidate = [np.full((9, *mask.shape), np.nan, dtype=source[0].dtype)
|
||||
for mask in new.leaf_masks]
|
||||
for level, (before, after) in enumerate(zip(old.leaf_masks, new.leaf_masks)):
|
||||
overlap = before & after
|
||||
candidate[level][:, overlap] = source[level][:, overlap]
|
||||
|
||||
# A child set uses a level-wide grid in its parent's allocated coordinates.
|
||||
# Thus child (y,x) belongs to parent (y//2,x//2), even for a shifted L1 window.
|
||||
y, x = np.nonzero(new.leaf_masks[2] & ~old.leaf_masks[2])
|
||||
if not old.leaf_masks[1][y//2, x//2].all():
|
||||
raise ValueError("new L2 requires an old owned L1 leaf")
|
||||
candidate[2][:, y, x] = source[1][:, y//2, x//2]
|
||||
|
||||
y, x = np.nonzero(new.leaf_masks[1] & ~old.leaf_masks[1])
|
||||
children = [(2*y+dy, 2*x+dx) for dy in (0, 1) for dx in (0, 1)]
|
||||
if any(not old.leaf_masks[2][cy, cx].all() for cy, cx in children):
|
||||
raise ValueError("reactivated L1 requires all four old owned L2 leaves")
|
||||
# Scale first to avoid an overflowing intermediate sum for finite FP64 G.
|
||||
mean = sum(source[2][:, cy, cx].astype(np.float64) * .25 for cy, cx in children)
|
||||
candidate[1][:, y, x] = mean
|
||||
_read_leaves(new, candidate, (None,)*3)
|
||||
return RemapCandidate(new, tuple(candidate), int(base_count), tuple(map(int, level_steps)),
|
||||
phase, tuple(map(float, frame)), float(spacing))
|
||||
@@ -157,6 +157,33 @@ class Simulation:
|
||||
return -1
|
||||
return self.bodies.add(obj)
|
||||
|
||||
def add_jet(self, jet) -> int:
|
||||
"""Register a body-independent Jet before ``initialize()``; returns its index.
|
||||
|
||||
The jet drives every scene cut link whose true hit point lies in its
|
||||
region (overlaps rejected at initialize). Not checkpointed.
|
||||
"""
|
||||
from .body.jets import Jet
|
||||
if not isinstance(jet, Jet):
|
||||
raise TypeError("add_jet expects a Jet")
|
||||
if self._initialized:
|
||||
raise RuntimeError("Jets must be added before initialize()")
|
||||
self.bodies.jets.append(jet)
|
||||
return len(self.bodies.jets) - 1
|
||||
|
||||
@context_bound
|
||||
def set_jet_amplitude(self, index: int, amplitude: float) -> None:
|
||||
"""Change one jet's signed amplitude; re-uploads per-link velocity only.
|
||||
|
||||
Invalid input changes nothing. A device error leaves the host amplitude
|
||||
unchanged but the device column undefined: treat it like any other CUDA
|
||||
exception here and close/recreate the Simulation before stepping again.
|
||||
"""
|
||||
jet = self.bodies.jets[index].with_amplitude(amplitude)
|
||||
if self._initialized:
|
||||
self.field.curved.set_jet_amplitude(index, amplitude, self.stream)
|
||||
self.bodies.jets[index] = jet # later geometry syncs keep the new amplitude
|
||||
|
||||
def remove_body(self, id: int) -> None:
|
||||
"""Remove a body from the simulation.
|
||||
|
||||
@@ -238,6 +265,7 @@ class Simulation:
|
||||
proposed.update({k: float(v) for k, v in (("omega", omega), ("vx", vx), ("vy", vy))
|
||||
if v is not None})
|
||||
obj.validate_surface_actuation(self.lbm_cfg, proposed)
|
||||
self.bodies.validate_jet_motion(id, proposed)
|
||||
changed = False
|
||||
if omega is not None:
|
||||
obj.state.omega = float(omega)
|
||||
@@ -433,6 +461,8 @@ class Simulation:
|
||||
self.field.flag = self.bodies.build_flags(self.field.flag)
|
||||
self.field.upload_flags()
|
||||
|
||||
if self.bodies.jets and self.bodies.count == 0:
|
||||
raise ValueError("Jets need bodies with cut links")
|
||||
self.stepper.initialize()
|
||||
if self.bodies.count > 0:
|
||||
self.bodies.sync_to_gpu(self.field, rebuild_flags=False)
|
||||
@@ -644,6 +674,8 @@ class Simulation:
|
||||
def save_checkpoint(self, path: str = None):
|
||||
"""Save full simulation state to an HDF5 file."""
|
||||
from .common.checkpoint import save_checkpoint
|
||||
if self.bodies.jets:
|
||||
raise NotImplementedError("Jets are not checkpointed yet")
|
||||
return save_checkpoint(self.field, self.stepper, self.lbm_cfg,
|
||||
self.bodies, path)
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""CelerisLab test package; keeps shared test helpers independent of discovery paths."""
|
||||
@@ -0,0 +1,457 @@
|
||||
"""CPU block layout contracts: ownership, halo pairs, packing and tagged pull."""
|
||||
import sys
|
||||
import unittest
|
||||
from unittest import mock
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from CelerisLab.body.geometry.base import CutLink
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.lbm.blocks import CORNER, FACE, NO_DONOR, NQ, BlockLayout2D, blocked_link_tables
|
||||
from CelerisLab.lbm.descriptors import D2Q9_EX, D2Q9_EY
|
||||
|
||||
CASES = ( # (ny, nx, by, bx, halo)
|
||||
(6, 8, 3, 4, 1), # 2x2 split
|
||||
(6, 12, 3, 4, 1), # 2x3 split
|
||||
(8, 8, 4, 4, 2), # wider halo
|
||||
(4, 8, 4, 4, 1), # one block along y
|
||||
)
|
||||
PERIODIC = ((True, True), (False, False), (True, False), (False, True))
|
||||
|
||||
|
||||
def tags(ny, nx):
|
||||
"""Unique, exactly representable value per dense population slot."""
|
||||
return np.arange(NQ * ny * nx, dtype=np.float64).reshape(NQ, ny, nx)
|
||||
|
||||
|
||||
def dense_pull(a, periodic):
|
||||
"""f[q](x) = a[q](x - c_q); NaN where a non-periodic exterior is crossed."""
|
||||
px, py = periodic
|
||||
_, ny, nx = a.shape
|
||||
gy, gx = np.mgrid[0:ny, 0:nx]
|
||||
out = np.empty_like(a)
|
||||
for q in range(NQ):
|
||||
sy, sx = gy - D2Q9_EY[q], gx - D2Q9_EX[q]
|
||||
valid = ((py | ((sy >= 0) & (sy < ny))) & (px | ((sx >= 0) & (sx < nx))))
|
||||
out[q] = np.where(valid, a[q, sy % ny, sx % nx], np.nan)
|
||||
return out
|
||||
|
||||
|
||||
def blocked_pull(layout, blocked):
|
||||
"""Exchange, then pull every core cell from its own block storage only."""
|
||||
layout.exchange(blocked)
|
||||
return blocked_pull_core(layout, blocked)
|
||||
|
||||
|
||||
def blocked_pull_core(layout, blocked):
|
||||
"""Pull core cells with no halo copy (a copy would undo BFL halo writes)."""
|
||||
out = np.full_like(blocked, np.nan)
|
||||
(by, bx), h = layout.block, layout.halo
|
||||
for q in range(NQ):
|
||||
ey, ex = D2Q9_EY[q], D2Q9_EX[q]
|
||||
out[:, q, h:h + by, h:h + bx] = blocked[:, q, h - ey:h - ey + by, h - ex:h - ex + bx]
|
||||
return out
|
||||
|
||||
|
||||
def opp(q):
|
||||
return q + 1 if q % 2 else q - 1
|
||||
|
||||
|
||||
def reflect(q, toward, other):
|
||||
"""Static linear Bouzidi stand-in; equivalence holds for any read->write map."""
|
||||
if q < .5:
|
||||
return 2 * q * toward + (1 - 2 * q) * other
|
||||
return toward / (2 * q) + (2 * q - 1) / (2 * q) * other
|
||||
|
||||
|
||||
def dense_bfl(a, links):
|
||||
out = a.copy()
|
||||
_, ny, nx = a.shape
|
||||
for link in links:
|
||||
y, x = divmod(link.fluid_idx, nx)
|
||||
q, d = link.q, link.dir
|
||||
if q < .5 and link.fallback == 0:
|
||||
other = a[d, (y - D2Q9_EY[d]) % ny, (x - D2Q9_EX[d]) % nx]
|
||||
elif q < .5:
|
||||
other = 0.0
|
||||
else:
|
||||
other = a[opp(d), y, x]
|
||||
out[opp(d), (y + D2Q9_EY[d]) % ny, (x + D2Q9_EX[d]) % nx] = reflect(q, a[d, y, x], other)
|
||||
return out
|
||||
|
||||
|
||||
def blocked_bfl(layout, blocked, links, mapped):
|
||||
"""Reads and writes only the receiver block's storage; no exchange inside."""
|
||||
flat = blocked.ravel()
|
||||
source = flat.copy()
|
||||
for link, receiver, donor, write in zip(links, mapped.receiver, mapped.donor, mapped.write):
|
||||
q, d = link.q, link.dir
|
||||
toward = source[int(layout.slot(receiver, d))]
|
||||
if donor != NO_DONOR:
|
||||
other = source[int(layout.slot(donor, d))]
|
||||
elif q < .5:
|
||||
other = 0.0
|
||||
else:
|
||||
other = source[int(layout.slot(receiver, opp(d)))]
|
||||
flat[int(write)] = reflect(q, toward, other)
|
||||
|
||||
|
||||
def seam_circle(n=16):
|
||||
"""Circle on the shared corner of a 2x2 split (integer-node frame)."""
|
||||
geometry = CircleGeometry(n / 2 - .5, n / 2 - .5, 3.3)
|
||||
links = geometry.build_cut_links(n, n)
|
||||
gy, gx = np.mgrid[0:n, 0:n]
|
||||
solid = (gx - (n / 2 - .5)) ** 2 + (gy - (n / 2 - .5)) ** 2 < 3.3 ** 2
|
||||
return links, solid
|
||||
|
||||
|
||||
class BlockLayoutTests(unittest.TestCase):
|
||||
def test_cpu_import_boundary(self):
|
||||
self.assertFalse(any(name == "pycuda" or name.startswith("pycuda.") for name in sys.modules))
|
||||
|
||||
def test_origins_and_unique_core_ownership(self):
|
||||
layout = BlockLayout2D.build(6, 8, 3, 4)
|
||||
np.testing.assert_array_equal(layout.origins, [[0, 0], [0, 4], [3, 0], [3, 4]])
|
||||
self.assertEqual(layout.blocked_shape, (4, NQ, 5, 6))
|
||||
for ny, nx, by, bx, h in CASES:
|
||||
layout = BlockLayout2D.build(ny, nx, by, bx, halo=h)
|
||||
ly, lx = layout.local_shape
|
||||
core = [b * ly * lx + (y + h) * lx + x + h
|
||||
for b in range(layout.nblocks) for y in range(by) for x in range(bx)]
|
||||
self.assertEqual(sorted(layout.owner.ravel().tolist()), sorted(core))
|
||||
for y in range(ny):
|
||||
for x in range(nx):
|
||||
b = (y // by) * (nx // bx) + x // bx
|
||||
self.assertEqual(layout.block_cell(b, y, x), layout.owner[y, x])
|
||||
|
||||
def test_halo_pairs_are_owner_core_to_unique_halo(self):
|
||||
for ny, nx, by, bx, h in CASES:
|
||||
for periodic in PERIODIC:
|
||||
layout = BlockLayout2D.build(ny, nx, by, bx, halo=h, periodic=periodic)
|
||||
core = set(layout.owner.ravel().tolist())
|
||||
dst = layout.halo_dst.tolist()
|
||||
self.assertEqual(dst, sorted(dst))
|
||||
self.assertEqual(len(dst), len(set(dst)))
|
||||
self.assertTrue(core.isdisjoint(dst))
|
||||
self.assertTrue(set(layout.halo_src.tolist()) <= core)
|
||||
self.assertTrue(set(layout.halo_kind.tolist()) <= {FACE, CORNER})
|
||||
full = BlockLayout2D.build(6, 8, 3, 4)
|
||||
per_block = np.bincount(full.halo_kind, minlength=2) // full.nblocks
|
||||
np.testing.assert_array_equal(per_block, [2 * (3 + 4), 4])
|
||||
closed = BlockLayout2D.build(6, 8, 3, 4, periodic=(False, False))
|
||||
# Each 2x2 block keeps one inner face column, one face row and one corner.
|
||||
self.assertEqual(len(closed.halo_dst), 4 * (3 + 4 + 1))
|
||||
|
||||
def test_pack_round_trip_and_exterior_stays_invalid(self):
|
||||
for ny, nx, by, bx, h in CASES:
|
||||
for periodic in PERIODIC:
|
||||
layout = BlockLayout2D.build(ny, nx, by, bx, halo=h, periodic=periodic)
|
||||
a = tags(ny, nx)
|
||||
blocked = layout.to_blocked(a)
|
||||
np.testing.assert_array_equal(layout.to_dense(blocked), a)
|
||||
filled = np.isfinite(blocked[:, 0]).sum()
|
||||
self.assertEqual(filled, ny * nx + len(layout.halo_dst))
|
||||
flat = blocked.ravel()
|
||||
for q in (0, 5):
|
||||
np.testing.assert_array_equal(flat[layout.slot(layout.halo_dst, q).astype(np.intp)],
|
||||
flat[layout.slot(layout.halo_src, q).astype(np.intp)])
|
||||
|
||||
def test_tagged_pull_matches_dense_pull(self):
|
||||
for ny, nx, by, bx, h in CASES:
|
||||
for periodic in PERIODIC:
|
||||
with self.subTest(case=(ny, nx, by, bx, h), periodic=periodic):
|
||||
layout = BlockLayout2D.build(ny, nx, by, bx, halo=h, periodic=periodic)
|
||||
a = tags(ny, nx)
|
||||
got = layout.to_dense(blocked_pull(layout, layout.to_blocked(a)))
|
||||
np.testing.assert_array_equal(got, dense_pull(a, periodic))
|
||||
|
||||
def test_block_cell_resolves_periodic_halo_images(self):
|
||||
layout = BlockLayout2D.build(6, 8, 3, 4)
|
||||
ly, lx = layout.local_shape
|
||||
# Block 0 sees x=7 (wrapped) in its west halo and y=5 in its south halo.
|
||||
self.assertEqual(layout.block_cell(0, 0, 7), 1 * lx + 0)
|
||||
self.assertEqual(layout.block_cell(0, 5, 0), 0 * lx + 1)
|
||||
closed = BlockLayout2D.build(6, 8, 3, 4, periodic=(False, False))
|
||||
with self.assertRaises(ValueError):
|
||||
closed.block_cell(0, 0, 7)
|
||||
with self.assertRaises(ValueError):
|
||||
layout.block_cell(0, 4, 0) # two rows past the one-cell halo
|
||||
|
||||
def test_invalid_inputs_rejected(self):
|
||||
for args, kw in (((6, 8, 4, 4), {}), ((6, 8, 3, 4), {"halo": 0}),
|
||||
((6, 8, 3, 4), {"halo": 4}), ((6, 8, 3, 4), {"periodic": (1, 1)}),
|
||||
((6, 8, 3, True), {}), ((6, 8.0, 3, 4), {})):
|
||||
with self.assertRaises(ValueError):
|
||||
BlockLayout2D.build(*args, **kw)
|
||||
layout = BlockLayout2D.build(6, 8, 3, 4)
|
||||
with self.assertRaises(ValueError):
|
||||
layout.to_blocked(np.zeros((NQ, 6, 8), dtype=np.int64))
|
||||
with self.assertRaises(ValueError):
|
||||
layout.to_dense(np.zeros((4, NQ, 5, 5)))
|
||||
|
||||
def test_cut_links_are_receiver_local_and_unique(self):
|
||||
links, _ = seam_circle()
|
||||
for periodic in ((True, True), (False, False)):
|
||||
layout = BlockLayout2D.build(16, 16, 8, 8, periodic=periodic)
|
||||
mapped = layout.map_cut_links(links)
|
||||
self.assertEqual(len(mapped.write), len(links)) # one row, one force per link
|
||||
self.assertEqual(len(set(mapped.write.tolist())), len(links))
|
||||
self.assertEqual(len(set(mapped.block.tolist())), 4) # seams are crossed
|
||||
cells = int(np.prod(layout.local_shape))
|
||||
core = set(layout.owner.ravel().tolist())
|
||||
a = tags(16, 16)
|
||||
flat = layout.to_blocked(a).ravel()
|
||||
halo_reads = 0
|
||||
for link, b, r, d, w in zip(links, mapped.block, mapped.receiver,
|
||||
mapped.donor, mapped.write):
|
||||
y, x = divmod(link.fluid_idx, 16)
|
||||
self.assertEqual(r, layout.owner[y, x])
|
||||
self.assertEqual(int(r) // cells, b)
|
||||
self.assertEqual(int(w) // (NQ * cells), b)
|
||||
sy, sx = y + D2Q9_EY[link.dir], x + D2Q9_EX[link.dir]
|
||||
self.assertEqual(flat[int(w)], a[opp(link.dir), sy, sx])
|
||||
if d != NO_DONOR:
|
||||
self.assertEqual(int(d) // cells, b)
|
||||
self.assertEqual(flat[int(layout.slot(d, link.dir))],
|
||||
a[link.dir, y - D2Q9_EY[link.dir], x - D2Q9_EX[link.dir]])
|
||||
halo_reads += int(d) not in core
|
||||
self.assertGreater(halo_reads, 0) # some q<.5 donors come from a neighbor's core
|
||||
|
||||
def test_static_bfl_pull_matches_dense_on_fluid_cells(self):
|
||||
links, solid = seam_circle()
|
||||
a = tags(16, 16) / 7.0
|
||||
expected = dense_pull(dense_bfl(a, links), (True, True))
|
||||
layout = BlockLayout2D.build(16, 16, 8, 8)
|
||||
blocked = layout.to_blocked(a) # gather halos
|
||||
blocked_bfl(layout, blocked, links, layout.map_cut_links(links))
|
||||
got = layout.to_dense(blocked_pull_core(layout, blocked))
|
||||
np.testing.assert_array_equal(got[:, ~solid], expected[:, ~solid])
|
||||
|
||||
def test_periodic_seam_links_follow_the_pulled_halo_image(self):
|
||||
# Receivers on x=0 / x=nx-1 / a corner whose sources wrap physically.
|
||||
links = [CutLink(fluid_idx=1 * 6 + 0, dir=2, q=.6, body_id=0),
|
||||
CutLink(fluid_idx=2 * 6 + 0, dir=2, q=.3, body_id=0),
|
||||
CutLink(fluid_idx=3 * 6 + 5, dir=1, q=.3, body_id=0),
|
||||
CutLink(fluid_idx=0 * 6 + 0, dir=6, q=.4, body_id=0)]
|
||||
sources = np.zeros((8, 6), dtype=bool)
|
||||
for y, x in ((1, 5), (2, 5), (3, 0), (7, 5)):
|
||||
sources[y, x] = True
|
||||
a = tags(8, 6) / 7.0
|
||||
expected = dense_pull(dense_bfl(a, links), (True, True))
|
||||
# One block along x, along y, along both (periodic self-images).
|
||||
for by, bx in ((4, 6), (8, 3), (8, 6)):
|
||||
with self.subTest(block=(by, bx)):
|
||||
layout = BlockLayout2D.build(8, 6, by, bx)
|
||||
mapped = layout.map_cut_links(links)
|
||||
blocked = layout.to_blocked(a)
|
||||
blocked_bfl(layout, blocked, links, mapped)
|
||||
got = layout.to_dense(blocked_pull_core(layout, blocked))
|
||||
np.testing.assert_array_equal(got[:, ~sources], expected[:, ~sources])
|
||||
|
||||
def test_cut_link_rejections(self):
|
||||
layout = BlockLayout2D.build(16, 16, 8, 8, periodic=(False, False))
|
||||
link = CutLink(fluid_idx=5 * 16 + 5, dir=1, q=.6, body_id=0)
|
||||
with self.assertRaises(ValueError):
|
||||
layout.map_cut_links([link, link])
|
||||
with self.assertRaises(ValueError):
|
||||
layout.map_cut_links([CutLink(fluid_idx=15, dir=1, q=.6, body_id=0)])
|
||||
with self.assertRaises(ValueError):
|
||||
layout.map_cut_links([CutLink(fluid_idx=5 * 16 + 5, dir=0, q=.6, body_id=0)])
|
||||
|
||||
def test_public_indices_are_rejected_not_truncated(self):
|
||||
layout = BlockLayout2D.build(4, 8, 4, 8) # one block, nx=8, ny=4
|
||||
for args in ((-1, 0, 0), (1, 0, 0), (True, 0, 0), (0.0, 0, 0), (0, 0.5, 0),
|
||||
(0, 1, 2.0), (0, -1, 0), (0, 4, 0), (0, 0, 8), (0, False, 0)):
|
||||
with self.subTest(block_cell=args), self.assertRaises(ValueError):
|
||||
layout.block_cell(*args)
|
||||
cells = int(np.prod(layout.local_shape))
|
||||
for args in ((-1, 1), (cells, 1), (True, 1), (1.0, 1), (0, NQ), (0, -1), (0, 1.0),
|
||||
(0, True), (np.array([0, cells]), 1)):
|
||||
with self.subTest(slot=args), self.assertRaises(ValueError):
|
||||
layout.slot(*args)
|
||||
for idx, d in ((5.7, 1), (True, 1), (-1, 1), (32, 1), (5, 1.0), (5, 9), (5, True), (5, 0)):
|
||||
with self.subTest(fluid_idx=idx, dir=d), self.assertRaises(ValueError):
|
||||
layout.map_cut_links([CutLink(fluid_idx=idx, dir=d, q=.6, body_id=0)])
|
||||
|
||||
def test_one_block_seam_reproducer(self):
|
||||
# Receiver (2,0) -x wraps to x=7; the write must land in the west halo.
|
||||
layout = BlockLayout2D.build(4, 8, 4, 8)
|
||||
mapped = layout.map_cut_links([CutLink(fluid_idx=2 * 8, dir=2, q=.6, body_id=0)])
|
||||
lx = layout.local_shape[1]
|
||||
self.assertEqual(int(mapped.write[0]), int(layout.slot(3 * lx + 0, 1)))
|
||||
|
||||
def test_capacity_rejected_before_allocation(self):
|
||||
fail = AssertionError("grid-sized allocation before the capacity check")
|
||||
with mock.patch.object(np, "arange", side_effect=fail):
|
||||
with self.assertRaises(ValueError):
|
||||
BlockLayout2D.build(2 ** 30, 2 ** 30, 1, 1)
|
||||
|
||||
def test_tables_are_readonly(self):
|
||||
layout = BlockLayout2D.build(6, 8, 3, 4)
|
||||
for array in (layout.origins, layout.owner, layout.halo_dst, layout.halo_src, layout.halo_kind):
|
||||
self.assertFalse(array.flags.writeable)
|
||||
|
||||
|
||||
def all_origins(ny, nx, by, bx):
|
||||
return [(y, x) for y in range(0, ny, by) for x in range(0, nx, bx)]
|
||||
|
||||
|
||||
def link(y, x, d, q, nx=12, fallback=0):
|
||||
return SimpleNamespace(fluid_idx=y * nx + x, dir=d, q=q, fallback=fallback)
|
||||
|
||||
|
||||
# 6x12 grid of 3x4 blocks (2x3 block grid); stored L: (0,0), (0,4), (3,4).
|
||||
L_ORIGINS = [(0, 0), (0, 4), (3, 4)]
|
||||
SPARSE = ( # (ny, nx, by, bx, halo, origins)
|
||||
(6, 12, 3, 4, 1, L_ORIGINS),
|
||||
(6, 12, 3, 4, 1, [(3, 8)]), # N=1 corner block
|
||||
(8, 8, 4, 4, 2, [(0, 4), (4, 0)]), # diagonal pair, wider halo
|
||||
(6, 8, 3, 4, 1, [(0, 0), (0, 4), (3, 0)]), # missing one of 2x2
|
||||
)
|
||||
|
||||
|
||||
class SparseBlockLayoutTests(unittest.TestCase):
|
||||
"""Explicit selected block origins: absent blocks are holes, not wrapped -1."""
|
||||
|
||||
def test_all_origins_reproduce_full_layout(self):
|
||||
for ny, nx, by, bx, h in CASES + ((4, 8, 4, 8, 1),): # last: N=1 full grid
|
||||
for periodic in PERIODIC:
|
||||
with self.subTest(case=(ny, nx, by, bx, h), periodic=periodic):
|
||||
full = BlockLayout2D.build(ny, nx, by, bx, halo=h, periodic=periodic)
|
||||
explicit = BlockLayout2D.build(ny, nx, by, bx, halo=h, periodic=periodic,
|
||||
origins=all_origins(ny, nx, by, bx))
|
||||
for name in ("origins", "owner", "halo_dst", "halo_src", "halo_kind"):
|
||||
np.testing.assert_array_equal(getattr(explicit, name), getattr(full, name))
|
||||
self.assertEqual(getattr(explicit, name).dtype, getattr(full, name).dtype)
|
||||
self.assertTrue(full.owned.all())
|
||||
self.assertEqual(explicit.hole, full.hole)
|
||||
|
||||
def test_holes_and_ownership(self):
|
||||
layout = BlockLayout2D.build(6, 12, 3, 4, periodic=(False, False), origins=L_ORIGINS)
|
||||
np.testing.assert_array_equal(layout.origins, L_ORIGINS)
|
||||
self.assertEqual(layout.nblocks, 3)
|
||||
cells = int(np.prod(layout.local_shape))
|
||||
self.assertEqual(layout.hole, 3 * cells)
|
||||
expected = np.zeros((6, 12), dtype=bool)
|
||||
expected[0:3, 0:8] = expected[3:6, 4:8] = True
|
||||
np.testing.assert_array_equal(layout.owned, expected)
|
||||
self.assertTrue((layout.owner[~expected] == layout.hole).all())
|
||||
for b, (y0, x0) in enumerate(L_ORIGINS):
|
||||
for y in range(y0, y0 + 3):
|
||||
for x in range(x0, x0 + 4):
|
||||
self.assertEqual(layout.block_cell(b, y, x), layout.owner[y, x])
|
||||
owned = layout.owner[expected].tolist()
|
||||
self.assertEqual(len(owned), len(set(owned)))
|
||||
with self.assertRaises(ValueError): # the hole value is never a valid slot
|
||||
layout.slot(layout.hole, 0)
|
||||
|
||||
def test_halo_pairs_skip_absent_blocks(self):
|
||||
layout = BlockLayout2D.build(6, 12, 3, 4, periodic=(False, False), origins=L_ORIGINS)
|
||||
# Block 0: 3 east faces + SE corner; block 1: 3 west + 4 south faces;
|
||||
# block 2: 4 north faces + NW corner. Nothing reads (3..5, 0..3) or x>=8.
|
||||
self.assertEqual(len(layout.halo_dst), 16)
|
||||
np.testing.assert_array_equal(np.bincount(layout.halo_kind, minlength=2), [14, 2])
|
||||
for ny, nx, by, bx, h, origins in SPARSE:
|
||||
for periodic in PERIODIC:
|
||||
with self.subTest(origins=origins, periodic=periodic):
|
||||
layout = BlockLayout2D.build(ny, nx, by, bx, halo=h, periodic=periodic,
|
||||
origins=origins)
|
||||
core = set(layout.owner[layout.owned].tolist())
|
||||
dst = layout.halo_dst.tolist()
|
||||
self.assertEqual(dst, sorted(dst))
|
||||
self.assertEqual(len(dst), len(set(dst)))
|
||||
self.assertTrue(core.isdisjoint(dst))
|
||||
self.assertTrue(set(layout.halo_src.tolist()) <= core)
|
||||
self.assertLess(max(dst + [-1]), layout.hole)
|
||||
|
||||
def test_pack_unpack_and_pull_with_holes(self):
|
||||
for ny, nx, by, bx, h, origins in SPARSE:
|
||||
for periodic in PERIODIC:
|
||||
with self.subTest(origins=origins, periodic=periodic):
|
||||
layout = BlockLayout2D.build(ny, nx, by, bx, halo=h, periodic=periodic,
|
||||
origins=origins)
|
||||
owned = layout.owned
|
||||
a = tags(ny, nx)
|
||||
holed = a.copy()
|
||||
holed[:, ~owned] = np.nan
|
||||
blocked = layout.to_blocked(a)
|
||||
np.testing.assert_array_equal(layout.to_dense(blocked), holed)
|
||||
poisoned = a.copy()
|
||||
poisoned[:, ~owned] = np.inf # hole values are ignored by packing
|
||||
np.testing.assert_array_equal(layout.to_blocked(poisoned), blocked)
|
||||
self.assertEqual(np.isfinite(blocked[:, 0]).sum(),
|
||||
owned.sum() + len(layout.halo_dst))
|
||||
expected = dense_pull(holed, periodic)
|
||||
expected[:, ~owned] = np.nan
|
||||
got = layout.to_dense(blocked_pull(layout, blocked))
|
||||
np.testing.assert_array_equal(got, expected)
|
||||
|
||||
def test_cut_links_in_or_next_to_absent_blocks_are_rejected(self):
|
||||
layout = BlockLayout2D.build(6, 12, 3, 4, periodic=(False, False), origins=L_ORIGINS)
|
||||
ok = [link(1, 1, 3, .6), link(1, 7, 2, .6), link(1, 4, 2, .3)]
|
||||
mapped = layout.map_cut_links(ok) # fully owned stencils, incl. across a seam
|
||||
cells = int(np.prod(layout.local_shape))
|
||||
np.testing.assert_array_equal(mapped.block, [0, 1, 1])
|
||||
np.testing.assert_array_equal(mapped.receiver, [layout.owner[1, 1], layout.owner[1, 7],
|
||||
layout.owner[1, 4]])
|
||||
self.assertEqual(int(mapped.donor[2]), int(layout.owner[1, 5]))
|
||||
# Same physical link with q<.5 is mapped separately (repeats are rejected).
|
||||
donor = layout.map_cut_links([link(1, 1, 3, .3)]).donor
|
||||
self.assertEqual(int(donor[0]), int(layout.owner[0, 1]))
|
||||
self.assertTrue((mapped.write < np.uint64(layout.nblocks * NQ * cells)).all())
|
||||
for bad in (link(4, 1, 1, .6), # receiver in an absent block
|
||||
link(2, 1, 3, .6), # solid neighbor (3,1) absent
|
||||
link(1, 7, 2, .3), # q<.5 donor (1,8) absent
|
||||
link(2, 7, 1, .6)): # solid neighbor (2,8) absent
|
||||
with self.subTest(fluid=bad.fluid_idx, dir=bad.dir, q=bad.q):
|
||||
with self.assertRaises(ValueError):
|
||||
layout.map_cut_links([bad])
|
||||
|
||||
def test_link_tables_store_owned_flags_only(self):
|
||||
layout = BlockLayout2D.build(6, 12, 3, 4, periodic=(False, False), origins=L_ORIGINS)
|
||||
flags = np.arange(1, 6 * 12 + 1, dtype=np.uint16)
|
||||
tables, _ = blocked_link_tables(layout, flags, [], [], [], [])
|
||||
owned = layout.owned.ravel()
|
||||
stored = tables["flags"]
|
||||
self.assertEqual(stored.shape, (layout.hole,))
|
||||
np.testing.assert_array_equal(stored[layout.owner.ravel()[owned].astype(np.intp)], flags[owned])
|
||||
self.assertEqual(np.count_nonzero(stored), owned.sum())
|
||||
|
||||
def test_caller_origins_are_copied(self):
|
||||
origins = np.array([[0, 0], [0, 4]], dtype=np.int64)
|
||||
layout = BlockLayout2D.build(6, 8, 3, 4, origins=origins)
|
||||
owner, address = layout.owner.copy(), layout.block_cell(0, 0, 0)
|
||||
self.assertTrue(origins.flags.writeable) # caller array is not frozen
|
||||
origins[0] = [3, 0]
|
||||
np.testing.assert_array_equal(layout.origins, [[0, 0], [0, 4]])
|
||||
np.testing.assert_array_equal(layout.owner, owner)
|
||||
self.assertEqual(layout.block_cell(0, 0, 0), address)
|
||||
self.assertEqual(address, layout.owner[0, 0])
|
||||
|
||||
def test_to_dense_dtype_contract(self):
|
||||
full = BlockLayout2D.build(6, 8, 3, 4)
|
||||
blocked = np.arange(np.prod(full.blocked_shape), dtype=np.int64).reshape(full.blocked_shape)
|
||||
dense = full.to_dense(blocked) # legacy: full layouts keep any dtype
|
||||
self.assertEqual(dense.dtype, np.int64)
|
||||
np.testing.assert_array_equal(dense, full.to_dense(blocked.astype(np.float64)))
|
||||
sparse = BlockLayout2D.build(6, 8, 3, 4, origins=[(0, 0), (3, 4)])
|
||||
for dtype in (np.int64, np.uint16, np.bool_):
|
||||
with self.subTest(dtype=dtype), self.assertRaises(ValueError):
|
||||
sparse.to_dense(np.zeros(sparse.blocked_shape, dtype=dtype))
|
||||
self.assertEqual(sparse.to_dense(np.zeros(sparse.blocked_shape, np.float32)).dtype, np.float32)
|
||||
|
||||
def test_invalid_origins_rejected(self):
|
||||
for origins in ([(0, 4), (0, 0)], # not row-major
|
||||
[(3, 0), (0, 4)], # not row-major across rows
|
||||
[(0, 0), (0, 0)], # repeated
|
||||
[(1, 0)], [(0, 2)], # misaligned
|
||||
[(6, 0)], [(0, 12)], [(-3, 0)], [(0, -4)], # outside
|
||||
np.zeros((0, 2), dtype=np.int64), # empty
|
||||
[(0.0, 0.0)], [(True, False)], [0, 0], [(0, 0, 0)]):
|
||||
with self.subTest(origins=origins), self.assertRaises(ValueError):
|
||||
BlockLayout2D.build(6, 12, 3, 4, origins=origins)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -213,3 +213,21 @@ def test_fine_rejects_ghost_solids_unresolved_circle_and_overlap(objects):
|
||||
cfg, patch = setup_patch()
|
||||
with pytest.raises(ValueError):
|
||||
refinement.prepare_fine_boundary(cfg, patch, objects)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('margin, ok', [(4, True), (3, False)])
|
||||
def test_fine_wall_guard_allows_read_only_bulk_donor_rows(margin, ok):
|
||||
cfg = LBMConfig(nx=24, ny=24, viscosity=.05)
|
||||
cfg.validate()
|
||||
patch = FixedPatch2D.from_config(cfg, (4, margin, 20, 24-margin))
|
||||
_, coarse, _ = refinement._transfer_footprint(patch)
|
||||
rows = {k // cfg.nx for k in coarse}
|
||||
assert min(rows) == margin-2 and max(rows) == cfg.ny-margin+1
|
||||
source = circle(center=(12.25, 12.25))
|
||||
# Footprint never violates the plain bulk-cell checks; only the wall rule differs.
|
||||
refinement.prepare_fine_boundary(cfg, patch, [source])
|
||||
if ok:
|
||||
refinement.prepare_fine_boundary(cfg, patch, [source], wall_aware=True)
|
||||
else:
|
||||
with pytest.raises(ValueError, match='wall reconstruction'):
|
||||
refinement.prepare_fine_boundary(cfg, patch, [source], wall_aware=True)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""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())
|
||||
walled = build_hierarchy(SMALL, [], wall_aware=True) # regression: no refinement
|
||||
self.assertTrue((walled.kinds[0][[0, -1]] == r.OUTER_GHOST).all())
|
||||
self.assertTrue((walled.kinds[0][1:-1] == r.ACTIVE).all())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Jet boundary-condition hook: velocity implemented, pressure reserved (host only, no CUDA)."""
|
||||
import pytest
|
||||
|
||||
from CelerisLab.body.jets import Jet, Parallel, Tube
|
||||
|
||||
|
||||
def region():
|
||||
return Tube((16., 12.), 0., 3., .7)
|
||||
|
||||
|
||||
def test_default_is_velocity_and_survives_amplitude_change():
|
||||
jet = Jet(region(), Parallel(0.), amplitude=.01)
|
||||
assert jet.condition == "velocity"
|
||||
assert jet.with_amplitude(-.02).condition == "velocity"
|
||||
# positional calls keep their meaning; condition is the new last field
|
||||
assert (Jet(region(), Parallel(0.), "parabolic", .01, "velocity")
|
||||
== Jet(region(), Parallel(0.), "parabolic", .01))
|
||||
|
||||
|
||||
def test_pressure_is_rejected_before_amplitude_validation():
|
||||
# An amplitude that the velocity check would reject must not decide the error.
|
||||
for amplitude in (0., 5., float("nan")):
|
||||
with pytest.raises(NotImplementedError, match="pressure jets are reserved"):
|
||||
Jet(region(), Parallel(0.), amplitude=amplitude, condition="pressure")
|
||||
with pytest.raises(NotImplementedError):
|
||||
Jet(region(), None, profile="no-such-profile", condition="pressure")
|
||||
|
||||
|
||||
def test_unknown_condition_is_a_value_error():
|
||||
for condition in ("Velocity", "flow_rate", "", None):
|
||||
with pytest.raises(ValueError, match="condition"):
|
||||
Jet(region(), Parallel(0.), amplitude=.01, condition=condition)
|
||||
@@ -0,0 +1,375 @@
|
||||
"""Body-independent Jet: true-hit spatial selection, fields, profiles, overlap, amplitude."""
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from CelerisLab.body.jets import (Jet, Parallel, Radial, Sector, Tube,
|
||||
edge_to_node_frame, fine_hits_to_edge_frame,
|
||||
jet_link_shapes)
|
||||
from CelerisLab.body.objects import SurfaceActuation
|
||||
from CelerisLab.lbm.curved_links import CurvedLinkSoA, surface_link_velocity
|
||||
from .test_state_regressions import device, make_field, manager
|
||||
from .test_surface_actuation import circle, projected
|
||||
|
||||
CENTER, RADIUS = (6., 5.), 2.999
|
||||
|
||||
|
||||
def scene(spec=None):
|
||||
"""Single circle links plus their true FP64 hits, row-aligned with the SoA."""
|
||||
obj = circle(spec)
|
||||
cl, cfg, flags = projected(obj)
|
||||
links = obj.geometry.build_cut_links(cfg.nx, cfg.ny, domain_flags=flags)
|
||||
hits = np.array([(link.hit_x, link.hit_y) for link in links])
|
||||
assert len(hits) == len(cl.dir)
|
||||
return obj, cl, cfg, flags, hits
|
||||
|
||||
|
||||
def arc(hits, angle, half_width):
|
||||
d = hits - CENTER
|
||||
delta = np.angle(np.exp(1j*(np.arctan2(d[:, 1], d[:, 0]) - angle)))
|
||||
return np.abs(delta) < half_width
|
||||
|
||||
|
||||
def test_concentric_sector_gives_inward_radial_and_tube_parallel_on_same_links():
|
||||
*_, hits = scene()
|
||||
half = math.radians(10)
|
||||
expected = arc(hits, 0., half)
|
||||
assert expected.sum() >= 2
|
||||
sector = Jet(Sector(CENTER, 0., half, RADIUS + .1), Radial(CENTER), "uniform", 1e-3)
|
||||
shape, jet_id = jet_link_shapes([sector], hits)
|
||||
assert np.array_equal(jet_id >= 0, expected)
|
||||
d = hits[expected] - CENTER
|
||||
np.testing.assert_allclose(shape[expected], -d/np.hypot(*d.T)[:, None], atol=1e-15)
|
||||
# Tube along +x through the same arc: lateral |y-5| < R sin(10 deg).
|
||||
tube = Jet(Tube((CENTER[0], CENTER[1]), 0., RADIUS + .1, RADIUS*math.sin(half)),
|
||||
Parallel(math.pi), "uniform", 1e-3)
|
||||
shape_t, id_t = jet_link_shapes([tube], hits)
|
||||
assert np.array_equal(id_t >= 0, expected)
|
||||
np.testing.assert_allclose(shape_t[expected], [[-1., 0.]]*expected.sum(), atol=1e-15)
|
||||
|
||||
|
||||
def test_off_centre_radial_points_to_field_origin_not_body_centre():
|
||||
*_, hits = scene()
|
||||
origin = (12., 9.)
|
||||
jet = Jet(Sector(CENTER, .1, math.pi, 10.), Radial(origin, inward=False))
|
||||
shape, jet_id = jet_link_shapes([jet], hits)
|
||||
assert np.all(jet_id == 0)
|
||||
d = hits - origin
|
||||
np.testing.assert_allclose(shape, d/np.hypot(*d.T)[:, None], atol=1e-15)
|
||||
assert not np.allclose(shape, (hits - CENTER)/RADIUS, atol=1e-3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("profile,expected", [("uniform", 1.), ("parabolic", .75), ("quartic", .5625)])
|
||||
def test_profiles_on_lateral_coordinate(profile, expected):
|
||||
hits = np.array([[1., .5]])
|
||||
jet = Jet(Tube((0., 0.), 0., 2., 1.), Parallel(0.), profile)
|
||||
shape, _ = jet_link_shapes([jet], hits)
|
||||
np.testing.assert_allclose(shape[0], [expected, 0.], rtol=1e-15)
|
||||
|
||||
|
||||
def test_selection_uses_true_hit_not_clipped_q():
|
||||
# Same link as test_aperture_uses_true_hit_not_fluid_node_or_clamped_q:
|
||||
# receiver (9,5), direction (-1,+1); true t < .01 but packed q == .01.
|
||||
t = (6-math.sqrt(36-8*(9-2.999**2)))/4
|
||||
angle = math.atan2(t, 3-t)
|
||||
_, cl, _, _, hits = scene()
|
||||
row = np.flatnonzero((cl.fluid_idx == 5*12 + 9) & (cl.dir == 8))
|
||||
assert len(row) == 1 and np.isclose(cl.q[row[0]], .01)
|
||||
clipped = np.array([9., 5.]) + .01*np.array([-1., 1.])
|
||||
jet = Jet(Sector(CENTER, angle, 1e-4, RADIUS + .1), Radial(CENTER))
|
||||
_, jet_id = jet_link_shapes([jet], hits)
|
||||
assert jet_id[row[0]] == 0
|
||||
with pytest.raises(ValueError, match="selects no"):
|
||||
jet_link_shapes([jet], clipped[None, :])
|
||||
|
||||
|
||||
def test_fine_half_cell_frame():
|
||||
edge = fine_hits_to_edge_frame([[0., 0.], [3., 1.5]], (4., 6.), .5)
|
||||
np.testing.assert_array_equal(edge, [[4.25, 6.25], [5.75, 7.]])
|
||||
np.testing.assert_array_equal(edge_to_node_frame(edge), [[3.75, 5.75], [5.25, 6.5]])
|
||||
|
||||
|
||||
def test_same_physical_hit_in_simulation_and_patch_frames():
|
||||
# One physical circle: Simulation node-frame centre C; patch edge-frame
|
||||
# centre C + 1/2; fine-local centre (C + 1/2 - origin)/dx - 1/2 as in
|
||||
# prepare_fine_boundary. Fine hits mapped edge -> node must lie on the
|
||||
# Simulation circle, and one node-frame Jet selects the same arc on both.
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
C, R, origin, dx = np.array([10.3, 9.6]), 2.15, np.array([4., 3.]), .5
|
||||
local = (C + .5 - origin)/dx - .5
|
||||
fine = CircleGeometry(*local, R/dx).build_cut_links(40, 40)
|
||||
coarse = CircleGeometry(*C, R).build_cut_links(24, 20)
|
||||
fine_hits = edge_to_node_frame(fine_hits_to_edge_frame(
|
||||
[(l.hit_x, l.hit_y) for l in fine], origin, dx))
|
||||
coarse_hits = np.array([(l.hit_x, l.hit_y) for l in coarse])
|
||||
np.testing.assert_allclose(np.hypot(*(fine_hits - C).T), R, rtol=0, atol=1e-12)
|
||||
np.testing.assert_allclose(np.hypot(*(coarse_hits - C).T), R, rtol=0, atol=1e-12)
|
||||
jet = Jet(Sector(tuple(C), .4, .5, R + .01, R - .01), Radial(tuple(C), inward=False))
|
||||
for hits in (fine_hits, coarse_hits):
|
||||
shape, jet_id = jet_link_shapes([jet], hits)
|
||||
d = hits - C
|
||||
angle = np.arctan2(d[:, 1], d[:, 0])
|
||||
assert np.array_equal(jet_id == 0, np.abs(angle - .4) < .5)
|
||||
np.testing.assert_allclose(shape[jet_id == 0], d[jet_id == 0]/R, atol=1e-12)
|
||||
# Relabelling instead of converting moves every hit off the circle.
|
||||
wrong = fine_hits_to_edge_frame([(l.hit_x, l.hit_y) for l in fine], origin, dx)
|
||||
assert np.abs(np.hypot(*(wrong - C).T) - R).max() > .3
|
||||
|
||||
|
||||
def test_links_are_distinct_by_receiver_and_direction_and_overlap_rejected():
|
||||
# Two physical links (different receiver/direction) sharing one hit point
|
||||
# are two rows, both driven; two jets on one link are rejected.
|
||||
hits = np.array([[1., 1.], [1., 1.]])
|
||||
a = Jet(Tube((0., 1.), 0., 2., .5), Parallel(0.))
|
||||
shape, jet_id = jet_link_shapes([a], hits)
|
||||
assert jet_id.tolist() == [0, 0]
|
||||
b = Jet(Sector((1., 0.), math.pi/2, .1, 2.), Parallel(0.))
|
||||
with pytest.raises(ValueError, match="overlaps"):
|
||||
jet_link_shapes([a, b], hits)
|
||||
obj, cl, cfg, flags, real = scene(SurfaceActuation(0., .3, .002))
|
||||
with pytest.raises(ValueError, match="SurfaceActuation"):
|
||||
surface_link_velocity([obj], cfg, flags, cl.fluid_idx, cl.dir, cl.body_id, cl.rx, cl.ry,
|
||||
jets=[Jet(Sector(CENTER, 0., .1, 4.), Radial(CENTER))], hits=real)
|
||||
with pytest.raises(ValueError, match="row-aligned"):
|
||||
surface_link_velocity([], cfg, flags, cl.fluid_idx, cl.dir, cl.body_id, cl.rx, cl.ry,
|
||||
jets=[a], hits=real[:-1])
|
||||
|
||||
|
||||
def test_amplitude_update_reuses_cached_shapes():
|
||||
obj, cl, cfg, flags, hits = scene()
|
||||
jet = Jet(Sector(CENTER, 0., .5, 4.), Radial(CENTER), "parabolic", 1e-3)
|
||||
cl.assign_surface([obj], cfg, flags, jets=[jet], hits=hits)
|
||||
shape, ids = cl.jet_shape, cl.jet_id
|
||||
before = cl.surface_velocity.copy()
|
||||
cl.set_jet_amplitude(0, -2e-3)
|
||||
assert cl.jet_shape is shape and cl.jet_id is ids
|
||||
np.testing.assert_allclose(cl.surface_velocity, -2*before, rtol=1e-6, atol=0)
|
||||
assert np.array_equal(cl.aperture, ids >= 0)
|
||||
with pytest.raises(ValueError):
|
||||
cl.set_jet_amplitude(0, 1.5)
|
||||
assert cl.jets[0].amplitude == -2e-3 and jet.amplitude == 1e-3 # registered Jet untouched
|
||||
np.testing.assert_allclose(cl.surface_velocity, -2*before, rtol=1e-6, atol=0)
|
||||
|
||||
|
||||
def test_jet_definition_is_immutable_and_amplitude_validated():
|
||||
jet = Jet(Sector(CENTER, 0., .5, 4.), Radial(CENTER), "parabolic", 1e-3)
|
||||
for name, value in (("field", Parallel(0.)), ("region", Tube(CENTER, 0., 1., 1.)),
|
||||
("profile", "uniform"), ("amplitude", float("nan"))):
|
||||
with pytest.raises(AttributeError):
|
||||
setattr(jet, name, value)
|
||||
for bad in (float("nan"), float("inf"), 1.0):
|
||||
with pytest.raises(ValueError):
|
||||
jet.with_amplitude(bad)
|
||||
assert jet.with_amplitude(-1e-3).field is jet.field and jet.amplitude == 1e-3
|
||||
with pytest.raises(ValueError, match="finite"):
|
||||
jet_link_shapes([jet], [[np.nan, 5.]])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("spec", [SurfaceActuation(0., .6, .002), SurfaceActuation(2., 1.1, -.003)])
|
||||
def test_legacy_adapter_measured_equivalence(spec):
|
||||
obj, legacy, cfg, flags, hits = scene(spec)
|
||||
cl = CurvedLinkSoA()
|
||||
cl.assign_host(legacy.fluid_idx, legacy.dir, legacy.q, legacy.body_id,
|
||||
legacy.rx, legacy.ry, legacy.rz, legacy.fallback_class)
|
||||
cl.assign_surface([circle()], cfg, flags, jets=[spec.as_jet(CENTER, RADIUS)], hits=hits)
|
||||
assert np.array_equal(cl.aperture, legacy.aperture)
|
||||
diff = np.abs(cl.surface_velocity - legacy.surface_velocity).max()
|
||||
print(f"legacy adapter max |dU| = {diff:.3e} (exact={diff == 0})")
|
||||
assert diff <= 4*np.finfo(np.float32).eps*abs(spec.normal_velocity)
|
||||
|
||||
|
||||
def jet_case(device, jets):
|
||||
field = make_field(device)
|
||||
bodies = manager(field, [circle(radius=2.)])
|
||||
bodies.jets.extend(jets)
|
||||
bodies.sync_to_gpu(field)
|
||||
return field, bodies
|
||||
|
||||
|
||||
def test_manager_passes_true_hits_and_reuploads_only_velocity(device):
|
||||
# CPU memory double only: checks host/device bookkeeping, not GPU numerics.
|
||||
jet = Jet(Sector(CENTER, 0., .6, 3.), Radial(CENTER, inward=False), "quartic", 2e-3)
|
||||
field, bodies = jet_case(device, [jet])
|
||||
cl = field.curved
|
||||
assert cl.jet_id is not None and (cl.jet_id == 0).sum() >= 2
|
||||
velocity_gpu = cl.surface_velocity_gpu
|
||||
np.testing.assert_array_equal(np.frombuffer(velocity_gpu.data, np.float32).reshape(-1, 2),
|
||||
cl.surface_velocity)
|
||||
geometry = {name: bytes(getattr(cl, name + "_gpu").data)
|
||||
for name in ("fluid_idx", "dir", "q", "body_id", "rx", "ry")}
|
||||
writes, before = device.writes, cl.surface_velocity.copy()
|
||||
cl.set_jet_amplitude(0, -1e-3, SimpleNamespace(synchronize=lambda: None))
|
||||
assert device.writes == writes + 1 and cl.surface_velocity_gpu is velocity_gpu
|
||||
np.testing.assert_array_equal(np.frombuffer(velocity_gpu.data, np.float32).reshape(-1, 2),
|
||||
cl.surface_velocity)
|
||||
assert all(bytes(getattr(cl, name + "_gpu").data) == data for name, data in geometry.items())
|
||||
np.testing.assert_allclose(cl.surface_velocity, -.5*before, rtol=1e-6, atol=0)
|
||||
np.testing.assert_array_equal(cl.surface_velocity[cl.jet_id < 0], 0.)
|
||||
|
||||
|
||||
def test_manager_rejects_overlapping_jets_and_moving_bodies(device):
|
||||
a = Jet(Sector(CENTER, 0., .6, 3.), Radial(CENTER))
|
||||
b = Jet(Tube(CENTER, 0., 3., .5), Parallel(0.))
|
||||
with pytest.raises(ValueError, match="overlaps"):
|
||||
jet_case(device, [a, b])
|
||||
field = make_field(device)
|
||||
moving = circle(radius=2.)
|
||||
moving.state.omega = 1e-3
|
||||
bodies = manager(field, [moving])
|
||||
bodies.jets.append(a)
|
||||
with pytest.raises(ValueError, match="stationary"):
|
||||
bodies.sync_to_gpu(field)
|
||||
|
||||
|
||||
def test_origins_are_frozen_float_pairs():
|
||||
point = [6., 5.]
|
||||
array = np.array([6., 5.])
|
||||
jets = [Jet(Sector(point, 0., .5, 4.), Radial(array)), Jet(Tube(array, 0., 1., 1.), Parallel(0.))]
|
||||
point[0], array[0] = 100., 100.
|
||||
assert jets[0].region.origin == (6., 5.) and jets[0].field.origin == (6., 5.)
|
||||
assert jets[1].region.origin == (6., 5.)
|
||||
assert all(type(v) is float for v in jets[0].region.origin)
|
||||
for bad in ((1., 2., 3.), (1., float("nan"))):
|
||||
with pytest.raises(ValueError):
|
||||
Radial(bad)
|
||||
|
||||
|
||||
def test_set_body_rejects_motion_of_jet_driven_body(device):
|
||||
from CelerisLab.simulation import Simulation
|
||||
jet = Jet(Sector(CENTER, 0., .6, 3.), Radial(CENTER, inward=False), "quartic", 2e-3)
|
||||
field, bodies = jet_case(device, [jet])
|
||||
sim = SimpleNamespace(bodies=bodies, field=field, lbm_cfg=field.cfg, _initialized=True)
|
||||
with pytest.raises(ValueError, match="stationary"):
|
||||
Simulation.set_body(sim, 0, omega=.01)
|
||||
with pytest.raises(ValueError, match="stationary"):
|
||||
Simulation.set_body(sim, 0, vx=.01)
|
||||
action = bodies.action.copy()
|
||||
with pytest.raises(ValueError, match="stationary"):
|
||||
bodies.set_body_state(0, omega=.01) # direct manager entry
|
||||
assert bodies.get(0).state.omega == 0 and np.array_equal(bodies.action, action)
|
||||
Simulation.set_body(sim, 0, omega=0.) # stationary updates stay allowed
|
||||
bodies.set_body_state(0, omega=0.)
|
||||
|
||||
|
||||
def test_action_upload_rejects_motion_of_jet_driven_body(device):
|
||||
# Direct edits of the public action array are checked at the upload gate.
|
||||
jet = Jet(Sector(CENTER, 0., .6, 3.), Radial(CENTER, inward=False), "quartic", 2e-3)
|
||||
field, bodies = jet_case(device, [jet])
|
||||
stream = SimpleNamespace(synchronize=lambda: None)
|
||||
slot = 3*field.cfg.dim
|
||||
for index in (0, 1, slot - 1): # vx, vy, omega
|
||||
bodies.action[:] = 0
|
||||
bodies.action[index] = .01
|
||||
writes = device.writes
|
||||
with pytest.raises(ValueError, match="stationary"):
|
||||
bodies._upload_action_async(stream)
|
||||
assert device.writes == writes # nothing reached the device
|
||||
bodies.action[:] = 0
|
||||
bodies._upload_action_async(stream) # zero motion stays accepted
|
||||
|
||||
|
||||
def test_fine_boundary_keeps_edge_frame_hits_and_checks_jets():
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm import refinement
|
||||
cfg = LBMConfig(nx=24, ny=24, viscosity=.05)
|
||||
cfg.validate()
|
||||
patch = refinement.FixedPatch2D.from_config(cfg, (4, 4, 20, 20))
|
||||
C, R = (12.25, 12.25), 2.15 # coarse cell-edge frame, as fine_objects
|
||||
body = SimObject(0, geometry=CircleGeometry(*C, R), center=C, radius=R)
|
||||
plan = refinement.prepare_fine_boundary(cfg, patch, [body])
|
||||
assert plan.curved_hits.shape == (len(plan.curved_host[0]), 2)
|
||||
assert not plan.curved_hits.flags.writeable
|
||||
np.testing.assert_allclose(np.hypot(*(plan.curved_hits - C).T), R, rtol=0, atol=1e-12)
|
||||
jet = Jet(Sector(C, 0., .5, R + .01), Radial(C, inward=False))
|
||||
refinement.prepare_fine_boundary(cfg, patch, [body], jets=[jet])
|
||||
away = Jet(Sector((2., 2.), 0., .1, .5), Parallel(0.))
|
||||
with pytest.raises(ValueError, match="selects no"):
|
||||
refinement.prepare_fine_boundary(cfg, patch, [body], jets=[away])
|
||||
with pytest.raises(ValueError, match="overlaps"):
|
||||
refinement.prepare_fine_boundary(cfg, patch, [body], jets=[jet, jet])
|
||||
with pytest.raises(ValueError, match="need fine boundary objects"):
|
||||
refinement.prepare_fine_boundary(cfg, patch, [], jets=[jet])
|
||||
# One fine jet over two physical bodies is rejected; one per body is accepted.
|
||||
A, B = (8.75, 12.25), (15.75, 12.25)
|
||||
pair = [SimObject(i, geometry=CircleGeometry(*c, 1.5), center=c, radius=1.5)
|
||||
for i, c in enumerate((A, B))]
|
||||
span = Jet(Tube((4.5, 12.25), 0., 15., .5), Parallel(0.))
|
||||
with pytest.raises(ValueError, match="one jet may drive only one body"):
|
||||
refinement.prepare_fine_boundary(cfg, patch, pair, jets=[span])
|
||||
refinement.prepare_fine_boundary(cfg, patch, pair, jets=[
|
||||
Jet(Sector(A, 0., .5, 2.), Radial(A, inward=False)),
|
||||
Jet(Sector(B, math.pi, .5, 2.), Radial(B, inward=False))])
|
||||
# Jet vs legacy SurfaceActuation overlap on the fine level (root's case).
|
||||
legacy = SimObject(0, geometry=CircleGeometry(*C, R), center=C, radius=R,
|
||||
surface_actuation=SurfaceActuation(0., .5, .002))
|
||||
with pytest.raises(ValueError, match="SurfaceActuation"):
|
||||
refinement.prepare_fine_boundary(cfg, patch, [legacy], jets=[jet])
|
||||
disjoint = Jet(Sector(C, math.pi, .5, R + .01), Radial(C, inward=False))
|
||||
refinement.prepare_fine_boundary(cfg, patch, [legacy], jets=[disjoint])
|
||||
|
||||
|
||||
def test_action_upload_keeps_cfg_none_fallback(device):
|
||||
# Default ObjectManager(cfg=None) keeps the 2D slot fallback, empty or not.
|
||||
from CelerisLab.body.manager import ObjectManager
|
||||
stream = SimpleNamespace(synchronize=lambda: None)
|
||||
bodies = ObjectManager(12, 10, 1, 9)
|
||||
bodies._upload_action_async(stream)
|
||||
bodies.add(circle(radius=2.))
|
||||
bodies._upload_action_async(stream)
|
||||
|
||||
|
||||
def two_body_case(device, jets):
|
||||
field = make_field(device)
|
||||
bodies = manager(field, [circle(center=(3., 5.), radius=1.6),
|
||||
circle(center=(8.5, 5.), radius=1.6)])
|
||||
bodies.jets.extend(jets)
|
||||
bodies.sync_to_gpu(field)
|
||||
return field, bodies
|
||||
|
||||
|
||||
@pytest.mark.parametrize("amplitude", [2e-3, 0.0]) # geometry checked even at zero amplitude
|
||||
def test_one_jet_spanning_two_bodies_rejected(device, amplitude):
|
||||
both = Jet(Tube((0., 5.), 0., 12., .5), Parallel(0.), amplitude=amplitude)
|
||||
with pytest.raises(ValueError, match="one jet may drive only one body"):
|
||||
two_body_case(device, [both])
|
||||
|
||||
|
||||
def test_separate_jets_on_separate_bodies_accepted(device):
|
||||
left = Jet(Sector((3., 5.), 0., .6, 2.), Radial((3., 5.), inward=False), amplitude=1e-3)
|
||||
right = Jet(Sector((8.5, 5.), math.pi, .6, 2.), Radial((8.5, 5.), inward=False), amplitude=-1e-3)
|
||||
field, _ = two_body_case(device, [left, right])
|
||||
cl = field.curved
|
||||
for j in (0, 1):
|
||||
assert len(np.unique(cl.body_id[cl.jet_id == j])) == 1
|
||||
assert cl.body_id[cl.jet_id == 0][0] != cl.body_id[cl.jet_id == 1][0]
|
||||
|
||||
|
||||
def test_one_body_with_noncontiguous_rows_accepted_and_mixed_rejected():
|
||||
# Synthetic rows: ownership is set membership over body_id, not row adjacency.
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm.descriptors import FLUID
|
||||
cfg = LBMConfig(nx=12, ny=10, viscosity=.1)
|
||||
cfg.validate()
|
||||
objs = [SimObject(i, geometry=CircleGeometry(3. + 5*i, 5., 1.), center=(3. + 5*i, 5.), radius=1.)
|
||||
for i in (0, 1)]
|
||||
flags = np.full(cfg.nx*cfg.ny, FLUID, np.uint16)
|
||||
fluid_idx = np.array([10, 20, 30], np.uint32)
|
||||
dirs = np.array([1, 1, 1], np.uint8)
|
||||
zeros = np.zeros(3, np.float32)
|
||||
hits = np.array([[0., 0.], [5., 5.], [0., 1.]])
|
||||
jet = Jet(Tube((0., -.5), math.pi/2, 2., .5), Parallel(0.)) # selects rows 0 and 2
|
||||
for body_id, ok in ((np.array([0, 1, 0], np.int32), True), (np.array([0, 1, 1], np.int32), False)):
|
||||
call = lambda: surface_link_velocity(objs, cfg, flags, fluid_idx, dirs, body_id,
|
||||
zeros, zeros, jets=[jet], hits=hits)
|
||||
if ok:
|
||||
_, aperture = call()
|
||||
assert aperture.tolist() == [True, False, True]
|
||||
else:
|
||||
with pytest.raises(ValueError, match="one jet may drive only one body"):
|
||||
call()
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Grok review cases for claude/jet (test-only).
|
||||
|
||||
The oracle and wrap tests are Grok's inline patch (Slack ts 1792052057.423679).
|
||||
The rotated-tube and square-wall cases follow Grok's stated checks; their text
|
||||
was clipped in transit, so they are re-written here, not copied verbatim.
|
||||
"""
|
||||
import math
|
||||
import numpy as np
|
||||
from CelerisLab.body.jets import Jet, Parallel, Radial, Sector, Tube, jet_link_shapes
|
||||
from .test_surface_actuation import circle
|
||||
|
||||
|
||||
def big_scene():
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.body.manager import ObjectManager
|
||||
from CelerisLab.lbm.descriptors import FLUID
|
||||
obj = circle(center=(20., 15.), radius=6.5)
|
||||
cfg = LBMConfig(nx=40, ny=30, viscosity=.1); cfg.validate()
|
||||
flags = ObjectManager.build_flags_for([obj], np.full(40*30, FLUID, np.uint16), nx=40, ny=30, nz=1)
|
||||
links = obj.geometry.build_cut_links(40, 30, domain_flags=flags)
|
||||
hits = np.array([(l.hit_x, l.hit_y) for l in links])
|
||||
fl, dr = obj.get_curved_list(40, 30, cfg.nq, domain_flags=flags)[:2]
|
||||
return hits, np.asarray(fl), np.asarray(dr)
|
||||
|
||||
|
||||
def test_frozen_5_link_sector_oracle_with_edge_margin():
|
||||
hits, fl, dr = big_scene()
|
||||
half = math.radians(5)
|
||||
sel, s = Sector((20., 15.), 0., half, 7.5, 5.5).select(hits)
|
||||
got = sorted((int(f % 40), int(f // 40), int(d)) for f, d in zip(fl[sel], dr[sel]))
|
||||
assert got == sorted([(27, 15, 2), (27, 14, 8), (27, 16, 6), (27, 15, 6), (27, 15, 8)])
|
||||
d = hits - (20., 15.)
|
||||
dth = np.abs(np.arctan2(d[:, 1], d[:, 0]))
|
||||
near = np.hypot(*d.T) < 7.5
|
||||
assert np.all(np.abs(dth[near] - half) >= 1e-3) # no hit within 1e-3 rad of the edge
|
||||
|
||||
|
||||
def test_sector_axis_pi_wraps():
|
||||
hits = np.array([[-1., 1e-3], [-1., -1e-3], [1., 0.]])
|
||||
sel, _ = Sector((0., 0.), math.pi, .01, 2.).select(hits)
|
||||
assert sel.tolist() == [True, True, False]
|
||||
sel, _ = Sector((0., 0.), -math.pi, .01, 2.).select(hits)
|
||||
assert sel.tolist() == [True, True, False]
|
||||
|
||||
|
||||
def test_rotated_tube_30deg_selection_and_parallel_axis():
|
||||
a = math.radians(30)
|
||||
u, n = np.array([math.cos(a), math.sin(a)]), np.array([-math.sin(a), math.cos(a)])
|
||||
hits = np.array([2*u, 2*u + .999*n, 2*u - .999*n, 2*u + 1.001*n, -.1*u, 4.1*u])
|
||||
jet = Jet(Tube((0., 0.), a, 4., 1.), Parallel(a))
|
||||
shape, jet_id = jet_link_shapes([jet], hits)
|
||||
assert (jet_id == 0).tolist() == [True, True, True, False, False, False]
|
||||
np.testing.assert_allclose(shape[:3], np.tile(u, (3, 1)), rtol=0, atol=1e-15)
|
||||
np.testing.assert_array_equal(shape[3:], 0.)
|
||||
|
||||
|
||||
def test_exact_edge_rule_axis_aligned():
|
||||
# Exactly representable samples: lateral |s| = 1 is excluded; Tube along
|
||||
# 0 and length and Sector r_min/r_max are included.
|
||||
tube = Tube((0., 0.), 0., 4., 1.)
|
||||
sel, s = tube.select(np.array([[2., 1.], [2., -1.], [2., .5], [0., 0.], [4., 0.]]))
|
||||
assert sel.tolist() == [False, False, True, True, True]
|
||||
assert s.tolist() == [1., -1., .5, 0., 0.]
|
||||
sel, _ = Sector((0., 0.), 0., .5, 2., 1.).select(np.array([[1., 0.], [2., 0.], [.5, 0.], [2.5, 0.]]))
|
||||
assert sel.tolist() == [True, True, False, False]
|
||||
|
||||
|
||||
def test_synthetic_square_wall_off_centre_radial():
|
||||
# Synthetic hit sampling on a flat face x=10 (no square geometry, cut links or
|
||||
# kernel involved): selection is purely spatial and the field points away
|
||||
# from (5, 0), not along the face normal (1, 0).
|
||||
y = np.linspace(-2., 2., 9)
|
||||
hits = np.stack((np.full_like(y, 10.), y), axis=1)
|
||||
jet = Jet(Tube((10., -1.), math.pi/2, 2., .5), Radial((5., 0.), inward=False), amplitude=1e-3)
|
||||
shape, jet_id = jet_link_shapes([jet], hits)
|
||||
assert np.array_equal(jet_id == 0, np.abs(y) <= 1)
|
||||
d = hits[jet_id == 0] - (5., 0.)
|
||||
np.testing.assert_allclose(shape[jet_id == 0], d/np.hypot(*d.T)[:, None], rtol=0, atol=1e-15)
|
||||
assert np.abs(shape[jet_id == 0, 1]).max() > .1 # not the wall normal
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Multiple body pins and variable fluid sets; mocked runtime is host-only."""
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.body.jets import Jet, Tube, Parallel
|
||||
from CelerisLab.body.objects import SurfaceActuation
|
||||
from CelerisLab.lbm.refinement import FixedPatch2D
|
||||
from CelerisLab.lbm.synchronized_remap import RemapTopology
|
||||
from tests.unit.test_pinned_body_remap import body, mesh
|
||||
from tests.unit.test_refinement_three_level_multipatch import mock_backend
|
||||
from tests.unit.test_synchronized_remap import fields, integrals, remap
|
||||
|
||||
PINS = ((16, 16, 32, 24), (56, 16, 72, 24))
|
||||
FLUID = ((16, 32, 32, 40), (56, 32, 72, 40))
|
||||
ADDED = ((16, 44, 32, 48),)
|
||||
MOVED = ((20, 32, 36, 40), (60, 32, 76, 40))
|
||||
|
||||
|
||||
def objects():
|
||||
return (body(center=(12., 10.)), body(center=(32., 10.)))
|
||||
|
||||
|
||||
def ready():
|
||||
bodies = objects()
|
||||
jets = tuple(Jet(Tube((x-1.5, 10.), 0., 3., .3), Parallel(0.),
|
||||
'parabolic', .003) for x in (12., 32.))
|
||||
with patch('tests.unit.test_refinement_three_level_multipatch.bodies_and_jets',
|
||||
return_value=(bodies, jets)):
|
||||
run, module, allocations = mock_backend(children=PINS+FLUID, bodies=True)
|
||||
storage = {}
|
||||
module.cuda.memcpy_htod.side_effect = lambda p, a: storage.__setitem__(id(p), np.array(a, copy=True))
|
||||
module.cuda.memcpy_dtoh.side_effect = lambda a, p: np.copyto(a, storage[id(p)])
|
||||
run.initialize(*fields(mesh(PINS+FLUID, bodies, jets), np.float32))
|
||||
run._step_count = 7
|
||||
return run, module, allocations, bodies
|
||||
|
||||
|
||||
class MultiplePinnedRemap(unittest.TestCase):
|
||||
def check_transfer(self, old, new, arrays, tolerance):
|
||||
out = remap(old, new, arrays)
|
||||
before = integrals(old, arrays)
|
||||
np.testing.assert_allclose(integrals(new, out.g), before, rtol=0,
|
||||
atol=tolerance*np.abs(before[:9]).sum())
|
||||
for a, b, om, nm in zip(arrays, out.g, old.leaf_masks, new.leaf_masks):
|
||||
self.assertEqual(a[:, om & nm].tobytes(), b[:, om & nm].tobytes())
|
||||
self.assertTrue(np.isnan(b[:, ~nm]).all())
|
||||
return out.g
|
||||
|
||||
def test_add_move_remove_and_body_only_all_populations(self):
|
||||
for dtype, tolerance in ((np.float64, 2e-13), (np.float32, 2e-7)):
|
||||
old = mesh(PINS+FLUID, objects())
|
||||
arrays = fields(old, dtype)
|
||||
for rects in (PINS+FLUID+ADDED, PINS+MOVED+ADDED, PINS, PINS+FLUID):
|
||||
new = mesh(rects, objects())
|
||||
self.assertEqual(new.pinned_rectangles, PINS)
|
||||
arrays = self.check_transfer(old, new, arrays, tolerance)
|
||||
old = new
|
||||
|
||||
def test_shared_pin_order_invariance_and_body_free(self):
|
||||
bodies = (body(center=(11., 14.)), body(center=(14., 14.)))
|
||||
rects = ((16, 16, 32, 40), (56, 16, 72, 40))
|
||||
old, new = mesh(rects, bodies), mesh(rects[::-1], bodies)
|
||||
self.assertEqual(old.pinned_rectangles, (rects[0],))
|
||||
self.assertEqual(new.pinned_rectangles, old.pinned_rectangles)
|
||||
self.check_transfer(old, new, fields(old), 2e-13)
|
||||
only = mesh((rects[0],), bodies)
|
||||
self.check_transfer(old, only, fields(old), 2e-13)
|
||||
self.assertEqual(mesh(rects, ()).pinned_rectangles, ())
|
||||
|
||||
def test_shifted_scalar_parent_coordinates(self):
|
||||
cfg = LBMConfig(nx=48, ny=32, viscosity=.1)
|
||||
parent = FixedPatch2D.from_config(cfg, (4, 4, 44, 28))
|
||||
self.assertEqual(parent.fine_origin, (2., 2.))
|
||||
bodies = (body(center=(14., 12.)), body(center=(34., 12.)))
|
||||
def topology(rects):
|
||||
return RemapTopology.from_config(cfg, parent, rects, child_objects=bodies)
|
||||
old, new = topology(PINS+FLUID), topology(PINS+MOVED)
|
||||
self.assertEqual(old.pinned_rectangles, PINS)
|
||||
self.check_transfer(old, new, fields(old), 2e-13)
|
||||
|
||||
def test_direct_helper_rejects_each_changed_pin_and_body_order(self):
|
||||
old = mesh(PINS+FLUID, objects())
|
||||
candidates = [mesh(PINS+FLUID, objects()[::-1])]
|
||||
for index in range(2):
|
||||
changed = list(PINS+FLUID)
|
||||
x0, y0, x1, y1 = changed[index]
|
||||
changed[index] = (x0-4, y0, x1, y1)
|
||||
candidates.append(mesh(changed, objects()))
|
||||
for new in candidates:
|
||||
# Invalid donors ensure boundary validation precedes array reads.
|
||||
with self.assertRaisesRegex(ValueError, 'pinned'):
|
||||
remap(old, new, None)
|
||||
|
||||
def test_live_independent_jets_and_source_ownership(self):
|
||||
run, module, allocations, bodies = ready()
|
||||
run.set_jet_amplitude(0, .017, level=2)
|
||||
run.set_jet_amplitude(1, -.011, level=2)
|
||||
before = run.download()
|
||||
clone = run.remap_child((PINS+MOVED+ADDED)[::-1], child_objects=bodies)
|
||||
try:
|
||||
self.assertEqual(tuple(j.amplitude for j in clone._boundaries[2].jets), (.017, -.011))
|
||||
np.testing.assert_array_equal(clone._boundaries[2].tables['surface_velocity'],
|
||||
run._boundaries[2].tables['surface_velocity'])
|
||||
clone.set_jet_amplitude(1, .005, level=2)
|
||||
self.assertEqual(run._boundaries[2].jets[1].amplitude, -.011)
|
||||
clone.step()
|
||||
self.assertEqual((run.step_count, clone.step_count), (7, 8))
|
||||
for got, want in zip(run.download(), before):
|
||||
np.testing.assert_array_equal(got, want)
|
||||
finally:
|
||||
clone.close()
|
||||
run.close()
|
||||
|
||||
def test_sub_ulp_cut_table_geometry_change_rejected(self):
|
||||
run, module, allocations, bodies = ready()
|
||||
changed = objects()
|
||||
changed[1].geometry._radius = np.nextafter(.8, np.inf)
|
||||
start = len(allocations)
|
||||
module.cuda.memcpy_dtoh.reset_mock()
|
||||
with self.assertRaisesRegex(ValueError, 'boundary'):
|
||||
run.remap_child(PINS+FLUID, child_objects=changed)
|
||||
self.assertEqual(len(allocations), start)
|
||||
module.cuda.memcpy_dtoh.assert_not_called()
|
||||
with self.assertRaisesRegex(ValueError, 'pinned'):
|
||||
remap(mesh(PINS+FLUID, bodies), mesh(PINS+FLUID, changed), None)
|
||||
run.close()
|
||||
|
||||
def test_each_pin_and_body_identity_rejected_before_device_access(self):
|
||||
run, module, allocations, bodies = ready()
|
||||
cases = [(PINS+FLUID, bodies[:1]), (PINS+FLUID, bodies[::-1]),
|
||||
(PINS+FLUID, (bodies[0], body(center=(32.1, 10.)))),
|
||||
(PINS+FLUID, (bodies[0], body(SurfaceActuation(0., .7, 0.), (32., 10.)))),
|
||||
(PINS+FLUID, run.child_boundary.objects)]
|
||||
for index in range(2):
|
||||
changed = list(PINS+FLUID)
|
||||
x0, y0, x1, y1 = changed[index]
|
||||
changed[index] = (x0-4, y0, x1, y1)
|
||||
cases.append((changed, bodies))
|
||||
cases.append((tuple(r for i, r in enumerate(PINS+FLUID) if i != index), bodies))
|
||||
start = len(allocations)
|
||||
module.cuda.memcpy_dtoh.reset_mock()
|
||||
run._stream.synchronize.reset_mock()
|
||||
for rects, supplied in cases:
|
||||
with self.subTest(rects=rects), self.assertRaises(ValueError):
|
||||
run.remap_child(rects, child_objects=supplied)
|
||||
self.assertEqual(len(allocations), start)
|
||||
module.cuda.memcpy_dtoh.assert_not_called()
|
||||
run._stream.synchronize.assert_not_called()
|
||||
self.assertEqual((run._status, run.step_count), ('ready', 7))
|
||||
run.close()
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Bounded pinned-body transfer and host lifecycle; no CUDA numerical claim."""
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import numpy as np
|
||||
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject, SurfaceActuation
|
||||
from CelerisLab.body.jets import Jet, Tube, Parallel
|
||||
from CelerisLab.lbm.synchronized_remap import RemapTopology, same_physical_boundary
|
||||
from tests.unit.test_synchronized_remap import CFG, PARENTS, fields, remap
|
||||
from tests.unit.test_refinement_three_level_multipatch import mock_backend
|
||||
from CelerisLab.lbm.refinement import FixedPatchSet2D
|
||||
|
||||
A = ((16,16,32,40), (56,16,72,40))
|
||||
B = ((16,16,32,40), (60,16,76,40))
|
||||
|
||||
|
||||
def body(spec=None, center=(12.,14.)):
|
||||
return SimObject(71, geometry=CircleGeometry(*center,.8), center=center,
|
||||
radius=.8, surface_actuation=spec)
|
||||
|
||||
|
||||
def jet():
|
||||
return Jet(Tube((10.5,14.),0.,3.,.3), Parallel(0.), 'parabolic', .003)
|
||||
|
||||
|
||||
def mesh(rects, objects, jets=()):
|
||||
return RemapTopology.from_config(CFG, FixedPatchSet2D.from_config(CFG,PARENTS),
|
||||
rects, child_objects=objects, child_jets=jets)
|
||||
|
||||
|
||||
def ready(objects=None, jets=None):
|
||||
objects = (body(),) if objects is None else objects
|
||||
jets = (jet(),) if jets is None else jets
|
||||
with patch('tests.unit.test_refinement_three_level_multipatch.bodies_and_jets',
|
||||
return_value=(objects,jets)):
|
||||
run, module, allocations = mock_backend(children=A,bodies=True)
|
||||
storage = {}
|
||||
module.cuda.memcpy_htod.side_effect = lambda p,a: storage.__setitem__(id(p),np.array(a,copy=True))
|
||||
module.cuda.memcpy_dtoh.side_effect = lambda a,p: np.copyto(a,storage[id(p)])
|
||||
run.initialize(*fields(mesh(A,objects,jets),np.float32))
|
||||
run._step_count = 7
|
||||
return run,module,allocations,storage,objects
|
||||
|
||||
|
||||
class PinnedBodyRemap(unittest.TestCase):
|
||||
def test_fluid_only_transfer_poison_and_round_trip(self):
|
||||
old,new = mesh(A,(body(),)),mesh(B,(body(),))
|
||||
arrays=fields(old,np.float32)
|
||||
for a,leaf in zip(arrays,old.leaf_masks): a[:,~leaf]=12345
|
||||
out=remap(old,new,arrays)
|
||||
for a,b,before,after in zip(arrays,out.g,old.leaf_masks,new.leaf_masks):
|
||||
np.testing.assert_array_equal(a[:,before & after],b[:,before & after])
|
||||
self.assertTrue(np.isnan(b[:,~after]).all())
|
||||
self.assertTrue(same_physical_boundary(old.boundary,new.boundary))
|
||||
back=remap(new,old,out.g)
|
||||
self.assertTrue(np.isnan(back.g[2][:,~old.leaf_masks[2]]).all())
|
||||
self.assertEqual(old.pinned_rectangles,(A[0],))
|
||||
|
||||
def test_current_jets_and_source_independence(self):
|
||||
run,module,allocations,storage,objects=ready()
|
||||
run.set_jet_amplitude(0,.017,level=2)
|
||||
before=run.download()
|
||||
clone=run.remap_child(B,child_objects=objects)
|
||||
self.assertEqual(clone._boundaries[2].jets[0].amplitude,.017)
|
||||
np.testing.assert_array_equal(clone._boundaries[2].tables['surface_velocity'],
|
||||
run._boundaries[2].tables['surface_velocity'])
|
||||
self.assertTrue(same_physical_boundary(run.child_boundary,clone.child_boundary))
|
||||
clone.step()
|
||||
self.assertEqual((run.step_count,clone.step_count),(7,8))
|
||||
for got,want in zip(run.download(),before): np.testing.assert_array_equal(got,want)
|
||||
clone.close();run.close()
|
||||
|
||||
def test_static_body_without_actuation(self):
|
||||
run,module,allocations,storage,objects=ready(jets=())
|
||||
clone=run.remap_child(A,child_objects=objects)
|
||||
self.assertFalse(clone._boundaries[2].actuated)
|
||||
self.assertNotIn('surface_velocity',clone._boundaries[2].tables)
|
||||
for a,b in zip(run.download(),clone.download()): np.testing.assert_array_equal(a,b)
|
||||
clone.close();run.close()
|
||||
|
||||
def test_reject_before_device_reads_or_allocation(self):
|
||||
run,module,allocations,storage,objects=ready()
|
||||
start=len(allocations)
|
||||
cases=[(B,()),(B,run.child_boundary.objects),(B,(body(center=(12.1,14.)),)),
|
||||
(((20,16,36,40),B[1]),objects),(((16,20,32,40),B[1]),objects),
|
||||
((B[1],),objects)]
|
||||
module.cuda.memcpy_dtoh.reset_mock()
|
||||
for rects,objs in cases:
|
||||
with self.subTest(rects=rects),self.assertRaises(ValueError):
|
||||
run.remap_child(rects,child_objects=objs)
|
||||
self.assertEqual(len(allocations),start)
|
||||
module.cuda.memcpy_dtoh.assert_not_called()
|
||||
self.assertEqual((run._status,run.step_count),('ready',7))
|
||||
run.close()
|
||||
|
||||
def test_legacy_velocity_and_zero_velocity_ownership_rejected(self):
|
||||
for speed in (.002,0.):
|
||||
run,module,allocations,storage,objects=ready(
|
||||
(body(SurfaceActuation(0.,.7,speed)),),())
|
||||
for spec in (SurfaceActuation(0.,.7,.003),SurfaceActuation(2.,.7,speed)):
|
||||
module.cuda.memcpy_dtoh.reset_mock()
|
||||
with self.assertRaises(ValueError): run.remap_child(B,child_objects=(body(spec),))
|
||||
module.cuda.memcpy_dtoh.assert_not_called()
|
||||
clone=run.remap_child(B,child_objects=objects)
|
||||
clone.close();run.close()
|
||||
|
||||
def test_allocation_failure_keeps_old_ready_and_count(self):
|
||||
run,module,allocations,storage,objects=ready()
|
||||
before=run.download(); saved=list(allocations)
|
||||
allocate=module.cuda.mem_alloc.side_effect
|
||||
calls=0
|
||||
def fail(size):
|
||||
nonlocal calls
|
||||
calls+=1
|
||||
if calls == 3: raise RuntimeError('candidate allocation')
|
||||
return allocate(size)
|
||||
with patch.object(module.cuda,'mem_alloc',side_effect=fail):
|
||||
with self.assertRaisesRegex(RuntimeError,'allocation'):
|
||||
run.remap_child(B,child_objects=objects)
|
||||
self.assertEqual((run._status,run.step_count),('ready',7))
|
||||
for got,want in zip(run.download(),before): np.testing.assert_array_equal(got,want)
|
||||
for a in saved: a.free.assert_not_called()
|
||||
for a in allocations[len(saved):]: a.free.assert_called_once()
|
||||
run.close()
|
||||
|
||||
def test_direct_helper_rejects_changed_pinned_rectangle(self):
|
||||
old=mesh(A,(body(),))
|
||||
new=mesh(((12,16,32,40),A[1]),(body(),))
|
||||
with self.assertRaisesRegex(ValueError,'pinned'): remap(old,new,fields(old))
|
||||
@@ -0,0 +1,170 @@
|
||||
"""CPU reduction and real host scheduling with CUDA doubles, not GPU physics."""
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import replace
|
||||
from unittest.mock import Mock
|
||||
import numpy as np
|
||||
import unittest
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject, SurfaceActuation
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm.blocks import BlockLayout2D
|
||||
from CelerisLab.lbm.refinement import FixedPatch2D, prepare_fine_boundary
|
||||
from CelerisLab.lbm.refinement_tables import _prepare_blocked_boundary
|
||||
from CelerisLab.lbm.raw_exchange import summarize_exchange
|
||||
from tests.unit.test_refinement_three_level_multipatch import host_module
|
||||
|
||||
|
||||
def body(center=(16., 16.), radius=.5, speed=0.):
|
||||
return SimObject(91, geometry=CircleGeometry(*center, radius), center=center, radius=radius,
|
||||
surface_actuation=SurfaceActuation(.7, .85, speed))
|
||||
|
||||
|
||||
def backend(observe=True, obj=None):
|
||||
host = host_module()
|
||||
calls = []
|
||||
module = Mock()
|
||||
module.get_global.return_value = (Mock(), 20)
|
||||
module.get_function.side_effect = lambda name: Mock(side_effect=lambda *a, **k: calls.append((name, a, k)))
|
||||
host.compiler.load_module.return_value = module
|
||||
host.cuda.mem_alloc.side_effect = lambda n: Mock(size=n)
|
||||
host.cuda.memcpy_dtoh.side_effect = lambda array, pointer: array.fill(0)
|
||||
ctx = Mock(activate=nullcontext, sm_arch='sm_70')
|
||||
run = host.FixedPatchStepper(LBMConfig(nx=48, ny=48, viscosity=.02), context=ctx,
|
||||
refinements=[[(6, 6, 26, 26)], [(20, 20, 44, 44)], [(56, 56, 72, 72)]],
|
||||
level_blocks=[(4, 4)]*4, level_objects=[(), (), (), (body() if obj is None else obj,)],
|
||||
observe_raw_exchange=observe)
|
||||
arrays = [np.full(l.shape, 1/9, np.float32) for l in run._levels]
|
||||
run.initialize(*arrays)
|
||||
return run, host, calls, arrays
|
||||
|
||||
|
||||
class RawExchange(unittest.TestCase):
|
||||
def _check_weights_split_and_window(self, level):
|
||||
h = 2. ** -level
|
||||
rows = np.array([[2, -3, 5, 7], [-1, 4, -2, -6], [99, 99, 99, 99]], np.float32)
|
||||
kw = dict(body_id=0, level=level, h=h, time_end=3, reference_center=(7, 8))
|
||||
last = summarize_exchange(rows, [0, 0, 1], [False, True, False], window='last_substep', **kw)
|
||||
integral = rows.astype(float)*[h*h, h*h, h**3, h*h]/h
|
||||
full = summarize_exchange(integral, [0, 0, 1], [False, True, False], window='last_base_step', **kw)
|
||||
np.testing.assert_array_equal(last['total']['force'], np.array([1, 1])*h)
|
||||
self.assertEqual(last['total']['torque'], 3 * h * h)
|
||||
self.assertEqual(last['total']['mass_into_fluid'], h * h)
|
||||
for name in ('force', 'torque', 'mass_rate'):
|
||||
np.testing.assert_array_equal(last['total'][name], full['total'][name])
|
||||
for name in ('force', 'impulse', 'torque', 'angular_impulse', 'mass_into_fluid'):
|
||||
np.testing.assert_array_equal(last['total'][name],
|
||||
np.asarray(last['wall'][name])+last['aperture'][name])
|
||||
self.assertEqual(last['time_start'], 3 - h)
|
||||
self.assertEqual(full['time_start'], 2)
|
||||
self.assertEqual(last['sample_count'], 1)
|
||||
self.assertEqual(full['sample_count'], 2 ** level)
|
||||
self.assertEqual(full['reference_center'], (7, 8))
|
||||
|
||||
def test_final_substep_is_not_interval_mean(self):
|
||||
kw = dict(body_id=0, level=1, h=.5, time_end=1, reference_center=(0, 0))
|
||||
last = summarize_exchange([[4, 0, 0, 0]], [0], [False], window='last_substep', **kw)
|
||||
full = summarize_exchange([[1.5, 0, 0, 0]], [0], [False], window='last_base_step', **kw)
|
||||
self.assertEqual(last['total']['force'][0], 2)
|
||||
self.assertEqual(full['total']['force'][0], 1.5)
|
||||
|
||||
def test_host_metadata_zero_jet_and_rows(self):
|
||||
cfg = LBMConfig(nx=32, ny=32, viscosity=.1)
|
||||
pair = FixedPatch2D.from_config(cfg, (4, 4, 28, 28))
|
||||
boundary = prepare_fine_boundary(cfg, pair, [body(radius=2.15)])
|
||||
local = replace(cfg, nx=pair.fine_shape[1], ny=pair.fine_shape[0], viscosity=.2)
|
||||
local.validate()
|
||||
layout = BlockLayout2D.build(*pair.fine_shape, 8, 8, periodic=(False, False))
|
||||
b = _prepare_blocked_boundary(boundary, layout, local, ())
|
||||
for key, idx in [('body_id', 3), ('rx', 4), ('ry', 5)]:
|
||||
np.testing.assert_array_equal(b.tables[key], boundary.curved_host[idx])
|
||||
self.assertTrue(b.tables['aperture'].any())
|
||||
self.assertTrue((~b.tables['aperture']).any())
|
||||
self.assertFalse(b.tables['surface_velocity'].any())
|
||||
# Classification does not disappear when prescribed velocity is zero.
|
||||
self.assertEqual(len(b.tables['cell']), len(boundary.curved_host[0]))
|
||||
|
||||
def test_four_level_schedule_publication_and_fixed_storage(self):
|
||||
run, host, calls, arrays = backend()
|
||||
b = run._level_boundaries[3]
|
||||
rows = len(b.tables['cell'])
|
||||
self.assertEqual(b.last_raw.size, rows * 16)
|
||||
self.assertEqual(b.interval_integral.size, rows * 32)
|
||||
with self.assertRaisesRegex(RuntimeError, 'completed'):
|
||||
run.read_raw_exchange(0, level=3)
|
||||
run.step()
|
||||
names = [name for name, _, _ in calls]
|
||||
self.assertEqual(names.count('BlockAccumulateExchange'), 8)
|
||||
for i, (name, args, kw) in enumerate(calls):
|
||||
if name == 'BlockAccumulateExchange':
|
||||
self.assertEqual(names[i - 1], 'BlockCurvedBoundary')
|
||||
self.assertEqual(names[i + 1], 'BlockStep')
|
||||
self.assertIs(args[0], b.last_raw)
|
||||
self.assertIs(args[1], b.interval_integral)
|
||||
self.assertEqual(args[3:], (0.125, 0.125))
|
||||
self.assertIs(kw['stream'], run._stream)
|
||||
self.assertEqual(host.cuda.memset_d8_async.call_count, 1)
|
||||
value = run.read_raw_exchange(0, level=3)
|
||||
self.assertEqual(value['sample_count'], 8)
|
||||
self.assertEqual(value['time_start'], 0)
|
||||
run.step(0)
|
||||
self.assertEqual(run.read_raw_exchange(0, level=3)['time_end'], 1)
|
||||
self.assertEqual(run.read_raw_exchange(0, level=3, window='last_substep')['time_start'], 0.875)
|
||||
run.step(2)
|
||||
self.assertEqual(run.read_raw_exchange(0, level=3)['time_start'], 2)
|
||||
run.initialize(*arrays)
|
||||
with self.assertRaisesRegex(RuntimeError, 'completed'):
|
||||
run.read_raw_exchange(0, level=3)
|
||||
run.close()
|
||||
|
||||
def test_torque_reference_uses_geometry_center_not_optional_object_center(self):
|
||||
for center in (None, (3., 4.)):
|
||||
obj = SimObject(91, geometry=CircleGeometry(16., 16., .5), center=center, radius=.5)
|
||||
run, _, _, _ = backend(obj=obj)
|
||||
run.step()
|
||||
result = run.read_raw_exchange(0, level=3)
|
||||
self.assertEqual(result['reference_center'], (16.0, 16.0))
|
||||
self.assertNotEqual(result['reference_center'], tuple(obj.center))
|
||||
run.close()
|
||||
|
||||
def test_disabled_has_nulls_and_no_observation_allocation_or_launch(self):
|
||||
run, host, calls, _ = backend(False)
|
||||
b = run._level_boundaries[3]
|
||||
self.assertIs(b.last_raw, b.interval_integral)
|
||||
self.assertIs(b.interval_integral, None)
|
||||
run.step()
|
||||
for name, args, _ in calls:
|
||||
if name == 'BlockCurvedBoundary':
|
||||
self.assertEqual(tuple(args[8:]), (0, 0, 0))
|
||||
self.assertTrue(all((n != 'BlockAccumulateExchange' for n, _, _ in calls)))
|
||||
host.cuda.memset_d8_async.assert_not_called()
|
||||
with self.assertRaisesRegex(RuntimeError, 'disabled'):
|
||||
run.read_raw_exchange(0, level=3)
|
||||
run.close()
|
||||
|
||||
def test_failed_sync_never_publishes_partial_interval(self):
|
||||
run, host, calls, _ = backend()
|
||||
run.step()
|
||||
run._stream.synchronize.side_effect = RuntimeError('device failure')
|
||||
with self.assertRaisesRegex(RuntimeError, 'device failure'):
|
||||
run.step()
|
||||
self.assertFalse(run._exchange_valid)
|
||||
with self.assertRaisesRegex(RuntimeError, 'failed'):
|
||||
run.read_raw_exchange(0, level=3)
|
||||
run._stream.synchronize.side_effect = None
|
||||
run.close()
|
||||
|
||||
def test_dense_observation_rejected_before_device_access(self):
|
||||
host = host_module()
|
||||
ctx = Mock()
|
||||
with self.assertRaisesRegex(ValueError, 'blocked body'):
|
||||
host.FixedPatchStepper(LBMConfig(nx=32, ny=32, viscosity=.1), (4, 4, 28, 28),
|
||||
context=ctx, fine_objects=[body(radius=2.15)], observe_raw_exchange=True)
|
||||
ctx.activate.assert_not_called()
|
||||
|
||||
def test_all_depth_weights(self):
|
||||
for level in (1, 2, 3, 7):
|
||||
self._check_weights_split_and_window(level)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -163,5 +163,221 @@ class FixedPatchTests(unittest.TestCase):
|
||||
p.check_synchronization(c, f, phase=phase)
|
||||
|
||||
|
||||
class FixedPatchSetTests(unittest.TestCase):
|
||||
"""Several separated patches: level-wide re-addressing of FixedPatch2D tables."""
|
||||
FACE = ((4, 4, 8, 12), (12, 4, 16, 12)) # 16x24 coarse, face gap 4
|
||||
S1 = ((4, 4, 12, 12), (20, 4, 28, 12)) # 16x32 coarse, translation copy
|
||||
|
||||
def build(self, rects, ny=16, nx=24):
|
||||
return refinement.FixedPatchSet2D.from_config(LBMConfig(nx=nx, ny=ny, viscosity=.1), rects)
|
||||
|
||||
def test_tables_are_shifted_single_patch_tables(self):
|
||||
s = self.build(self.FACE)
|
||||
fy, fx = s.fine_shape
|
||||
self.assertEqual((fy, fx), (32, 48))
|
||||
rows = cells = 0
|
||||
for p in s.patches:
|
||||
y0, x0 = p.fine_level_origin
|
||||
ly, lx = p.fine_shape
|
||||
np.testing.assert_array_equal(s.fine_kind[y0:y0 + ly, x0:x0 + lx], p.fine_kind)
|
||||
gy, gx = np.divmod(p.ghost_fine.astype(np.int64), lx)
|
||||
np.testing.assert_array_equal(s.ghost_fine[cells:cells + len(gy)],
|
||||
(gy + y0) * fx + gx + x0)
|
||||
np.testing.assert_array_equal(s.ghost_coarse[cells:cells + len(gy)], p.ghost_coarse)
|
||||
q, c = np.divmod(p.coalesce_fine.astype(np.int64), ly * lx)
|
||||
cy, cx = np.divmod(c, lx)
|
||||
np.testing.assert_array_equal(s.coalesce_fine[rows:rows + len(q)],
|
||||
q * fy * fx + (cy + y0) * fx + cx + x0)
|
||||
np.testing.assert_array_equal(s.coalesce_coarse[rows:rows + len(q)], p.coalesce_coarse)
|
||||
rows, cells = rows + len(q), cells + len(gy)
|
||||
self.assertEqual((rows, cells), (len(s.coalesce_coarse), len(s.ghost_fine)))
|
||||
self.assertEqual(int((s.fine_kind == ACTIVE).sum()), 4 * int(s.covered.sum()))
|
||||
|
||||
def test_input_order_is_irrelevant(self):
|
||||
a, b = self.build(self.FACE), self.build(self.FACE[::-1])
|
||||
for name in ("fine_kind", "ghost_fine", "ghost_coarse", "coalesce_coarse", "coalesce_fine"):
|
||||
np.testing.assert_array_equal(getattr(a, name), getattr(b, name))
|
||||
self.assertEqual(a.bounds, b.bounds)
|
||||
|
||||
def test_one_patch_set_matches_fixed_patch(self):
|
||||
p = FixedPatch2D.from_config(config(), (4, 4, 12, 12))
|
||||
s = self.build(((4, 4, 12, 12),), nx=16)
|
||||
np.testing.assert_array_equal(s.covered, p.covered)
|
||||
self.assertEqual((s.tau_coarse, s.tau_fine), (p.tau_coarse, p.tau_fine))
|
||||
np.testing.assert_array_equal(s.coalesce_coarse, p.coalesce_coarse)
|
||||
np.testing.assert_array_equal(s.ghost_coarse, p.ghost_coarse)
|
||||
|
||||
def test_gap_and_overlap_rejected(self):
|
||||
for gap in (0, 2, 3):
|
||||
with self.subTest(gap=gap), self.assertRaisesRegex(ValueError, "closer"):
|
||||
self.build(((4, 4, 8, 12), (8 + gap, 4, 12 + gap, 12)))
|
||||
with self.assertRaises(ValueError):
|
||||
self.build(())
|
||||
with self.assertRaises(ValueError): # FixedPatch2D margin still applies
|
||||
self.build(((1, 4, 8, 12), (12, 4, 16, 12)))
|
||||
|
||||
def test_sparse_fine_layout_stores_exactly_the_supports(self):
|
||||
for rects, nx in ((self.FACE, 24), (self.S1, 32)):
|
||||
s = self.build(rects, nx=nx)
|
||||
layout = s.fine_layout((4, 4))
|
||||
support = np.zeros(s.fine_shape, bool)
|
||||
for p in s.patches:
|
||||
y0, x0 = p.fine_level_origin
|
||||
support[y0:y0 + p.fine_shape[0], x0:x0 + p.fine_shape[1]] = True
|
||||
np.testing.assert_array_equal(layout.owned, support)
|
||||
self.assertTrue(layout.owned.ravel()[s.ghost_fine.astype(np.intp)].all())
|
||||
with self.assertRaisesRegex(ValueError, "aligned"):
|
||||
self.build(self.FACE).fine_layout((5, 4))
|
||||
for block in ((0, 4), (4, 0), (-4, 4), (4.0, 4), (True, 4), (4,), (4, 4, 4), (np.bool_(1), 4)):
|
||||
with self.subTest(block=block), self.assertRaisesRegex(ValueError, "positive integers"):
|
||||
self.build(self.FACE).fine_layout(block)
|
||||
|
||||
|
||||
class PatchSetBoundaryTests(unittest.TestCase):
|
||||
"""fine_objects/jets on a level-wide patch set (16x32, patches 4 cells apart)."""
|
||||
PATCHES = ((2, 2, 14, 14), (18, 2, 30, 14))
|
||||
|
||||
@staticmethod
|
||||
def body(x, y, obj_id=0):
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
return SimObject(obj_id, geometry=CircleGeometry(x, y, 2.15), center=(x, y), radius=2.15)
|
||||
|
||||
def prepare(self, nx, rects, objects, jets=()):
|
||||
cfg = LBMConfig(nx=nx, ny=16, viscosity=.1)
|
||||
s = refinement.FixedPatchSet2D.from_config(cfg, rects)
|
||||
return s, refinement.prepare_fine_boundary(cfg, s, objects, jets=jets)
|
||||
|
||||
def test_two_bodies_are_the_one_body_case_translated(self):
|
||||
_, one = self.prepare(16, self.PATCHES[:1], [self.body(8., 8.)])
|
||||
_, two = self.prepare(32, self.PATCHES, [self.body(8., 8., 7), self.body(24., 8., 7)])
|
||||
f1, f2 = one.flags.reshape(32, 32), two.flags.reshape(32, 64)
|
||||
np.testing.assert_array_equal(f2[:, :32], f1)
|
||||
np.testing.assert_array_equal(f2[:, 32:], f1)
|
||||
n = len(one.curved_host[0])
|
||||
self.assertEqual(len(two.curved_host[0]), 2 * n)
|
||||
body_id = two.curved_host[3]
|
||||
self.assertEqual(sorted(set(body_id.tolist())), [0, 1]) # positions, not obj_id 7
|
||||
# Translation must reproduce identical link geometry (prerequisite of the
|
||||
# bitwise GPU tiling gate): dirs, q and fallback equal, receivers shifted.
|
||||
fidx, dirs, q, fallback = (two.curved_host[i] for i in (0, 1, 2, 7))
|
||||
for column in (dirs, q, fallback):
|
||||
np.testing.assert_array_equal(column[:n], column[n:])
|
||||
y, x = np.divmod(fidx.astype(np.int64), 64)
|
||||
np.testing.assert_array_equal(y[:n], y[n:])
|
||||
np.testing.assert_array_equal(x[:n] + 32, x[n:])
|
||||
|
||||
def test_body_outside_a_single_patch_rejected(self):
|
||||
for x in (16., 13.): # in the gap / crossing the patch edge
|
||||
with self.subTest(x=x), self.assertRaises(ValueError):
|
||||
self.prepare(32, self.PATCHES, [self.body(x, 8.)])
|
||||
|
||||
def test_one_jet_over_two_bodies_rejected_even_at_zero_amplitude(self):
|
||||
from CelerisLab.body.jets import Jet, Parallel, Tube
|
||||
bodies = [self.body(8., 8.), self.body(24., 8.)]
|
||||
span = Jet(Tube((5., 8.), 0., 22., .6), Parallel(0.), amplitude=0.)
|
||||
with self.assertRaisesRegex(ValueError, "one jet"):
|
||||
self.prepare(32, self.PATCHES, bodies, jets=[span])
|
||||
own = [Jet(Tube((5., 8.), 0., 6., .6), Parallel(0.), amplitude=.002),
|
||||
Jet(Tube((21., 8.), 0., 6., .6), Parallel(0.), amplitude=.002)]
|
||||
self.prepare(32, self.PATCHES, bodies, jets=own) # one jet per body: accepted
|
||||
|
||||
|
||||
class NestPatchTests(unittest.TestCase):
|
||||
"""Three-level single chain: L2 bounds in L1 window cells (probe fixture)."""
|
||||
def setUp(self):
|
||||
self.cfg = config()
|
||||
self.l1 = FixedPatch2D.from_config(self.cfg, (4, 4, 12, 12)) # 24x24 window
|
||||
|
||||
def test_probe_fixture_composes_kinds(self):
|
||||
child, kind = refinement.nest_patch(self.cfg, self.l1, (8, 8, 16, 16))
|
||||
self.assertEqual(child.fine_shape, (24, 24))
|
||||
self.assertAlmostEqual(child.tau_coarse, self.l1.tau_fine)
|
||||
base = self.l1.fine_kind
|
||||
for role in (INNER_GHOST, OUTER_GHOST):
|
||||
np.testing.assert_array_equal(kind[base == role], role)
|
||||
self.assertTrue((kind[child.covered] == OUTER_GHOST).all())
|
||||
self.assertEqual(int((kind == ACTIVE).sum()), 192)
|
||||
self.assertEqual(int((kind == INNER_GHOST).sum()), 144)
|
||||
self.assertEqual(int(child.covered.sum()), 64)
|
||||
|
||||
def test_invalid_nesting_rejected(self):
|
||||
for bounds in ((2, 8, 16, 16), # covers inherited INNER
|
||||
(4, 8, 16, 16), # explosion donors in INNER
|
||||
(8, 8, 20, 16), # donors reach OUTER/INNER at the far side
|
||||
(5, 8, 16, 16)): # one-cell outward: restriction footprint/donors
|
||||
with self.subTest(bounds=bounds), self.assertRaises(ValueError):
|
||||
refinement.nest_patch(self.cfg, self.l1, bounds)
|
||||
|
||||
|
||||
class ChildBoundaryTests(unittest.TestCase):
|
||||
@staticmethod
|
||||
def body(center=(8., 8.), radius=.8, obj_id=99, spec=None):
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
return SimObject(obj_id, geometry=CircleGeometry(*center, radius), center=center,
|
||||
radius=radius, surface_actuation=spec)
|
||||
|
||||
def prepare(self, objects, jets=(), large=False):
|
||||
from dataclasses import replace
|
||||
cfg = LBMConfig(nx=32 if large else 16, ny=32 if large else 16, viscosity=.1)
|
||||
parent = FixedPatch2D.from_config(cfg, (4, 4, 28, 28) if large else (4, 4, 12, 12))
|
||||
child, _ = refinement.nest_patch(cfg, parent, (8, 8, 40, 40) if large else (8, 8, 16, 16))
|
||||
middle = replace(cfg, nx=parent.fine_shape[1], ny=parent.fine_shape[0], viscosity=.2)
|
||||
return child, refinement.prepare_fine_boundary(middle, child, objects, jets=jets,
|
||||
parent_origin=parent.fine_origin, parent_spacing=.5)
|
||||
|
||||
def test_root_frame_matches_independent_parent_frame_projection(self):
|
||||
from CelerisLab.body.jets import Jet, Parallel, Tube, jet_link_shapes
|
||||
jet = Jet(Tube((6.5, 8.), 0., 3., .3), Parallel(0.), amplitude=.002)
|
||||
original = self.body()
|
||||
child, b = self.prepare([original], [jet])
|
||||
middle = LBMConfig(nx=24, ny=24, viscosity=.2)
|
||||
transformed = self.body((12., 12.), 1.6)
|
||||
local_jet = Jet(Tube((9., 12.), 0., 6., .6), Parallel(0.), amplitude=.002)
|
||||
other = refinement.prepare_fine_boundary(middle, child, [transformed], jets=[local_jet])
|
||||
for a, c in zip(b.curved_host, other.curved_host):
|
||||
np.testing.assert_array_equal(a, c)
|
||||
np.testing.assert_array_equal(b.flags, other.flags)
|
||||
np.testing.assert_allclose(b.curved_hits, 2 + .5 * other.curved_hits, atol=0, rtol=0)
|
||||
for a, c in zip(jet_link_shapes([jet], b.curved_hits),
|
||||
jet_link_shapes([local_jet], other.curved_hits)):
|
||||
np.testing.assert_allclose(a, c, atol=1e-14, rtol=0)
|
||||
self.assertEqual(len(b.curved_host[0]), 60)
|
||||
self.assertAlmostEqual(child.tau_fine, .5 + 12 * .1)
|
||||
self.assertEqual(original.geometry.center, (8., 8.))
|
||||
self.assertEqual(original.obj_id, 99)
|
||||
|
||||
def test_invalid_body_and_jet_contracts(self):
|
||||
from CelerisLab.body.jets import Jet, Parallel, Tube
|
||||
from CelerisLab.body.objects import SurfaceActuation
|
||||
jet = Jet(Tube((6.5, 8.), 0., 3., .3), Parallel(0.), amplitude=.002)
|
||||
for body in (self.body((6., 8.)), self.body((6.9, 8.)), self.body(radius=2.1)):
|
||||
with self.assertRaises(ValueError):
|
||||
self.prepare([body])
|
||||
moving = self.body()
|
||||
moving.state.vx = .01
|
||||
with self.assertRaisesRegex(ValueError, "stationary"):
|
||||
self.prepare([moving])
|
||||
with self.assertRaises(ValueError):
|
||||
self.prepare([self.body()], [jet, jet])
|
||||
empty = Jet(Tube((0., 0.), 0., 1., .1), Parallel(0.), amplitude=0.)
|
||||
with self.assertRaises(ValueError):
|
||||
self.prepare([self.body()], [empty])
|
||||
spec = SurfaceActuation(.7, .85, .002)
|
||||
with self.assertRaisesRegex(ValueError, "SurfaceActuation"):
|
||||
self.prepare([self.body(spec=spec)], [spec.as_jet((8., 8.), .8)])
|
||||
|
||||
def test_one_jet_two_real_bodies_same_caller_id_rejected(self):
|
||||
from CelerisLab.body.jets import Jet, Parallel, Tube
|
||||
bodies = [self.body((12., 14.), 1., 7), self.body((17., 14.), 1., 7)]
|
||||
_, boundary = self.prepare(bodies, large=True) # establish legal geometry first
|
||||
self.assertEqual(np.unique(boundary.curved_host[3]).tolist(), [0, 1])
|
||||
for amplitude in (0., .002):
|
||||
jet = Jet(Tube((10., 14.), 0., 9., .4), Parallel(0.), amplitude=amplitude)
|
||||
with self.assertRaisesRegex(ValueError, "one jet may drive only one body"):
|
||||
self.prepare(bodies, [jet], large=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,334 @@
|
||||
"""CPU-only union geometry and production host-control-flow tests.
|
||||
|
||||
The AST loader omits CUDA imports and supplies explicit mocks; it executes
|
||||
unchanged production definitions, never CUDA kernels or a numerical emulator.
|
||||
"""
|
||||
import ast
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm import refinement as r
|
||||
|
||||
|
||||
def host_module():
|
||||
path=Path(r.__file__).with_name('refinement_stepper.py')
|
||||
tree=ast.parse(path.read_text())
|
||||
tree.body=[node for node in tree.body if not (
|
||||
isinstance(node,ast.Import) and any(a.name=='pycuda.driver' for a in node.names)
|
||||
or isinstance(node,ast.ImportFrom) and node.module in (
|
||||
'cuda','block_stepper','curved_links'))]
|
||||
module=types.ModuleType('CelerisLab.lbm._test_host_refinement')
|
||||
module.__package__='CelerisLab.lbm'
|
||||
from CelerisLab.body.jets import surface_link_velocity
|
||||
module.__dict__.update(cuda=Mock(),compiler=Mock(),MAX_GRID_DIM=65535,
|
||||
surface_link_velocity=surface_link_velocity)
|
||||
exec(compile(tree,str(path),'exec'),module.__dict__)
|
||||
return module
|
||||
|
||||
|
||||
host=host_module()
|
||||
CFG = LBMConfig(nx=48, ny=32, viscosity=.1)
|
||||
PARENTS = ((4,4,20,28), (24,4,44,28)) # exact gap=4 coarse cells
|
||||
CHILDREN = ((16,16,32,40), (56,16,80,40)) # parent-allocated L1 cells
|
||||
|
||||
|
||||
class Gate(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.parent = r.FixedPatchSet2D.from_config(CFG, PARENTS)
|
||||
|
||||
def test_one_element_equivalence(self):
|
||||
cfg = LBMConfig(nx=16,ny=16,viscosity=.1)
|
||||
local = r.FixedPatch2D.from_config(cfg,(4,4,12,12))
|
||||
global_parent = r.FixedPatchSet2D.from_config(cfg,[(4,4,12,12)])
|
||||
a, ak = r.nest_patch(cfg,local,(8,8,16,16))
|
||||
b, bk = r.nest_patch_set(cfg,global_parent,[(12,12,20,20)])
|
||||
local_set, local_kind = r.nest_patch_set(cfg,local,[(8,8,16,16)])
|
||||
np.testing.assert_array_equal(ak,local_kind)
|
||||
np.testing.assert_array_equal(a.fine_kind,local_set.patches[0].fine_kind)
|
||||
np.testing.assert_array_equal(a.ghost_coarse,local_set.ghost_coarse)
|
||||
np.testing.assert_array_equal(a.coalesce_coarse,local_set.coalesce_coarse)
|
||||
np.testing.assert_array_equal(ak, bk[4:28,4:28])
|
||||
# L2 node-index offsets in global L2 grid: local parent origin=2 L0.
|
||||
ay,ax=np.nonzero(a.fine_kind == r.ACTIVE)
|
||||
by,bx=np.nonzero(b.fine_kind == r.ACTIVE)
|
||||
np.testing.assert_array_equal(np.stack([ay+20,ax+20],-1),np.stack([by,bx],-1))
|
||||
np.testing.assert_array_equal(a.fine_kind,b.fine_kind[20:44,20:44])
|
||||
# Compare complete per-region maps after undoing set addressing.
|
||||
bp=b.patches[0]
|
||||
np.testing.assert_array_equal(a.coalesce_fine,bp.coalesce_fine)
|
||||
aq,ac=np.divmod(a.coalesce_coarse,24*24)
|
||||
bq,bc=np.divmod(bp.coalesce_coarse,32*32)
|
||||
np.testing.assert_array_equal(aq,bq)
|
||||
np.testing.assert_array_equal(np.stack(np.divmod(ac,24),-1)+4,np.stack(np.divmod(bc,32),-1))
|
||||
ay,ax=np.divmod(a.ghost_coarse,24)
|
||||
by,bx=np.divmod(bp.ghost_coarse,32)
|
||||
np.testing.assert_array_equal(np.stack([ay+4,ax+4],-1),np.stack([by,bx],-1))
|
||||
|
||||
def test_twin_tile_chains_and_order(self):
|
||||
children=((16,16,32,40),(56,16,72,40))
|
||||
child,kind=r.nest_patch_set(CFG,self.parent,children)
|
||||
other,ok=r.nest_patch_set(CFG,r.FixedPatchSet2D.from_config(CFG,PARENTS[::-1]),children[::-1])
|
||||
for name in ('fine_kind','ghost_fine','ghost_coarse','coalesce_coarse','coalesce_fine'):
|
||||
np.testing.assert_array_equal(getattr(child,name),getattr(other,name))
|
||||
np.testing.assert_array_equal(kind,ok)
|
||||
for p in child.patches:
|
||||
self.assertEqual(p.fine_shape,child.patches[0].fine_shape)
|
||||
np.testing.assert_array_equal(child.patches[0].fine_kind,child.patches[1].fine_kind)
|
||||
self.assertEqual(child.tau_coarse,self.parent.tau_fine)
|
||||
self.assertAlmostEqual(child.tau_fine,1.7)
|
||||
|
||||
def test_asymmetric_no_child_region(self):
|
||||
child,kind=r.nest_patch_set(CFG,self.parent,[CHILDREN[0]])
|
||||
np.testing.assert_array_equal(kind[:,48:],self.parent.fine_kind[:,48:])
|
||||
self.assertEqual(int(child.covered.sum()),16*24)
|
||||
|
||||
def test_two_children_one_parent(self):
|
||||
child,kind=r.nest_patch_set(CFG,self.parent,[(16,16,32,24),(16,28,32,40)])
|
||||
self.assertEqual(len(child.patches),2)
|
||||
self.assertEqual(int(child.covered.sum()),16*20)
|
||||
self.assertEqual(int((kind==r.ACTIVE).sum()),int((self.parent.fine_kind==r.ACTIVE).sum())-16*20)
|
||||
|
||||
def test_holes_donors_receivers_footprint_and_invalid_pull(self):
|
||||
child,_=r.nest_patch_set(CFG,self.parent,CHILDREN)
|
||||
cases=[('inherited ACTIVE', lambda: r.nest_patch_set(CFG,self.parent,[(40,16,48,40)])),
|
||||
('donors/receivers', lambda: r.nest_patch_set(CFG,self.parent,[(8,16,32,40)]))]
|
||||
for text,call in cases:
|
||||
with self.subTest(text=text),self.assertRaisesRegex(ValueError,text):call()
|
||||
# Synthetic upstream dependency inside child coverage isolates the final guard.
|
||||
upstream=self.parent.coalesce_fine.copy()
|
||||
upstream[0,:]=20*self.parent.fine_shape[1]+20 # q=0, deep inherited ACTIVE
|
||||
with self.assertRaisesRegex(ValueError,'restriction footprint'):
|
||||
r._nested_kind(replace(self.parent,coalesce_fine=upstream),child)
|
||||
hole=int(np.flatnonzero(~self.parent.fine_layout((4,4)).owned.ravel())[0])
|
||||
donors=child.ghost_coarse.copy();donors[0]=hole
|
||||
with self.assertRaisesRegex(ValueError,'donors/receivers'):
|
||||
r._nested_kind(self.parent,replace(child,ghost_coarse=donors))
|
||||
receivers=child.coalesce_coarse.copy();receivers[0]=hole
|
||||
with self.assertRaisesRegex(ValueError,'donors/receivers'):
|
||||
r._nested_kind(self.parent,replace(child,coalesce_coarse=receivers))
|
||||
# Remove all supplying rows; covered-to-uncovered pulls must be rejected.
|
||||
with self.assertRaisesRegex(ValueError,'surviving parent ACTIVE pull'):
|
||||
r._nested_kind(self.parent,replace(child,coalesce_coarse=child.coalesce_coarse[:0],coalesce_fine=child.coalesce_fine[:0]))
|
||||
|
||||
def test_existing_l2_body_jet_preparation_on_union(self):
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.body.jets import Jet, Tube, Parallel, jet_link_shapes
|
||||
child,_=r.nest_patch_set(CFG,self.parent,CHILDREN)
|
||||
centers=((12.,14.),(34.,14.))
|
||||
objects=[SimObject(99,geometry=CircleGeometry(*c,.8),center=c,radius=.8) for c in centers]
|
||||
jets=[Jet(Tube((c[0]-1.5,c[1]),0.,3.,.3),Parallel(0.),amplitude=.002) for c in centers]
|
||||
middle=replace(CFG,nx=self.parent.fine_shape[1],ny=self.parent.fine_shape[0],viscosity=.2)
|
||||
boundary=r.prepare_fine_boundary(middle,child,objects,jets=jets,
|
||||
parent_origin=self.parent.fine_origin,parent_spacing=.5)
|
||||
ids=boundary.curved_host[3]
|
||||
np.testing.assert_array_equal(np.unique(ids),[0,1])
|
||||
self.assertEqual(int((ids==0).sum()),int((ids==1).sum()))
|
||||
np.testing.assert_allclose(boundary.curved_hits[ids==1]-boundary.curved_hits[ids==0],
|
||||
np.broadcast_to([22.,0.],boundary.curved_hits[ids==0].shape),atol=1e-14,rtol=0)
|
||||
_,jid=jet_link_shapes(jets,boundary.curved_hits)
|
||||
for i in (0,1):
|
||||
self.assertTrue((ids[jid==i]==i).all())
|
||||
self.assertTrue((jid==i).any())
|
||||
|
||||
def test_sparse_parent_tables_preserve_inherited_kinds(self):
|
||||
child,kind=r.nest_patch_set(CFG,self.parent,CHILDREN)
|
||||
layout=self.parent.fine_layout((4,4));order=np.argsort(child.coalesce_coarse)
|
||||
donors,targets,bkind=host.blocked_base_tables(child,layout,order,composed_kind=kind)
|
||||
self.assertTrue((donors < layout.hole).all())
|
||||
self.assertTrue((targets < np.prod(layout.blocked_shape)).all())
|
||||
np.testing.assert_array_equal(bkind[layout.owner[layout.owned]],kind[layout.owned])
|
||||
inherited=self.parent.fine_kind != r.ACTIVE
|
||||
np.testing.assert_array_equal(kind[inherited],self.parent.fine_kind[inherited])
|
||||
self.assertTrue((kind[child.covered] == r.OUTER_GHOST).all())
|
||||
l2=child.fine_layout((4,4))
|
||||
ghosts,children,ckind=host.blocked_fine_tables(child,l2,order)
|
||||
self.assertTrue((ghosts<l2.hole).all())
|
||||
self.assertTrue((children<np.prod(l2.blocked_shape)).all())
|
||||
for p,lay in ((self.parent,layout),(child,l2)):
|
||||
self.assertTrue(lay.owned.ravel()[p.ghost_fine].all())
|
||||
self.assertTrue(lay.owned.ravel()[p.coalesce_fine % np.uint64(np.prod(p.fine_shape))].all())
|
||||
hole=int(np.flatnonzero(~layout.owned.ravel())[0])
|
||||
bad=child.ghost_coarse.copy();bad[0]=hole
|
||||
with self.assertRaisesRegex(ValueError,'owned uncovered'):
|
||||
host.blocked_base_tables(replace(child,ghost_coarse=bad),layout,order,composed_kind=kind)
|
||||
bad=child.coalesce_coarse.copy();bad[0]=hole
|
||||
with self.assertRaisesRegex(ValueError,'owned uncovered'):
|
||||
host.blocked_base_tables(replace(child,coalesce_coarse=bad),layout,order,composed_kind=kind)
|
||||
|
||||
|
||||
def bodies_and_jets(speed=.002):
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.body.jets import Jet, Tube, Parallel
|
||||
centers=((12.,14.),(34.,14.))
|
||||
bodies=[SimObject(99,geometry=CircleGeometry(*c,.8),center=c,radius=.8) for c in centers]
|
||||
jets=[Jet(Tube((c[0]-1.5,c[1]),0.,3.,.3),Parallel(0.),amplitude=speed) for c in centers]
|
||||
return bodies,jets
|
||||
|
||||
|
||||
KW=dict(base_block=(4,4),fine_block=(4,4),child_block=(4,4),
|
||||
child_rectangles_in_parent=CHILDREN)
|
||||
|
||||
|
||||
def mock_backend(*, children=CHILDREN, bodies=False, fail_compile=False, fail_upload=False):
|
||||
module=host_module()
|
||||
context=Mock(activate=nullcontext,sm_arch='sm_70')
|
||||
allocations=[]
|
||||
def allocate(size):
|
||||
pointer=Mock(name=f'allocation_{len(allocations)}')
|
||||
allocations.append(pointer)
|
||||
return pointer
|
||||
module.cuda.mem_alloc.side_effect=allocate
|
||||
def load(ptx):
|
||||
gpu=Mock()
|
||||
gpu.get_function.side_effect=lambda name: Mock(name=name)
|
||||
gpu.get_global.side_effect=lambda name: (Mock(),20 if name=='d_params' else 16)
|
||||
return gpu
|
||||
module.compiler.load_module.side_effect=load
|
||||
if fail_compile:
|
||||
module.compiler.compile_kernel.side_effect=['first','second',RuntimeError('L2 compile failed')]
|
||||
if fail_upload:
|
||||
def upload(*args):
|
||||
if len(allocations)>20:
|
||||
raise RuntimeError('table upload failed')
|
||||
module.cuda.memcpy_htod.side_effect=upload
|
||||
objects,jets=bodies_and_jets() if bodies else ((),())
|
||||
try:
|
||||
run=module.FixedPatchStepper(CFG,PARENTS,context=context,
|
||||
child_objects=objects,child_jets=jets,
|
||||
**dict(KW,child_rectangles_in_parent=children))
|
||||
except RuntimeError:
|
||||
for allocation in allocations:
|
||||
allocation.free.assert_called_once_with()
|
||||
raise
|
||||
return run,module,allocations
|
||||
|
||||
|
||||
class ConstructorAndSchedule(unittest.TestCase):
|
||||
def test_invalid_inputs_fail_before_context_or_allocations(self):
|
||||
context=Mock()
|
||||
cases=[dict(child=(8,8,16,16)),dict(child_rectangles_in_parent=[]),
|
||||
dict(child_rectangles_in_parent=[(16,16,32)]),
|
||||
dict(child_rectangles_in_parent=[(16.5,16,32,40)]),
|
||||
dict(child_rectangles_in_parent=[(16,16,32,24),(16,27,32,40)]),
|
||||
dict(child_rectangles_in_parent=[(40,16,48,40)]),
|
||||
dict(child_rectangles_in_parent=[(8,16,32,40)]),
|
||||
dict(child_block=None),dict(fine_block=None),dict(base_block=None),
|
||||
dict(child_block=(5,4)),dict(fine_block=(5,4)),
|
||||
dict(child_block=(4,)),dict(child_rectangles_in_parent=(16,16,32,40))]
|
||||
for changes in cases:
|
||||
with self.subTest(changes=changes),self.assertRaises((ValueError,TypeError)):
|
||||
host.FixedPatchStepper(CFG,PARENTS,context=context,**dict(KW,**changes))
|
||||
with self.assertRaisesRegex(ValueError,'closer'):
|
||||
host.FixedPatchStepper(CFG,[(4,4,20,28),(23,4,44,28)],context=context,**KW)
|
||||
objects,jets=bodies_and_jets()
|
||||
with self.assertRaisesRegex(ValueError,'only on L2'):
|
||||
host.FixedPatchStepper(CFG,PARENTS,context=context,fine_objects=objects,**KW)
|
||||
from CelerisLab.body.jets import Jet,Tube,Parallel
|
||||
spanning=Jet(Tube((10.5,14.),0.,25.,.3),Parallel(0.),amplitude=0.)
|
||||
with self.assertRaisesRegex(ValueError,'one jet'):
|
||||
host.FixedPatchStepper(CFG,PARENTS,context=context,child_objects=objects,
|
||||
child_jets=[spanning],**KW)
|
||||
context.activate.assert_not_called()
|
||||
host.cuda.mem_alloc.assert_not_called()
|
||||
|
||||
def test_aggregate_schedule_independent_of_region_count(self):
|
||||
for children,bodies in ((CHILDREN,True),(CHILDREN[:1],False),
|
||||
(((16,16,32,24),(16,28,32,40)),False)):
|
||||
run,_,allocations=mock_backend(children=children,bodies=bodies)
|
||||
self.assertEqual(len(run._levels),3)
|
||||
c,f,g=run._levels
|
||||
self.assertEqual(len({id(level.current) for level in run._levels} |
|
||||
{id(level.spare) for level in run._levels}),6)
|
||||
events=[]
|
||||
initial_c=c.current
|
||||
def record(name):
|
||||
return lambda source,*a,**kw: events.append((name,source))
|
||||
run._pairs[0].explode.side_effect=record('explode01')
|
||||
run._pairs[1].explode.side_effect=record('explode12')
|
||||
for i,level in enumerate(run._levels):
|
||||
level.kernel.side_effect=record(f'step{i}')
|
||||
if bodies:
|
||||
g.boundary.kernel.side_effect=record('bfl2')
|
||||
run._pairs[1].coalesce.side_effect=lambda src,dst,*a,**kw: events.append(('restrict21',dst))
|
||||
run._pairs[0].coalesce.side_effect=lambda src,dst,*a,**kw: events.append(('restrict10',dst))
|
||||
run._status='ready'
|
||||
expected=[('explode01',initial_c)]
|
||||
for middle in (f.current,f.spare):
|
||||
expected.append(('explode12',middle))
|
||||
for leaf in (g.current,g.spare):
|
||||
expected.append(('halo2',leaf))
|
||||
if bodies:
|
||||
expected.append(('bfl2',leaf))
|
||||
expected.append(('step2',leaf))
|
||||
expected.extend([('halo1',middle),('restrict21',middle),('step1',middle)])
|
||||
expected.extend([('halo0',initial_c),('restrict10',initial_c),('step0',initial_c)])
|
||||
def gather(level,buffer,**kw):
|
||||
events.append((f'halo{next(i for i,l in enumerate(run._levels) if l is level)}',buffer))
|
||||
with patch.object(run,'_gather_halo',side_effect=gather):
|
||||
run.step()
|
||||
self.assertEqual(events,expected)
|
||||
self.assertEqual([l.kernel.call_count for l in run._levels],[1,2,4])
|
||||
# A stale-feed implementation must fail the source-identity guard.
|
||||
feeds=[]
|
||||
advance=run._advance
|
||||
def checked_advance(index, buffer, **kw):
|
||||
if index == 2: # L1 -> L2 feed: must be the L1 hop source
|
||||
self.assertIs(buffer,(f.current,f.spare)[len(feeds)])
|
||||
feeds.append(buffer)
|
||||
advance(index,buffer,**kw)
|
||||
with patch.object(run,'_advance',side_effect=lambda index,buffer,**kw:
|
||||
checked_advance(index,f.current if index == 2 else buffer,**kw)):
|
||||
with self.assertRaises(AssertionError):
|
||||
run.step()
|
||||
# A per-region shared-parent advance must fail the 1:2:4 guard.
|
||||
run._status='ready'
|
||||
counts=[0,0,0]
|
||||
def count(index, multiple=1):
|
||||
def step(*a,**kw):
|
||||
counts[index]+=multiple
|
||||
return step
|
||||
c.kernel.side_effect=count(0)
|
||||
f.kernel.side_effect=count(1,2) # mutant: twice per shared L1 hop
|
||||
g.kernel.side_effect=count(2)
|
||||
run.step()
|
||||
with self.assertRaises(AssertionError):
|
||||
self.assertEqual(counts,[1,2,4])
|
||||
run.close();run.close()
|
||||
for allocation in allocations:
|
||||
allocation.free.assert_called_once_with()
|
||||
|
||||
def test_partial_construction_frees_every_allocation(self):
|
||||
for options in (dict(fail_compile=True),dict(fail_upload=True)):
|
||||
with self.subTest(options=options),self.assertRaisesRegex(RuntimeError,'failed'):
|
||||
mock_backend(**options)
|
||||
|
||||
|
||||
|
||||
|
||||
class InitialLevels(unittest.TestCase):
|
||||
"""initialize() entry adapter: positional per-level arrays or the legacy names, never both."""
|
||||
|
||||
def test_forms(self):
|
||||
a, b, c = object(), object(), object()
|
||||
f = host._initial_levels
|
||||
self.assertEqual(f((a, b), None, None, None), (a, b))
|
||||
self.assertEqual(f((a, b, c), None, None, None), (a, b, c))
|
||||
self.assertEqual(f((a, b), None, None, c), (a, b, c)) # old initialize(c, f, child_g=g)
|
||||
self.assertEqual(f((), a, b, None), (a, b))
|
||||
self.assertEqual(f((), a, b, c), (a, b, c))
|
||||
for args in (((a,), None, None, c), ((a, b, c), None, None, c), ((a,), a, b, None),
|
||||
((), a, None, None), ((), None, b, c)):
|
||||
with self.subTest(args=args), self.assertRaises(TypeError):
|
||||
f(*args)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,123 @@
|
||||
"""CPU mocks execute production remap lifecycle; no GPU numerical claim."""
|
||||
from dataclasses import replace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from tests.unit.test_refinement_three_level_multipatch import mock_backend
|
||||
from tests.unit.test_synchronized_remap import A, B, fields, topology, remap
|
||||
|
||||
|
||||
def ready_backend():
|
||||
run, module, allocations = mock_backend(children=A)
|
||||
storage = {}
|
||||
module.cuda.memcpy_htod.side_effect = lambda ptr, a: storage.__setitem__(id(ptr), np.array(a, copy=True))
|
||||
module.cuda.memcpy_dtoh.side_effect = lambda a, ptr: np.copyto(a, storage[id(ptr)])
|
||||
run.initialize(*fields(topology(A), np.float32))
|
||||
run._step_count = 7
|
||||
return run, module, allocations, storage
|
||||
|
||||
|
||||
class RuntimeChildRemap(unittest.TestCase):
|
||||
def test_current_snapshot_identity_and_count_continuation(self):
|
||||
run, module, allocations, storage = ready_backend()
|
||||
# Make current state distinct from initialization and spare, as after a step.
|
||||
for level in run._levels:
|
||||
storage[id(level.current)] *= np.float32(1.01)
|
||||
before = run.download()
|
||||
saved = {key: value.copy() for key, value in storage.items()}
|
||||
old_allocations = list(allocations)
|
||||
module.cuda.memcpy_dtoh.reset_mock()
|
||||
clone = run.remap_child(A)
|
||||
self.assertEqual(module.cuda.memcpy_dtoh.call_count, 3)
|
||||
for a, b in zip(clone.download(), before):
|
||||
np.testing.assert_array_equal(a, b)
|
||||
self.assertEqual((run.step_count, clone.step_count), (7, 7))
|
||||
for key, value in saved.items():
|
||||
np.testing.assert_array_equal(storage[key], value)
|
||||
for allocation in old_allocations:
|
||||
allocation.free.assert_not_called()
|
||||
clone.step()
|
||||
self.assertEqual((run.step_count, clone.step_count), (7, 8))
|
||||
run.step()
|
||||
self.assertEqual(run.step_count, 8)
|
||||
clone.close(); run.close()
|
||||
|
||||
def test_shift_uses_cpu_remap_and_resets_both_buffers(self):
|
||||
run, module, allocations, storage = ready_backend()
|
||||
before = run.download()
|
||||
expected = remap(topology(A), topology(B), before).g
|
||||
clone = run.remap_child(B)
|
||||
for level, want, got in zip(clone._levels, expected, clone.download()):
|
||||
np.testing.assert_array_equal(got, want)
|
||||
for ptr in (level.current, level.spare):
|
||||
np.testing.assert_array_equal(storage[id(ptr)], level.layout.to_blocked(want))
|
||||
for a, b in zip(run.download(), before):
|
||||
np.testing.assert_array_equal(a, b)
|
||||
clone.initialize(*expected)
|
||||
self.assertEqual(clone.step_count, 0) # Existing public initialization semantics.
|
||||
clone.close(); run.close()
|
||||
|
||||
def test_invalid_state_geometry_and_body_reject_before_reads_allocations(self):
|
||||
run, module, allocations, storage = ready_backend()
|
||||
start = len(allocations)
|
||||
module.cuda.memcpy_dtoh.reset_mock()
|
||||
for status in ('new', 'failed', 'closed', 'advancing'):
|
||||
run._status = status
|
||||
with self.assertRaises(RuntimeError): run.remap_child(B)
|
||||
run._status = 'ready'
|
||||
for bad in ([], [(40,16,48,40)], [(16,16,32,24),(16,27,32,40)]):
|
||||
with self.assertRaises(ValueError): run.remap_child(bad)
|
||||
hosts, pairs = run._boundary_hosts, run.hierarchy.pairs
|
||||
for attribute, value in (('_wall_aware', True),
|
||||
('_boundary_hosts', [*hosts[:2], object()]), # child boundary
|
||||
('_boundary_hosts', [hosts[0], object(), hosts[2]]), # fine boundary
|
||||
('hierarchy', replace(run.hierarchy, pairs=(pairs[0], None)))):
|
||||
with patch.object(run, attribute, value):
|
||||
with self.assertRaises(ValueError): run.remap_child(B)
|
||||
self.assertEqual(len(allocations), start)
|
||||
module.cuda.memcpy_dtoh.assert_not_called()
|
||||
run.close()
|
||||
|
||||
def test_candidate_construction_or_upload_failure_preserves_source(self):
|
||||
for failure in ('construction', 'initialize'):
|
||||
run, module, allocations, storage = ready_backend()
|
||||
before = run.download()
|
||||
old_allocations = list(allocations)
|
||||
if failure == 'construction':
|
||||
operation = patch.object(module.compiler, 'compile_kernel', side_effect=RuntimeError('candidate compile'))
|
||||
else:
|
||||
initialize = type(run).initialize
|
||||
def fail(candidate, *arrays):
|
||||
upload = module.cuda.memcpy_htod.side_effect
|
||||
calls = 0
|
||||
def partial_upload(pointer, array):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 2:
|
||||
raise RuntimeError('candidate upload')
|
||||
upload(pointer, array)
|
||||
with patch.object(module.cuda, 'memcpy_htod', side_effect=partial_upload):
|
||||
initialize(candidate, *arrays)
|
||||
operation = patch.object(type(run), 'initialize', fail)
|
||||
with operation, self.assertRaisesRegex(RuntimeError, 'candidate'):
|
||||
run.remap_child(B)
|
||||
self.assertEqual((run._status, run.step_count), ('ready', 7))
|
||||
for a, b in zip(run.download(), before): np.testing.assert_array_equal(a, b)
|
||||
for allocation in old_allocations: allocation.free.assert_not_called()
|
||||
for allocation in allocations[len(old_allocations):]: allocation.free.assert_called_once()
|
||||
run.close()
|
||||
|
||||
def test_old_sync_or_read_failure_marks_only_old_failed(self):
|
||||
for operation in ('sync', 'read'):
|
||||
run, module, allocations, storage = ready_backend()
|
||||
start = len(allocations)
|
||||
target = run._stream.synchronize if operation == 'sync' else module.cuda.memcpy_dtoh
|
||||
target.side_effect = RuntimeError('old device failure')
|
||||
with self.assertRaisesRegex(RuntimeError, 'old device'):
|
||||
run.remap_child(B)
|
||||
self.assertEqual(run._status, 'failed')
|
||||
self.assertEqual(len(allocations), start)
|
||||
target.side_effect = None
|
||||
run.close()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""CPU-only research-example contracts; no solver/GPU import required."""
|
||||
import unittest
|
||||
import numpy as np
|
||||
from research.shear_refinement.boundary_shear_tagging import tag_cells, strain_rate
|
||||
from research.shear_refinement.example import (CHILDREN, grow_rectangle, topology,
|
||||
observe, initial_fields)
|
||||
|
||||
|
||||
class ShearRefinementExample(unittest.TestCase):
|
||||
def test_affine_shear_physical_spacing_and_rotation(self):
|
||||
y, x = np.indices((12, 20), dtype=float)
|
||||
x, y = 7.+.5*(x+.5), 3.+.5*(y+.5)
|
||||
valid = np.ones(x.shape, bool)
|
||||
np.testing.assert_allclose(strain_rate(.003*y, 0*x, valid, .5), .003, atol=1e-17)
|
||||
np.testing.assert_allclose(strain_rate(-.003*y, .003*x, valid, .5), 0., atol=1e-17)
|
||||
|
||||
def test_holes_are_unknown_not_walls_or_zero(self):
|
||||
valid = np.zeros((7, 7), bool); valid[3, 3] = True
|
||||
u = np.full(valid.shape, np.nan); u[3, 3] = .1
|
||||
result = tag_cells(u, u, np.zeros_like(valid), valid=valid, owned=valid,
|
||||
dx_level=.5, origin=(7., 3.), U_ref=.05, L_ref=1.,
|
||||
shear_on=.01, shear_off=0., band_on=0., band_off=0., n_buffer=0)
|
||||
self.assertTrue(result.unevaluable[3, 3])
|
||||
self.assertTrue(np.isnan(result.strain_star[3, 3]))
|
||||
self.assertFalse(result.tagged.any())
|
||||
self.assertTrue(np.isinf(result.wall_distance).all())
|
||||
|
||||
def test_masked_hole_never_supplies_a_gradient(self):
|
||||
y, x = np.indices((9, 9), dtype=float)
|
||||
valid = np.ones(x.shape, bool); valid[:, 4] = False
|
||||
ux = .003*(5.+.5*y); uy = np.zeros_like(ux)
|
||||
ux[~valid] = np.inf; uy[~valid] = np.nan
|
||||
strain = strain_rate(ux, uy, valid, .5)
|
||||
np.testing.assert_allclose(strain[valid], .003, atol=1e-17)
|
||||
self.assertTrue(np.isnan(strain[~valid]).all())
|
||||
|
||||
def test_predictable_growth_and_input_unchanged(self):
|
||||
mask = np.zeros((64, 96), bool); mask[22, 74] = True
|
||||
before = mask.copy()
|
||||
self.assertEqual(grow_rectangle(CHILDREN[1], mask), (56, 16, 76, 40))
|
||||
np.testing.assert_array_equal(mask, before)
|
||||
mask[:] = False
|
||||
self.assertEqual(grow_rectangle(CHILDREN[1], mask), CHILDREN[1])
|
||||
|
||||
def test_budget_and_geometry_rejection(self):
|
||||
mask = np.zeros((64, 96), bool); mask[22, 74] = True
|
||||
with self.assertRaisesRegex(ValueError, 'area cap'):
|
||||
grow_rectangle(CHILDREN[1], mask, area_cap=479)
|
||||
with self.assertRaises(ValueError):
|
||||
grow_rectangle((57, 16, 72, 40), mask)
|
||||
mask = np.zeros((9, 9), bool); mask[8, 8] = True
|
||||
with self.assertRaisesRegex(ValueError, 'frame'):
|
||||
grow_rectangle((0, 0, 4, 4), mask)
|
||||
with self.assertRaises(ValueError):
|
||||
topology((CHILDREN[0], (56, 16, 88, 40)))
|
||||
|
||||
def test_uniform_velocity_observation_does_not_grow(self):
|
||||
from CelerisLab.lbm.equilibrium import compute_feq_d2q9
|
||||
mesh = topology()
|
||||
g = np.broadcast_to(compute_feq_d2q9(1., .01, 0.)[:, None, None],
|
||||
(9, *mesh.leaf_masks[1].shape)).copy()
|
||||
g[:, ~mesh.leaf_masks[1]] = np.nan
|
||||
rectangles, report = observe(g, mesh)
|
||||
self.assertEqual(rectangles, CHILDREN)
|
||||
self.assertEqual(report['requested'], 0)
|
||||
|
||||
def test_observation_growth_and_low_strain_no_change(self):
|
||||
mesh = topology()
|
||||
g = initial_fields(mesh)[1]
|
||||
g[:, ~mesh.leaf_masks[1]] = np.nan
|
||||
before = g.copy()
|
||||
rectangles, report = observe(g, mesh)
|
||||
self.assertEqual(rectangles, (CHILDREN[0], (56, 16, 76, 40)))
|
||||
self.assertEqual(report['requested'], 64)
|
||||
self.assertEqual(report['corridor_unknown'], 0)
|
||||
self.assertEqual(report['corridor_unavailable'], 0)
|
||||
self.assertGreater(report['out_of_scope'], 0)
|
||||
np.testing.assert_array_equal(g, before)
|
||||
rectangles, report = observe(g, mesh, shear_on=1.)
|
||||
self.assertEqual(rectangles, CHILDREN)
|
||||
self.assertEqual(report['requested'], 0)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,205 @@
|
||||
"""CPU remap tests: full-population conservation, never a runtime AMR claim."""
|
||||
from dataclasses import replace
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm.blocks import BlockLayout2D
|
||||
from CelerisLab.lbm.descriptors import D2Q9_EX, D2Q9_EY
|
||||
from CelerisLab.lbm.refinement import FixedPatch2D, FixedPatchSet2D
|
||||
from CelerisLab.lbm.synchronized_remap import RemapTopology, remap_synchronized
|
||||
|
||||
|
||||
CFG = LBMConfig(nx=48, ny=32, viscosity=.1)
|
||||
PARENTS = [(4, 4, 20, 28), (24, 4, 44, 28)]
|
||||
A, B = [(16, 16, 32, 40)], [(20, 16, 36, 40)]
|
||||
|
||||
|
||||
def topology(rectangles, parent=None, cfg=CFG):
|
||||
if parent is None:
|
||||
parent = FixedPatchSet2D.from_config(cfg, PARENTS)
|
||||
return RemapTopology.from_config(cfg, parent, rectangles)
|
||||
|
||||
|
||||
def fields(mesh, dtype=np.float64):
|
||||
rng = np.random.default_rng(8473)
|
||||
result = []
|
||||
for leaf in mesh.leaf_masks:
|
||||
# Direction-dependent and non-equilibrium, with independently varying
|
||||
# children: q0 and momentum cannot be recovered from equilibrium rho/u.
|
||||
g = rng.uniform(.03, .15, (9, *leaf.shape)).astype(dtype)
|
||||
g += np.arange(9, dtype=dtype)[:, None, None] * .01
|
||||
g[:, ~leaf] = np.nan
|
||||
result.append(g)
|
||||
return result
|
||||
|
||||
|
||||
def remap(old, new, g, **kwargs):
|
||||
options = dict(base_count=7, level_steps=(7, 14, 28), phase='postcollision_g',
|
||||
origin=(-3., 2.), spacing=1.25)
|
||||
options.update(kwargs)
|
||||
return remap_synchronized(old, new, g, **options)
|
||||
|
||||
|
||||
def integrals(mesh, g, spacing=1.25):
|
||||
populations = sum(a[:, mask].sum(axis=1, dtype=np.float64) * spacing**2 / 4**level
|
||||
for level, (a, mask) in enumerate(zip(g, mesh.leaf_masks)))
|
||||
return np.r_[populations, populations.sum(), populations @ D2Q9_EX,
|
||||
populations @ D2Q9_EY]
|
||||
|
||||
|
||||
class SynchronizedRemapTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.old, self.new = topology(A), topology(B)
|
||||
self.g = fields(self.old)
|
||||
|
||||
def test_identity_bitwise_and_no_mutation_or_count_advance(self):
|
||||
copies = [a.copy() for a in self.g]
|
||||
flags = [a.flags.writeable for a in self.g]
|
||||
out = remap(self.old, self.old, self.g)
|
||||
self.assertEqual((out.base_count, out.level_steps, out.phase, out.origin, out.spacing),
|
||||
(7, (7, 14, 28), 'postcollision_g', (-3., 2.), 1.25))
|
||||
for a, b, saved, leaf, flag in zip(self.g, out.g, copies, self.old.leaf_masks, flags):
|
||||
self.assertEqual(a[:, leaf].tobytes(), b[:, leaf].tobytes())
|
||||
np.testing.assert_array_equal(a, saved)
|
||||
self.assertEqual(a.flags.writeable, flag)
|
||||
self.assertFalse(np.shares_memory(a, b))
|
||||
self.assertTrue(np.isnan(b[:, ~leaf]).all())
|
||||
|
||||
def test_shift_preserves_physical_overlap_not_local_patch_index(self):
|
||||
out = remap(self.old, self.new, self.g)
|
||||
for level in range(3):
|
||||
overlap = self.old.leaf_masks[level] & self.new.leaf_masks[level]
|
||||
self.assertEqual(self.g[level][:, overlap].tobytes(), out.g[level][:, overlap].tobytes())
|
||||
y, x = np.nonzero(self.new.leaf_masks[2] & ~self.old.leaf_masks[2])
|
||||
np.testing.assert_array_equal(out.g[2][:, y, x], self.g[1][:, y//2, x//2])
|
||||
y, x = np.nonzero(self.new.leaf_masks[1] & ~self.old.leaf_masks[1])
|
||||
expected = sum(self.g[2][:, 2*y+dy, 2*x+dx] * .25
|
||||
for dy in (0, 1) for dx in (0, 1))
|
||||
np.testing.assert_array_equal(out.g[1][:, y, x], expected)
|
||||
self.assertGreater(np.max(np.abs(expected[0] - self.g[2][0, 2*y, 2*x])), .001)
|
||||
|
||||
def test_fp64_and_fp32_area_population_mass_momentum_conservation(self):
|
||||
for dtype, tolerance in ((np.float64, 2e-13), (np.float32, 2e-7)):
|
||||
g = fields(self.old, dtype)
|
||||
out = remap(self.old, self.new, g)
|
||||
before, after = integrals(self.old, g), integrals(self.new, out.g)
|
||||
# FP64 accumulation; absolute scale handles near-cancelled momentum.
|
||||
scale = np.sum(np.abs(before[:9]))
|
||||
np.testing.assert_allclose(after, before, rtol=0, atol=tolerance * scale)
|
||||
for array, leaf in zip(out.g, self.new.leaf_masks):
|
||||
self.assertEqual(array.dtype, dtype)
|
||||
self.assertTrue(np.isfinite(array[:, leaf]).all())
|
||||
self.assertTrue(np.isnan(array[:, ~leaf]).all())
|
||||
|
||||
def test_layout_and_rectangle_permutation_independence(self):
|
||||
old = topology(A + [(56, 16, 80, 40)])
|
||||
new = topology(B + [(56, 16, 80, 40)])
|
||||
reordered = topology(list(reversed(B + [(56, 16, 80, 40)])),
|
||||
FixedPatchSet2D.from_config(CFG, list(reversed(PARENTS))))
|
||||
g = fields(old)
|
||||
expected = remap(old, new, g)
|
||||
for block in ((4, 4), (2, 2)):
|
||||
layouts = (BlockLayout2D.build(CFG.ny, CFG.nx, *block),
|
||||
old.parent.fine_layout(block), old.child.fine_layout(block))
|
||||
blocked = [layout.to_blocked(a) for layout, a in zip(layouts, g)]
|
||||
# Corrupt all block halos; only owner-core populations are admissible.
|
||||
for layout, a in zip(layouts, blocked):
|
||||
h = layout.halo
|
||||
a[:, :, :h, :] = np.inf
|
||||
a[:, :, -h:, :] = np.inf
|
||||
a[:, :, :, :h] = np.inf
|
||||
a[:, :, :, -h:] = np.inf
|
||||
saved = [a.copy() for a in blocked]
|
||||
actual = remap(old, reordered, blocked, layouts=layouts)
|
||||
for a, b in zip(expected.g, actual.g):
|
||||
np.testing.assert_array_equal(a, b)
|
||||
for a, b in zip(saved, blocked):
|
||||
np.testing.assert_array_equal(a, b)
|
||||
|
||||
def test_shifted_parent_physical_frame(self):
|
||||
# L1 window origin=(2,2) in root units; child coordinates remain parent-local.
|
||||
cfg = LBMConfig(nx=32, ny=32, viscosity=.1)
|
||||
parent = FixedPatch2D.from_config(cfg, (4, 4, 28, 28))
|
||||
old, new = topology(A, parent, cfg), topology(B, parent, cfg)
|
||||
g = fields(old)
|
||||
out = remap(old, new, g, origin=(10., -7.))
|
||||
self.assertEqual(out.topology.parent.fine_origin, (2., 2.))
|
||||
overlap = old.leaf_masks[2] & new.leaf_masks[2]
|
||||
np.testing.assert_array_equal(out.g[2][:, overlap], g[2][:, overlap])
|
||||
np.testing.assert_allclose(integrals(old, g), integrals(new, out.g), rtol=2e-13, atol=2e-12)
|
||||
|
||||
def test_outside_leaf_nan_inf_ignored_required_leaf_rejected(self):
|
||||
for level in range(3):
|
||||
dirty = [a.copy() for a in self.g]
|
||||
dirty[level][:, ~self.old.leaf_masks[level]] = np.inf
|
||||
actual = remap(self.old, self.new, dirty)
|
||||
expected = remap(self.old, self.new, self.g)
|
||||
for a, b in zip(expected.g, actual.g):
|
||||
np.testing.assert_array_equal(a, b)
|
||||
# Specifically test restriction children, prolongation donors, and overlap.
|
||||
required = [(0, self.old.leaf_masks[0]),
|
||||
(1, self.old.leaf_masks[1] & ~self.new.leaf_masks[1]),
|
||||
(2, self.old.leaf_masks[2] & ~self.new.leaf_masks[2])]
|
||||
for level, mask in required:
|
||||
y, x = np.argwhere(mask)[0]
|
||||
for bad in (np.nan, np.inf, -np.inf):
|
||||
dirty = [a.copy() for a in self.g]
|
||||
dirty[level][0, y, x] = bad
|
||||
with self.assertRaisesRegex(ValueError, 'required leaf donors'):
|
||||
remap(self.old, self.new, dirty)
|
||||
dirty = [a.copy() for a in self.g]
|
||||
dirty[0][:, 0, 0] = -1
|
||||
with self.assertRaisesRegex(ValueError, 'positive density'):
|
||||
remap(self.old, self.new, dirty)
|
||||
|
||||
def test_absent_required_block_rejected(self):
|
||||
layouts = (None, None, BlockLayout2D.build(*self.old.leaf_masks[2].shape, 4, 4,
|
||||
periodic=(False, False), origins=[(0, 0)]))
|
||||
arrays = [*self.g[:2], layouts[2].to_blocked(self.g[2])]
|
||||
with self.assertRaisesRegex(ValueError, 'own every required leaf'):
|
||||
remap(self.old, self.new, arrays, layouts=layouts)
|
||||
|
||||
def test_coarse_fine_coarse_identity_not_general_inverse(self):
|
||||
# Grow then shrink: newly refined cells copy one parent value, so means
|
||||
# recover it exactly. Shrink then grow loses arbitrary child variation.
|
||||
wide = topology([(16, 16, 36, 40)])
|
||||
refined = remap(self.old, wide, self.g)
|
||||
restored = remap(wide, self.old, refined.g)
|
||||
for a, b in zip(self.g, restored.g):
|
||||
np.testing.assert_array_equal(a, b)
|
||||
shifted = remap(self.old, self.new, self.g)
|
||||
returned = remap(self.new, self.old, shifted.g)
|
||||
lost = self.old.leaf_masks[2] & ~self.new.leaf_masks[2]
|
||||
self.assertFalse(np.array_equal(self.g[2][:, lost], returned.g[2][:, lost]))
|
||||
|
||||
def test_invalid_geometry_counts_representation_frame(self):
|
||||
for rectangles in ([], [(2, 2, 10, 10)], [(16, 16, 32, 40)] * 2,
|
||||
[(16, 16, 33.5, 40)], [(16, 16, 32, 40), (33, 16, 36, 40)]):
|
||||
with self.assertRaises(ValueError):
|
||||
topology(rectangles)
|
||||
parent = self.old.parent
|
||||
for changes in (dict(lattice_model='D3Q19'), dict(ddf_shifting=True),
|
||||
dict(collision='TRT'), dict(les_enabled=True), dict(nz=2)):
|
||||
with self.assertRaises(ValueError):
|
||||
RemapTopology.from_config(replace(CFG, **changes), parent, A)
|
||||
for kwargs in (dict(coarse_boundary='slot_reservoir'), dict(objects=(object(),))):
|
||||
with self.assertRaisesRegex(ValueError, 'periodic 2D'):
|
||||
RemapTopology.from_config(CFG, parent, A, **kwargs)
|
||||
different = topology(A, cfg=replace(CFG, viscosity=.12))
|
||||
with self.assertRaisesRegex(ValueError, 'unchanged'):
|
||||
remap(self.old, different, self.g)
|
||||
for kwargs in (dict(base_count=True), dict(base_count=-1), dict(level_steps=(7, 14, 27)),
|
||||
dict(level_steps=(7, 14)), dict(level_steps=None), dict(phase='arrival_f'),
|
||||
dict(origin=(np.nan, 0)), dict(spacing=0), dict(spacing='bad')):
|
||||
with self.assertRaises(ValueError):
|
||||
remap(self.old, self.new, self.g, **kwargs)
|
||||
for g in (self.g[:2], [self.g[0].astype(np.float32), *self.g[1:]],
|
||||
[self.g[0][0], *self.g[1:]]):
|
||||
with self.assertRaises(ValueError):
|
||||
remap(self.old, self.new, g)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,335 @@
|
||||
"""Periodic body-free block backend: CPU contract doubles plus one short GPU case.
|
||||
|
||||
Frozen GPU gates (32x24, 8 steps, positive low-Mach non-equilibrium state):
|
||||
finite cores; bit-identical 1x1, 2x2 and 4x2 splits; max |G - FP64 oracle|
|
||||
<= 3e-6. Static circle (centre (15.5, 11.5), R=4.3, on the 2x2 corner seam), same
|
||||
case: halo writes and q<.5 halo donors asserted present; finite fluid / NaN
|
||||
solid cores; bit-identical splits; max |G - FP64 BFL+pull/SRT| <= 3e-6 on
|
||||
fluid cells, from the same FP32-packed link data and initial populations.
|
||||
Mass/momentum drift is reported, not gated.
|
||||
"""
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
import resource
|
||||
from threading import RLock
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, Mock, patch
|
||||
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.cuda import compiler_v2 as compiler
|
||||
from CelerisLab.lbm import block_stepper as implementation
|
||||
from CelerisLab.lbm.blocks import NO_DONOR, BlockLayout2D
|
||||
from CelerisLab.lbm.block_stepper import PeriodicBlockStepper
|
||||
from CelerisLab.lbm.descriptors import D2Q9_EX, D2Q9_EY
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
NX, NY, NU, STEPS, ORACLE_ATOL = 32, 24, .1, 8, 3e-6
|
||||
SPLITS = ((24, 32), (12, 16), (12, 8)) # 1x1, 2x2, 4x2 blocks (by, bx)
|
||||
W = np.array([4 / 9] + [1 / 9] * 4 + [1 / 36] * 4)
|
||||
CX, CY = np.array(D2Q9_EX, float), np.array(D2Q9_EY, float)
|
||||
|
||||
|
||||
def config(**kwargs):
|
||||
return LBMConfig(**dict(nx=NX, ny=NY, viscosity=NU, **kwargs))
|
||||
|
||||
|
||||
def feq(rho, ux, uy):
|
||||
cu = CX[:, None, None] * ux + CY[:, None, None] * uy
|
||||
return W[:, None, None] * rho * (1 + 3 * cu + 4.5 * cu * cu - 1.5 * (ux * ux + uy * uy))
|
||||
|
||||
|
||||
def initial_state():
|
||||
"""Positive low-Mach equilibrium plus a seeded non-equilibrium part."""
|
||||
y, x = np.mgrid[0:NY, 0:NX]
|
||||
rho = 1 + 1e-3 * np.cos(2 * np.pi * x / NX)
|
||||
ux = .02 * np.sin(2 * np.pi * y / NY)
|
||||
uy = .01 * np.cos(2 * np.pi * x / NX)
|
||||
noise = np.random.default_rng(2026).uniform(-1, 1, (9, NY, NX)) * 1e-3 * W[:, None, None]
|
||||
return (feq(rho, ux, uy) + noise).astype(np.float32)
|
||||
|
||||
|
||||
def oracle(g, steps):
|
||||
"""FP64 periodic pull + SRT, from the same FP32-rounded G_0."""
|
||||
g = g.astype(np.float64)
|
||||
omega = 1 / (3 * NU + .5)
|
||||
for _ in range(steps):
|
||||
f = np.stack([np.roll(g[q], (D2Q9_EY[q], D2Q9_EX[q]), axis=(0, 1)) for q in range(9)])
|
||||
rho = f.sum(axis=0)
|
||||
ux, uy = (CX[:, None, None] * f).sum(axis=0) / rho, (CY[:, None, None] * f).sum(axis=0) / rho
|
||||
g = f + omega * (feq(rho, ux, uy) - f)
|
||||
return g
|
||||
|
||||
|
||||
CENTER, RADIUS = (15.5, 11.5), 4.3
|
||||
|
||||
|
||||
def circle(center=CENTER, radius=RADIUS):
|
||||
return SimObject(0, geometry=CircleGeometry(*center, radius), center=center, radius=radius)
|
||||
|
||||
|
||||
def dense_flags():
|
||||
"""FLUID everywhere, circle flags on its solids (as the stepper builds them)."""
|
||||
mask = circle().get_flag_mask(NX, NY)
|
||||
flags = np.full(NX * NY, 1, np.uint16)
|
||||
flags[(mask & 2) != 0] = mask[(mask & 2) != 0]
|
||||
return flags
|
||||
|
||||
|
||||
def circle_oracle(g, steps, solid, links):
|
||||
"""FP64 periodic static linear BFL -> pull -> SRT on fluid; solids NaN."""
|
||||
g = g.astype(np.float64)
|
||||
g[:, solid] = np.nan
|
||||
omega = 1 / (3 * NU + .5)
|
||||
rows = [(*divmod(int(link.fluid_idx), NX), int(link.dir), float(np.float32(link.q)),
|
||||
int(link.fallback)) for link in links]
|
||||
for _ in range(steps):
|
||||
staged = g.copy()
|
||||
for y, x, d, q, fallback in rows:
|
||||
ey, ex, o = D2Q9_EY[d], D2Q9_EX[d], d + 1 if d % 2 else d - 1
|
||||
toward = g[d, y, x]
|
||||
if fallback:
|
||||
value = toward
|
||||
elif q < .5:
|
||||
value = 2 * q * toward + (1 - 2 * q) * g[d, (y - ey) % NY, (x - ex) % NX]
|
||||
else:
|
||||
value = toward / (2 * q) + (1 - 1 / (2 * q)) * g[o, y, x]
|
||||
staged[o, (y + ey) % NY, (x + ex) % NX] = value
|
||||
f = np.stack([np.roll(staged[q], (D2Q9_EY[q], D2Q9_EX[q]), axis=(0, 1)) for q in range(9)])
|
||||
rho = f.sum(axis=0)
|
||||
ux, uy = (CX[:, None, None] * f).sum(axis=0) / rho, (CY[:, None, None] * f).sum(axis=0) / rho
|
||||
g = f + omega * (feq(rho, ux, uy) - f)
|
||||
g[:, solid] = np.nan
|
||||
return g
|
||||
|
||||
|
||||
def totals(g):
|
||||
g = g.astype(np.float64)
|
||||
return g.sum(), (CX[:, None, None] * g).sum(), (CY[:, None, None] * g).sum()
|
||||
|
||||
|
||||
class CpuContracts(unittest.TestCase):
|
||||
"""No device: driver doubles prove rejection before allocation and lifecycle."""
|
||||
|
||||
def forbidden_context(self):
|
||||
return Mock(activate=Mock(side_effect=AssertionError("CUDA reached")), sm_arch="sm_70")
|
||||
|
||||
def test_unsupported_inputs_rejected_before_cuda(self):
|
||||
layout = BlockLayout2D.build(NY, NX, 12, 16)
|
||||
cases = ((config(), BlockLayout2D.build(NY, NX, 12, 16, periodic=(True, False))),
|
||||
(config(), BlockLayout2D.build(NY, NX * 2, 12, 16)),
|
||||
(config(collision="MRT"), layout),
|
||||
(config(), "layout"))
|
||||
for cfg, lay in cases:
|
||||
with self.subTest(cfg=cfg.collision, layout=getattr(lay, "periodic", lay)):
|
||||
with self.assertRaises(ValueError):
|
||||
PeriodicBlockStepper(cfg, lay, context=self.forbidden_context())
|
||||
moving = circle()
|
||||
moving.state.vx = .01
|
||||
build_links = CircleGeometry.build_cut_links
|
||||
for objects in ([moving], [circle((1.5, 11.5), 2.0)], [circle(), circle()]):
|
||||
with self.assertRaises(ValueError):
|
||||
PeriodicBlockStepper(config(), layout, context=self.forbidden_context(), objects=objects)
|
||||
for center, radius in (((16.0, 12.0), -.1), ((16.0, 12.0), -.5), ((15.5, 11.5), np.nan),
|
||||
((np.inf, 11.5), 4.3), ((15.5, np.nan), 4.3)):
|
||||
with self.subTest(center=center, radius=radius), self.assertRaises(ValueError):
|
||||
PeriodicBlockStepper(config(), layout, context=self.forbidden_context(),
|
||||
objects=[circle(center, radius)])
|
||||
with patch.object(implementation, "_static_circles") as prepare:
|
||||
with self.assertRaisesRegex(AssertionError, "CUDA reached"): # body-free path
|
||||
PeriodicBlockStepper(config(), layout, context=self.forbidden_context(), objects=iter(()))
|
||||
prepare.assert_not_called()
|
||||
with patch.object(CircleGeometry, "build_cut_links",
|
||||
lambda geometry, *a, **k: build_links(geometry, *a, **k)[1:]):
|
||||
with self.assertRaisesRegex(ValueError, "cover every fluid pull"):
|
||||
PeriodicBlockStepper(config(), layout, context=self.forbidden_context(),
|
||||
objects=[circle()])
|
||||
with patch.object(implementation, "MAX_GRID_DIM", 3):
|
||||
with self.assertRaisesRegex(ValueError, "launch limits"):
|
||||
PeriodicBlockStepper(config(), layout, context=self.forbidden_context())
|
||||
|
||||
def test_memory_and_param_layout_rejected_before_allocation(self):
|
||||
layout = BlockLayout2D.build(NY, NX, 12, 16)
|
||||
context = Mock(activate=nullcontext, sm_arch="sm_70")
|
||||
with patch.object(cuda, "mem_get_info", return_value=(1024, 1 << 30)), \
|
||||
patch.object(cuda, "Stream") as stream, patch.object(cuda, "mem_alloc") as alloc:
|
||||
with self.assertRaises(MemoryError):
|
||||
PeriodicBlockStepper(config(), layout, context=context)
|
||||
stream.assert_not_called()
|
||||
alloc.assert_not_called()
|
||||
module = Mock()
|
||||
module.get_global.return_value = (Mock(), 16)
|
||||
with patch.object(cuda, "mem_get_info", return_value=(1 << 30, 1 << 30)), \
|
||||
patch.object(cuda, "Stream"), patch.object(compiler, "generate_config"), \
|
||||
patch.object(compiler, "compile_kernel") as compile_kernel, \
|
||||
patch.object(compiler, "cleanup_build_dir"), \
|
||||
patch.object(compiler, "load_module", return_value=module), \
|
||||
patch.object(cuda, "mem_alloc") as alloc, patch.object(cuda, "memcpy_htod") as upload:
|
||||
with self.assertRaisesRegex(RuntimeError, "layout mismatch"):
|
||||
PeriodicBlockStepper(config(), layout, context=context)
|
||||
self.assertEqual(compile_kernel.call_args.kwargs["source"], "blocks.cu")
|
||||
alloc.assert_not_called()
|
||||
upload.assert_not_called()
|
||||
|
||||
def test_static_circle_tables(self):
|
||||
layout = BlockLayout2D.build(NY, NX, 12, 16)
|
||||
tables = implementation._static_circles(layout, (circle(),))
|
||||
links = CircleGeometry(*CENTER, RADIUS).build_cut_links(NX, NY, domain_flags=dense_flags())
|
||||
self.assertEqual(len(tables["cell"]), len(links))
|
||||
np.testing.assert_array_equal(tables["q"], np.array([l.q for l in links], np.float32))
|
||||
solid_cells = layout.owner[tables["solid"]].astype(np.intp)
|
||||
self.assertTrue((tables["flags"][solid_cells] & 2).all())
|
||||
self.assertEqual(int(np.count_nonzero(tables["flags"] & 2)), int(tables["solid"].sum()))
|
||||
|
||||
def fake_backend(self):
|
||||
backend = PeriodicBlockStepper.__new__(PeriodicBlockStepper)
|
||||
backend.layout = BlockLayout2D.build(NY, NX, 12, 16)
|
||||
backend.ctx = Mock(activate=nullcontext)
|
||||
backend._lock = RLock()
|
||||
backend._status = "ready"
|
||||
backend._step_count = 0
|
||||
backend._stream = Mock()
|
||||
backend._module = Mock()
|
||||
backend._copy = backend._step = Mock()
|
||||
backend.boundary, backend._curved, backend._tables, backend._links = None, None, {}, 0
|
||||
backend._dst, backend._src = Mock(), Mock()
|
||||
backend._block, backend._grid, backend._copy_grid = (32, 1, 1), (1, 1, 1), (1, 1)
|
||||
backend._allocations = [Mock(), Mock()]
|
||||
backend._current, backend._spare = backend._allocations
|
||||
return backend
|
||||
|
||||
def test_initialize_rejects_bad_state_before_upload(self):
|
||||
backend = self.fake_backend()
|
||||
good = initial_state()
|
||||
bad = (good[:, :-1], np.where(np.arange(NX) == 3, np.nan, good), -good)
|
||||
with patch.object(cuda, "memcpy_htod") as upload:
|
||||
for g in bad:
|
||||
with self.assertRaises(ValueError):
|
||||
backend.initialize(g)
|
||||
upload.assert_not_called()
|
||||
backend.initialize(good)
|
||||
self.assertEqual(upload.call_count, 2)
|
||||
self.assertTrue(np.isnan(upload.call_args_list[1].args[1]).all())
|
||||
backend.close()
|
||||
|
||||
def test_failed_launch_and_download_make_backend_unusable(self):
|
||||
for failure in ("step", "download"):
|
||||
backend = self.fake_backend()
|
||||
if failure == "step":
|
||||
backend._step = Mock(side_effect=RuntimeError("launch failed"))
|
||||
with self.assertRaisesRegex(RuntimeError, "launch failed"):
|
||||
backend.step()
|
||||
else:
|
||||
with patch.object(cuda, "memcpy_dtoh", side_effect=RuntimeError("read failed")):
|
||||
with self.assertRaisesRegex(RuntimeError, "read failed"):
|
||||
backend.download()
|
||||
for operation in (backend.download, backend.step):
|
||||
with self.assertRaisesRegex(RuntimeError, "failed"):
|
||||
operation()
|
||||
backend.close()
|
||||
for allocation in backend_allocations(backend):
|
||||
allocation.free.assert_called_once()
|
||||
|
||||
def test_activation_failure_retains_resources_for_retry(self):
|
||||
backend = self.fake_backend()
|
||||
allocations, stream, module = backend._allocations[:], backend._stream, backend._module
|
||||
unavailable = MagicMock()
|
||||
unavailable.__enter__.side_effect = RuntimeError("activation failed")
|
||||
backend.ctx.activate = Mock(side_effect=[unavailable, nullcontext()])
|
||||
with self.assertRaisesRegex(RuntimeError, "activation failed"):
|
||||
backend.close()
|
||||
self.assertEqual(backend._status, "failed")
|
||||
self.assertEqual(backend._allocations, allocations)
|
||||
self.assertIs(backend._stream, stream)
|
||||
self.assertIs(backend._module, module)
|
||||
backend.close()
|
||||
self.assertEqual(backend._status, "closed")
|
||||
self.assertIsNone(backend._module)
|
||||
self.assertIsNone(backend._copy)
|
||||
self.assertIsNone(backend._step)
|
||||
for allocation in allocations:
|
||||
allocation.free.assert_called_once()
|
||||
|
||||
|
||||
def backend_allocations(backend):
|
||||
return (backend._current, backend._spare)
|
||||
|
||||
|
||||
class PeriodicBlockGPU(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.assertEqual(Path(implementation.__file__).resolve(),
|
||||
ROOT / "src/CelerisLab/lbm/block_stepper.py")
|
||||
|
||||
def tearDown(self):
|
||||
rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
|
||||
print(f"host_peak_rss={rss:.3f} MiB", flush=True)
|
||||
|
||||
def test_splits_bit_identical_and_fp64_oracle(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
g0 = initial_state()
|
||||
results = []
|
||||
with CudaContext(0) as context:
|
||||
for by, bx in SPLITS:
|
||||
layout = BlockLayout2D.build(NY, NX, by, bx)
|
||||
with PeriodicBlockStepper(config(), layout, context=context) as backend:
|
||||
backend.initialize(g0)
|
||||
backend.step(STEPS)
|
||||
self.assertEqual(backend.step_count, STEPS)
|
||||
results.append(backend.download())
|
||||
for (by, bx), g in zip(SPLITS, results):
|
||||
self.assertTrue(np.isfinite(g).all(), (by, bx))
|
||||
np.testing.assert_array_equal(g, results[0], err_msg=f"split {(by, bx)}")
|
||||
error = np.abs(results[0].astype(np.float64) - oracle(g0, STEPS)).max()
|
||||
before, after = totals(g0), totals(results[0])
|
||||
print(f"max_abs_oracle_error={error:.3e} gate={ORACLE_ATOL:.0e}", flush=True)
|
||||
print("drift mass={:.3e} jx={:.3e} jy={:.3e}".format(
|
||||
*(a - b for a, b in zip(after, before))), flush=True)
|
||||
self.assertLessEqual(error, ORACLE_ATOL)
|
||||
|
||||
def test_static_circle_across_block_seams(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
flags = dense_flags()
|
||||
solid = ((flags & 2) != 0).reshape(NY, NX)
|
||||
links = CircleGeometry(*CENTER, RADIUS).build_cut_links(NX, NY, domain_flags=flags)
|
||||
for by, bx in SPLITS[1:]: # fixture must exercise receiver-local halo staging
|
||||
layout = BlockLayout2D.build(NY, NX, by, bx)
|
||||
mapped = layout.map_cut_links(links)
|
||||
cells = int(np.prod(layout.local_shape))
|
||||
core = set(layout.owner.ravel().tolist())
|
||||
writes = {int(w) // (9 * cells) * cells + int(w) % cells for w in mapped.write}
|
||||
self.assertTrue(writes - core, (by, bx))
|
||||
self.assertTrue({int(d) for d in mapped.donor if d != NO_DONOR} - core, (by, bx))
|
||||
g0 = initial_state()
|
||||
results = []
|
||||
with CudaContext(0) as context:
|
||||
for by, bx in SPLITS:
|
||||
layout = BlockLayout2D.build(NY, NX, by, bx)
|
||||
with PeriodicBlockStepper(config(), layout, context=context, objects=[circle()]) as backend:
|
||||
for key, values, dtype in (("q", [l.q for l in links], np.float32),
|
||||
("dir", [l.dir for l in links], np.uint8),
|
||||
("fallback", [l.fallback for l in links], np.uint8)):
|
||||
np.testing.assert_array_equal(backend.boundary[key], np.array(values, dtype))
|
||||
backend.initialize(g0)
|
||||
backend.step(STEPS)
|
||||
results.append(backend.download())
|
||||
for (by, bx), g in zip(SPLITS, results):
|
||||
self.assertTrue(np.isfinite(g[:, ~solid]).all(), (by, bx))
|
||||
self.assertTrue(np.isnan(g[:, solid]).all(), (by, bx))
|
||||
np.testing.assert_array_equal(g, results[0], err_msg=f"split {(by, bx)}")
|
||||
expected = circle_oracle(g0, STEPS, solid, links)
|
||||
error = np.abs(results[0][:, ~solid].astype(np.float64) - expected[:, ~solid]).max()
|
||||
start = g0.copy()
|
||||
start[:, solid] = 0
|
||||
before, after = totals(start), totals(np.nan_to_num(results[0]))
|
||||
print(f"circle max_abs_oracle_error={error:.3e} gate={ORACLE_ATOL:.0e} links={len(links)}", flush=True)
|
||||
print("circle drift mass={:.3e} jx={:.3e} jy={:.3e}".format(
|
||||
*(a - b for a, b in zip(after, before))), flush=True)
|
||||
self.assertLessEqual(error, ORACLE_ATOL)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Manual GPU gates for two pinned bodies and several fluid-only L2 regions.
|
||||
|
||||
Run explicitly on an approved idle GPU. The CPU helper checks immediate
|
||||
whole-population transfer at the same physical time, not independent evolution
|
||||
accuracy. Continuation checks cover finite leaves and no-op bitwise identity;
|
||||
they do not establish an independent BFL replay or a numerical error bound.
|
||||
"""
|
||||
from contextlib import ExitStack
|
||||
import unittest
|
||||
|
||||
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.cuda.context import CudaContext
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
from CelerisLab.lbm.synchronized_remap import (
|
||||
RemapTopology, remap_synchronized, same_physical_boundary,
|
||||
)
|
||||
from test_refinement_blocked_base import exact
|
||||
from test_refinement_three_level_multipatch_gpu import CFG, PARENTS
|
||||
from test_runtime_child_remap_gpu import RuntimeChildRemapGPU, initial
|
||||
|
||||
|
||||
# All bounds use the allocated L1 frame, with support aligned to 4x4 blocks.
|
||||
PINS = ((16, 16, 32, 24), (56, 16, 72, 24))
|
||||
FLUID = ((16, 32, 32, 40), (56, 32, 72, 40))
|
||||
EXTRA = ((16, 44, 32, 48),)
|
||||
MOVED = ((20, 32, 36, 40), (60, 32, 76, 40))
|
||||
START = PINS + FLUID
|
||||
CHANGES = (
|
||||
('add', START + EXTRA, (.017, -.011)),
|
||||
('move', PINS + MOVED + EXTRA, (-.009, .005)),
|
||||
('remove', PINS + MOVED, (.013, -.007)),
|
||||
)
|
||||
|
||||
|
||||
def make(context):
|
||||
centers = ((12., 10.), (32., 10.))
|
||||
objects = tuple(
|
||||
SimObject(71 + index, geometry=CircleGeometry(*center, .8),
|
||||
center=center, radius=.8)
|
||||
for index, center in enumerate(centers)
|
||||
)
|
||||
jets = tuple(
|
||||
Jet(Tube((x - 1.5, y), 0., 3., .3), Parallel(0.), 'parabolic', amplitude)
|
||||
for (x, y), amplitude in zip(centers, (.003, -.002))
|
||||
)
|
||||
run = FixedPatchStepper(
|
||||
CFG, PARENTS, context=context, base_block=(4, 4), fine_block=(4, 4),
|
||||
child_block=(4, 4), child_rectangles_in_parent=START,
|
||||
child_objects=objects, child_jets=jets,
|
||||
)
|
||||
return run, objects
|
||||
|
||||
|
||||
def topology(run, rectangles, objects):
|
||||
return RemapTopology.from_config(
|
||||
CFG, run.patch, rectangles, child_objects=objects,
|
||||
child_jets=run._boundaries[2].jets,
|
||||
)
|
||||
|
||||
|
||||
def population_integrals(mesh, arrays):
|
||||
"""Nine separate area integrals in the root frame, accumulated in FP64."""
|
||||
return sum(array[:, leaf].sum(axis=1, dtype=np.float64) / 4**level
|
||||
for level, (array, leaf) in enumerate(zip(arrays, mesh.leaf_masks)))
|
||||
|
||||
|
||||
class MultiplePinnedRemapGPU(unittest.TestCase):
|
||||
check_public = RuntimeChildRemapGPU.check_public
|
||||
check_reset = RuntimeChildRemapGPU.check_reset
|
||||
|
||||
def change_amplitudes(self, run, amplitudes):
|
||||
# Each jet selects a different body. Updating one must preserve the
|
||||
# other body's current per-link velocities, including its driven links.
|
||||
boundary = run._boundaries[2]
|
||||
body_ids = run.child_boundary.curved_host[3]
|
||||
for index, amplitude in enumerate(amplitudes):
|
||||
before = boundary.tables['surface_velocity'].copy()
|
||||
run.set_jet_amplitude(index, amplitude, level=2)
|
||||
after = boundary.tables['surface_velocity']
|
||||
exact(self, after[body_ids != index], before[body_ids != index],
|
||||
'other body velocity unchanged')
|
||||
self.assertTrue(np.any(after[body_ids == index] != before[body_ids == index]))
|
||||
self.assertEqual(tuple(jet.amplitude for jet in boundary.jets), amplitudes)
|
||||
|
||||
def check_boundary(self, old, new, mesh, amplitudes):
|
||||
self.assertEqual(mesh.pinned_rectangles, PINS)
|
||||
self.assertTrue(same_physical_boundary(old.child_boundary, new.child_boundary))
|
||||
self.assertTrue(same_physical_boundary(new.child_boundary, mesh.boundary))
|
||||
# Compare physical cut-link rows, never layout-dependent blocked addresses.
|
||||
for run in (old, new):
|
||||
boundary = run._boundaries[2]
|
||||
self.assertEqual(tuple(jet.amplitude for jet in boundary.jets), amplitudes)
|
||||
exact(self, boundary.tables['surface_velocity'], mesh.surface_velocity,
|
||||
'latest physical per-link velocities')
|
||||
|
||||
def test_noop_next_step_bitwise(self):
|
||||
with CudaContext(0) as context, ExitStack() as owned:
|
||||
old, objects = make(context)
|
||||
owned.enter_context(old)
|
||||
old.initialize(*initial(old, False))
|
||||
old.step(2)
|
||||
amplitudes = (.017, -.011)
|
||||
self.change_amplitudes(old, amplitudes)
|
||||
before, count = old.download(), old.step_count
|
||||
mesh = topology(old, START, objects)
|
||||
# Input order is irrelevant even with several pins and fluid regions.
|
||||
new = owned.enter_context(old.remap_child(START[::-1], child_objects=objects))
|
||||
self.assertIsNot(old, new)
|
||||
self.assertEqual((old.step_count, new.step_count), (count, count))
|
||||
self.check_boundary(old, new, mesh, amplitudes)
|
||||
self.check_reset(new, before)
|
||||
for got, want in zip(old.download(), before):
|
||||
exact(self, got, want, 'no-op source unchanged')
|
||||
old.step()
|
||||
new.step()
|
||||
self.assertEqual((old.step_count, new.step_count), (count + 1, count + 1))
|
||||
for got, want in zip(new.download(), old.download()):
|
||||
exact(self, got, want, 'no-op next step bitwise')
|
||||
self.check_public(old)
|
||||
self.check_public(new)
|
||||
|
||||
def test_add_move_remove_immediate_transfer_and_source_independence(self):
|
||||
with CudaContext(0) as context, ExitStack() as owned:
|
||||
current, objects = make(context)
|
||||
owned.enter_context(current)
|
||||
current.initialize(*initial(current, False))
|
||||
current.step(2)
|
||||
for action, rectangles, amplitudes in CHANGES:
|
||||
with self.subTest(action=action):
|
||||
previous = current
|
||||
self.change_amplitudes(previous, amplitudes)
|
||||
before, count = previous.download(), previous.step_count
|
||||
old_mesh = topology(previous, previous.child_patch.bounds, objects)
|
||||
new_mesh = topology(previous, rectangles, objects)
|
||||
expected = remap_synchronized(
|
||||
old_mesh, new_mesh, before, base_count=count,
|
||||
level_steps=(count, 2 * count, 4 * count),
|
||||
phase='postcollision_g',
|
||||
).g
|
||||
current = owned.enter_context(
|
||||
previous.remap_child(rectangles, child_objects=objects))
|
||||
self.assertIsNot(previous, current)
|
||||
self.assertEqual((previous.step_count, current.step_count), (count, count))
|
||||
self.check_boundary(previous, current, new_mesh, amplitudes)
|
||||
self.check_reset(current, expected)
|
||||
actual = current.download()
|
||||
for got, want, source, old_leaf, new_leaf in zip(
|
||||
actual, expected, before, old_mesh.leaf_masks, new_mesh.leaf_masks):
|
||||
exact(self, got, want, 'immediate CPU transfer parity')
|
||||
exact(self, got[:, old_leaf & new_leaf], source[:, old_leaf & new_leaf],
|
||||
'same-level physical fluid overlap')
|
||||
self.assertTrue(np.isfinite(got[:, new_leaf]).all())
|
||||
self.assertTrue(np.isnan(got[:, ~new_leaf]).all())
|
||||
# Conservation is asserted only across remap, not collision.
|
||||
np.testing.assert_allclose(
|
||||
population_integrals(new_mesh, actual),
|
||||
population_integrals(old_mesh, before),
|
||||
rtol=2 * np.finfo(np.float32).eps, atol=0,
|
||||
err_msg='all nine area-weighted population integrals',
|
||||
)
|
||||
self.check_public(current)
|
||||
current.step()
|
||||
self.assertEqual((previous.step_count, current.step_count), (count, count + 1))
|
||||
for got, want in zip(previous.download(), before):
|
||||
exact(self, got, want, 'source unchanged after candidate advances')
|
||||
self.check_boundary(previous, current, new_mesh, amplitudes)
|
||||
self.check_public(current)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Pinned-body GPU lifecycle gates. NOT executed by CPU test collection.
|
||||
|
||||
No evolution accuracy tolerance is asserted here: an independent BFL replay
|
||||
reference is required before a 3e-6 FP32-vs-FP64 gate can be claimed. These
|
||||
checks require exact physical boundary/velocity, remap overlap and no-op next
|
||||
step identity; they never compare blocked boundary addresses across layouts.
|
||||
"""
|
||||
from contextlib import ExitStack
|
||||
import unittest
|
||||
import numpy as np
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
from CelerisLab.lbm.synchronized_remap import RemapTopology, remap_synchronized
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.body.jets import Jet, Tube, Parallel
|
||||
from test_runtime_child_remap_gpu import RuntimeChildRemapGPU, initial
|
||||
from test_refinement_three_level_multipatch_gpu import CFG, PARENTS
|
||||
from test_refinement_blocked_base import exact
|
||||
|
||||
A = ((16,16,32,40), (56,16,72,40))
|
||||
B = ((16,16,32,40), (60,16,76,40))
|
||||
|
||||
|
||||
def make(ctx):
|
||||
body = SimObject(71, geometry=CircleGeometry(12.,14.,.8),center=(12.,14.),radius=.8)
|
||||
jet = Jet(Tube((10.5,14.),0.,3.,.3),Parallel(0.),'parabolic',.003)
|
||||
run = FixedPatchStepper(CFG,PARENTS,context=ctx,base_block=(4,4),fine_block=(4,4),
|
||||
child_block=(4,4),child_rectangles_in_parent=A,
|
||||
child_objects=(body,),child_jets=(jet,))
|
||||
return run,(body,)
|
||||
|
||||
|
||||
class PinnedBodyRemapGPU(unittest.TestCase):
|
||||
check_public = RuntimeChildRemapGPU.check_public
|
||||
check_reset = RuntimeChildRemapGPU.check_reset
|
||||
|
||||
def check_boundary(self, before, after):
|
||||
for name in ('flags','boundary_cells','curved_hits'):
|
||||
exact(self,getattr(after.child_boundary,name),getattr(before.child_boundary,name),name)
|
||||
for a,b in zip(after.child_boundary.curved_host,before.child_boundary.curved_host):
|
||||
exact(self,a,b,'physical cut links')
|
||||
exact(self,after._boundaries[2].tables['surface_velocity'],
|
||||
before._boundaries[2].tables['surface_velocity'],'current per-link velocities')
|
||||
self.assertEqual(after._boundaries[2].jets[0].amplitude,.017)
|
||||
|
||||
def test_noop_next_step_bitwise(self):
|
||||
with CudaContext(0) as ctx, ExitStack() as owned:
|
||||
old,objects=make(ctx);owned.enter_context(old)
|
||||
old.initialize(*initial(old,False));old.step(2)
|
||||
old.set_jet_amplitude(0,.017,level=2)
|
||||
before=old.download()
|
||||
new=owned.enter_context(old.remap_child(A,child_objects=objects))
|
||||
self.check_boundary(old,new);self.check_reset(new,before)
|
||||
old.step();new.step()
|
||||
for a,b in zip(new.download(),old.download()): exact(self,a,b,'no-op next step bitwise')
|
||||
self.assertEqual((old.step_count,new.step_count),(3,3))
|
||||
self.check_public(new)
|
||||
|
||||
def test_moved_fluid_return_and_source_independence(self):
|
||||
with CudaContext(0) as ctx, ExitStack() as owned:
|
||||
current,objects=make(ctx);owned.enter_context(current)
|
||||
current.initialize(*initial(current,False));current.step(2)
|
||||
current.set_jet_amplitude(0,.017,level=2)
|
||||
for rects in (B,A):
|
||||
previous=current;before=previous.download();count=previous.step_count
|
||||
jets=previous._boundaries[2].jets
|
||||
old=RemapTopology.from_config(CFG,previous.patch,previous.child_patch.bounds,
|
||||
child_objects=objects,child_jets=jets)
|
||||
new=RemapTopology.from_config(CFG,previous.patch,rects,
|
||||
child_objects=objects,child_jets=jets)
|
||||
expected=remap_synchronized(old,new,before,base_count=count,
|
||||
level_steps=(count,2*count,4*count),phase='postcollision_g').g
|
||||
current=owned.enter_context(previous.remap_child(rects,child_objects=objects))
|
||||
self.check_boundary(previous,current);self.check_reset(current,expected)
|
||||
for a,b,om,nm in zip(current.download(),before,old.leaf_masks,new.leaf_masks):
|
||||
exact(self,a[:,om & nm],b[:,om & nm],'physical-fluid overlap')
|
||||
current.step(2)
|
||||
self.assertEqual((previous.step_count,current.step_count),(count,count+2))
|
||||
for a,b in zip(previous.download(),before): exact(self,a,b,'source independent')
|
||||
self.check_public(current)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,264 @@
|
||||
"""GPU gates for raw exchange. Run explicitly; requires PyCUDA and CUDA.
|
||||
|
||||
Independent census reads actual staged incoming/outgoing populations, including
|
||||
non-body ACTIVE-boundary flux, then checks postcollision fluid momentum/mass.
|
||||
This is a discrete implementation gate, NOT a physical nozzle-load validation.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
import unittest
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
from CelerisLab.body.jets import Jet, Tube, Parallel
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
from CelerisLab.lbm.descriptors import D2Q9_EX, D2Q9_EY, SOLID
|
||||
|
||||
CX, CY = np.asarray(D2Q9_EX), np.asarray(D2Q9_EY)
|
||||
OPP = np.array([np.flatnonzero((CX == -x) & (CY == -y))[0] for x, y in zip(CX, CY)])
|
||||
W = np.array([4/9] + [1/9]*4 + [1/36]*4, np.float32)
|
||||
CFG = LBMConfig(nx=32, ny=24, viscosity=.1)
|
||||
BOUNDS = (8, 6, 24, 18)
|
||||
|
||||
|
||||
def circle():
|
||||
return SimObject(17, geometry=CircleGeometry(16., 12., 2.15), center=(16., 12.), radius=2.15)
|
||||
|
||||
|
||||
def jet():
|
||||
# Asymmetric aperture avoids hiding exchange errors by paired-jet cancellation.
|
||||
return Jet(Tube((16., 12.), 0., 3., .7), Parallel(0.), amplitude=0.)
|
||||
|
||||
|
||||
def state(shape, ux=.013):
|
||||
cu = CX[:, None, None]*ux
|
||||
values = W[:, None, None]*(1+3*cu+4.5*cu*cu-1.5*ux*ux)
|
||||
return np.broadcast_to(values, shape).astype(np.float32).copy()
|
||||
|
||||
|
||||
def download(pointer, shape, dtype=np.float32):
|
||||
result = np.empty(shape, dtype)
|
||||
cuda.memcpy_dtoh(result, pointer)
|
||||
return result
|
||||
|
||||
|
||||
def totals(g, leaf):
|
||||
values = g[:, leaf].astype(np.float64)
|
||||
return np.array([(values*CX[:, None]).sum(), (values*CY[:, None]).sum(), values.sum()])
|
||||
|
||||
|
||||
def census(run, index, buffer):
|
||||
"""Independent incoming/outgoing face census on ACTIVE fluid cells.
|
||||
|
||||
Reads the receiver's actual block window, not a freshly gathered owner image
|
||||
(that would erase BFL/restriction staging). Classifies external flux solely
|
||||
from geometry, without consulting raw observation arrays.
|
||||
"""
|
||||
level = run._levels[index]
|
||||
layout, b = level.layout, level.boundary
|
||||
g = download(buffer, layout.blocked_shape)
|
||||
dense = layout.to_dense(g)
|
||||
leaf = run._leaf[index]
|
||||
ny, nx = leaf.shape
|
||||
solid = (b.host.flags.reshape(ny, nx) & SOLID) != 0
|
||||
y, x = np.nonzero(leaf)
|
||||
owner = layout.owner[y, x].astype(np.intp)
|
||||
cells = int(np.prod(layout.local_shape))
|
||||
block, cell = np.divmod(owner, cells)
|
||||
flat = g.reshape(layout.nblocks, 9, cells)
|
||||
external = np.zeros(3, np.float64)
|
||||
for q, (cx, cy) in enumerate(zip(CX, CY)):
|
||||
sy, sx = y-cy, x-cx
|
||||
incoming = flat[block, q, cell-cy*layout.local_shape[1]-cx].astype(np.float64)
|
||||
entering = ~leaf[sy, sx] & ~solid[sy, sx]
|
||||
external += np.array([cx, cy, 1])*incoming[entering].sum()
|
||||
dy, dx = y+cy, x+cx
|
||||
leaving = ~leaf[dy, dx] & ~solid[dy, dx]
|
||||
outgoing = flat[block, q, cell].astype(np.float64)
|
||||
external -= np.array([cx, cy, 1])*outgoing[leaving].sum()
|
||||
receiver, direction, _, _, rx, ry, _, _ = b.host.curved_host
|
||||
owner = layout.owner.ravel()[receiver].astype(np.intp)
|
||||
block, cell = np.divmod(owner, cells)
|
||||
a = flat[block, direction, cell].astype(np.float64)
|
||||
source = cell+CY[direction]*layout.local_shape[1]+CX[direction]
|
||||
incoming = flat[block, OPP[direction], source].astype(np.float64)
|
||||
jx, jy = CX[direction]*(a+incoming), CY[direction]*(a+incoming)
|
||||
independent = np.column_stack((jx, jy, rx*jy-ry*jx, incoming-a))
|
||||
return totals(dense, leaf), external, independent
|
||||
|
||||
|
||||
class RawExchangeGPU(unittest.TestCase):
|
||||
def test_row_ledger_interval_jet_switch_and_no_population_effect(self):
|
||||
with CudaContext(0) as ctx:
|
||||
for block in ((32, 40), (16, 20), (8, 10)):
|
||||
with FixedPatchStepper(CFG, BOUNDS, context=ctx, fine_block=block,
|
||||
fine_objects=[circle()], jets=[jet()], observe_raw_exchange=True) as measured, \
|
||||
FixedPatchStepper(CFG, BOUNDS, context=ctx, fine_block=block,
|
||||
fine_objects=[circle()], jets=[jet()]) as plain:
|
||||
arrays = [state(l.shape) for l in measured._levels]
|
||||
measured.initialize(*arrays)
|
||||
plain.initialize(*arrays)
|
||||
b = measured._level_boundaries[1]
|
||||
count = len(b.tables['cell'])
|
||||
kernel = measured._levels[1].kernel
|
||||
samples = []
|
||||
|
||||
def audited_step(src, dst, *args, **kw):
|
||||
measured._stream.synchronize()
|
||||
before, external, independent = census(measured, 1, src)
|
||||
raw = download(b.last_raw, (count, 4))
|
||||
np.testing.assert_allclose(raw, independent, rtol=2e-6, atol=2e-7)
|
||||
kernel(src, dst, *args, **kw)
|
||||
measured._stream.synchronize()
|
||||
after = measured._levels[1].layout.to_dense(
|
||||
download(dst, measured._levels[1].layout.blocked_shape))
|
||||
change = totals(after, measured._leaf[1])-before
|
||||
expected = external + np.array([-raw[:, 0].astype(float).sum(),
|
||||
-raw[:, 1].astype(float).sum(),
|
||||
raw[:, 3].astype(float).sum()])
|
||||
np.testing.assert_allclose(change, expected, rtol=2e-4, atol=8e-5)
|
||||
samples.append(raw.copy())
|
||||
measured._levels[1].kernel = audited_step
|
||||
for speed in (0., .002, -.001, 0.):
|
||||
measured.set_jet_amplitude(0, speed)
|
||||
plain.set_jet_amplitude(0, speed)
|
||||
samples.clear()
|
||||
measured.step()
|
||||
plain.step()
|
||||
for a, e in zip(measured.download(), plain.download()):
|
||||
np.testing.assert_array_equal(a, e)
|
||||
integral = download(b.interval_integral, (count, 4), np.float64)
|
||||
expected = sum(s.astype(float)*[.25, .25, .125, .25] for s in samples)
|
||||
np.testing.assert_array_equal(integral, expected)
|
||||
last = download(b.last_raw, (count, 4))
|
||||
np.testing.assert_array_equal(last, samples[-1])
|
||||
obs = measured.read_raw_exchange(0)
|
||||
assert obs['sample_count'] == 2
|
||||
assert b.tables['aperture'].any()
|
||||
measured.step(0)
|
||||
np.testing.assert_array_equal(measured.read_raw_exchange(0)['total']['impulse'],
|
||||
obs['total']['impulse'])
|
||||
|
||||
def test_dense_fine_storage_reference(self):
|
||||
"""Same fine resolution/initial data with dense storage: a numerical
|
||||
reference for cut-link rows, not a uniform-whole-domain convergence study."""
|
||||
with CudaContext(0) as ctx:
|
||||
with FixedPatchStepper(CFG, BOUNDS, context=ctx, fine_objects=[circle()], jets=[jet()]) as dense, \
|
||||
FixedPatchStepper(CFG, BOUNDS, context=ctx, fine_block=(16, 20),
|
||||
fine_objects=[circle()], jets=[jet()], observe_raw_exchange=True) as blocked:
|
||||
arrays = [state(l.shape) for l in blocked._levels]
|
||||
dense.initialize(*arrays)
|
||||
blocked.initialize(*arrays)
|
||||
for speed in (0., .002, 0.):
|
||||
dense.set_jet_amplitude(0, speed)
|
||||
blocked.set_jet_amplitude(0, speed)
|
||||
dense.step(); blocked.step()
|
||||
for a, e in zip(blocked.download(), dense.download()):
|
||||
np.testing.assert_array_equal(a, e)
|
||||
count = dense._fine_curved.count
|
||||
expected = download(dense._fine_curved.link_exchange_gpu, (count, 3))
|
||||
actual = download(blocked._level_boundaries[1].last_raw, (count, 4))
|
||||
np.testing.assert_array_equal(actual[:, :3], expected)
|
||||
|
||||
def test_depth_four_interval_storage_and_sampling(self):
|
||||
cfg = LBMConfig(nx=48, ny=48, viscosity=.02)
|
||||
obj = SimObject(0, geometry=CircleGeometry(16., 16., .5), center=(16., 16.), radius=.5)
|
||||
drive = Jet(Tube((16., 16.), 0., .75, .2), Parallel(0.), amplitude=0.)
|
||||
settings = dict(refinements=[[(6, 6, 26, 26)], [(20, 20, 44, 44)], [(56, 56, 72, 72)]],
|
||||
level_blocks=[(4, 4)]*4, level_objects=[(), (), (), (obj,)],
|
||||
level_jets=[(), (), (), (drive,)])
|
||||
with CudaContext(0) as ctx:
|
||||
with FixedPatchStepper(cfg, context=ctx, observe_raw_exchange=True, **settings) as run, \
|
||||
FixedPatchStepper(cfg, context=ctx, **settings) as plain:
|
||||
arrays = [state(l.shape, ux=0.) for l in run._levels]
|
||||
run.initialize(*arrays); plain.initialize(*arrays)
|
||||
b = run._level_boundaries[3]
|
||||
count = len(b.tables['cell'])
|
||||
kernel = run._levels[3].kernel
|
||||
samples, independent_samples = [], []
|
||||
def audited_step(src, dst, *args, **kw):
|
||||
run._stream.synchronize()
|
||||
before, external, independent = census(run, 3, src)
|
||||
raw = download(b.last_raw, (count, 4))
|
||||
np.testing.assert_allclose(raw, independent, rtol=2e-6, atol=2e-7)
|
||||
kernel(src, dst, *args, **kw)
|
||||
run._stream.synchronize()
|
||||
after = run._levels[3].layout.to_dense(
|
||||
download(dst, run._levels[3].layout.blocked_shape))
|
||||
change = totals(after, run._leaf[3])-before
|
||||
expected = external + np.array([-independent[:, 0].sum(),
|
||||
-independent[:, 1].sum(), independent[:, 3].sum()])
|
||||
np.testing.assert_allclose(change, expected, rtol=2e-4, atol=8e-5)
|
||||
samples.append(raw)
|
||||
independent_samples.append(independent)
|
||||
run._levels[3].kernel = audited_step
|
||||
for speed in (0., .002, 0.):
|
||||
run.set_jet_amplitude(0, speed, level=3)
|
||||
plain.set_jet_amplitude(0, speed, level=3)
|
||||
samples.clear(); independent_samples.clear()
|
||||
run.step(); plain.step()
|
||||
self.assertEqual(len(samples), 8)
|
||||
weights = np.array([1/64, 1/64, 1/512, 1/64])
|
||||
integral = download(b.interval_integral, (count, 4), np.float64)
|
||||
np.testing.assert_array_equal(integral, sum(v.astype(float)*weights for v in samples))
|
||||
np.testing.assert_allclose(integral, sum(v*weights for v in independent_samples),
|
||||
rtol=2e-6, atol=2e-7)
|
||||
np.testing.assert_array_equal(download(b.last_raw, (count, 4)), samples[-1])
|
||||
for actual, expected in zip(run.download(), plain.download()):
|
||||
np.testing.assert_array_equal(actual, expected)
|
||||
result = run.read_raw_exchange(0, level=3)
|
||||
self.assertEqual(result['sample_count'], 8)
|
||||
self.assertEqual(result['time_start'], run.step_count-1)
|
||||
if run.step_count == 1:
|
||||
np.testing.assert_allclose(result['total']['force'], 0, atol=2e-7)
|
||||
self.assertAlmostEqual(result['total']['torque'], 0, delta=2e-7)
|
||||
|
||||
def test_uniform_whole_domain_fine_short_time_reference(self):
|
||||
"""Same root geometry, nu and Jet speed on a whole-domain fine mesh.
|
||||
Eight local hops are a short-time equivalence check, not convergence.
|
||||
The test adapter only enables the standalone kernel's optional inputs.
|
||||
"""
|
||||
from CelerisLab.lbm.blocks import BlockLayout2D
|
||||
from CelerisLab.lbm.block_stepper import PeriodicBlockStepper
|
||||
fine_cfg = replace(CFG, nx=64, ny=48, viscosity=.2)
|
||||
obj = SimObject(0, geometry=CircleGeometry(31.5, 23.5, 4.3),
|
||||
center=(31.5, 23.5), radius=4.3)
|
||||
layout = BlockLayout2D.build(48, 64, 8, 8)
|
||||
with CudaContext(0) as ctx:
|
||||
with PeriodicBlockStepper(fine_cfg, layout, context=ctx, objects=[obj]) as uniform, \
|
||||
FixedPatchStepper(CFG, BOUNDS, context=ctx, fine_block=(16, 20),
|
||||
fine_objects=[circle()], jets=[jet()], observe_raw_exchange=True) as amr:
|
||||
amr.initialize(*(state(l.shape) for l in amr._levels))
|
||||
uniform.initialize(state((9, 48, 64)))
|
||||
b = amr._level_boundaries[1]
|
||||
count = len(b.tables['cell'])
|
||||
links = obj.geometry.build_cut_links(64, 48)
|
||||
np.testing.assert_array_equal([v.dir for v in links], b.tables['dir'])
|
||||
np.testing.assert_allclose([v.q for v in links], b.tables['q'], atol=2e-7, rtol=0)
|
||||
# Same fine-grid force arms after translation to the same center.
|
||||
rx = uniform._upload(b.tables['rx'])
|
||||
ry = uniform._upload(b.tables['ry'])
|
||||
velocity = uniform._upload(b.tables['surface_velocity'])
|
||||
raw = uniform._allocate(count*16)
|
||||
original = uniform._curved
|
||||
samples = []
|
||||
def measured_boundary(*args, **kw):
|
||||
original(*args[:7], velocity, rx, ry, raw, **kw)
|
||||
uniform._stream.synchronize()
|
||||
samples.append(download(raw, (count, 4)))
|
||||
uniform._curved = measured_boundary
|
||||
for speed in (0., .002, -.001, 0.):
|
||||
amr.set_jet_amplitude(0, speed)
|
||||
cuda.memcpy_htod(velocity, b.tables['surface_velocity'])
|
||||
samples.clear()
|
||||
amr.step(); uniform.step(2)
|
||||
expected = sum(v.astype(float)*[.25, .25, .125, .25] for v in samples)
|
||||
actual = download(b.interval_integral, (count, 4), np.float64)
|
||||
np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=2e-6)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,324 @@
|
||||
"""All-blocked fixed patch: transfer ordering, failure ownership and CUDA parity.
|
||||
|
||||
Run CPU and GPU classes in separate processes. GPU callers must first check
|
||||
resources/device availability; this file never selects or reserves a GPU.
|
||||
"""
|
||||
from contextlib import ExitStack, contextmanager, nullcontext
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from CelerisLab.cuda import compiler_v2 as compiler
|
||||
from CelerisLab.lbm import refinement_stepper
|
||||
from CelerisLab.lbm.blocks import BlockLayout2D
|
||||
from CelerisLab.lbm.descriptors import D2Q9_EX, D2Q9_EY
|
||||
from CelerisLab.lbm.refinement import ACTIVE, OUTER_GHOST, FixedPatch2D
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper, blocked_base_tables
|
||||
from test_refinement_blocked_fine import NX, NY, BOUNDS, config, state, circle, actuation
|
||||
|
||||
BASE_BLOCKS = ((24, 32), (12, 8), (3, 4), (1, 1))
|
||||
FINE_BLOCK = (16, 20)
|
||||
|
||||
|
||||
def raw(backend):
|
||||
arrays = []
|
||||
for level in backend._levels:
|
||||
array = np.empty(level.shape if level.layout is None else level.layout.blocked_shape,
|
||||
np.float32)
|
||||
cuda.memcpy_dtoh(array, level.current)
|
||||
arrays.append(array if level.layout is None else level.layout.to_dense(array))
|
||||
return tuple(arrays)
|
||||
|
||||
|
||||
def exact(test, actual, expected, label):
|
||||
"""Compare the complete invalid mask and every finite FP32 bit (incl. -0)."""
|
||||
np.testing.assert_array_equal(np.isnan(actual), np.isnan(expected), err_msg=label)
|
||||
test.assertFalse(np.isinf(actual).any(), label)
|
||||
test.assertFalse(np.isinf(expected).any(), label)
|
||||
finite = np.isfinite(expected)
|
||||
np.testing.assert_array_equal(actual[finite].view(np.uint32),
|
||||
expected[finite].view(np.uint32), err_msg=label)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def mocked_backend(mode="periodic", fail_alloc=None):
|
||||
"""Use the real constructor, uploads and launch logic, recording driver calls."""
|
||||
calls, allocations, uploads, functions = [], [], [], {}
|
||||
stream = Mock()
|
||||
context = Mock(activate=nullcontext, sm_arch="sm_70")
|
||||
|
||||
def function(name):
|
||||
if name not in functions:
|
||||
functions[name] = Mock(side_effect=lambda *a, **kw: calls.append((name, a, kw)))
|
||||
return functions[name]
|
||||
|
||||
def allocate(size):
|
||||
if len(allocations) == fail_alloc:
|
||||
raise MemoryError("injected allocation failure")
|
||||
if size <= 0:
|
||||
raise AssertionError("empty allocation")
|
||||
pointer = Mock()
|
||||
allocations.append(pointer)
|
||||
return pointer
|
||||
|
||||
module = Mock(get_function=Mock(side_effect=function))
|
||||
module.get_global.side_effect = lambda name: (name, 16 if name == "d_block_wall" else 20)
|
||||
with ExitStack() as stack:
|
||||
for name in ("generate_config", "compile_kernel", "cleanup_build_dir"):
|
||||
stack.enter_context(patch.object(compiler, name))
|
||||
stack.enter_context(patch.object(compiler, "load_module", return_value=module))
|
||||
stack.enter_context(patch.object(cuda, "Stream", return_value=stream))
|
||||
stack.enter_context(patch.object(cuda, "mem_alloc", side_effect=allocate))
|
||||
stack.enter_context(patch.object(cuda, "memcpy_htod",
|
||||
side_effect=lambda p, a: uploads.append((p, a))))
|
||||
yield dict(context=context, calls=calls, allocations=allocations, uploads=uploads,
|
||||
functions=functions, stream=stream)
|
||||
|
||||
|
||||
class BlockedBaseCPU(unittest.TestCase):
|
||||
def test_reject_before_cuda(self):
|
||||
context = Mock(activate=Mock(side_effect=AssertionError("CUDA reached")))
|
||||
for kwargs in ({"base_block": (12, 8)},
|
||||
{"base_block": (7, 8), "fine_block": FINE_BLOCK},
|
||||
{"base_block": (12,), "fine_block": FINE_BLOCK}):
|
||||
with self.subTest(kwargs=kwargs), self.assertRaises(ValueError):
|
||||
FixedPatchStepper(config("periodic"), BOUNDS, context=context, **kwargs)
|
||||
context.activate.assert_not_called()
|
||||
|
||||
def test_all_arrival_rows_donors_and_kind_masks(self):
|
||||
p = FixedPatch2D.from_config(config("periodic"), BOUNDS)
|
||||
order = np.argsort(p.coalesce_coarse)
|
||||
self.assertEqual(len(order), 172)
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
leaves = np.ones((NY, NX), bool)
|
||||
x0, y0, x1, y1 = BOUNDS
|
||||
leaves[y0:y1, x0:x1] = False
|
||||
if mode != "periodic":
|
||||
leaves[[0, -1]] = False
|
||||
for by, bx in BASE_BLOCKS:
|
||||
layout = BlockLayout2D.build(NY, NX, by, bx, periodic=(True, mode == "periodic"))
|
||||
donors, targets, kind = blocked_base_tables(p, layout, order, mode != "periodic")
|
||||
ly, lx = layout.local_shape
|
||||
L = ly * lx
|
||||
expected, source_cells = [], []
|
||||
for slot in p.coalesce_coarse[order]:
|
||||
q, receiver = divmod(int(slot), NX * NY)
|
||||
y, x = divmod(receiver, NX)
|
||||
block = (y // by) * (NX // bx) + x // bx
|
||||
# Scalar coordinate construction independent of layout.owner / slot.
|
||||
sy, sx = y % by + 1 - D2Q9_EY[q], x % bx + 1 - D2Q9_EX[q]
|
||||
expected.append((block * 9 + q) * L + sy * lx + sx)
|
||||
source_cells.append((y - D2Q9_EY[q], x - D2Q9_EX[q]))
|
||||
np.testing.assert_array_equal(targets, expected)
|
||||
self.assertEqual(len(set(targets.tolist())), 172)
|
||||
self.assertEqual(sum(not (y0 <= y < y1 and x0 <= x < x1)
|
||||
for y, x in source_cells), 8)
|
||||
expected_donors = []
|
||||
for cell in p.ghost_coarse:
|
||||
y, x = divmod(int(cell), NX)
|
||||
block = (y // by) * (NX // bx) + x // bx
|
||||
expected_donors.append(block * L + (y % by + 1) * lx + x % bx + 1)
|
||||
np.testing.assert_array_equal(donors, expected_donors)
|
||||
expected_kind = np.full(layout.nblocks * L, OUTER_GHOST, np.uint8)
|
||||
expected_kind[layout.owner[leaves].astype(np.intp)] = ACTIVE
|
||||
np.testing.assert_array_equal(kind, expected_kind)
|
||||
|
||||
def test_staging_negative_controls_detect_seam_and_donor_corruption(self):
|
||||
p = FixedPatch2D.from_config(config("periodic"), BOUNDS)
|
||||
order = np.argsort(p.coalesce_coarse)
|
||||
layout = BlockLayout2D.build(NY, NX, 3, 4)
|
||||
donors, targets, _ = blocked_base_tables(p, layout, order)
|
||||
dense = np.arange(9 * NY * NX, dtype=np.float32).reshape(9, NY, NX)
|
||||
initial = layout.to_blocked(dense)
|
||||
arrivals = np.arange(len(targets), dtype=np.float32) + 10000
|
||||
staged = initial.copy()
|
||||
staged.ravel()[targets.astype(np.intp)] = arrivals
|
||||
def pull(storage):
|
||||
out = np.empty_like(dense)
|
||||
by, bx = layout.block
|
||||
ly, lx = layout.local_shape
|
||||
for y in range(NY):
|
||||
for x in range(NX):
|
||||
b = (y // by) * (NX // bx) + x // bx
|
||||
for q in range(9):
|
||||
out[q, y, x] = storage[b, q, y % by + 1 - D2Q9_EY[q],
|
||||
x % bx + 1 - D2Q9_EX[q]]
|
||||
return out
|
||||
|
||||
expected = np.array([np.roll(dense[q], (D2Q9_EY[q], D2Q9_EX[q]), axis=(0, 1))
|
||||
for q in range(9)])
|
||||
expected.ravel()[p.coalesce_coarse[order].astype(np.intp)] = arrivals
|
||||
leaves = np.ones((NY, NX), bool)
|
||||
leaves[6:18, 8:24] = False
|
||||
# Compare ALL parent arrivals, not only the slots deliberately written.
|
||||
np.testing.assert_array_equal(pull(staged)[:, leaves], expected[:, leaves])
|
||||
# A late halo gather erases receiver-local arrivals at seams.
|
||||
late_gather = staged.copy()
|
||||
layout.exchange(late_gather)
|
||||
self.assertGreater(np.count_nonzero(pull(late_gather)[:, leaves] != expected[:, leaves]), 0)
|
||||
# Canonical source owners are not the slots read by each receiver's pull.
|
||||
q, receiver = np.divmod(p.coalesce_coarse[order], NX * NY)
|
||||
y, x = np.divmod(receiver.astype(np.intp), NX)
|
||||
owners = layout.owner[y - np.asarray(D2Q9_EY)[q.astype(np.intp)],
|
||||
x - np.asarray(D2Q9_EX)[q.astype(np.intp)]]
|
||||
wrong = initial.copy()
|
||||
wrong.ravel()[layout.slot(owners, q).astype(np.intp)] = arrivals
|
||||
self.assertGreater(np.count_nonzero(pull(wrong)[:, leaves] != expected[:, leaves]), 0)
|
||||
# With one parent block, all eight grazing sources are owner cores.
|
||||
# Each is read for four fine ghost children: late explosion corrupts32.
|
||||
single = BlockLayout2D.build(NY, NX, NY, NX)
|
||||
donors, targets, _ = blocked_base_tables(p, single, order)
|
||||
initial = single.to_blocked(dense)
|
||||
staged = initial.copy()
|
||||
staged.ravel()[targets.astype(np.intp)] = arrivals
|
||||
donor_slots = single.slot(donors[None, :], np.arange(9)[:, None]).astype(np.intp)
|
||||
self.assertEqual(np.count_nonzero(staged.ravel()[donor_slots]
|
||||
!= initial.ravel()[donor_slots]), 32)
|
||||
|
||||
def test_raw_mask_gate_detects_leak_hidden_by_download_mask(self):
|
||||
valid = state(NY, NX, 1)
|
||||
valid[:, 6:18, 8:24] = np.nan
|
||||
leaked = valid.copy()
|
||||
leaked[5, 6, 8] = 42 # skipped invalid-cell store leaves stale staging data
|
||||
public = leaked.copy()
|
||||
public[:, 6:18, 8:24] = np.nan
|
||||
exact(self, public, valid, "masked download cannot detect stale staging")
|
||||
with self.assertRaises(AssertionError):
|
||||
exact(self, leaked, valid, "raw owner-core must detect stale staging")
|
||||
|
||||
def test_launch_order_stream_wall_constants_and_buffer_swaps(self):
|
||||
with mocked_backend("slot_reservoir") as m:
|
||||
backend = FixedPatchStepper(config("slot_reservoir"), BOUNDS, context=m["context"],
|
||||
coarse_boundary="slot_reservoir", fine_block=FINE_BLOCK,
|
||||
base_block=(3, 4), fine_objects=[circle(actuation(.002))])
|
||||
try:
|
||||
backend.initialize(state(NY, NX, 1), state(*backend.patch.fine_shape, 2))
|
||||
coarse, fine = backend._levels
|
||||
current, spare, fine_current = coarse.current, coarse.spare, fine.current
|
||||
backend.step(2)
|
||||
names = [name for name, _, _ in m["calls"]]
|
||||
interval = ["BlockExplode", "BlockHaloCopy", "BlockCurvedBoundary", "BlockStep",
|
||||
"BlockHaloCopy", "BlockCurvedBoundary", "BlockStep",
|
||||
"BlockHaloCopy", "BlockCoalesce", "BlockStep"]
|
||||
self.assertEqual(names, interval * 2)
|
||||
self.assertEqual(backend.step_count, 2)
|
||||
self.assertIs(coarse.current, current)
|
||||
self.assertIs(coarse.spare, spare)
|
||||
self.assertIs(fine.current, fine_current)
|
||||
for _, _, kw in m["calls"]:
|
||||
self.assertIs(kw["stream"], m["stream"])
|
||||
for offset, src, dst in ((0, current, spare), (10, spare, current)):
|
||||
explode, gather, stage, collide = [m["calls"][offset + i][1] for i in (0, 7, 8, 9)]
|
||||
self.assertIs(explode[0], src)
|
||||
self.assertIs(gather[0], src)
|
||||
self.assertIs(stage[0], fine_current)
|
||||
self.assertIs(stage[1], src)
|
||||
self.assertIs(collide[0], src)
|
||||
self.assertIs(collide[1], dst)
|
||||
self.assertIs(collide[4], coarse.kind)
|
||||
walls = [a for ptr, a in m["uploads"] if isinstance(ptr, str) and ptr == "d_block_wall"]
|
||||
self.assertEqual(len(walls), 1)
|
||||
width, height, slot, speed = struct.unpack("=IIIf", walls[0])
|
||||
self.assertEqual((width, height, slot), (NX, NY, 8))
|
||||
self.assertAlmostEqual(speed, .001)
|
||||
finally:
|
||||
backend.close()
|
||||
for allocation in m["allocations"]:
|
||||
allocation.free.assert_called_once_with()
|
||||
|
||||
def test_allocation_failure_releases_every_owned_buffer(self):
|
||||
# Fail during the first level, second level and transfer-table uploads.
|
||||
for fail_at in (1, 6, 10):
|
||||
with self.subTest(fail_at=fail_at), mocked_backend(fail_alloc=fail_at) as m:
|
||||
with self.assertRaisesRegex(MemoryError, "injected allocation"):
|
||||
FixedPatchStepper(config("periodic"), BOUNDS, context=m["context"],
|
||||
fine_block=FINE_BLOCK, base_block=(3, 4))
|
||||
self.assertEqual(len(m["allocations"]), fail_at)
|
||||
for allocation in m["allocations"]:
|
||||
allocation.free.assert_called_once_with()
|
||||
|
||||
def test_failed_parent_stage_cannot_publish_or_resume(self):
|
||||
with mocked_backend() as m:
|
||||
backend = FixedPatchStepper(config("periodic"), BOUNDS, context=m["context"],
|
||||
fine_block=FINE_BLOCK, base_block=(3, 4))
|
||||
backend.initialize(state(NY, NX, 1), state(*backend.patch.fine_shape, 2))
|
||||
m["functions"]["BlockCoalesce"].side_effect = RuntimeError("injected parent stage failure")
|
||||
current = backend._levels[0].current
|
||||
with self.assertRaisesRegex(RuntimeError, "injected parent stage"):
|
||||
backend.step()
|
||||
self.assertEqual(backend.step_count, 0)
|
||||
self.assertEqual(backend._status, "failed")
|
||||
self.assertIs(backend._levels[0].current, current)
|
||||
with self.assertRaisesRegex(RuntimeError, "failed"):
|
||||
backend.download()
|
||||
with self.assertRaisesRegex(RuntimeError, "failed"):
|
||||
backend.step()
|
||||
backend.close()
|
||||
for allocation in m["allocations"]:
|
||||
allocation.free.assert_called_once_with()
|
||||
|
||||
|
||||
class BlockedBaseGPU(unittest.TestCase):
|
||||
def test_bodyfree_exact_parity_and_raw_invalid_slots(self):
|
||||
self.compare([(None, ((24, 32), (3, 4), (1, 1)), 8)])
|
||||
|
||||
def test_actuated_circle_exact_parity_and_raw_invalid_slots(self):
|
||||
self.compare([(.002, ((12, 8),), 8), (-.002, ((12, 8),), 8)])
|
||||
|
||||
def test_non_power_two_slot_width_exact_parity(self):
|
||||
self.compare([(None, ((3, 4),), 7), (None, ((3, 4),), 10)], ("slot_reservoir",))
|
||||
|
||||
def compare(self, cases, modes=("periodic", "slot_reservoir")):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
expected_source = Path(__file__).resolve().parents[3] / "src/CelerisLab/lbm/refinement_stepper.py"
|
||||
self.assertEqual(Path(refinement_stepper.__file__).resolve(), expected_source)
|
||||
with CudaContext(0) as context:
|
||||
for mode in modes:
|
||||
for speed, layouts, width in cases:
|
||||
cfg = config(mode)
|
||||
if mode == "slot_reservoir":
|
||||
cfg = replace(cfg, wall_slot_width=width)
|
||||
p = FixedPatch2D.from_config(cfg, BOUNDS)
|
||||
arrays = state(NY, NX, 1), state(*p.fine_shape, 2)
|
||||
reference = None
|
||||
for base_block in (None, *layouts):
|
||||
label = f"{mode} width={width} speed={speed} base={base_block}"
|
||||
snapshots = []
|
||||
with FixedPatchStepper(cfg, BOUNDS, context=context, coarse_boundary=mode,
|
||||
fine_block=FINE_BLOCK, base_block=base_block,
|
||||
fine_objects=() if speed is None else [circle(actuation(speed))]) as backend:
|
||||
backend.initialize(*arrays)
|
||||
for step in (0, 1, 2, 8):
|
||||
if step == 1 and base_block is not None:
|
||||
# Blocked staging dirties invalid input slots; its output
|
||||
# must poison them. Dense parent does not stage there.
|
||||
coarse = backend._levels[0]
|
||||
spare = coarse.layout.to_blocked(np.full(coarse.shape, 42, np.float32))
|
||||
cuda.memcpy_htod(coarse.spare, spare)
|
||||
backend.step(step - backend.step_count)
|
||||
public, owner = backend.download(), raw(backend)
|
||||
self.assertEqual(backend.step_count, step)
|
||||
self.assertTrue(np.isnan(owner[0][:, 6:18, 8:24]).all(), label)
|
||||
if mode != "periodic":
|
||||
self.assertTrue(np.isnan(owner[0][:, (0, -1), :]).all(), label)
|
||||
snapshots.append(public + owner)
|
||||
backend.initialize(*arrays)
|
||||
self.assertEqual(backend.step_count, 0)
|
||||
for actual, expected in zip(backend.download() + raw(backend), snapshots[0]):
|
||||
exact(self, actual, expected, label + " reset")
|
||||
if reference is None:
|
||||
reference = snapshots
|
||||
else:
|
||||
for step, actual, expected in zip((0, 1, 2, 8), snapshots, reference):
|
||||
for index, (a, b) in enumerate(zip(actual, expected)):
|
||||
exact(self, a, b, f"{label} step={step} array={index}")
|
||||
print(f"PASS {label}: full finite bits/NaN masks at 0,1,2,8 + reset", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,369 @@
|
||||
"""Opt-in blocked fine storage for FixedPatchStepper: CPU tables plus GPU gate.
|
||||
|
||||
Frozen GPU gate (same stream, 8 coarse steps, nonequilibrium start), in both
|
||||
periodic and slot_reservoir modes: dense fine storage vs 1x1, 2x2 and 4x2
|
||||
fine blocks give bit-identical masked downloads AND bit-identical raw coarse
|
||||
and unpacked owner-core fine arrays, including patch-ghost values/NaN masks.
|
||||
"""
|
||||
from contextlib import nullcontext
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject, SurfaceActuation
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.cuda import compiler_v2 as compiler
|
||||
from CelerisLab.lbm import curved_links
|
||||
from CelerisLab.lbm.blocks import NO_DONOR, BlockLayout2D, blocked_link_tables
|
||||
from CelerisLab.lbm.descriptors import D2Q9_EX, D2Q9_EY
|
||||
from CelerisLab.lbm.descriptors import SOLID
|
||||
from CelerisLab.lbm.refinement import (ACTIVE, INNER_GHOST, OUTER_GHOST, FixedPatch2D,
|
||||
prepare_fine_boundary)
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper, blocked_fine_tables
|
||||
|
||||
NX, NY, BOUNDS, STEPS = 32, 24, (8, 6, 24, 18), 8
|
||||
FINE_BLOCKS = ((32, 40), (16, 20), (16, 10)) # fine window 32x40: 1x1, 2x2, 4x2
|
||||
W = np.array([4 / 9] + [1 / 9] * 4 + [1 / 36] * 4)
|
||||
CX, CY = np.array(D2Q9_EX, float), np.array(D2Q9_EY, float)
|
||||
|
||||
|
||||
def config(mode):
|
||||
if mode == "periodic":
|
||||
return LBMConfig(nx=NX, ny=NY, viscosity=.1)
|
||||
return LBMConfig(nx=NX, ny=NY, viscosity=.1, velocity=0, wall_normal_velocity=.001,
|
||||
wall_slot_width=8, y_wall_bc="on_site_velocity", top_wall_bc="reservoir")
|
||||
|
||||
|
||||
def state(ny, nx, seed):
|
||||
"""Positive low-Mach equilibrium plus a seeded nonequilibrium part."""
|
||||
y, x = np.mgrid[0:ny, 0:nx]
|
||||
rho = 1 + 1e-3 * np.cos(2 * np.pi * x / nx)
|
||||
ux, uy = .02 * np.sin(2 * np.pi * y / ny), .01 * np.cos(2 * np.pi * x / nx)
|
||||
cu = CX[:, None, None] * ux + CY[:, None, None] * uy
|
||||
feq = W[:, None, None] * rho * (1 + 3 * cu + 4.5 * cu * cu - 1.5 * (ux * ux + uy * uy))
|
||||
noise = np.random.default_rng(seed).uniform(-1, 1, feq.shape) * 1e-3 * W[:, None, None]
|
||||
return (feq + noise).astype(np.float32)
|
||||
|
||||
|
||||
def circle(spec=None):
|
||||
"""Astra fixture: coarse cell-edge C=(16,12), R=2.15 -> fine C=(19.5,15.5), R=4.3."""
|
||||
return SimObject(0, geometry=CircleGeometry(16.0, 12.0, 2.15), center=(16.0, 12.0),
|
||||
radius=2.15, surface_actuation=spec)
|
||||
|
||||
|
||||
def actuation(speed):
|
||||
"""Astra's seam fixture: 21 aperture links; in each decomposed layout 3 of them
|
||||
write a halo image and 2 read a q<.5 donor from a halo. Coarse lattice units:
|
||||
prepare_fine_boundary does the (acoustic) fine scaling, never scale twice."""
|
||||
return SurfaceActuation(0.7, 0.85, speed)
|
||||
|
||||
|
||||
def fine_circle(mode, spec=None):
|
||||
cfg = config(mode)
|
||||
patch = FixedPatch2D.from_config(cfg, BOUNDS)
|
||||
return patch, prepare_fine_boundary(cfg, patch, (circle(spec),),
|
||||
wall_aware=mode == "slot_reservoir")
|
||||
|
||||
|
||||
def fine_cfg(mode, patch):
|
||||
from dataclasses import replace
|
||||
cfg = replace(config(mode), nx=patch.fine_shape[1], ny=patch.fine_shape[0], viscosity=.2)
|
||||
if mode == "slot_reservoir":
|
||||
cfg = replace(cfg, y_wall_bc="bounce_back", top_wall_bc="velocity",
|
||||
wall_slot_width=0, wall_normal_velocity=0.0, velocity=0.0)
|
||||
cfg.validate() # as the stepper does before surface_link_velocity
|
||||
return cfg
|
||||
|
||||
|
||||
def seam_cells(layout, mapped):
|
||||
"""Distinct non-core cells written / read as q<.5 donors (receiver-local halos)."""
|
||||
L = int(np.prod(layout.local_shape))
|
||||
core = set(layout.owner.ravel().tolist())
|
||||
writes = {int(w) // (9 * L) * L + int(w) % L for w in mapped.write}
|
||||
donors = {int(d) for d in mapped.donor if d != NO_DONOR}
|
||||
return len(writes - core), len(donors - core)
|
||||
|
||||
|
||||
def raw(backend):
|
||||
"""Unmasked device arrays; blocked fine storage unpacked from owner cores."""
|
||||
coarse, fine = backend._levels
|
||||
out = [np.empty(coarse.shape, np.float32)]
|
||||
out.append(np.empty(fine.shape if backend.fine_layout is None
|
||||
else backend.fine_layout.blocked_shape, np.float32))
|
||||
cuda.memcpy_dtoh(out[0], coarse.current)
|
||||
cuda.memcpy_dtoh(out[1], fine.current)
|
||||
if backend.fine_layout is not None:
|
||||
out[1] = backend.fine_layout.to_dense(out[1])
|
||||
return out
|
||||
|
||||
|
||||
class BlockedFineCPU(unittest.TestCase):
|
||||
def forbidden_context(self):
|
||||
return Mock(activate=Mock(side_effect=AssertionError("CUDA reached")), sm_arch="sm_70")
|
||||
|
||||
def test_rejections_before_cuda(self):
|
||||
for kw in ({"fine_block": (7, 7)}, {"fine_block": (16,)}):
|
||||
with self.subTest(kw=kw), self.assertRaises(ValueError):
|
||||
FixedPatchStepper(config("periodic"), BOUNDS, context=self.forbidden_context(), **kw)
|
||||
|
||||
def test_single_block_layout_allocates_no_empty_halo_tables(self):
|
||||
# A 1x1 non-periodic fine layout has zero halo pairs; CUDA rejects mem_alloc(0).
|
||||
context = Mock(activate=nullcontext, sm_arch="sm_70")
|
||||
module = Mock()
|
||||
module.get_global.return_value = (Mock(), 20)
|
||||
sizes = []
|
||||
|
||||
def alloc(size):
|
||||
if size <= 0:
|
||||
raise AssertionError("zero-byte device allocation")
|
||||
sizes.append(size)
|
||||
return Mock()
|
||||
with patch.object(cuda, "Stream"), patch.object(compiler, "generate_config"), \
|
||||
patch.object(compiler, "compile_kernel"), patch.object(compiler, "cleanup_build_dir"), \
|
||||
patch.object(compiler, "load_module", return_value=module), \
|
||||
patch.object(cuda, "mem_alloc", side_effect=alloc), patch.object(cuda, "memcpy_htod"):
|
||||
backend = FixedPatchStepper(config("periodic"), BOUNDS, context=context,
|
||||
fine_block=FINE_BLOCKS[0])
|
||||
self.assertEqual(len(backend.fine_layout.halo_dst), 0)
|
||||
self.assertIsNone(backend._levels[1].halo_dst)
|
||||
backend._gather_halo(backend._levels[1], Mock()) # no launch without pairs
|
||||
module.get_function.return_value.assert_not_called()
|
||||
backend.close()
|
||||
self.assertTrue(sizes)
|
||||
|
||||
def test_circle_fixture_counts_and_seam_staging(self):
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
patch, boundary = fine_circle(mode)
|
||||
fluid_idx, dirs, q, _, _, _, _, fallback = boundary.curved_host
|
||||
self.assertEqual(len(fluid_idx), 76, mode)
|
||||
self.assertEqual(int(np.count_nonzero(q < .5)), 68, mode)
|
||||
self.assertTrue((fallback[q < .5] == 0).all(), mode) # every q<.5 link uses its donor
|
||||
for by, bx in FINE_BLOCKS:
|
||||
layout = BlockLayout2D.build(*patch.fine_shape, by, bx, periodic=(False, False))
|
||||
_, mapped = blocked_link_tables(layout, boundary.flags, fluid_idx, dirs, q, fallback)
|
||||
single = layout.nblocks == 1
|
||||
self.assertEqual(seam_cells(layout, mapped), (0, 0) if single else (8, 8), (mode, by, bx))
|
||||
self.assertEqual(len(set(mapped.block.tolist())), 1 if single else 4, (mode, by, bx))
|
||||
|
||||
def test_storage_adapter_flags_sizing(self):
|
||||
patch, boundary = fine_circle("periodic")
|
||||
columns = [boundary.curved_host[i] for i in (0, 1, 2, 7)]
|
||||
layout = BlockLayout2D.build(*patch.fine_shape, 16, 20, periodic=(False, False))
|
||||
tables, mapped = blocked_link_tables(layout, boundary.flags, *columns)
|
||||
L = int(np.prod(layout.local_shape))
|
||||
self.assertEqual(tables["flags"].shape, (layout.nblocks * L,))
|
||||
np.testing.assert_array_equal(tables["flags"][layout.owner.ravel().astype(np.intp)],
|
||||
boundary.flags)
|
||||
np.testing.assert_array_equal(tables["cell"], mapped.receiver % np.uint64(L))
|
||||
for bad in (boundary.flags[:-1], boundary.flags.astype(np.uint32)):
|
||||
with self.assertRaises(ValueError):
|
||||
blocked_link_tables(layout, bad, *columns)
|
||||
|
||||
def mocked_backend(self, objects):
|
||||
"""Real constructor/initialize with driver doubles; kernels record (name, args)."""
|
||||
context = Mock(activate=nullcontext, sm_arch="sm_70")
|
||||
calls, functions = [], {}
|
||||
|
||||
def get_function(name):
|
||||
return functions.setdefault(name, Mock(side_effect=lambda *a, **k: calls.append((name, a))))
|
||||
module = Mock(get_function=Mock(side_effect=get_function))
|
||||
module.get_global.return_value = (Mock(), 20)
|
||||
with patch.object(cuda, "Stream"), patch.object(compiler, "generate_config"), \
|
||||
patch.object(compiler, "compile_kernel"), patch.object(compiler, "cleanup_build_dir"), \
|
||||
patch.object(compiler, "load_module", return_value=module), \
|
||||
patch.object(cuda, "mem_alloc", side_effect=lambda size: Mock()), \
|
||||
patch.object(cuda, "memcpy_htod"), \
|
||||
patch.object(curved_links, "CurvedLinkSoA", side_effect=AssertionError("dense SoA built")):
|
||||
backend = FixedPatchStepper(config("periodic"), BOUNDS, context=context,
|
||||
fine_objects=objects, fine_block=FINE_BLOCKS[1])
|
||||
backend.initialize(state(NY, NX, 1), state(*backend.patch.fine_shape, 2))
|
||||
return backend, calls
|
||||
|
||||
def test_same_buffer_halo_bfl_step_launch_order(self):
|
||||
for spec in (None, actuation(.002)):
|
||||
backend, calls = self.mocked_backend([circle(spec)])
|
||||
c, f = backend._levels
|
||||
coarse, cur, spare = c.current, f.current, f.spare
|
||||
flags, kind = backend._fine_flags, backend._levels[1].kind
|
||||
velocity = backend._link_tables.get("surface_velocity")
|
||||
self.assertEqual(velocity is None, spec is None)
|
||||
backend.step(1)
|
||||
backend.close()
|
||||
order = [(name, a[0]) for name, a in calls]
|
||||
self.assertEqual(order, [("BlockExplode", coarse),
|
||||
("BlockHaloCopy", cur), ("BlockCurvedBoundary", cur), ("BlockStep", cur),
|
||||
("BlockHaloCopy", spare), ("BlockCurvedBoundary", spare),
|
||||
("BlockStep", spare), ("PatchCoarseStep", coarse)])
|
||||
steps = [a for name, a in calls if name == "BlockStep"]
|
||||
self.assertEqual([a[1] for a in steps], [spare, cur])
|
||||
for a in steps:
|
||||
self.assertIs(a[3], flags) # blocked flags, not null
|
||||
self.assertIs(a[4], kind)
|
||||
for a in (a for name, a in calls if name == "BlockCurvedBoundary"):
|
||||
if spec is None: # explicit null at the raw launch ABI
|
||||
self.assertIsInstance(a[7], np.uintp)
|
||||
self.assertEqual(int(a[7]), 0)
|
||||
else:
|
||||
self.assertIs(a[7], velocity)
|
||||
|
||||
def test_actuation_without_velocity_buffer_fails_before_bfl(self):
|
||||
for speed in (0.0, .002): # any spec, even zero amplitude
|
||||
backend, calls = self.mocked_backend([circle(actuation(speed))])
|
||||
self.assertIsNotNone(backend._fine_tables["surface_velocity"])
|
||||
del backend._link_tables["surface_velocity"]
|
||||
with self.assertRaisesRegex(RuntimeError, "Surface velocity device buffer is missing"):
|
||||
backend.step(1)
|
||||
names = [name for name, _ in calls]
|
||||
self.assertNotIn("BlockCurvedBoundary", names)
|
||||
self.assertNotIn("BlockStep", names)
|
||||
self.assertEqual(backend._status, "failed")
|
||||
backend.close()
|
||||
|
||||
def test_surface_velocity_helper_matches_dense_soa(self):
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
patch, boundary = fine_circle(mode, actuation(-.002))
|
||||
cfg = fine_cfg(mode, patch)
|
||||
soa = curved_links.CurvedLinkSoA()
|
||||
soa.assign_host(*boundary.curved_host)
|
||||
soa.assign_surface(boundary.objects, cfg, boundary.flags)
|
||||
fluid_idx, dirs, _, body_id, rx, ry, _, _ = boundary.curved_host
|
||||
velocity, aperture = curved_links.surface_link_velocity(
|
||||
boundary.objects, cfg, boundary.flags, fluid_idx, dirs, body_id, rx, ry)
|
||||
np.testing.assert_array_equal(velocity, soa.surface_velocity)
|
||||
np.testing.assert_array_equal(aperture, soa.aperture)
|
||||
self.assertEqual(curved_links.surface_link_velocity(
|
||||
(circle(),), cfg, boundary.flags, fluid_idx, dirs, body_id, rx, ry), (None, None))
|
||||
# Actuated (not just geometric) seam coverage in both decomposed layouts.
|
||||
self.assertEqual(int(aperture.sum()), 21, mode)
|
||||
self.assertTrue(np.all(np.any(velocity[aperture] != 0, axis=1)), mode)
|
||||
for by, bx in FINE_BLOCKS[1:]:
|
||||
layout = BlockLayout2D.build(*patch.fine_shape, by, bx, periodic=(False, False))
|
||||
_, mapped = blocked_link_tables(layout, boundary.flags, fluid_idx, dirs,
|
||||
boundary.curved_host[2], boundary.curved_host[7])
|
||||
L = int(np.prod(layout.local_shape))
|
||||
core = set(layout.owner.ravel().tolist())
|
||||
halo_write = np.array([int(w) // (9 * L) * L + int(w) % L not in core
|
||||
for w in mapped.write])
|
||||
halo_donor = np.array([d != NO_DONOR and int(d) not in core for d in mapped.donor])
|
||||
self.assertEqual((int((halo_write & aperture).sum()),
|
||||
int((halo_donor & aperture).sum())), (3, 2), (mode, by, bx))
|
||||
|
||||
def test_tables_map_back_to_dense_slots_in_order(self):
|
||||
patch = FixedPatch2D.from_config(config("periodic"), BOUNDS)
|
||||
fy, fx = patch.fine_shape
|
||||
cells = fy * fx
|
||||
order = np.argsort(patch.coalesce_coarse)
|
||||
for by, bx in FINE_BLOCKS:
|
||||
layout = BlockLayout2D.build(fy, fx, by, bx, periodic=(False, False))
|
||||
core = set(layout.owner.ravel().tolist())
|
||||
targets, children, kind = blocked_fine_tables(patch, layout, order)
|
||||
# Explosion targets: owner cores of exactly the non-ACTIVE fine cells.
|
||||
np.testing.assert_array_equal(targets, layout.owner.ravel()[patch.ghost_fine])
|
||||
self.assertEqual(sorted(targets.tolist()),
|
||||
sorted(layout.owner[patch.fine_kind != ACTIVE].tolist()))
|
||||
# Children: same rows/child order, same (q, dense cell), owner cores.
|
||||
L = int(np.prod(layout.local_shape))
|
||||
b, rest = np.divmod(children, np.uint64(9 * L))
|
||||
q, c = np.divmod(rest, np.uint64(L))
|
||||
dense = patch.coalesce_fine[order]
|
||||
np.testing.assert_array_equal(q, dense // cells)
|
||||
np.testing.assert_array_equal(b * np.uint64(L) + c,
|
||||
layout.owner.ravel()[(dense % cells).astype(np.intp)])
|
||||
self.assertTrue(set((b * np.uint64(L) + c).ravel().tolist()) <= core)
|
||||
# Kinds follow owner cores; unused halo entries are OUTER.
|
||||
np.testing.assert_array_equal(kind[layout.owner.ravel().astype(np.intp)],
|
||||
patch.fine_kind.ravel())
|
||||
self.assertEqual(set(np.unique(kind).tolist()) - {ACTIVE, INNER_GHOST, OUTER_GHOST}, set())
|
||||
|
||||
|
||||
class BlockedFineGPU(unittest.TestCase):
|
||||
def test_dense_and_blocked_fine_storage_are_bit_identical(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
cfg = config(mode)
|
||||
patch = FixedPatch2D.from_config(cfg, BOUNDS)
|
||||
g_coarse, g_fine = state(NY, NX, 1), state(*patch.fine_shape, 2)
|
||||
results = []
|
||||
with CudaContext(0) as context:
|
||||
for fine_block in (None, *FINE_BLOCKS):
|
||||
with FixedPatchStepper(cfg, BOUNDS, context=context, coarse_boundary=mode,
|
||||
fine_block=fine_block) as backend:
|
||||
backend.initialize(g_coarse, g_fine)
|
||||
backend.step(STEPS)
|
||||
self.assertEqual(backend.step_count, STEPS)
|
||||
results.append((backend.download(), raw(backend)))
|
||||
(dense_public, dense_raw), blocked = results[0], results[1:]
|
||||
kind = patch.fine_kind
|
||||
self.assertTrue(np.isnan(dense_raw[1][:, kind == OUTER_GHOST]).all(), mode)
|
||||
# INNER populations may be NaN after hop 2 (pulled from poisoned OUTER);
|
||||
# their exact pattern is pinned by the dense-vs-blocked comparison below.
|
||||
self.assertTrue(np.isfinite(dense_raw[1][:, kind == ACTIVE]).all(), mode)
|
||||
for fine_block, (public, raw_arrays) in zip(FINE_BLOCKS, blocked):
|
||||
msg = f"{mode} fine_block={fine_block}"
|
||||
for a, b in zip(public + tuple(raw_arrays), dense_public + tuple(dense_raw)):
|
||||
np.testing.assert_array_equal(a, b, err_msg=msg) # values and NaN masks
|
||||
print(f"{mode}: dense vs {len(blocked)} fine-block layouts bit-identical "
|
||||
f"after {STEPS} coarse steps", flush=True)
|
||||
|
||||
def test_passive_circle_dense_and_blocked_fine_storage_are_bit_identical(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
cfg = config(mode)
|
||||
patch, boundary = fine_circle(mode)
|
||||
solid = (boundary.flags.reshape(patch.fine_shape) & SOLID) != 0
|
||||
g_coarse, g_fine = state(NY, NX, 1), state(*patch.fine_shape, 2)
|
||||
results = []
|
||||
with CudaContext(0) as context:
|
||||
for fine_block in (None, *FINE_BLOCKS):
|
||||
with FixedPatchStepper(cfg, BOUNDS, context=context, coarse_boundary=mode,
|
||||
fine_objects=[circle()], fine_block=fine_block) as backend:
|
||||
backend.initialize(g_coarse, g_fine)
|
||||
backend.step(STEPS)
|
||||
results.append((backend.download(), raw(backend)))
|
||||
(dense_public, dense_raw), blocked = results[0], results[1:]
|
||||
fine = dense_raw[1]
|
||||
self.assertTrue(np.isfinite(fine[:, (patch.fine_kind == ACTIVE) & ~solid]).all(), mode)
|
||||
self.assertTrue(np.isnan(fine[:, solid]).all(), mode)
|
||||
self.assertTrue(np.isnan(fine[:, patch.fine_kind == OUTER_GHOST]).all(), mode)
|
||||
for fine_block, (public, raw_arrays) in zip(FINE_BLOCKS, blocked):
|
||||
msg = f"circle {mode} fine_block={fine_block}"
|
||||
for a, b in zip(public + tuple(raw_arrays), dense_public + tuple(dense_raw)):
|
||||
np.testing.assert_array_equal(a, b, err_msg=msg) # values and NaN masks
|
||||
print(f"circle {mode}: dense vs {len(blocked)} fine-block layouts bit-identical "
|
||||
f"after {STEPS} coarse steps", flush=True)
|
||||
|
||||
def test_actuated_circle_dense_and_blocked_fine_storage_are_bit_identical(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
for speed in (.002, -.002):
|
||||
cfg = config(mode)
|
||||
patch, boundary = fine_circle(mode, actuation(speed))
|
||||
solid = (boundary.flags.reshape(patch.fine_shape) & SOLID) != 0
|
||||
g_coarse, g_fine = state(NY, NX, 1), state(*patch.fine_shape, 2)
|
||||
results = []
|
||||
with CudaContext(0) as context:
|
||||
for fine_block in (None, *FINE_BLOCKS):
|
||||
with FixedPatchStepper(cfg, BOUNDS, context=context, coarse_boundary=mode,
|
||||
fine_objects=[circle(actuation(speed))],
|
||||
fine_block=fine_block) as backend:
|
||||
backend.initialize(g_coarse, g_fine)
|
||||
backend.step(STEPS)
|
||||
results.append((backend.download(), raw(backend)))
|
||||
(dense_public, dense_raw), blocked = results[0], results[1:]
|
||||
fine = dense_raw[1]
|
||||
self.assertTrue(np.isfinite(fine[:, (patch.fine_kind == ACTIVE) & ~solid]).all())
|
||||
self.assertTrue(np.isnan(fine[:, solid]).all())
|
||||
self.assertTrue(np.isnan(fine[:, patch.fine_kind == OUTER_GHOST]).all())
|
||||
for fine_block, (public, raw_arrays) in zip(FINE_BLOCKS, blocked):
|
||||
msg = f"actuated {speed} {mode} fine_block={fine_block}"
|
||||
for a, b in zip(public + tuple(raw_arrays), dense_public + tuple(dense_raw)):
|
||||
np.testing.assert_array_equal(a, b, err_msg=msg) # values and NaN masks
|
||||
print(f"actuated {speed:+.3f} {mode}: dense vs {len(blocked)} fine-block layouts "
|
||||
f"bit-identical after {STEPS} coarse steps", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -106,11 +106,12 @@ class FaultGuardsCPU(unittest.TestCase):
|
||||
|
||||
def fake_backend(self):
|
||||
backend = PeriodicPatchStepper.__new__(PeriodicPatchStepper)
|
||||
backend.fine_layout = None # dense fine storage
|
||||
backend.ctx = Mock(activate=nullcontext)
|
||||
backend._lock = RLock()
|
||||
backend._status = "ready"
|
||||
backend._stream = Mock()
|
||||
backend._levels = [Mock(shape=(9, 1, 1)), Mock(shape=(9, 1, 1))]
|
||||
backend._levels = [Mock(shape=(9, 1, 1), layout=None), Mock(shape=(9, 1, 1), layout=None)]
|
||||
backend._allocations = [Mock(), Mock()]
|
||||
return backend
|
||||
|
||||
|
||||
@@ -194,7 +194,7 @@ class CoupledGPU(unittest.TestCase):
|
||||
f"max_corner_packet={max_corner:.9g}; ownership/counts PASS", flush=True)
|
||||
|
||||
# Fail before any additional time step; no stale synchronized export.
|
||||
with patch.object(backend, "_explode", side_effect=RuntimeError("injected launch failure")):
|
||||
with patch.object(backend._pairs[0], "explode", side_effect=RuntimeError("injected launch failure")):
|
||||
with self.assertRaisesRegex(RuntimeError, "injected"):
|
||||
backend.step()
|
||||
with self.assertRaisesRegex(RuntimeError, "failed"):
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Jets on the FixedPatchStepper fine level: CPU wiring checks plus GPU gates.
|
||||
|
||||
Jets use the same coarse cell-edge frame as fine_objects. The equivalent jet
|
||||
of Astra's actuated fixture is SurfaceActuation(0.7, 0.85, U).as_jet((16, 12),
|
||||
2.15). Frozen GPU gates (8 coarse steps, both coarse boundary modes):
|
||||
G1 jet run: dense vs 1x1/2x2/4x2 fine blocks bit-identical (values + NaN masks);
|
||||
G2 jet vs legacy actuation (dense): max |dG| over finite fine ACTIVE fluid
|
||||
populations <= 1e-6 (velocity rows differ only by FP32 rounding; reported);
|
||||
G3 amplitude change after 4 steps (+U -> -U), 4 more steps: dense vs blocked
|
||||
bit-identical and the run differs from the unchanged run.
|
||||
"""
|
||||
from contextlib import nullcontext
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from CelerisLab.cuda import compiler_v2 as compiler
|
||||
from CelerisLab.lbm.descriptors import SOLID
|
||||
from CelerisLab.lbm.refinement import ACTIVE, FixedPatch2D, prepare_fine_boundary
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
from test_refinement_blocked_fine import (BOUNDS, FINE_BLOCKS, NX, NY, STEPS, actuation,
|
||||
circle, config, fine_circle, raw, state)
|
||||
|
||||
SPEED = .002
|
||||
|
||||
|
||||
def jet(speed=SPEED):
|
||||
return actuation(speed).as_jet((16.0, 12.0), 2.15)
|
||||
|
||||
|
||||
def mocked(objects, jets, fine_block):
|
||||
"""Real constructor with driver doubles; returns backend and the memcpy mock."""
|
||||
context = Mock(activate=nullcontext, sm_arch="sm_70")
|
||||
module = Mock(get_function=Mock(return_value=Mock()))
|
||||
module.get_global.return_value = (Mock(), 20)
|
||||
htod = Mock()
|
||||
with patch.object(cuda, "Stream"), patch.object(compiler, "generate_config"), \
|
||||
patch.object(compiler, "compile_kernel"), patch.object(compiler, "cleanup_build_dir"), \
|
||||
patch.object(compiler, "load_module", return_value=module), \
|
||||
patch.object(cuda, "mem_alloc", side_effect=lambda size: Mock()), \
|
||||
patch.object(cuda, "memcpy_htod", htod):
|
||||
backend = FixedPatchStepper(config("periodic"), BOUNDS, context=context,
|
||||
fine_objects=objects, fine_block=fine_block, jets=jets)
|
||||
return backend, htod
|
||||
|
||||
|
||||
class JetStepperCPU(unittest.TestCase):
|
||||
def test_one_body_across_blocks_accepted(self):
|
||||
# Fine circle (19.5, 15.5) R4.3 crosses the 2x2 block seams; one body, one jet.
|
||||
import math
|
||||
from CelerisLab.body.jets import Jet, Radial, Sector
|
||||
C = (16.0, 12.0)
|
||||
whole = Jet(Sector(C, .1, math.pi, 3.), Radial(C, inward=False), amplitude=0.)
|
||||
backend, _ = mocked([circle()], [whole], FINE_BLOCKS[1])
|
||||
_, jet_id = backend._jet_cache
|
||||
self.assertGreater(len(np.unique(backend._fine_tables["block"][jet_id == 0])), 1)
|
||||
backend.close()
|
||||
|
||||
def test_fine_ownership_uses_remapped_physical_owner(self):
|
||||
# Caller ids (99, 7) are remapped to fine owners (0, 1); block ids never count.
|
||||
import math
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.jets import Jet, Parallel, Radial, Sector, Tube
|
||||
from CelerisLab.body.objects import SimObject
|
||||
C = (16.0, 12.0)
|
||||
source = SimObject(99, geometry=CircleGeometry(*C, 2.15), center=C, radius=2.15)
|
||||
whole = Jet(Sector(C, .1, math.pi, 3.), Radial(C, inward=False), amplitude=0.)
|
||||
backend, _ = mocked([source], [whole], FINE_BLOCKS[1])
|
||||
_, jet_id = backend._jet_cache
|
||||
owners = backend.fine_boundary.curved_host[3][jet_id == 0]
|
||||
self.assertEqual(np.unique(owners).tolist(), [0])
|
||||
self.assertGreater(len(np.unique(backend._fine_tables["block"][jet_id == 0])), 1)
|
||||
self.assertEqual(source.obj_id, 99)
|
||||
backend.close()
|
||||
cfg = config("periodic")
|
||||
patch_ = FixedPatch2D.from_config(cfg, BOUNDS)
|
||||
A, B = (12.5, 12.0), (19.5, 12.0)
|
||||
pair = [SimObject(i, geometry=CircleGeometry(*c, 1.5), center=c, radius=1.5)
|
||||
for i, c in ((99, A), (7, B))]
|
||||
for amplitude in (0., .002):
|
||||
with self.assertRaisesRegex(ValueError, "one jet may drive only one body"):
|
||||
prepare_fine_boundary(cfg, patch_, pair,
|
||||
jets=[Jet(Tube((9., 12.), 0., 14., .5), Parallel(0.),
|
||||
amplitude=amplitude)])
|
||||
self.assertEqual([o.obj_id for o in pair], [99, 7])
|
||||
|
||||
def test_blocked_jet_velocity_matches_legacy_rows(self):
|
||||
legacy, _ = mocked([circle(actuation(SPEED))], (), FINE_BLOCKS[1])
|
||||
driven, _ = mocked([circle()], [jet()], FINE_BLOCKS[1])
|
||||
a = legacy._fine_tables["surface_velocity"]
|
||||
b = driven._fine_tables["surface_velocity"]
|
||||
diff = np.abs(a - b).max()
|
||||
print(f"fine jet vs legacy velocity rows: max |dU| = {diff:.3e} (exact={diff == 0})")
|
||||
self.assertLessEqual(diff, 4 * np.finfo(np.float32).eps * SPEED)
|
||||
legacy.close(), driven.close()
|
||||
|
||||
def test_blocked_amplitude_update_rewrites_only_velocity_column(self):
|
||||
backend, htod = mocked([circle()], [jet()], FINE_BLOCKS[1])
|
||||
before = backend._fine_tables["surface_velocity"].copy()
|
||||
device = backend._link_tables["surface_velocity"]
|
||||
with patch.object(cuda, "memcpy_htod", htod):
|
||||
htod.reset_mock()
|
||||
backend.set_jet_amplitude(0, -SPEED)
|
||||
(ptr, sent), _ = htod.call_args
|
||||
self.assertEqual(htod.call_count, 1)
|
||||
self.assertIs(ptr, device)
|
||||
np.testing.assert_allclose(sent, -before, rtol=1e-6, atol=0)
|
||||
np.testing.assert_array_equal(backend._fine_tables["surface_velocity"], sent)
|
||||
with self.assertRaises(ValueError):
|
||||
backend.set_jet_amplitude(0, 1.5)
|
||||
self.assertEqual(htod.call_count, 1)
|
||||
self.assertEqual(backend._jets[0].amplitude, -SPEED)
|
||||
backend.close()
|
||||
|
||||
def test_copy_failure_marks_failed_and_keeps_host_amplitude(self):
|
||||
for fine_block in (None, FINE_BLOCKS[1]): # dense SoA and blocked tables
|
||||
backend, _ = mocked([circle()], [jet()], fine_block)
|
||||
status = backend._status
|
||||
for bad, error in ((1.5, ValueError), (float("nan"), ValueError)):
|
||||
with self.assertRaises(error):
|
||||
backend.set_jet_amplitude(0, bad)
|
||||
self.assertEqual(backend._status, status) # invalid input stays usable
|
||||
with self.assertRaises(IndexError):
|
||||
backend.set_jet_amplitude(1, -SPEED)
|
||||
self.assertEqual(backend._status, status)
|
||||
dense = backend._fine_curved
|
||||
before = (dense.surface_velocity if dense is not None
|
||||
else backend._fine_tables["surface_velocity"]).copy()
|
||||
boom = Mock(side_effect=RuntimeError("copy failed"))
|
||||
with patch.object(cuda, "memcpy_htod", boom), patch.object(cuda, "memcpy_htod_async", boom), \
|
||||
patch.object(cuda, "pagelocked_empty", side_effect=lambda shape, dtype: np.empty(shape, dtype)):
|
||||
with self.assertRaisesRegex(RuntimeError, "copy failed"):
|
||||
backend.set_jet_amplitude(0, -SPEED)
|
||||
self.assertEqual(backend._status, "failed", fine_block)
|
||||
self.assertEqual(backend._jets[0].amplitude, SPEED)
|
||||
if dense is not None:
|
||||
self.assertEqual(dense.jets[0].amplitude, SPEED)
|
||||
np.testing.assert_array_equal(dense.surface_velocity, before)
|
||||
else:
|
||||
np.testing.assert_array_equal(backend._fine_tables["surface_velocity"], before)
|
||||
with self.assertRaisesRegex(RuntimeError, "failed"):
|
||||
backend.step(1)
|
||||
with self.assertRaisesRegex(RuntimeError, "failed"):
|
||||
backend.set_jet_amplitude(0, -SPEED)
|
||||
backend.close()
|
||||
|
||||
def test_jet_overlapping_legacy_aperture_rejected_before_cuda(self):
|
||||
with patch.object(cuda, "Stream", side_effect=AssertionError("CUDA touched")):
|
||||
with self.assertRaisesRegex(ValueError, "SurfaceActuation"):
|
||||
FixedPatchStepper(config("periodic"), BOUNDS, context=Mock(),
|
||||
fine_objects=[circle(actuation(SPEED))], jets=[jet()])
|
||||
|
||||
|
||||
def run(mode, fine_block, *, objects, jets, switch=None):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
cfg = config(mode)
|
||||
patch_ = FixedPatch2D.from_config(cfg, BOUNDS)
|
||||
with CudaContext(0) as context, FixedPatchStepper(
|
||||
cfg, BOUNDS, context=context, coarse_boundary=mode, fine_objects=objects,
|
||||
fine_block=fine_block, jets=jets) as backend:
|
||||
backend.initialize(state(NY, NX, 1), state(*patch_.fine_shape, 2))
|
||||
if switch is None:
|
||||
backend.step(STEPS)
|
||||
else:
|
||||
backend.step(STEPS // 2)
|
||||
backend.set_jet_amplitude(0, switch)
|
||||
backend.step(STEPS - STEPS // 2)
|
||||
return backend.download(), raw(backend)
|
||||
|
||||
|
||||
class JetStepperGPU(unittest.TestCase):
|
||||
def test_g1_g2_jet_layouts_identical_and_close_to_legacy(self):
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
patch_, boundary = fine_circle(mode)
|
||||
fluid = (patch_.fine_kind == ACTIVE) & (
|
||||
(boundary.flags.reshape(patch_.fine_shape) & SOLID) == 0)
|
||||
dense = run(mode, None, objects=[circle()], jets=[jet()])
|
||||
self.assertTrue(np.isfinite(dense[1][1][:, fluid]).all(), mode)
|
||||
for fine_block in FINE_BLOCKS:
|
||||
public, raw_arrays = run(mode, fine_block, objects=[circle()], jets=[jet()])
|
||||
for a, b in zip(public + tuple(raw_arrays), dense[0] + tuple(dense[1])):
|
||||
np.testing.assert_array_equal(a, b, err_msg=f"G1 {mode} {fine_block}")
|
||||
legacy = run(mode, None, objects=[circle(actuation(SPEED))], jets=())
|
||||
diff = np.abs(dense[1][1][:, fluid] - legacy[1][1][:, fluid]).max()
|
||||
print(f"G2 {mode}: jet vs legacy fine max |dG| = {diff:.3e}", flush=True)
|
||||
self.assertLessEqual(diff, 1e-6, mode)
|
||||
|
||||
def test_g3_amplitude_switch_layouts_identical(self):
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
dense = run(mode, None, objects=[circle()], jets=[jet()], switch=-SPEED)
|
||||
steady = run(mode, None, objects=[circle()], jets=[jet()])
|
||||
self.assertFalse(np.array_equal(dense[1][1], steady[1][1], equal_nan=True), mode)
|
||||
for fine_block in FINE_BLOCKS:
|
||||
public, raw_arrays = run(mode, fine_block, objects=[circle()], jets=[jet()],
|
||||
switch=-SPEED)
|
||||
for a, b in zip(public + tuple(raw_arrays), dense[0] + tuple(dense[1])):
|
||||
np.testing.assert_array_equal(a, b, err_msg=f"G3 {mode} {fine_block}")
|
||||
print(f"G3 {mode}: amplitude switch dense vs {len(FINE_BLOCKS)} layouts identical",
|
||||
flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Opt-in multipatch FixedPatchStepper (FixedPatchSet2D): CPU guards plus GPU gates.
|
||||
|
||||
Run CPU and GPU classes in separate processes. GPU gates (frozen before any run):
|
||||
- one rectangle through the multipatch interface is bit-identical to the old
|
||||
single-patch blocked path (both boundary modes, raw owner masks included);
|
||||
- S1 translation copy: two patches on 16x32 equal the 16x16 one-patch run tiled
|
||||
twice, bit for bit, every step;
|
||||
- reversed rectangle order gives bit-identical results;
|
||||
- face gap-4 pair (16x24): ACTIVE leaves finite, covered/hole masks exact, also on
|
||||
raw owner cores per patch (INNER partly invalid by contract, not asserted).
|
||||
Weighted leaf mass is printed as a diagnostic only.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm.refinement import ACTIVE, OUTER_GHOST, FixedPatch2D, FixedPatchSet2D
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
from test_refinement_blocked_fine import BOUNDS, NX, NY, config, state, circle
|
||||
from test_refinement_blocked_base import exact, raw
|
||||
|
||||
FACE = ((4, 4, 8, 12), (12, 4, 16, 12))
|
||||
S1 = ((4, 4, 12, 12), (20, 4, 28, 12))
|
||||
|
||||
|
||||
def level_fine(patch_set, windows):
|
||||
"""Level-wide fine array with each patch window filled from `windows`."""
|
||||
out = np.full((9, *patch_set.fine_shape), np.nan, np.float32)
|
||||
for p, w in zip(patch_set.patches, windows):
|
||||
y0, x0 = p.fine_level_origin
|
||||
out[:, y0:y0 + p.fine_shape[0], x0:x0 + p.fine_shape[1]] = w
|
||||
return out
|
||||
|
||||
|
||||
def window(patch_set, index, fine):
|
||||
p = patch_set.patches[index]
|
||||
y0, x0 = p.fine_level_origin
|
||||
return fine[:, y0:y0 + p.fine_shape[0], x0:x0 + p.fine_shape[1]]
|
||||
|
||||
|
||||
class MultipatchCPU(unittest.TestCase):
|
||||
def test_rejections_before_cuda(self):
|
||||
cfg = config("periodic")
|
||||
context = object() # never activated: every case must fail first
|
||||
for kw in (dict(), dict(fine_block=(8, 4)), dict(base_block=(4, 4)),
|
||||
dict(fine_block=(8, 4), base_block=(4, 4), fine_objects=[circle()]),
|
||||
dict(fine_block=(5, 4), base_block=(4, 4))):
|
||||
with self.subTest(kw=kw), self.assertRaises(ValueError):
|
||||
FixedPatchStepper(cfg, ((4, 4, 8, 12), (14, 4, 18, 12)), context=context, **kw)
|
||||
with self.assertRaisesRegex(ValueError, "closer"):
|
||||
FixedPatchStepper(cfg, ((4, 4, 8, 12), (10, 4, 14, 12)), context=context,
|
||||
fine_block=(8, 4), base_block=(4, 4))
|
||||
from CelerisLab.body.jets import Jet, Parallel, Tube
|
||||
cfg32 = LBMConfig(nx=32, ny=16, viscosity=.1)
|
||||
span = Jet(Tube((5., 8.), 0., 22., .6), Parallel(0.), amplitude=0.)
|
||||
with self.assertRaisesRegex(ValueError, "one jet"): # same obj_id cannot bypass it
|
||||
FixedPatchStepper(cfg32, ((2, 2, 14, 14), (18, 2, 30, 14)), context=context,
|
||||
fine_block=(4, 4), base_block=(4, 4),
|
||||
fine_objects=[body(8., 8.), body(24., 8.)], jets=[span])
|
||||
|
||||
|
||||
class MultipatchGPU(unittest.TestCase):
|
||||
STEPS = (0, 1, 2, 8)
|
||||
|
||||
def run_steps(self, context, cfg, bounds, coarse, fine, **kw):
|
||||
out = []
|
||||
with FixedPatchStepper(cfg, bounds, context=context, **kw) as backend:
|
||||
backend.initialize(coarse, fine)
|
||||
for step in self.STEPS:
|
||||
backend.step(step - backend.step_count)
|
||||
out.append(backend.download() + raw(backend))
|
||||
return out
|
||||
|
||||
def test_one_rectangle_matches_single_patch_path(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
with CudaContext(0) as context:
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
cfg = config(mode)
|
||||
p = FixedPatch2D.from_config(cfg, BOUNDS)
|
||||
s = FixedPatchSet2D.from_config(cfg, (BOUNDS,))
|
||||
coarse, fine = state(NY, NX, 1), state(*p.fine_shape, 2)
|
||||
kw = dict(coarse_boundary=mode, fine_block=(8, 4), base_block=(3, 4))
|
||||
old = self.run_steps(context, cfg, BOUNDS, coarse, fine, **kw)
|
||||
new = self.run_steps(context, cfg, (BOUNDS,), coarse, level_fine(s, [fine]), **kw)
|
||||
for step, a, b in zip(self.STEPS, old, new):
|
||||
label = f"{mode} step {step}"
|
||||
exact(self, b[0], a[0], label + " coarse")
|
||||
exact(self, window(s, 0, b[1]), a[1], label + " fine")
|
||||
exact(self, b[2], a[2], label + " raw coarse")
|
||||
exact(self, window(s, 0, b[3]), a[3], label + " raw fine")
|
||||
|
||||
def test_s1_translation_copy_and_order(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
cfg16 = LBMConfig(nx=16, ny=16, viscosity=.1)
|
||||
cfg32 = replace(cfg16, nx=32)
|
||||
one = FixedPatchSet2D.from_config(cfg16, (S1[0],))
|
||||
two = FixedPatchSet2D.from_config(cfg32, S1)
|
||||
coarse, fine = state(16, 16, 3), state(*one.patches[0].fine_shape, 4)
|
||||
kw = dict(fine_block=(4, 4), base_block=(4, 4))
|
||||
with CudaContext(0) as context:
|
||||
ref = self.run_steps(context, cfg16, (S1[0],), coarse, level_fine(one, [fine]), **kw)
|
||||
tiled = np.concatenate([coarse, coarse], axis=2)
|
||||
for bounds in (S1, S1[::-1]):
|
||||
got = self.run_steps(context, cfg32, bounds, tiled,
|
||||
level_fine(two, [fine, fine]), **kw)
|
||||
for step, a, b in zip(self.STEPS, ref, got):
|
||||
label = f"order {bounds[0]} step {step}"
|
||||
exact(self, b[0], np.concatenate([a[0], a[0]], axis=2), label + " coarse")
|
||||
for i in (0, 1):
|
||||
exact(self, window(two, i, b[1]), window(one, 0, a[1]), f"{label} fine {i}")
|
||||
|
||||
def test_face_gap4_finite_masks_and_order(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
cfg = LBMConfig(nx=24, ny=16, viscosity=.1)
|
||||
s = FixedPatchSet2D.from_config(cfg, FACE)
|
||||
coarse = state(16, 24, 5)
|
||||
fine = level_fine(s, [state(*p.fine_shape, 6 + i) for i, p in enumerate(s.patches)])
|
||||
kw = dict(fine_block=(4, 4), base_block=(4, 4))
|
||||
leaf = s.fine_kind == ACTIVE
|
||||
support = s.fine_layout((4, 4)).owned
|
||||
outer = support & (s.fine_kind == OUTER_GHOST)
|
||||
holes = ~support
|
||||
with CudaContext(0) as context:
|
||||
runs = [self.run_steps(context, cfg, bounds, coarse, fine, **kw)
|
||||
for bounds in (FACE, FACE[::-1])]
|
||||
for step, a, b in zip(self.STEPS, *runs):
|
||||
for x, y in zip(a, b):
|
||||
exact(self, y, x, f"reversed order step {step}")
|
||||
c, f = a[0], a[1]
|
||||
self.assertTrue(np.isfinite(c[:, ~s.covered]).all())
|
||||
self.assertTrue(np.isnan(c[:, s.covered]).all())
|
||||
self.assertTrue(np.isfinite(f[:, leaf]).all())
|
||||
self.assertTrue(np.isnan(f[:, ~leaf]).all())
|
||||
# Raw owner cores, independent of the download mask (every patch).
|
||||
# INNER may be partly NaN after hop 2 by contract: not asserted.
|
||||
rc, rf = a[2], a[3]
|
||||
label = f"raw step {step}"
|
||||
self.assertTrue(np.isfinite(rc[:, ~s.covered]).all(), label + " coarse leaves")
|
||||
if step: # covered parent cores are poisoned by the parent step
|
||||
self.assertTrue(np.isnan(rc[:, s.covered]).all(), label + " covered")
|
||||
self.assertTrue(np.isfinite(rf[:, leaf]).all(), label + " fine ACTIVE")
|
||||
self.assertTrue(np.isnan(rf[:, outer]).all(), label + " fine OUTER")
|
||||
self.assertTrue(np.isnan(rf[:, holes]).all(), label + " fine holes")
|
||||
for i, p in enumerate(s.patches):
|
||||
active = window(s, i, rf)[:, p.fine_kind == ACTIVE]
|
||||
self.assertTrue(np.isfinite(active).all(), f"{label} patch {i} ACTIVE")
|
||||
mass = float(np.nansum(c, dtype=np.float64) + .25 * np.nansum(f, dtype=np.float64))
|
||||
print(f"face gap4 step {step}: weighted leaf mass {mass:.9g} (diagnostic)", flush=True)
|
||||
|
||||
|
||||
def body(x, y, obj_id=0):
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
return SimObject(obj_id, geometry=CircleGeometry(x, y, 2.15), center=(x, y), radius=2.15)
|
||||
|
||||
|
||||
class MultipatchBodiesGPU(unittest.TestCase):
|
||||
"""fine_objects/jets on several patches (frozen gates, bitwise)."""
|
||||
PATCHES = ((2, 2, 14, 14), (18, 2, 30, 14))
|
||||
STEPS = (0, 1, 2, 8)
|
||||
|
||||
def run_steps(self, context, cfg, bounds, coarse, fine, switch=None, **kw):
|
||||
out = []
|
||||
with FixedPatchStepper(cfg, bounds, context=context, **kw) as backend:
|
||||
backend.initialize(coarse, fine)
|
||||
for step in self.STEPS:
|
||||
if switch is not None and step == 8:
|
||||
for index, amplitude in switch:
|
||||
backend.set_jet_amplitude(index, amplitude)
|
||||
backend.step(step - backend.step_count)
|
||||
out.append(backend.download() + raw(backend))
|
||||
return out
|
||||
|
||||
def test_one_body_matches_single_patch_path(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
with CudaContext(0) as context:
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
cfg = config(mode)
|
||||
p = FixedPatch2D.from_config(cfg, BOUNDS)
|
||||
s = FixedPatchSet2D.from_config(cfg, (BOUNDS,))
|
||||
coarse, fine = state(NY, NX, 1), state(*p.fine_shape, 2)
|
||||
kw = dict(coarse_boundary=mode, fine_block=(8, 4), base_block=(3, 4),
|
||||
fine_objects=[circle()])
|
||||
old = self.run_steps(context, cfg, BOUNDS, coarse, fine, **kw)
|
||||
new = self.run_steps(context, cfg, (BOUNDS,), coarse, level_fine(s, [fine]), **kw)
|
||||
for step, a, b in zip(self.STEPS, old, new):
|
||||
label = f"{mode} step {step}"
|
||||
exact(self, b[0], a[0], label + " coarse")
|
||||
exact(self, window(s, 0, b[1]), a[1], label + " fine")
|
||||
exact(self, window(s, 0, b[3]), a[3], label + " raw fine")
|
||||
|
||||
def test_two_bodies_and_jets_equal_tiled_single(self):
|
||||
"""Translation copy across a block seam, with jets and an amplitude switch."""
|
||||
from CelerisLab.body.jets import Jet, Parallel, Tube
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
cfg16 = LBMConfig(nx=16, ny=16, viscosity=.1)
|
||||
cfg32 = replace(cfg16, nx=32)
|
||||
one = FixedPatchSet2D.from_config(cfg16, self.PATCHES[:1])
|
||||
two = FixedPatchSet2D.from_config(cfg32, self.PATCHES)
|
||||
coarse, fine = state(16, 16, 3), state(*one.patches[0].fine_shape, 4)
|
||||
jet = lambda x: Jet(Tube((x, 8.), 0., 6., .6), Parallel(0.), amplitude=.002)
|
||||
kw = dict(fine_block=(4, 4), base_block=(4, 4))
|
||||
with CudaContext(0) as context:
|
||||
for jets in ((), (jet(5.),)):
|
||||
ref = self.run_steps(context, cfg16, self.PATCHES[:1], coarse, level_fine(one, [fine]),
|
||||
switch=[(0, -.001)] if jets else None,
|
||||
fine_objects=[body(8., 8.)], jets=jets, **kw)
|
||||
both = jets and (jet(5.), jet(21.))
|
||||
got = self.run_steps(context, cfg32, self.PATCHES, np.concatenate([coarse, coarse], 2),
|
||||
level_fine(two, [fine, fine]),
|
||||
switch=[(0, -.001), (1, -.001)] if jets else None,
|
||||
fine_objects=[body(8., 8., 5), body(24., 8., 5)],
|
||||
jets=both or (), **kw)
|
||||
for step, a, b in zip(self.STEPS, ref, got):
|
||||
label = f"jets={len(jets)} step {step}"
|
||||
exact(self, b[0], np.concatenate([a[0], a[0]], axis=2), label + " coarse")
|
||||
for i in (0, 1):
|
||||
exact(self, window(two, i, b[1]), window(one, 0, a[1]), f"{label} fine {i}")
|
||||
exact(self, window(two, i, b[3]), window(one, 0, a[3]), f"{label} raw fine {i}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Nested three-level FixedPatchStepper (child=..., single chain): CPU guards and GPU gates.
|
||||
|
||||
Fixture = reviewed CPU probe: L0 16x16 periodic, L1 (4,4,12,12) -> 24x24 window,
|
||||
L2 (8,8,16,16) in L1 window cells -> 24x24 window; 4x4 blocks on every level.
|
||||
Run CPU and GPU classes in separate processes. GPU gates (frozen before any run):
|
||||
- uniform moving equilibrium stays on all three levels' ACTIVE leaves, |dG| <= 1e-6;
|
||||
- seeded non-equilibrium: every level's ACTIVE leaves finite, raw owner cores NaN on
|
||||
OUTER/covered (INNER partly invalid by contract, not asserted);
|
||||
- each L1 hop feeds L2 from the L1 buffer it is about to step (current, then the new
|
||||
G written by the first hop), never from L0: 2 child advances per coarse step.
|
||||
Numerical comparison against the CPU probe (G vs C(f)) is done by the acceptance run.
|
||||
"""
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import replace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm.equilibrium import compute_feq_d2q9
|
||||
from CelerisLab.lbm.refinement import ACTIVE, OUTER_GHOST
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
from test_refinement_blocked_fine import state, circle
|
||||
from test_refinement_blocked_base import raw
|
||||
|
||||
CFG = LBMConfig(nx=16, ny=16, viscosity=.1)
|
||||
L1, L2 = (4, 4, 12, 12), (8, 8, 16, 16)
|
||||
KW = dict(fine_block=(4, 4), base_block=(4, 4), child=L2, child_block=(4, 4))
|
||||
|
||||
|
||||
def child_body(spec=None):
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
return SimObject(99, geometry=CircleGeometry(8., 8., .8), center=(8., 8.), radius=.8,
|
||||
surface_actuation=spec)
|
||||
|
||||
|
||||
def child_jet(speed=.002):
|
||||
from CelerisLab.body.jets import Jet, Tube, Parallel
|
||||
return Jet(Tube((6.5, 8.), 0., 3., .3), Parallel(0.), amplitude=speed)
|
||||
|
||||
|
||||
def mocked_child():
|
||||
from CelerisLab.cuda import compiler_v2 as compiler
|
||||
context = Mock(activate=nullcontext, sm_arch="sm_70")
|
||||
module = Mock(get_function=Mock(side_effect=lambda name: Mock(name=name)))
|
||||
module.get_global.return_value = (Mock(), 20)
|
||||
with patch.object(cuda, "Stream"), patch.object(compiler, "generate_config"), \
|
||||
patch.object(compiler, "compile_kernel"), patch.object(compiler, "cleanup_build_dir"), \
|
||||
patch.object(compiler, "load_module", return_value=module), \
|
||||
patch.object(cuda, "mem_alloc", side_effect=lambda size: Mock()), \
|
||||
patch.object(cuda, "memcpy_htod"):
|
||||
return FixedPatchStepper(CFG, L1, context=context, child_objects=[child_body()],
|
||||
child_jets=[child_jet()], **KW)
|
||||
|
||||
|
||||
class ThreeLevelCPU(unittest.TestCase):
|
||||
def test_rejections_before_cuda(self):
|
||||
context = object() # never activated: every case must fail first
|
||||
bad = (dict(KW, child_block=None), dict(KW, fine_block=None),
|
||||
dict(KW, fine_objects=[circle()]), dict(KW, child=(4, 8, 16, 16)),
|
||||
dict(KW, child_block=(5, 4)))
|
||||
for kw in bad:
|
||||
with self.subTest(kw=kw), self.assertRaises(ValueError):
|
||||
FixedPatchStepper(CFG, L1, context=context, **kw)
|
||||
for kw in (dict(child_objects=[child_body()]), dict(child_jets=[child_jet()]),
|
||||
dict(KW, child_jets=[child_jet()])):
|
||||
with self.assertRaises(ValueError):
|
||||
FixedPatchStepper(CFG, L1, context=context, **kw)
|
||||
with self.assertRaises(ValueError): # several L1 patches + child: not yet
|
||||
FixedPatchStepper(LBMConfig(nx=32, ny=16, viscosity=.1), ((4, 4, 12, 12), (20, 4, 28, 12)),
|
||||
context=context, **KW)
|
||||
|
||||
|
||||
def test_four_halo_bfl_steps_and_fresh_middle_feeds(self):
|
||||
run = mocked_child()
|
||||
run._status = "ready"
|
||||
f, g = run._levels[1:]
|
||||
b = g.boundary
|
||||
events, feeds = [], []
|
||||
advance, gather = run._advance_child, run._gather_halo
|
||||
def record_feed(buffer, **kw):
|
||||
self.assertIs(buffer, (f.current, f.spare)[len(feeds)])
|
||||
feeds.append(buffer)
|
||||
advance(buffer, **kw)
|
||||
def record_halo(level, buffer, **kw):
|
||||
if level is g:
|
||||
events.append(("halo", buffer))
|
||||
gather(level, buffer, **kw)
|
||||
b.kernel.side_effect = lambda buffer, *a, **k: events.append(("bfl", buffer))
|
||||
def record_step(src, dst, halo, flags, kind, **kw):
|
||||
self.assertIs(flags, b.flags)
|
||||
self.assertIs(kind, g.kind)
|
||||
events.append(("step", src))
|
||||
g.kernel.side_effect = record_step
|
||||
with patch.object(run, "_advance_child", side_effect=record_feed), \
|
||||
patch.object(run, "_gather_halo", side_effect=record_halo):
|
||||
run.step()
|
||||
self.assertEqual(feeds, [f.current, f.spare])
|
||||
expected = [(kind, buffer) for buffer in (g.current, g.spare, g.current, g.spare)
|
||||
for kind in ("halo", "bfl", "step")]
|
||||
self.assertEqual(events, expected)
|
||||
self.assertGreater(len(np.unique(b.tables["block"])), 1)
|
||||
# Negative control: reusing L1's old source at the midpoint must fail.
|
||||
feeds.clear()
|
||||
with patch.object(run, "_advance_child", side_effect=lambda buffer, **kw:
|
||||
record_feed(f.current, **kw)):
|
||||
with self.assertRaises(AssertionError):
|
||||
run.step()
|
||||
run.close()
|
||||
|
||||
def test_child_update_isolated_and_failure_atomic(self):
|
||||
run = mocked_child()
|
||||
b = run._levels[2].boundary
|
||||
before = b.tables["surface_velocity"].copy()
|
||||
with self.assertRaises(IndexError):
|
||||
run.set_jet_amplitude(0, -.002) # default stays L1
|
||||
for level in (0, 3, True):
|
||||
with self.assertRaises(ValueError):
|
||||
run.set_jet_amplitude(0, -.002, level=level)
|
||||
with patch.object(cuda, "memcpy_htod") as upload:
|
||||
run.set_jet_amplitude(0, -.002, level=2)
|
||||
self.assertEqual(upload.call_count, 1)
|
||||
self.assertIs(upload.call_args.args[0], b.device["surface_velocity"])
|
||||
np.testing.assert_array_equal(b.tables["surface_velocity"], -before)
|
||||
self.assertEqual(run._jets, ())
|
||||
with patch.object(cuda, "memcpy_htod", side_effect=RuntimeError("copy failed")):
|
||||
with self.assertRaisesRegex(RuntimeError, "copy failed"):
|
||||
run.set_jet_amplitude(0, .002, level=2)
|
||||
self.assertEqual(run._status, "failed")
|
||||
self.assertEqual(b.jets[0].amplitude, -.002)
|
||||
np.testing.assert_array_equal(b.tables["surface_velocity"], -before)
|
||||
run.close()
|
||||
|
||||
def test_child_public_masks_include_solids(self):
|
||||
from CelerisLab.lbm.descriptors import SOLID
|
||||
run = mocked_child()
|
||||
solid = run.child_boundary.flags.reshape(run.child_patch.fine_shape) & SOLID != 0
|
||||
self.assertTrue(solid.any())
|
||||
self.assertFalse(run._child_leaf[solid].any())
|
||||
arrays = [np.ones(level.shape, np.float32) for level in run._levels]
|
||||
run._mask_nonleaves(*arrays)
|
||||
self.assertTrue(np.isnan(arrays[2][:, solid]).all())
|
||||
with patch.object(cuda, "memcpy_htod") as upload:
|
||||
run.initialize(*arrays)
|
||||
sent = upload.call_args_list[-1].args[1]
|
||||
dense = run.child_layout.to_dense(sent)
|
||||
self.assertTrue(np.isnan(dense[:, ~run._child_leaf]).all())
|
||||
run.close()
|
||||
|
||||
|
||||
class ThreeLevelGPU(unittest.TestCase):
|
||||
def test_equilibrium_is_kept_on_every_level(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
feq = np.asarray(compute_feq_d2q9(1.0, .03, -.02), np.float32)[:, None, None]
|
||||
with CudaContext(0) as ctx, FixedPatchStepper(CFG, L1, context=ctx, **KW) as run:
|
||||
shapes = ((16, 16), run.patch.fine_shape, run.child_patch.fine_shape)
|
||||
run.initialize(*(np.broadcast_to(feq, (9, *s)).copy() for s in shapes))
|
||||
run.step(8)
|
||||
self.assertEqual(run.step_count, 8)
|
||||
for level, g in enumerate(run.download()):
|
||||
leaf = np.isfinite(g[0])
|
||||
self.assertTrue(leaf.any(), f"level {level}")
|
||||
np.testing.assert_allclose(g[:, leaf], np.broadcast_to(feq, g.shape)[:, leaf],
|
||||
atol=1e-6, rtol=0, err_msg=f"level {level}")
|
||||
|
||||
def test_nonequilibrium_masks_and_fresh_middle_feeds(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
with CudaContext(0) as ctx, FixedPatchStepper(CFG, L1, context=ctx, **KW) as run:
|
||||
p1, p2 = run.patch, run.child_patch
|
||||
run.initialize(state(16, 16, 1), state(*p1.fine_shape, 2), state(*p2.fine_shape, 3))
|
||||
f = run._levels[1]
|
||||
feeds, original = [], run._advance_child
|
||||
def record(buffer, **kw):
|
||||
feeds.append(int(buffer))
|
||||
original(buffer, **kw)
|
||||
with patch.object(run, "_advance_child", side_effect=record):
|
||||
cur, spare = int(f.current), int(f.spare)
|
||||
run.step(1)
|
||||
self.assertEqual(feeds, [cur, spare]) # current G, then the new G of hop 1
|
||||
run.step(7)
|
||||
middle = run._middle_kind
|
||||
for g, leaf in zip(run.download(), (~p1.covered, middle == ACTIVE, p2.fine_kind == ACTIVE)):
|
||||
self.assertTrue(np.isfinite(g[:, leaf]).all())
|
||||
self.assertTrue(np.isnan(g[:, ~leaf]).all())
|
||||
rc, rf, rg = raw(run)
|
||||
self.assertTrue(np.isnan(rc[:, p1.covered]).all())
|
||||
self.assertTrue(np.isfinite(rf[:, middle == ACTIVE]).all())
|
||||
self.assertTrue(np.isnan(rf[:, middle == OUTER_GHOST]).all()) # incl. child-covered
|
||||
self.assertTrue(np.isnan(rf[:, p2.covered]).all())
|
||||
self.assertTrue(np.isfinite(rg[:, p2.fine_kind == ACTIVE]).all())
|
||||
self.assertTrue(np.isnan(rg[:, p2.fine_kind == OUTER_GHOST]).all())
|
||||
|
||||
|
||||
class ThreeLevelBodyGPU(unittest.TestCase):
|
||||
"""Frozen gates; CPU mocks do not establish these numerical results."""
|
||||
def run_case(self, mode, block, *, jets=(), spec=None, switch=False):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
from CelerisLab.lbm.descriptors import SOLID
|
||||
cfg = CFG if mode == "periodic" else replace(
|
||||
CFG, velocity=0., wall_normal_velocity=.001, wall_slot_width=4,
|
||||
y_wall_bc="on_site_velocity", top_wall_bc="reservoir")
|
||||
with CudaContext(0) as ctx, FixedPatchStepper(
|
||||
cfg, L1, context=ctx, coarse_boundary=mode, child_objects=[child_body(spec)],
|
||||
child_jets=jets, **dict(KW, child_block=block)) as run:
|
||||
run.initialize(*(state(*level.shape[1:], i + 1) for i, level in enumerate(run._levels)))
|
||||
snapshots = []
|
||||
for stop in (0, 1, 2, 4, 8):
|
||||
run.step(stop - run.step_count)
|
||||
if stop == 4 and switch:
|
||||
run.set_jet_amplitude(0, -.002, level=2)
|
||||
public, stored = run.download(), raw(run)
|
||||
leaves = [~run.patch.covered, run._fine_leaf, run._child_leaf]
|
||||
if mode != "periodic":
|
||||
leaves[0][[0, -1]] = False
|
||||
for g, mask in zip(public, leaves):
|
||||
self.assertTrue(np.isfinite(g[:, mask]).all())
|
||||
self.assertTrue(np.isnan(g[:, ~mask]).all())
|
||||
invalid = [run.patch.covered.copy(), run._middle_kind == OUTER_GHOST,
|
||||
(run.child_patch.fine_kind == OUTER_GHOST) |
|
||||
((run.child_boundary.flags.reshape(run.child_patch.fine_shape) & SOLID) != 0)]
|
||||
if mode != "periodic":
|
||||
invalid[0][[0, -1]] = True
|
||||
for g, mask in zip(stored, invalid):
|
||||
self.assertTrue(np.isnan(g[:, mask]).all())
|
||||
snapshots.append(public + tuple(stored))
|
||||
return snapshots
|
||||
|
||||
def test_layouts_static_driven_switched_and_zero(self):
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
cases = [self.run_case(mode, (4, 4), jets=jets, switch=switch)
|
||||
for jets, switch in (((), False), ([child_jet()], False),
|
||||
([child_jet()], True), ([child_jet(0.)], False))]
|
||||
for a, b in zip(cases[0], cases[3]):
|
||||
for x, y in zip(a, b):
|
||||
np.testing.assert_array_equal(x, y)
|
||||
self.assertFalse(np.array_equal(cases[1][-1][2], cases[2][-1][2], equal_nan=True))
|
||||
for block in ((8, 4), (4, 8)):
|
||||
for expected, (jets, switch) in zip(cases, (((), False), ([child_jet()], False),
|
||||
([child_jet()], True), ([child_jet(0.)], False))):
|
||||
actual = self.run_case(mode, block, jets=jets, switch=switch)
|
||||
for a, b in zip(actual, expected):
|
||||
for x, y in zip(a, b):
|
||||
np.testing.assert_array_equal(x, y)
|
||||
|
||||
def test_legacy_surface_equivalence(self):
|
||||
from CelerisLab.body.objects import SurfaceActuation
|
||||
spec = SurfaceActuation(.7, .85, .002)
|
||||
for mode in ("periodic", "slot_reservoir"):
|
||||
legacy = self.run_case(mode, (4, 4), spec=spec)[-1][2]
|
||||
driven = self.run_case(mode, (4, 4), jets=[spec.as_jet((8., 8.), .8)])[-1][2]
|
||||
mask = np.isfinite(legacy)
|
||||
np.testing.assert_array_equal(mask, np.isfinite(driven))
|
||||
self.assertLessEqual(np.max(np.abs(legacy[mask] - driven[mask])), 1e-6)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Frozen GPU gates for the bounded three-level separated-union backend.
|
||||
|
||||
Run explicitly on an available GPU; CPU geometry/mocks live in tests/unit.
|
||||
Snapshots 0/1/2/8: finite public leaves, exact NaN masks, raw invalid cores;
|
||||
reversed order and aligned layout changes must be bit-identical. The scalar
|
||||
window comparison uses root physical coordinates, never equal array indices.
|
||||
These equivalence checks supplement, not replace, independent dense CPU replay.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from CelerisLab.config import LBMConfig
|
||||
from CelerisLab.lbm.descriptors import SOLID
|
||||
from CelerisLab.lbm.equilibrium import compute_feq_d2q9
|
||||
from CelerisLab.lbm.refinement import OUTER_GHOST
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
from test_refinement_blocked_base import raw, exact
|
||||
|
||||
CFG = LBMConfig(nx=48, ny=32, viscosity=.1)
|
||||
PARENTS = ((4, 4, 20, 28), (24, 4, 44, 28))
|
||||
CHILDREN = ((16, 16, 32, 40), (56, 16, 80, 40))
|
||||
TOPOLOGIES = {
|
||||
'twins': ((16, 16, 32, 40), (56, 16, 72, 40)),
|
||||
'asymmetric': (CHILDREN[0],),
|
||||
'multiple_children': ((16, 16, 32, 24), (16, 28, 32, 40)),
|
||||
}
|
||||
# 8-wide blocks require support edges divisible by 8, i.e. rectangle edges
|
||||
# equal 2 modulo 4 in each pair's parent frame. The default fixture is 4-only.
|
||||
ALIGNED_CFG = LBMConfig(nx=56, ny=40, viscosity=.1)
|
||||
ALIGNED_PARENTS = ((6, 6, 22, 34), (26, 6, 50, 34))
|
||||
ALIGNED_CHILDREN = ((18, 18, 34, 50), (58, 18, 90, 50))
|
||||
STOPS = (0, 1, 2, 8)
|
||||
|
||||
|
||||
def config(cfg, mode):
|
||||
return cfg if mode == 'periodic' else replace(
|
||||
cfg, velocity=0., wall_normal_velocity=.001, wall_slot_width=4,
|
||||
y_wall_bc='on_site_velocity', top_wall_bc='reservoir')
|
||||
|
||||
|
||||
def bodies():
|
||||
from CelerisLab.body.geometry.circle import CircleGeometry
|
||||
from CelerisLab.body.objects import SimObject
|
||||
return [SimObject(99, geometry=CircleGeometry(x, 14., .8), center=(x, 14.), radius=.8)
|
||||
for x in (12., 34.)]
|
||||
|
||||
|
||||
def jets(speed):
|
||||
from CelerisLab.body.jets import Jet, Tube, Parallel
|
||||
return [Jet(Tube((x-1.5, 14.), 0., 3., .3), Parallel(0.), amplitude=speed)
|
||||
for x in (12., 34.)]
|
||||
|
||||
|
||||
def frames(run):
|
||||
middle_origin = np.asarray(run.patch.fine_origin)
|
||||
return ((np.zeros(2), 1.), (middle_origin, .5),
|
||||
(middle_origin + .5*np.asarray(run.child_patch.fine_origin), .25))
|
||||
|
||||
|
||||
def physical_state(shape, origin, spacing):
|
||||
"""Same smooth non-equilibrium G at the same physical cell centers."""
|
||||
y, x = np.indices(shape, dtype=np.float64)
|
||||
x, y = origin[0] + spacing*(x+.5), origin[1] + spacing*(y+.5)
|
||||
equilibrium = np.asarray(compute_feq_d2q9(1., .013, -.007), np.float64)[:, None, None]
|
||||
q = np.arange(9)[:, None, None]
|
||||
return (equilibrium + 1e-4*np.sin(.17*x + .23*y + q)).astype(np.float32)
|
||||
|
||||
|
||||
def physical_leaves(array, origin, spacing):
|
||||
y, x = np.nonzero(np.isfinite(array[0]))
|
||||
coordinates = np.stack((origin[1]+spacing*(y+.5), origin[0]+spacing*(x+.5)), axis=-1)
|
||||
return coordinates, array[:, y, x]
|
||||
|
||||
|
||||
class ThreeLevelMultipatchGPU(unittest.TestCase):
|
||||
def run_case(self, ctx, cfg=CFG, parents=PARENTS, children=CHILDREN,
|
||||
mode='periodic', blocks=((4, 4), (4, 4)), objects=(), drive=(), switch=False,
|
||||
scalar_child=None):
|
||||
kwargs = dict(child_rectangles_in_parent=children) if scalar_child is None else dict(child=scalar_child)
|
||||
with FixedPatchStepper(config(cfg, mode), parents, context=ctx, coarse_boundary=mode,
|
||||
base_block=(4, 4), fine_block=blocks[0], child_block=blocks[1],
|
||||
child_objects=objects, child_jets=drive, **kwargs) as run:
|
||||
frame = frames(run)
|
||||
run.initialize(*(physical_state(level.shape[1:], *f)
|
||||
for level, f in zip(run._levels, frame)))
|
||||
snapshots = []
|
||||
for stop in STOPS:
|
||||
run.step(stop-run.step_count)
|
||||
if switch and stop == 2:
|
||||
for index in range(len(drive)):
|
||||
run.set_jet_amplitude(index, -.002, level=2)
|
||||
public, stored = run.download(), raw(run)
|
||||
masks = [~run.patch.covered, run._fine_leaf, run._child_leaf]
|
||||
if mode != 'periodic':
|
||||
masks[0][[0, -1]] = False
|
||||
invalid = [run.patch.covered.copy(), run._middle_kind == OUTER_GHOST,
|
||||
run.child_patch.fine_kind == OUTER_GHOST]
|
||||
if mode != 'periodic':
|
||||
invalid[0][[0, -1]] = True
|
||||
if run.child_boundary is not None:
|
||||
invalid[2] |= (run.child_boundary.flags.reshape(run.child_patch.fine_shape) & SOLID) != 0
|
||||
for level, (g, mask, dense, bad) in enumerate(zip(public, masks, stored, invalid)):
|
||||
label = f'{mode} stop={stop} level={level}'
|
||||
self.assertTrue(np.isfinite(g[:, mask]).all(), label)
|
||||
self.assertTrue(np.isnan(g[:, ~mask]).all(), label)
|
||||
self.assertTrue(np.isnan(dense[:, bad]).all(), label)
|
||||
snapshots.append((public, stored, frame))
|
||||
return snapshots
|
||||
|
||||
def compare(self, actual, expected):
|
||||
for stop, a, b in zip(STOPS, actual, expected):
|
||||
for kind in (0, 1):
|
||||
for level, (x, y) in enumerate(zip(a[kind], b[kind])):
|
||||
exact(self, x, y, f'stop={stop} kind={kind} level={level}')
|
||||
|
||||
def test_topologies_reversed_order_and_masks(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
with CudaContext(0) as ctx:
|
||||
for mode in ('periodic', 'slot_reservoir'):
|
||||
for name, children in TOPOLOGIES.items():
|
||||
with self.subTest(mode=mode, topology=name):
|
||||
expected = self.run_case(ctx, children=children, mode=mode)
|
||||
actual = self.run_case(ctx, parents=PARENTS[::-1], children=children[::-1], mode=mode)
|
||||
self.compare(actual, expected)
|
||||
|
||||
def test_independently_varied_aligned_layouts(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
with CudaContext(0) as ctx:
|
||||
for mode in ('periodic', 'slot_reservoir'):
|
||||
kwargs = dict(cfg=ALIGNED_CFG, parents=ALIGNED_PARENTS,
|
||||
children=ALIGNED_CHILDREN, mode=mode)
|
||||
expected = self.run_case(ctx, **kwargs)
|
||||
for middle in ((4, 4), (8, 4), (4, 8)):
|
||||
for leaf in ((4, 4), (8, 4), (4, 8)):
|
||||
self.compare(self.run_case(ctx, blocks=(middle, leaf), **kwargs), expected)
|
||||
|
||||
def test_one_element_equivalent_physical_frames(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
cfg = LBMConfig(nx=16, ny=16, viscosity=.1)
|
||||
parent = (4, 4, 12, 12)
|
||||
with CudaContext(0) as ctx:
|
||||
for mode in ('periodic', 'slot_reservoir'):
|
||||
old = self.run_case(ctx, cfg=cfg, parents=parent, mode=mode, scalar_child=(8, 8, 16, 16))
|
||||
# Test both set-on-scalar and set-on-set allocated frames.
|
||||
for parents, child in ((parent, (8, 8, 16, 16)), ((parent,), (12, 12, 20, 20))):
|
||||
new = self.run_case(ctx, cfg=cfg, parents=parents, children=[child], mode=mode)
|
||||
for a, b in zip(new, old):
|
||||
for level in range(3):
|
||||
ax, av = physical_leaves(a[0][level], *a[2][level])
|
||||
bx, bv = physical_leaves(b[0][level], *b[2][level])
|
||||
np.testing.assert_array_equal(ax, bx)
|
||||
exact(self, av, bv, f'physical level={level}')
|
||||
|
||||
def test_two_l2_bodies_zero_driven_switched_order_and_layout(self):
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
with CudaContext(0) as ctx:
|
||||
for mode in ('periodic', 'slot_reservoir'):
|
||||
kwargs = dict(cfg=ALIGNED_CFG, parents=ALIGNED_PARENTS,
|
||||
children=ALIGNED_CHILDREN, mode=mode, objects=bodies())
|
||||
static = self.run_case(ctx, **kwargs)
|
||||
zero = self.run_case(ctx, drive=jets(0.), **kwargs)
|
||||
self.compare(zero, static)
|
||||
driven = self.run_case(ctx, drive=jets(.002), **kwargs)
|
||||
switched = self.run_case(ctx, drive=jets(.002), switch=True, **kwargs)
|
||||
self.assertFalse(np.array_equal(driven[-1][0][2], static[-1][0][2], equal_nan=True))
|
||||
self.assertFalse(np.array_equal(driven[-1][0][2], switched[-1][0][2], equal_nan=True))
|
||||
for drive, switch, expected in (((), False, static), (jets(0.), False, zero),
|
||||
(jets(.002), False, driven), (jets(.002), True, switched)):
|
||||
for middle, leaf in (((8, 4), (4, 8)), ((4, 8), (8, 4))):
|
||||
actual = self.run_case(ctx, blocks=(middle, leaf), drive=drive, switch=switch,
|
||||
**dict(kwargs, parents=ALIGNED_PARENTS[::-1], children=ALIGNED_CHILDREN[::-1]))
|
||||
self.compare(actual, expected)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Manual L2 continuation gates; run explicitly on an approved idle GPU.
|
||||
|
||||
Frozen numerical gate: max |G - independent FP64 replay| <= 3e-6 on all
|
||||
ACTIVE leaves, with exact masks and exact same-level overlap at remap. The
|
||||
separate independent capture/replay acceptance harness supplies that numerical
|
||||
comparison; these tests cover lifecycle, exact transfer and GPU continuation.
|
||||
Remap mass/momentum must agree to FP32 roundoff, not per-q conservation during
|
||||
advancement (collision changes individual populations). No GPU run is implied.
|
||||
"""
|
||||
from contextlib import ExitStack
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
import pycuda.driver as cuda
|
||||
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
from CelerisLab.lbm.equilibrium import compute_feq_d2q9
|
||||
from CelerisLab.lbm.refinement_stepper import FixedPatchStepper
|
||||
from CelerisLab.lbm.synchronized_remap import RemapTopology, remap_synchronized
|
||||
from test_refinement_blocked_base import exact
|
||||
from test_refinement_three_level_multipatch_gpu import CFG, PARENTS, frames, physical_state
|
||||
|
||||
A = ((16, 16, 32, 40),)
|
||||
B = ((20, 16, 36, 40),)
|
||||
FP64_ATOL = 3e-6
|
||||
|
||||
|
||||
def make(ctx):
|
||||
return FixedPatchStepper(CFG, PARENTS, context=ctx, base_block=(4, 4),
|
||||
fine_block=(4, 4), child_block=(4, 4),
|
||||
child_rectangles_in_parent=A)
|
||||
|
||||
|
||||
def initial(run, uniform):
|
||||
equilibrium = np.asarray(compute_feq_d2q9(1., .013, -.007), np.float32)[:, None, None]
|
||||
return tuple(np.broadcast_to(equilibrium, level.shape).copy() if uniform else
|
||||
physical_state(level.shape[1:], *frame)
|
||||
for level, frame in zip(run._levels, frames(run)))
|
||||
|
||||
|
||||
class RuntimeChildRemapGPU(unittest.TestCase):
|
||||
def check_public(self, run):
|
||||
for array, leaf in zip(run.download(), (~run.patch.covered, run._fine_leaf, run._child_leaf)):
|
||||
self.assertTrue(np.isfinite(array[:, leaf]).all())
|
||||
self.assertTrue(np.isnan(array[:, ~leaf]).all())
|
||||
|
||||
def check_reset(self, run, expected):
|
||||
for level, want in zip(run._levels, expected):
|
||||
blocked = level.layout.to_blocked(want)
|
||||
for pointer in (level.current, level.spare):
|
||||
actual = np.empty(level.layout.blocked_shape, np.float32)
|
||||
cuda.memcpy_dtoh(actual, pointer)
|
||||
exact(self, actual, blocked, 'fresh current and spare, including halos')
|
||||
|
||||
def test_identity_next_step_bitwise_and_old_still_usable(self):
|
||||
with CudaContext(0) as ctx, ExitStack() as owned:
|
||||
old = owned.enter_context(make(ctx))
|
||||
old.initialize(*initial(old, False))
|
||||
old.step(2)
|
||||
before = old.download()
|
||||
new = owned.enter_context(old.remap_child(A))
|
||||
self.assertEqual((old.step_count, new.step_count), (2, 2))
|
||||
self.check_reset(new, before)
|
||||
for got, want in zip(old.download(), before): exact(self, got, want, 'old unchanged')
|
||||
old.step(); new.step()
|
||||
self.assertEqual((old.step_count, new.step_count), (3, 3))
|
||||
for got, want in zip(new.download(), old.download()):
|
||||
exact(self, got, want, 'identity next step')
|
||||
self.check_public(new)
|
||||
|
||||
def test_shift_then_return_uniform_and_nonequilibrium(self):
|
||||
for uniform in (True, False):
|
||||
with self.subTest(uniform=uniform), CudaContext(0) as ctx, ExitStack() as owned:
|
||||
current = owned.enter_context(make(ctx))
|
||||
current.initialize(*initial(current, uniform))
|
||||
current.step(2)
|
||||
for rectangles in (B, A):
|
||||
before, count = current.download(), current.step_count
|
||||
old_mesh = RemapTopology.from_config(CFG, current.patch, current.child_patch.bounds)
|
||||
new_mesh = RemapTopology.from_config(CFG, current.patch, rectangles)
|
||||
expected = remap_synchronized(old_mesh, new_mesh, before, base_count=count,
|
||||
level_steps=(count, 2*count, 4*count), phase='postcollision_g').g
|
||||
previous = current
|
||||
current = owned.enter_context(previous.remap_child(rectangles))
|
||||
self.assertEqual(current.step_count, count)
|
||||
self.check_reset(current, expected)
|
||||
for got, want, old_g, old_leaf, new_leaf in zip(
|
||||
current.download(), expected, before, old_mesh.leaf_masks, new_mesh.leaf_masks):
|
||||
exact(self, got, want, 'CPU remap exact')
|
||||
overlap = old_leaf & new_leaf
|
||||
exact(self, got[:, overlap], old_g[:, overlap], 'same-level overlap')
|
||||
for got, want in zip(previous.download(), before):
|
||||
exact(self, got, want, 'source unchanged')
|
||||
current.step(2)
|
||||
self.assertEqual(current.step_count, count+2)
|
||||
self.assertEqual(previous.step_count, count)
|
||||
self.check_public(current)
|
||||
if uniform:
|
||||
equilibrium = np.asarray(compute_feq_d2q9(1., .013, -.007), np.float64)
|
||||
for array in current.download():
|
||||
leaf = np.isfinite(array[0])
|
||||
self.assertLessEqual(np.max(np.abs(array[:, leaf]-equilibrium[:, None])), FP64_ATOL)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Run explicitly on an idle GPU; automatic/manual identical-layout equivalence.
|
||||
|
||||
This is not independent flow-accuracy validation. CPU collection never runs it.
|
||||
PYTHONPATH=src:.:tests/validation/multigrid python -m unittest discover \
|
||||
-s tests/validation/multigrid -p test_shear_refinement_example_gpu.py -v
|
||||
"""
|
||||
from contextlib import ExitStack
|
||||
import unittest
|
||||
import numpy as np
|
||||
from CelerisLab.cuda.context import CudaContext
|
||||
from research.shear_refinement.example import (CHILDREN, make, initialize, observe,
|
||||
topology, objects)
|
||||
|
||||
|
||||
class ShearRefinementGPU(unittest.TestCase):
|
||||
def test_measured_growth_matches_explicit_manual_continuation(self):
|
||||
with CudaContext(0) as ctx, ExitStack() as owned:
|
||||
old = owned.enter_context(make(ctx))
|
||||
initialize(old)
|
||||
old.step(2)
|
||||
before = old.download()
|
||||
chosen, report = observe(before[1], topology())
|
||||
manual = (CHILDREN[0], (56, 16, 76, 40))
|
||||
self.assertEqual(chosen, manual)
|
||||
self.assertGreater(report['requested'], 0)
|
||||
self.assertEqual(report['corridor_unknown'], 0)
|
||||
self.assertEqual(report['corridor_unavailable'], 0)
|
||||
auto = owned.enter_context(old.remap_child(chosen, child_objects=objects()))
|
||||
explicit = owned.enter_context(old.remap_child(manual, child_objects=objects()))
|
||||
for run in (auto, explicit):
|
||||
self.assertEqual(run.child_patch.bounds[0], CHILDREN[0])
|
||||
self.assertEqual(run.step_count, 2)
|
||||
run.step(2)
|
||||
for a, b, leaf in zip(auto.download(), explicit.download(), topology(manual).leaf_masks):
|
||||
np.testing.assert_array_equal(a, b)
|
||||
self.assertTrue(np.isfinite(a[:, leaf]).all())
|
||||
self.assertTrue(np.isnan(a[:, ~leaf]).all())
|
||||
for a, b in zip(old.download(), before):
|
||||
np.testing.assert_array_equal(a, b)
|
||||
self.assertEqual((old.step_count, auto.step_count, explicit.step_count), (2, 4, 4))
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
Reference in new issue
Block a user