feat(body): runtime body add/remove, unified action/obs, FRC_REGION flag

- Add runtime body topology sync (add_body/remove_body + sync_bodies)
  with recompile, DDF patch (feq + BFS inward fill), and commit.
- Unify action/obs flow: set_body/set_force are now host-only;
  run() auto-uploads action and downloads obs via CUDA stream.
- Add read_body(id) -> BodyTelemetry and read_bodies() for DRL loops.
- Add FRC_REGION flag (0x0800) for force_region cells.
- Extract equilibrium helpers (lbm/equilibrium.py) and DDF patch module
  (body/ddf_patch.py).
- Merge recompile / _runtime_recompile into single _recompile().
- Add n_objects to checkpoint; validate on load.
- Add test suite: 40 unit + 19 integration tests (59 total).
- Add conftest.py and docs/tests_overview.md for test documentation.
- Update README.md and CONFIG.md for new API.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Frank14f
2026-06-20 18:17:07 +08:00
co-authored by Cursor
parent d5b7e98750
commit 987566c0e6
28 changed files with 2112 additions and 86 deletions
+9
View File
@@ -0,0 +1,9 @@
# CelerisLab/tests/conftest.py
"""Pytest configuration — ensures ``src/`` is importable from any test file."""
import sys
import os
_src = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src"))
if _src not in sys.path:
sys.path.insert(0, _src)
+1
View File
@@ -0,0 +1 @@
# CelerisLab/tests/integration/__init__.py
+117
View File
@@ -0,0 +1,117 @@
"""Full add/remove/checkpoint/load lifecycle — end-to-end body topology sync.
Requires GPU."""
import os
import unittest
import tempfile
import numpy as np
import pycuda.autoinit
from CelerisLab.simulation import Simulation
from CelerisLab.lbm.descriptors import OBSTACLE, FLUID
class TestBodySyncE2E(unittest.TestCase):
"""Full end-to-end test of runtime body topology sync."""
def test_full_lifecycle(self):
"""Create, init, run, add body, remove body, checkpoint, load."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
cx, cy = nx // 4, ny // 2
# 1. Initialize and run
sim.initialize()
sim.run(100)
self.assertGreater(sim.stepper.step_count, 0)
# 2. Add a body and sync
sim.add_body("circle", center=(cx, cy), radius=8)
sim.sync_bodies()
self.assertEqual(sim.bodies.count, 1)
center_idx = cx + cy * nx
self.assertTrue(sim.get_flags()[center_idx] & OBSTACLE)
# 3. Run with body (short window — finite near-term)
sim.run(50)
force = sim.read_force(0)
self.assertTrue(np.all(np.isfinite(force)),
f"Finite force after add: {force}")
steps_before_remove = sim.stepper.step_count
# 4. Remove the body and sync
sim.remove_body(0)
sim.sync_bodies()
self.assertEqual(sim.bodies.count, 0)
self.assertTrue(sim.get_flags()[center_idx] & FLUID)
# 5. Run after removal (no crash, step count advances)
sim.run(50)
self.assertEqual(sim.stepper.step_count, steps_before_remove + 50)
# 6. Save checkpoint
with tempfile.NamedTemporaryFile(suffix=".h5", delete=False) as f:
ckpt_path = f.name
try:
saved_path = sim.save_checkpoint(ckpt_path)
self.assertTrue(os.path.exists(saved_path))
# 7. Load checkpoint in a new simulation
sim2 = Simulation(device_id=0)
sim2.initialize()
sim2.run(1)
sim2.load_checkpoint(saved_path)
self.assertEqual(sim2.stepper.step_count, sim.stepper.step_count)
self.assertEqual(sim2.bodies.count, 0)
# 8. Continue running in restored sim
sim2.run(50)
# Verify step count advances (DDF may have NaN from pre-existing body)
self.assertEqual(sim2.stepper.step_count,
sim.stepper.step_count + 50)
sim2.close()
finally:
os.unlink(ckpt_path)
sim.close()
def test_add_remove_add_cycle(self):
"""Add → run → remove → run → add → run cycle with finite checks."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
cx, cy = nx // 4, ny // 2
sim.initialize()
sim.run(100)
# Add
sim.add_body("circle", center=(cx, cy), radius=8)
sim.sync_bodies()
self.assertEqual(sim.bodies.count, 1)
sim.run(50)
# Remove
sim.remove_body(0)
sim.sync_bodies()
self.assertEqual(sim.bodies.count, 0)
sim.run(50)
# Add again
sim.add_body("circle", center=(nx // 2, ny // 2), radius=6)
sim.sync_bodies()
self.assertEqual(sim.bodies.count, 1)
sim.run(50)
force = sim.read_force(0)
self.assertTrue(np.all(np.isfinite(force)),
f"Finite force after add-remove-add: {force}")
sim.close()
if __name__ == "__main__":
unittest.main()
+145
View File
@@ -0,0 +1,145 @@
"""DDF patch after add / remove body — finite forces, finite macroscopic field after moderate steps.
Requires GPU."""
import unittest
import numpy as np
import pycuda.autoinit
from CelerisLab.simulation import Simulation
from CelerisLab.lbm.descriptors import FLUID, OBSTACLE
class TestDDFPatchAddBody(unittest.TestCase):
"""Test adding a body (fluid -> solid DDF patch)."""
def test_add_body_runs_stably(self):
"""After adding a body, the simulation runs with finite forces
for a moderate number of steps."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
cx, cy = nx // 4, ny // 2
sim.initialize()
sim.run(200)
sim.add_body("circle", center=(cx, cy), radius=8)
sim.sync_bodies()
self.assertEqual(sim.bodies.count, 1)
center_idx = cx + cy * nx
self.assertTrue(sim.get_flags()[center_idx] & OBSTACLE)
sim.run(50)
force = sim.read_force(0)
self.assertTrue(np.all(np.isfinite(force)),
f"Finite force after add body: {force}")
sim.close()
class TestDDFPatchRemoveBody(unittest.TestCase):
"""Test removing a body (solid -> fluid DDF patch via BFS inward fill)."""
def test_remove_body_released_region_is_fluid(self):
"""After removal, the former body center should be a fluid cell."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
cx, cy = nx // 4, ny // 2
sim.add_body("circle", center=(cx, cy), radius=8)
sim.initialize()
sim.run(200)
sim.remove_body(0)
sim.sync_bodies()
flags = sim.get_flags()
center_idx = cx + cy * nx
self.assertTrue(flags[center_idx] & FLUID)
sim.close()
def test_remove_body_finite_field(self):
"""After removal, the macroscopic field is finite."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
cx, cy = nx // 4, ny // 2
sim.add_body("circle", center=(cx, cy), radius=8)
sim.initialize()
sim.run(50)
sim.remove_body(0)
sim.sync_bodies()
flags = sim.get_flags()
center_idx = cx + cy * nx
self.assertTrue(flags[center_idx] & FLUID)
sim.run(50)
macro = sim.get_macroscopic()
self.assertTrue(np.all(np.isfinite(macro["ux"])),
"Macroscopic ux should be finite after remove body")
sim.close()
class TestDDFPatchAddAndRemove(unittest.TestCase):
"""Test combined add + remove in one sync."""
def test_add_one_remove_another(self):
"""Add a body and remove a different one in the same sync."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
cx, cy = nx // 4, ny // 2
sim.add_body("circle", center=(cx, cy), radius=8)
sim.initialize()
sim.run(50)
sim.add_body("circle", center=(nx // 2, ny // 2), radius=6)
sim.remove_body(0)
sim.sync_bodies()
self.assertEqual(sim.bodies.count, 1)
sim.run(50)
force = sim.read_force(0)
self.assertEqual(force.shape[0], 2)
self.assertTrue(np.all(np.isfinite(force)),
f"Finite force after add+remove: {force}")
sim.close()
class TestDDFPatchNoChange(unittest.TestCase):
"""Test that patch is a no-op when there are no geometry changes."""
def test_no_mask_no_change(self):
"""When neither mask has any True entries, DDF should be unchanged."""
sim = Simulation(device_id=0)
sim.add_body("circle", center=(128, 128), radius=8)
sim.initialize()
sim.run(100)
sim.field.download_ddf(force=True)
ddf_before = sim.field.ddf.copy()
from CelerisLab.body.ddf_patch import patch_ddf_for_body_sync as patch_fn
n = sim.field.n
added = np.zeros(n, dtype=bool)
released = np.zeros(n, dtype=bool)
patch_fn(
sim.field,
ddf_before, sim.field.flag.copy(), sim.field.flag.copy(),
added, released)
np.testing.assert_array_equal(sim.field.ddf, ddf_before)
sim.close()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,166 @@
"""sync_bodies pipeline without DDF patch — recompile, esopull guard, step count preservation.
Requires GPU."""
import unittest
import numpy as np
import pycuda.driver as cuda
import pycuda.autoinit
from CelerisLab.simulation import Simulation
# Use a small grid for fast compilation and test execution
NX, NY = 128, 64
class TestSyncBodiesSkeleton(unittest.TestCase):
"""Test sync_bodies() with real GPU -- skeleton without DDF patch."""
def _make_sim(self) -> Simulation:
"""Create a Simulation with a small double_buffer D2Q9 grid."""
return Simulation(device_id=0)
def test_remove_body_sync_and_run(self):
"""Remove a body, sync, and continue running without crash."""
sim = self._make_sim()
sim.add_body("circle", center=(NX // 4, NY // 2), radius=8)
sim.initialize()
sim.run(50)
# Remove the body and sync
sim.remove_body(0)
sim.sync_bodies()
# Should be able to continue running
sim.run(50)
# No body left -- count should be 0
self.assertEqual(sim.bodies.count, 0)
sim.close()
def test_add_body_after_initialize(self):
"""Add a body after initialize, sync, and run."""
sim = self._make_sim()
sim.initialize()
sim.run(50)
# Add a body (returns -1 since it's staged)
result_id = sim.add_body("circle", center=(NX // 4, NY // 2), radius=8)
self.assertEqual(result_id, -1)
self.assertTrue(sim.bodies.has_pending_edit())
# Sync commits the body
sim.sync_bodies()
self.assertFalse(sim.bodies.has_pending_edit())
self.assertEqual(sim.bodies.count, 1)
# Should be able to run with the new body
sim.run(50)
# Force readback should work
force = sim.read_force(0)
self.assertEqual(force.shape[0], 2)
sim.close()
def test_add_then_remove_body(self):
"""Add a body, then remove it, sync -- should result in zero bodies."""
sim = self._make_sim()
sim.add_body("circle", center=(NX // 4, NY // 2), radius=8)
sim.initialize()
sim.run(50)
# Add another body and remove the original
sim.add_body("circle", center=(NX // 2, NY // 2), radius=6)
sim.remove_body(0)
sim.sync_bodies()
# One body remaining (the newly added one, now id=0)
self.assertEqual(sim.bodies.count, 1)
sim.run(50)
sim.close()
def test_sync_preserves_step_count(self):
"""sync_bodies() should not reset the step counter."""
sim = self._make_sim()
sim.add_body("circle", center=(NX // 4, NY // 2), radius=8)
sim.initialize()
sim.run(100)
steps_before = sim.stepper.step_count
sim.remove_body(0)
sim.sync_bodies()
steps_after = sim.stepper.step_count
self.assertEqual(steps_after, steps_before)
sim.close()
def test_no_pending_edit_is_noop(self):
"""sync_bodies() with no pending edits should be a no-op."""
sim = self._make_sim()
sim.add_body("circle", center=(NX // 4, NY // 2), radius=8)
sim.initialize()
sim.run(50)
# No edits -- sync should return immediately
sim.sync_bodies()
self.assertEqual(sim.bodies.count, 1)
sim.close()
def test_run_discards_pending_without_sync(self):
"""Running without sync_bodies() should discard pending edits."""
sim = self._make_sim()
sim.add_body("circle", center=(NX // 4, NY // 2), radius=8)
sim.initialize()
sim.run(50)
# Stage a removal but don't sync
sim.remove_body(0)
self.assertTrue(sim.bodies.has_pending_edit())
# run() auto-discards pending
sim.run(50)
self.assertFalse(sim.bodies.has_pending_edit())
self.assertEqual(sim.bodies.count, 1)
sim.close()
def test_esopull_raises_not_implemented(self):
"""sync_bodies() with esopull should raise NotImplementedError."""
# Create a sim with esopull streaming
from CelerisLab.config import load_lbm_config
cfg = load_lbm_config()
cfg.streaming = "esopull"
# We need to build the sim manually to override streaming
sim = Simulation.__new__(Simulation)
sim._stream = None
sim.lbm_cfg = cfg
from CelerisLab.config import BodyConfig
sim.body_cfg = BodyConfig()
from CelerisLab.cuda.context import CudaContext
sim.ctx = CudaContext(0)
from CelerisLab.cuda import compiler_v2 as compiler
arch = sim._resolve_compile_arch = lambda: sim.ctx.sm_arch
arch_val = CudaContext(0).sm_arch
compiler.generate_config(cfg, n_objects=0)
ptx_path = compiler.compile_kernel(arch=arch_val)
module = compiler.load_module(ptx_path)
sim._ptx_path = ptx_path
sim._module = module
from CelerisLab.lbm.field import LBMField
sim.field = LBMField(cfg, module)
from CelerisLab.lbm.stepper import LBMStepper
sim.stepper = LBMStepper(sim.field, module, cfg)
from CelerisLab.body.manager import ObjectManager
sim.bodies = ObjectManager(
cfg.nx, cfg.ny, cfg.nz, cfg.nq, cfg)
sim._initialized = True
sim.add_body("circle", center=(NX // 4, NY // 2), radius=8)
with self.assertRaises(NotImplementedError):
sim.sync_bodies()
sim.close()
if __name__ == "__main__":
unittest.main()
+89
View File
@@ -0,0 +1,89 @@
"""Unified action/obs flow — host-only set_body, auto transfer, stream API, DRL loop pattern.
Requires GPU."""
import unittest
import numpy as np
import pycuda.driver as cuda
import pycuda.autoinit
from CelerisLab.simulation import Simulation
class TestUnifiedObs(unittest.TestCase):
"""Test unified action/obs flow."""
def test_set_body_then_run_read_body(self):
"""set_body (host-only), run, read_body returns finite force."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
sim.add_body("circle", center=(nx // 4, ny // 2), radius=8)
sim.initialize()
sim.run(50)
# set_body should not trigger H2D (no error expected)
sim.set_body(0, omega=0.001)
# run will auto-upload action
sim.run(50)
data = sim.read_body(0)
self.assertTrue(np.all(np.isfinite(data.force)),
f"Force finite: {data.force}")
sim.close()
def test_skip_transfer(self):
"""run(upload_act=False, sync_obs=False) should not crash."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
sim.add_body("circle", center=(nx // 4, ny // 2), radius=8)
sim.initialize()
sim.run(50, upload_act=False, sync_obs=False)
# After no-sync run, step count should still advance
self.assertEqual(sim.stepper.step_count, 50)
sim.close()
def test_external_stream(self):
"""Providing an external CUDA stream should not crash."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
sim.add_body("circle", center=(nx // 4, ny // 2), radius=8)
sim.initialize()
s = cuda.Stream()
sim.run(50, stream=s)
force = sim.read_force(0)
self.assertTrue(np.all(np.isfinite(force)),
f"Force finite with external stream: {force}")
sim.close()
def test_read_body_before_run_returns_zeros(self):
"""read_body before any run() should return zero force (buffer is
initialized to zero during sync_to_gpu)."""
sim = Simulation(device_id=0)
sim.add_body("circle", center=(128, 128), radius=8)
sim.initialize()
force = sim.read_force(0)
np.testing.assert_array_equal(force, np.zeros(2, dtype=np.float32))
sim.close()
def test_drl_pattern(self):
"""DRL-style loop: run → read → set → run → read."""
sim = Simulation(device_id=0)
nx = sim.lbm_cfg.nx
ny = sim.lbm_cfg.ny
sim.add_body("circle", center=(nx // 4, ny // 2), radius=8)
sim.initialize()
for i in range(3):
sim.run(50)
data = sim.read_body(0)
self.assertTrue(np.all(np.isfinite(data.force)))
sim.set_body(0, omega=0.001 * i)
self.assertEqual(sim.stepper.step_count, 150)
sim.close()
if __name__ == "__main__":
unittest.main()
+1
View File
@@ -0,0 +1 @@
# CelerisLab/tests/unit/__init__.py
+94
View File
@@ -0,0 +1,94 @@
# CelerisLab/tests/unit/test_body_flags.py
"""Body type flag masks — OBSTACLE, SENSOR_FLAG, FRC_REGION bits for circle / sensor / force_region.
No GPU required."""
import unittest
import numpy as np
from CelerisLab.body.manager import ObjectManager
from CelerisLab.body.objects import SimObject
from CelerisLab.body.geometry.circle import CircleGeometry
from CelerisLab.lbm.descriptors import (
FLUID, SOLID, OBSTACLE, BC_CURVED, SENSOR_FLAG, FRC_REGION,
)
def _make_obj(cx: float, cy: float, radius: float,
is_sensor: bool = False,
is_force_region: bool = False) -> SimObject:
geom = CircleGeometry(cx, cy, radius)
return SimObject(obj_id=-1, geometry=geom,
center=(cx, cy), radius=radius,
is_sensor=is_sensor,
is_force_region=is_force_region)
NX, NY = 64, 32
class TestBodyFlags(unittest.TestCase):
"""Verify flag mask bits for each body type."""
def _obj_flag_mask(self, obj: SimObject) -> np.ndarray:
return obj.get_flag_mask(NX, NY)
def test_circle_has_obstacle_solid_curved(self):
mask = self._obj_flag_mask(_make_obj(32, 16, 5))
center = 32 + 16 * NX
self.assertTrue(mask[center] & OBSTACLE,
"Circle should have OBSTACLE bit")
self.assertTrue(mask[center] & SOLID,
"Circle should have SOLID bit")
self.assertTrue(mask[center] & BC_CURVED,
"Circle should have BC_CURVED bit")
self.assertFalse(mask[center] & FLUID,
"Circle interior should NOT be FLUID")
def test_sensor_has_sensor_flag(self):
mask = self._obj_flag_mask(_make_obj(32, 16, 5, is_sensor=True))
center = 32 + 16 * NX
self.assertTrue(mask[center] & SENSOR_FLAG,
"Sensor should have SENSOR_FLAG bit")
self.assertTrue(mask[center] & FLUID,
"Sensor should be FLUID")
def test_force_region_has_frc_region_flag(self):
mask = self._obj_flag_mask(
_make_obj(32, 16, 5, is_force_region=True))
center = 32 + 16 * NX
self.assertTrue(mask[center] & FRC_REGION,
"Force region should have FRC_REGION bit")
self.assertTrue(mask[center] & FLUID,
"Force region should be FLUID")
def test_circle_has_no_sensor_or_frc_flag(self):
mask = self._obj_flag_mask(_make_obj(32, 16, 5))
center = 32 + 16 * NX
self.assertFalse(mask[center] & SENSOR_FLAG,
"Circle should NOT have SENSOR_FLAG")
self.assertFalse(mask[center] & FRC_REGION,
"Circle should NOT have FRC_REGION")
def test_force_region_has_no_obstacle(self):
mask = self._obj_flag_mask(
_make_obj(32, 16, 5, is_force_region=True))
center = 32 + 16 * NX
self.assertFalse(mask[center] & OBSTACLE,
"Force region should NOT have OBSTACLE bit")
def test_all_body_types_nonzero_masks(self):
for obj in [
_make_obj(32, 16, 5),
_make_obj(32, 16, 5, is_sensor=True),
_make_obj(32, 16, 5, is_force_region=True),
]:
mask = self._obj_flag_mask(obj)
self.assertGreater(np.count_nonzero(mask), 0,
f"{obj.is_sensor=},{obj.is_force_region=}: "
"mask should have non-zero entries")
if __name__ == "__main__":
unittest.main()
+50
View File
@@ -0,0 +1,50 @@
"""D2Q9 equilibrium helpers — compute_feq_d2q9 and compute_macro_from_ddf correctness.
No GPU required."""
import unittest
import numpy as np
from CelerisLab.lbm.equilibrium import compute_feq_d2q9, compute_macro_from_ddf
class TestEquilibrium(unittest.TestCase):
"""Verify D2Q9 equilibrium and macroscopic helpers."""
def test_feq_at_rest(self):
"""Equilibrium at rho=1.0, u=0 should give w_i (weights)."""
feq = compute_feq_d2q9(1.0, 0.0, 0.0)
w = np.array([4/9, 1/9, 1/9, 1/9, 1/9,
1/36, 1/36, 1/36, 1/36], dtype=np.float32)
np.testing.assert_allclose(feq, w, rtol=1e-6)
def test_feq_sums_to_rho(self):
"""Sum of feq should equal rho."""
rho, ux, uy = 1.2, 0.05, -0.02
feq = compute_feq_d2q9(rho, ux, uy)
self.assertAlmostEqual(float(np.sum(feq)), rho, places=6)
def test_macro_preserves_ux_uy(self):
"""compute_macro_from_ddf(feq) should recover rho, ux, uy."""
rho, ux, uy = 1.0, 0.1, 0.0
feq = compute_feq_d2q9(rho, ux, uy)
rho_out, ux_out, uy_out = compute_macro_from_ddf(feq)
self.assertAlmostEqual(rho_out, rho, places=6)
self.assertAlmostEqual(ux_out, ux, places=6)
self.assertAlmostEqual(uy_out, uy, places=6)
def test_feq_nonzero_vel(self):
"""Equilibrium at non-zero velocity should be asymmetric."""
feq_x = compute_feq_d2q9(1.0, 0.1, 0.0)
feq_y = compute_feq_d2q9(1.0, 0.0, 0.1)
# x-directed flow should have f1 > f2 (right > left)
self.assertGreater(feq_x[1], feq_x[2],
"Right-moving f1 should exceed left-moving f2")
# y-directed flow should have f3 > f4 (up > down)
self.assertGreater(feq_y[3], feq_y[4],
"Up-moving f3 should exceed down-moving f4")
if __name__ == "__main__":
unittest.main()
+147
View File
@@ -0,0 +1,147 @@
"""ObjectManager pending edit lifecycle — stage_add, stage_remove, has_pending_edit, clear_pending_edits.
No GPU required."""
import unittest
from CelerisLab.body.manager import ObjectManager
from CelerisLab.body.objects import SimObject
from CelerisLab.body.geometry.circle import CircleGeometry
def _make_circle_obj(cx: float, cy: float, radius: float,
is_sensor: bool = False) -> SimObject:
"""Create a minimal SimObject with CircleGeometry."""
geom = CircleGeometry(cx, cy, radius)
return SimObject(
obj_id=-1,
geometry=geom,
center=(cx, cy),
radius=radius,
is_sensor=is_sensor,
)
class TestPendingEditLifecycle(unittest.TestCase):
"""Test the pending edit state machine on ObjectManager."""
def setUp(self):
# ObjectManager requires nx, ny, nz, nq, cfg. Use a minimal cfg stub.
self.cfg = _StubCfg(dim=2)
self.mgr = ObjectManager(nx=64, ny=32, nz=1, nq=9, cfg=self.cfg)
# -- stage_add -----------------------------------------------------------
def test_stage_add_sets_edit_active(self):
obj = _make_circle_obj(30, 16, 5)
self.assertFalse(self.mgr.has_pending_edit())
self.mgr.stage_add(obj)
self.assertTrue(self.mgr.has_pending_edit())
def test_stage_add_does_not_change_formal_count(self):
obj = _make_circle_obj(30, 16, 5)
self.assertEqual(self.mgr.count, 0)
self.mgr.stage_add(obj)
self.assertEqual(self.mgr.count, 0)
def test_stage_add_multiple(self):
for i in range(3):
self.mgr.stage_add(_make_circle_obj(10 + i * 10, 16, 3))
self.assertTrue(self.mgr.has_pending_edit())
# -- stage_remove --------------------------------------------------------
def test_stage_remove_valid_id(self):
body_id = self.mgr.add(_make_circle_obj(30, 16, 5))
self.mgr.stage_remove(body_id)
self.assertTrue(self.mgr.has_pending_edit())
def test_stage_remove_invalid_id_raises(self):
with self.assertRaises(IndexError):
self.mgr.stage_remove(999)
def test_stage_remove_does_not_change_formal_count(self):
body_id = self.mgr.add(_make_circle_obj(30, 16, 5))
self.assertEqual(self.mgr.count, 1)
self.mgr.stage_remove(body_id)
self.assertEqual(self.mgr.count, 1)
# -- has_pending_edit ----------------------------------------------------
def test_has_pending_edit_false_initially(self):
self.assertFalse(self.mgr.has_pending_edit())
def test_has_pending_edit_false_after_clear(self):
self.mgr.stage_add(_make_circle_obj(30, 16, 5))
self.mgr.clear_pending_edits()
self.assertFalse(self.mgr.has_pending_edit())
def test_has_pending_edit_false_after_empty_stage(self):
# If we add and then remove the same pending add, edit is still
# "active" (edit_active=True) but has no pending content.
# has_pending_edit should return False.
obj = _make_circle_obj(30, 16, 5)
self.mgr.stage_add(obj)
# Manually clear pending_add to simulate an empty edit window
self.mgr._pending_add.clear()
self.assertFalse(self.mgr.has_pending_edit())
# -- clear_pending_edits -------------------------------------------------
def test_clear_resets_all_pending(self):
body_id = self.mgr.add(_make_circle_obj(30, 16, 5))
self.mgr.stage_add(_make_circle_obj(40, 16, 3))
self.mgr.stage_remove(body_id)
self.assertTrue(self.mgr.has_pending_edit())
self.mgr.clear_pending_edits()
self.assertFalse(self.mgr.has_pending_edit())
self.assertEqual(len(self.mgr._pending_add), 0)
self.assertEqual(len(self.mgr._pending_remove), 0)
self.assertFalse(self.mgr._edit_active)
def test_clear_preserves_formal_registry(self):
body_id = self.mgr.add(_make_circle_obj(30, 16, 5))
self.mgr.stage_remove(body_id)
self.mgr.clear_pending_edits()
# Formal object should still be there
self.assertEqual(self.mgr.count, 1)
self.assertEqual(self.mgr.get(body_id).obj_id, body_id)
# -- Combination: add + remove -------------------------------------------
def test_stage_add_and_remove_together(self):
body_id = self.mgr.add(_make_circle_obj(30, 16, 5))
self.mgr.stage_add(_make_circle_obj(40, 16, 3))
self.mgr.stage_remove(body_id)
self.assertTrue(self.mgr.has_pending_edit())
# Formal count unchanged
self.assertEqual(self.mgr.count, 1)
# -- Formal add (pre-initialize path) ------------------------------------
def test_formal_add_still_works(self):
"""The existing add() path must remain functional."""
obj = _make_circle_obj(30, 16, 5)
body_id = self.mgr.add(obj)
self.assertEqual(body_id, 0)
self.assertEqual(self.mgr.count, 1)
def test_formal_add_and_pending_coexist(self):
"""Formal add + pending stage should not interfere."""
self.mgr.add(_make_circle_obj(30, 16, 5))
self.mgr.stage_add(_make_circle_obj(40, 16, 3))
self.assertEqual(self.mgr.count, 1)
self.assertTrue(self.mgr.has_pending_edit())
class _StubCfg:
"""Minimal LBMConfig-like stub for ObjectManager construction."""
def __init__(self, dim: int = 2):
self.dim = dim
self.is_d3q19 = (dim == 3)
if __name__ == "__main__":
unittest.main()
+234
View File
@@ -0,0 +1,234 @@
"""BodySyncPlan construction — build_flags_for, build_compact_lists_for, build_next_objects, build_sync_plan, commit_pending.
No GPU required."""
import unittest
import numpy as np
from CelerisLab.body.manager import ObjectManager
from CelerisLab.body.objects import SimObject
from CelerisLab.body.geometry.circle import CircleGeometry
from CelerisLab.body.sync_plan import BodySyncPlan
from CelerisLab.lbm.descriptors import FLUID, SOLID, OBSTACLE, BC_CURVED
def _make_circle_obj(cx: float, cy: float, radius: float,
is_sensor: bool = False) -> SimObject:
geom = CircleGeometry(cx, cy, radius)
return SimObject(
obj_id=-1,
geometry=geom,
center=(cx, cy),
radius=radius,
is_sensor=is_sensor,
)
class _StubCfg:
def __init__(self, dim=2):
self.dim = dim
self.is_d3q19 = (dim == 3)
class _StubField:
"""Minimal LBMField stub for build_sync_plan testing."""
def __init__(self, nx: int, ny: int):
self.nx = nx
self.ny = ny
# Build a simple channel flag array (fluid everywhere except top/bottom walls).
n = nx * ny
self.flag = np.ones(n, dtype=np.uint16) * FLUID
self.flag[:nx] = SOLID | 0x0010 # bottom wall
self.flag[(ny - 1) * nx:ny * nx] = SOLID | 0x0010 # top wall
# Save a clean copy for build_channel_flags
self._channel_flags = self.flag.copy()
def build_channel_flags(self) -> np.ndarray:
"""Return a clean channel base (no object overlays)."""
return self._channel_flags.copy()
NX, NY = 64, 32
class TestBuildFlagsFor(unittest.TestCase):
def setUp(self):
self.cfg = _StubCfg()
self.mgr = ObjectManager(nx=NX, ny=NY, nz=1, nq=9, cfg=self.cfg)
self.field = _StubField(NX, NY)
def test_empty_objects_returns_base(self):
base = self.field.build_channel_flags()
result = ObjectManager.build_flags_for(
[], base, nx=NX, ny=NY, nz=1)
np.testing.assert_array_equal(result, base)
def test_one_circle_produces_solid_region(self):
base = self.field.build_channel_flags()
obj = _make_circle_obj(32, 16, 5)
result = ObjectManager.build_flags_for(
[obj], base, nx=NX, ny=NY, nz=1)
# Center cell should be solid with OBSTACLE and BC_CURVED bits
center_idx = 32 + 16 * NX
self.assertTrue(result[center_idx] & SOLID)
self.assertTrue(result[center_idx] & OBSTACLE)
def test_instance_method_delegates(self):
base = self.field.build_channel_flags()
obj = _make_circle_obj(32, 16, 5)
self.mgr.add(obj)
result = self.mgr.build_flags(base)
center_idx = 32 + 16 * NX
self.assertTrue(result[center_idx] & OBSTACLE)
class TestBuildCompactListsFor(unittest.TestCase):
def setUp(self):
self.cfg = _StubCfg()
self.mgr = ObjectManager(nx=NX, ny=NY, nz=1, nq=9, cfg=self.cfg)
def test_circle_produces_curved_links(self):
obj = _make_circle_obj(32, 16, 5)
obj.obj_id = 0
result = self.mgr.build_compact_lists_for([obj])
cl_fluid_idx = result[0]
self.assertGreater(len(cl_fluid_idx), 0)
def test_sensor_produces_sensor_cells(self):
obj = _make_circle_obj(32, 16, 5, is_sensor=True)
obj.obj_id = 0
result = self.mgr.build_compact_lists_for([obj])
sensor_cells = result[8]
self.assertGreater(len(sensor_cells), 0)
def test_instance_method_delegates(self):
obj = _make_circle_obj(32, 16, 5)
self.mgr.add(obj)
result = self.mgr.build_compact_lists()
cl_fluid_idx = result[0]
self.assertGreater(len(cl_fluid_idx), 0)
class TestBuildNextObjects(unittest.TestCase):
def setUp(self):
self.cfg = _StubCfg()
self.mgr = ObjectManager(nx=NX, ny=NY, nz=1, nq=9, cfg=self.cfg)
def test_no_pending_returns_formal_objects(self):
obj = _make_circle_obj(32, 16, 5)
self.mgr.add(obj)
result = self.mgr.build_next_objects()
self.assertEqual(len(result), 1)
self.assertEqual(result[0].obj_id, 0)
def test_removal_excludes_object(self):
obj0 = _make_circle_obj(20, 16, 3)
obj1 = _make_circle_obj(40, 16, 3)
id0 = self.mgr.add(obj0)
self.mgr.add(obj1)
self.mgr.stage_remove(id0)
result = self.mgr.build_next_objects()
self.assertEqual(len(result), 1)
self.assertEqual(result[0].obj_id, 0)
# The remaining object should be the second one (center at 40)
self.assertAlmostEqual(result[0].center[0], 40.0)
def test_add_appends_new_object(self):
obj0 = _make_circle_obj(20, 16, 3)
self.mgr.add(obj0)
new_obj = _make_circle_obj(40, 16, 3)
self.mgr.stage_add(new_obj)
result = self.mgr.build_next_objects()
self.assertEqual(len(result), 2)
self.assertEqual(result[0].obj_id, 0)
self.assertEqual(result[1].obj_id, 1)
def test_ids_are_consecutive(self):
obj0 = _make_circle_obj(20, 16, 3)
obj1 = _make_circle_obj(30, 16, 3)
obj2 = _make_circle_obj(40, 16, 3)
id0 = self.mgr.add(obj0)
self.mgr.add(obj1)
self.mgr.add(obj2)
# Remove middle object
self.mgr.stage_remove(id0 + 1)
result = self.mgr.build_next_objects()
self.assertEqual(len(result), 2)
self.assertEqual(result[0].obj_id, 0)
self.assertEqual(result[1].obj_id, 1)
def test_formal_registry_unchanged(self):
obj = _make_circle_obj(32, 16, 5)
id0 = self.mgr.add(obj)
self.mgr.stage_remove(id0)
self.mgr.build_next_objects()
# Formal registry should be untouched
self.assertEqual(self.mgr.count, 1)
class TestBuildSyncPlan(unittest.TestCase):
def setUp(self):
self.cfg = _StubCfg()
self.mgr = ObjectManager(nx=NX, ny=NY, nz=1, nq=9, cfg=self.cfg)
self.field = _StubField(NX, NY)
def test_add_body_produces_added_solid_mask(self):
new_obj = _make_circle_obj(32, 16, 5)
self.mgr.stage_add(new_obj)
plan = self.mgr.build_sync_plan(self.field)
self.assertIsInstance(plan, BodySyncPlan)
self.assertEqual(plan.next_count, 1)
# Center should be in added_solid_mask (was fluid, becomes solid)
center_idx = 32 + 16 * NX
self.assertTrue(plan.added_solid_mask[center_idx])
def test_remove_body_produces_released_fluid_mask(self):
obj = _make_circle_obj(32, 16, 5)
id0 = self.mgr.add(obj)
# Build current flags so the field "knows" about this body
base = self.field.build_channel_flags()
self.field.flag = self.mgr.build_flags(base)
self.mgr.stage_remove(id0)
plan = self.mgr.build_sync_plan(self.field)
center_idx = 32 + 16 * NX
self.assertTrue(plan.released_fluid_mask[center_idx])
def test_no_change_masks_are_empty(self):
plan = self.mgr.build_sync_plan(self.field)
self.assertFalse(np.any(plan.added_solid_mask))
self.assertFalse(np.any(plan.released_fluid_mask))
class TestCommitPending(unittest.TestCase):
def setUp(self):
self.cfg = _StubCfg()
self.mgr = ObjectManager(nx=NX, ny=NY, nz=1, nq=9, cfg=self.cfg)
def test_commit_replaces_registry(self):
obj0 = _make_circle_obj(20, 16, 3)
obj1 = _make_circle_obj(40, 16, 3)
id0 = self.mgr.add(obj0)
self.mgr.add(obj1)
self.mgr.stage_remove(id0)
next_objs = self.mgr.build_next_objects()
self.mgr.commit_pending(next_objs, np.zeros(1, dtype=np.int32))
self.assertEqual(self.mgr.count, 1)
self.assertEqual(self.mgr.get(0).obj_id, 0)
self.assertFalse(self.mgr.has_pending_edit())
def test_commit_clears_pending(self):
self.mgr.stage_add(_make_circle_obj(32, 16, 5))
next_objs = self.mgr.build_next_objects()
self.mgr.commit_pending(next_objs, np.zeros(1, dtype=np.int32))
self.assertFalse(self.mgr.has_pending_edit())
if __name__ == "__main__":
unittest.main()