Compare commits

...
14 Commits
Author SHA1 Message Date
ClaudeandClaude Opus 5.5 f1e03423f3 Action upload: keep 2D slot fallback for ObjectManager(cfg=None)
19bd308 computed slot = 3*self.cfg.dim unconditionally, so a default
manager without cfg raised even when empty. Use the existing fallback
(cfg.dim if cfg else 2). Regression for empty and one-body managers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 09:03:11 +00:00
ClaudeandClaude Opus 5.5 e67799812e Jet review tests: rotated tube, exact edge rule, synthetic flat wall
Test-only. Rotated 30-degree tube: lateral .999 in, 1.001 out, along -0.1
and 4.1 out, Parallel(30 deg) gives the axis unit vector. Separate
axis-aligned exact-edge check: |s| = 1 excluded, Tube along 0/length and
Sector r_min/r_max included. Synthetic hit sampling on a flat face x=10
(no non-circle geometry or kernel coverage): spatial selection |y| <= 1
and off-centre radial vectors from (5, 0) rather than the face normal.
Re-written from Grok's stated cases; the original text was clipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 09:02:05 +00:00
ClaudeandClaude Opus 5.5 19bd3088ef Gate action upload on Jet stationarity; document setter device-error handling
ObjectManager._upload_action_async is the single entry for every action
path (setters, direct edits of the public action array, run()). It now
also rejects nonzero vx/vy/omega slots of Jet-driven bodies via
validate_jet_motion, before any device copy. Regression: each motion
slot edited directly is rejected with no device write; zero motion
uploads. Simulation.set_jet_amplitude documents that a device error
requires close/recreate, as for other CUDA exceptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:58:17 +00:00
ClaudeandClaude Opus 5.5 063508d1a3 Jet amplitude setter: failed state on device errors, commit after upload
FixedPatchStepper.set_jet_amplitude validates index/amplitude and builds
the new rows before touching the device; invalid input leaves the
instance usable. A copy/sync error marks it failed (as initialize/step/
download do) and re-raises; host state (_jets, blocked velocity table)
commits only after a successful upload. CurvedLinkSoA.set_jet_amplitude
likewise uploads a new array first and commits jets/surface_velocity
afterwards. Focused mocked-driver tests for dense and blocked copy
failure, invalid input and IndexError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:49:35 +00:00
ClaudeandClaude Opus 5.5 508d412e43 Add Grok's Jet review tests (5-link sector oracle, axis wrap)
Taken from Grok's inline patch (Slack ts 1792052057.423679); the selector
fix in that patch was already applied in b1cd555. The rotated-tube and
non-circle-wall cases were clipped in transit and are not included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:42:51 +00:00
ClaudeandClaude Opus 5.5 aebef52345 Wire Jets into FixedPatchStepper fine level (dense and blocked)
FixedPatchStepper(..., jets=()) passes jets (coarse cell-edge frame, as
fine_objects) to prepare_fine_boundary, which runs the shared assignment
checks before CUDA. Dense fine path: assign_surface with jets and the
boundary's true hits. Blocked path: surface_link_velocity with jets/hits;
unit-amplitude shapes cached. set_jet_amplitude (new/ready only) validates
first, then rewrites the dense SoA column or the blocked jet rows and
re-uploads only the velocity buffer after a stream sync. Scheduling,
kernels and launch ABI unchanged.

tests/validation/multigrid/test_refinement_jets.py: mocked-driver CPU
checks and frozen GPU gates G1-G3 (layout identity, jet vs legacy <=1e-6,
amplitude switch).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:42:51 +00:00
ClaudeandClaude Opus 5.5 f26410f94a Merge base-blocked FixedPatchStepper 906e0d9 into claude/jet
Exact codex/refinement-blocked-base-20261015 head, cleared by Astra/root.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:41:38 +00:00
ClaudeandClaude Opus 5.5 038a759ff1 Jets: one shared assignment check for dense and fine levels
Move surface_link_velocity (pure host code) from lbm/curved_links.py to
body/jets.py, re-exported by curved_links, so refinement.py can reuse it
without importing PyCUDA. prepare_fine_boundary now runs the same
assignment validation as the steppers when jets are given, rejecting
jet-vs-SurfaceActuation overlap (root's C(12.25,12.25) R2.15 case) as
well as empty/overlapping jets. Test the overlap and a disjoint pair.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:35:12 +00:00
ClaudeandClaude Opus 5.5 f7753be0e4 Jets: enforce stationary rule at ObjectManager.set_body_state too
Move the Jet motion check into ObjectManager.validate_jet_motion (uses the
synced field's cut-link jet_id) and call it from both Simulation.set_body
and the direct ObjectManager.set_body_state entry, before any state or
action change. Test both entries, vx too, and that action is untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:32:29 +00:00
ClaudeandClaude Opus 5.5 62c525e735 Jets: freeze origins, guard set_body, fine-boundary hit helper
Sector/Tube/Radial store origin as a validated float 2-tuple, so caller
lists/arrays cannot change a registered definition. Simulation.set_body
rejects nonzero motion for bodies with Jet-driven links once initialized
(before initialize the sync-time stationary check applies).
prepare_fine_boundary accepts jets in the same coarse cell-edge frame as
fine objects, records read-only FP64 edge-frame hits (FineBoundary2D
.curved_hits, default None) and rejects empty or overlapping selections
before CUDA. FixedPatchStepper wiring is not included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:27:35 +00:00
ClaudeandClaude Opus 5.5 da8bfb0d4a Jets: explicit cell-edge/node frame conversion, same-physical-hit test
Replace fine_hits_to_physical with fine_hits_to_edge_frame (patch
cell-edge frame, coarse centers at I+1/2, as FixedPatchStepper uses) and
edge_to_node_frame (Simulation integer-node frame, shift -1/2). Test one
physical circle through both frames: fine hits converted to node frame
lie on the Simulation circle and one node-frame Jet selects the same arc
on coarse and fine links; relabelling without conversion is detected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:23:28 +00:00
ClaudeandClaude Opus 5.5 b1cd555b0f Jet review fixes: frozen Jet, validated amplitude replacement, test selector
Jet is a frozen dataclass; with_amplitude returns a validated copy, so
region/field/profile cannot drift from the cached per-link shapes and
amplitude cannot bypass validation. CurvedLinkSoA.set_jet_amplitude and
Simulation.set_jet_amplitude replace the Jet (Simulation also updates the
registered list so later geometry syncs keep the amplitude). Reject
non-finite hits; document edge rule (|s|<1 exclusive, radial/along
bounds inclusive). Fix the clipped-q test selector to receiver (9,5)
dir 8, as in test_surface_actuation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:18:29 +00:00
ClaudeandClaude Opus 5.5 932702f779 Wire Jets through ObjectManager and Simulation
ObjectManager.jets holds scene-level Jets. build_compact_lists_for
collects true FP64 hits (SimObject.get_curved_list hits_out) row-aligned
with the cut-link columns; BodySyncPlan carries them as curved_hits, and
sync_to_gpu / apply_sync_plan / the pre-sync check pass jets+hits to
assign_surface. Jets require D2Q9/FP32/unshifted/double_buffer and may
only drive links of stationary bodies. Simulation.add_jet (before
initialize) and set_jet_amplitude (velocity column re-upload only);
save_checkpoint refuses scenes with jets. Fine-path wiring not included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:15:22 +00:00
ClaudeandClaude Opus 5.5 611a64c54a Add body-independent Jet: true-hit spatial selection, fields, profiles
Jet(region, field, profile, amplitude) with Sector/Tube regions,
Radial/Parallel fields and uniform/parabolic/quartic profiles. Selection
uses true FP64 hit points over all scene cut links, no body association.
Overlap between jets or with a SurfaceActuation aperture is rejected.
CurvedLinkSoA caches unit-amplitude shapes; set_jet_amplitude rewrites
and re-uploads only the surface-velocity column. SurfaceActuation.as_jet
is the legacy adapter (equivalence measured in tests). Kernel and SoA
geometry columns unchanged. Manager/Simulation/fine-path wiring pending.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 08:10:31 +00:00
12 changed files with 996 additions and 54 deletions

No files matched your search

+2
View File
@@ -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",
]
+234
View File
@@ -0,0 +1,234 @@
# 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.
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
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.
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
def __post_init__(self):
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
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
+47 -12
View File
@@ -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
+18 -2
View File
@@ -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):
+2
View File
@@ -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
+34 -30
View File
@@ -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:
@@ -42,33 +44,6 @@ def _upload_columns(columns, stream=None):
stream.synchronize()
def surface_link_velocity(objects, cfg, flags, fluid_idx, dir, body_id, rx, ry):
"""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 no object carries surface actuation.
"""
enabled = [obj for obj in objects if obj.surface_actuation is not None]
if not enabled:
return None, None
from .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
return surface_velocity, surface_aperture
@dataclass
class CurvedLinkSoA:
"""Cut-link columns on host with matching ``*_gpu`` device buffers."""
@@ -107,12 +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."""
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
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)
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.
@@ -198,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.
+22 -3
View File
@@ -153,6 +153,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 +184,20 @@ def _transfer_footprint(patch):
return fine, coarse, _readonly(sorted(reads), np.int64)
def prepare_fine_boundary(cfg, patch, objects, *, wall_aware=False):
def prepare_fine_boundary(cfg, patch, objects, *, wall_aware=False, jets=()):
"""Project fixed circles and reject boundary/transfer overlap before CUDA.
Input centers/radii are in coarse physical coordinates (dx=dt=1).
SurfaceActuation retains its lattice-velocity meaning: input coarse units
are converted into independent fine-local objects with dx=dt=.5.
Original objects are not retained or mutated. No runtime geometry updates.
``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).
"""
if not objects:
if jets:
raise ValueError("Fine jets need fine boundary objects")
return None
checked = replace(cfg)
checked.validate()
@@ -286,8 +292,21 @@ def prepare_fine_boundary(cfg, patch, objects, *, wall_aware=False):
# 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],
patch.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))
+48 -7
View File
@@ -16,6 +16,7 @@ import pycuda.driver as cuda
from ..cuda import compiler_v2 as compiler
from .blocks import BlockLayout2D, blocked_link_tables
from .curved_links import surface_link_velocity
from ..body.jets import jet_link_shapes, jet_link_velocity
from .block_stepper import MAX_GRID_DIM
from .refinement import ACTIVE, HALO, OUTER_GHOST, FixedPatch2D, prepare_fine_boundary
from .descriptors import SOLID, D2Q9_EX, D2Q9_EY
@@ -106,9 +107,12 @@ class FixedPatchStepper:
covered cells are explicitly poisoned on every step. Public shapes stay dense.
Blocked mode applies prescribed surface velocity only; its per-link
exchange diagnostic is unavailable (rows keep physical cut-link order).
``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.
"""
def __init__(self, cfg, bounds, *, context, coarse_boundary="periodic", fine_objects=(),
fine_block=None, base_block=None):
fine_block=None, base_block=None, jets=()):
if HALO != 4:
raise RuntimeError("refinement.cu requires a four-cell fine halo")
if coarse_boundary not in ("periodic", "slot_reservoir"):
@@ -143,9 +147,10 @@ class FixedPatchStepper:
if (self.fine_layout.nblocks > MAX_GRID_DIM
or self.fine_layout.local_shape[0] > MAX_GRID_DIM):
raise ValueError("fine blocks exceed launch limits")
self._jets = tuple(jets)
self.fine_boundary = prepare_fine_boundary(
cfg, self.patch, fine_objects, wall_aware=self._wall_aware)
self._fine_tables, self._actuated = None, False
cfg, self.patch, fine_objects, wall_aware=self._wall_aware, jets=self._jets)
self._fine_tables, self._actuated, self._jet_cache = None, False, None
if self.fine_layout is not None and self.fine_boundary is not None:
fluid_idx, dirs, q, _, _, _, _, fallback = self.fine_boundary.curved_host
self._fine_tables, _ = blocked_link_tables(
@@ -172,12 +177,16 @@ class FixedPatchStepper:
if self._fine_tables is not None:
# Any actuation spec (even zero amplitude) requires the velocity buffer.
b = self.fine_boundary
self._actuated = any(obj.surface_actuation is not None for obj in b.objects)
self._actuated = bool(self._jets) or any(
obj.surface_actuation is not None for obj in b.objects)
if self._actuated:
fine_cfg.validate() # derives nq etc.; the unique-writer key needs them
fluid_idx, dirs, _, body_id, rx, ry, _, _ = b.curved_host
self._fine_tables["surface_velocity"], _ = surface_link_velocity(
b.objects, fine_cfg, b.flags, fluid_idx, dirs, body_id, rx, ry)
b.objects, fine_cfg, b.flags, fluid_idx, dirs, body_id, rx, ry,
jets=self._jets, hits=b.curved_hits)
if self._jets:
self._jet_cache = jet_link_shapes(self._jets, b.curved_hits)
with self.ctx.activate():
try:
self._stream = cuda.Stream()
@@ -257,7 +266,8 @@ class FixedPatchStepper:
# 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._jets, hits=boundary.curved_hits)
self._fine_curved.upload()
self._curved = self._levels[1].module.get_function("CurvedBoundaryKernel")
except BaseException:
@@ -333,7 +343,8 @@ class FixedPatchStepper:
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._jets) or any(
obj.surface_actuation is not None for obj in self.fine_boundary.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,
@@ -343,6 +354,36 @@ 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):
"""Replace one jet's amplitude between steps; no geometry/table rebuild.
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")
jets = list(self._jets)
jets[index] = jets[index].with_amplitude(amplitude) # validates first
velocity = None
if self._fine_curved is None and self._jet_cache is not None:
shape, jet_id = self._jet_cache
velocity = self._fine_tables["surface_velocity"].copy()
driven = jet_id >= 0
velocity[driven] = jet_link_velocity(jets, shape, jet_id)[driven]
try:
if 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(self._link_tables["surface_velocity"], velocity)
except BaseException:
self._status = "failed"
raise
if velocity is not None:
self._fine_tables["surface_velocity"] = velocity
self._jets = tuple(jets)
def _blocked_fine_boundary(self, buffer, **kw):
if self._fine_tables is None:
return
+32
View File
@@ -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)
+312
View File
@@ -0,0 +1,312 @@
"""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])
# 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)
+79
View File
@@ -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,166 @@
"""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
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_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()