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>
234 lines
8.9 KiB
Python
234 lines
8.9 KiB
Python
# CelerisLab/body/objects.py
|
|
"""
|
|
SimObject -- container wrapping geometry, state, and control.
|
|
|
|
Design:
|
|
SimObject is a thin container that holds a Geometry instance (shape),
|
|
an ObjectState (position/velocity), and an ObjectControl (control input).
|
|
Concrete geometry logic lives in ``body/geometry/*.py``.
|
|
|
|
The ``get_curved_list()`` / ``get_sensor_list()`` methods exist for
|
|
backward compatibility with ``ObjectManager.build_compact_lists()``.
|
|
They delegate to the Geometry's build methods and the SoA packer.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
import math
|
|
from typing import Optional, Tuple
|
|
|
|
import numpy as np
|
|
|
|
from .geometry.base import Geometry
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Constants
|
|
# ---------------------------------------------------------------------------
|
|
FALLBACK_CLASS_BOUZIDI = np.uint8(0)
|
|
FALLBACK_CLASS_HALFWAY_BOUNCEBACK = np.uint8(1)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# State / Control containers
|
|
# ---------------------------------------------------------------------------
|
|
@dataclass
|
|
class ObjectState:
|
|
"""Position, velocity, orientation (z reserved for 3D layouts)."""
|
|
x: float = 0.0
|
|
y: float = 0.0
|
|
z: float = 0.0
|
|
theta: float = 0.0
|
|
vx: float = 0.0
|
|
vy: float = 0.0
|
|
omega: float = 0.0
|
|
|
|
|
|
@dataclass
|
|
class ObjectControl:
|
|
"""Control input (force / velocity / displacement target)."""
|
|
ax: float = 0.0
|
|
ay: float = 0.0
|
|
alpha: float = 0.0
|
|
mode: int = 0 # 0=force, 1=velocity, 2=displacement
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class SurfaceActuation:
|
|
"""Fixed circular aperture: angles in radians, velocity in lattice units.
|
|
|
|
``angle`` is measured counterclockwise from +x; ``half_width`` is the arc
|
|
half-angle. Positive normal_velocity blows from solid into fluid. The C1
|
|
profile (1-s*s)^2 uses the true hit angle, not a fluid-node aperture mask.
|
|
This immutable specification is set before initialization; no moving nozzle.
|
|
"""
|
|
angle: float
|
|
half_width: float
|
|
normal_velocity: float
|
|
|
|
def __post_init__(self):
|
|
if not all(math.isfinite(v) for v in (self.angle, self.half_width, self.normal_velocity)):
|
|
raise ValueError("Surface actuation values must be finite")
|
|
if not 0 < self.half_width <= math.pi or abs(self.normal_velocity) >= 1:
|
|
raise ValueError("Require 0 < half_width <= pi and abs(normal_velocity) < 1")
|
|
|
|
def project(self, rx, ry):
|
|
"""Project stored true hit-center vectors; returns velocity and aperture mask."""
|
|
radius = np.hypot(rx, ry)
|
|
if np.any(radius <= 0):
|
|
raise ValueError("Surface normal requires nonzero hit-center distance")
|
|
delta = np.arctan2(np.sin(np.arctan2(ry, rx)-self.angle),
|
|
np.cos(np.arctan2(ry, rx)-self.angle))
|
|
aperture = np.abs(delta) < self.half_width
|
|
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
|
|
# ---------------------------------------------------------------------------
|
|
class SimObject:
|
|
"""Container for a simulation object: geometry, state, control.
|
|
|
|
The Geometry instance handles shape-specific operations (cut-link
|
|
enumeration, flag mask generation). SimObject wraps it with runtime
|
|
state and an id for bookkeeping.
|
|
|
|
The *is_sensor* flag selects the flag mask variant for sensors
|
|
(``FLUID|SENSOR_FLAG``) vs. obstacle bodies (``SOLID|OBSTACLE|BC_CURVED``).
|
|
"""
|
|
|
|
obj_type: str = "generic"
|
|
|
|
def __init__(
|
|
self,
|
|
obj_id: int,
|
|
geometry: Optional[Geometry] = None,
|
|
center: Optional[Tuple[float, ...]] = None,
|
|
radius: float = 0.0,
|
|
is_sensor: bool = False,
|
|
is_force_region: bool = False,
|
|
surface_actuation: Optional[SurfaceActuation] = None,
|
|
) -> None:
|
|
self.obj_id = obj_id
|
|
self.center = center if center is not None else (0.0, 0.0)
|
|
self.radius = radius
|
|
self._geometry = geometry
|
|
self._is_sensor = is_sensor
|
|
self._is_force_region = is_force_region
|
|
self._surface_actuation = (SurfaceActuation(**surface_actuation)
|
|
if isinstance(surface_actuation, dict) else surface_actuation)
|
|
if self._surface_actuation is not None and not isinstance(self._surface_actuation, SurfaceActuation):
|
|
raise TypeError("surface_actuation must be a SurfaceActuation or dict")
|
|
|
|
c = self.center
|
|
z0 = float(c[2]) if len(c) > 2 else 0.0
|
|
self.state = ObjectState(
|
|
x=float(c[0]), y=float(c[1]), z=z0,
|
|
)
|
|
self.control = ObjectControl()
|
|
|
|
@property
|
|
def surface_actuation(self):
|
|
return self._surface_actuation
|
|
|
|
def validate_surface_actuation(self, cfg, state=None):
|
|
if self.surface_actuation is None:
|
|
return
|
|
from .geometry.circle import CircleGeometry
|
|
if (type(self.geometry) is not CircleGeometry or self.is_sensor or self.is_force_region
|
|
or cfg is None or not cfg.is_d2q9 or cfg.store_precision != "FP32"
|
|
or cfg.streaming != "double_buffer" or cfg.ddf_shifting):
|
|
raise ValueError("Surface actuation requires a circle and D2Q9/FP32/unshifted/double_buffer")
|
|
values = vars(self.state) if state is None else state
|
|
if any(values.get(k, 0.) != 0 for k in ("vx", "vy", "omega")):
|
|
raise ValueError("Surface actuation requires a stationary circle")
|
|
|
|
@property
|
|
def geometry(self) -> Geometry:
|
|
if self._geometry is None:
|
|
raise RuntimeError(
|
|
f"SimObject id={self.obj_id} has no geometry assigned.")
|
|
return self._geometry
|
|
|
|
@geometry.setter
|
|
def geometry(self, g: Geometry) -> None:
|
|
self._geometry = g
|
|
|
|
@property
|
|
def is_sensor(self) -> bool:
|
|
return self._is_sensor
|
|
|
|
@property
|
|
def is_force_region(self) -> bool:
|
|
return self._is_force_region
|
|
|
|
# ------------------------------------------------------------------
|
|
# Methods consumed by ObjectManager.build_compact_lists() / build_flags()
|
|
# ------------------------------------------------------------------
|
|
def get_flag_mask(self, nx: int, ny: int, nz: int = 1) -> np.ndarray:
|
|
"""Return (nx*ny,) uint16 array with flag bits set for this object.
|
|
|
|
Sensors produce ``FLUID|SENSOR_FLAG``; bodies produce
|
|
``SOLID|OBSTACLE|BC_CURVED``; force-region objects produce
|
|
``FLUID|FRC_REGION``.
|
|
"""
|
|
if self._is_force_region:
|
|
return self.geometry.build_force_region_flag_mask(nx, ny)
|
|
if self._is_sensor:
|
|
return self.geometry.build_sensor_flag_mask(nx, ny)
|
|
return self.geometry.build_flag_mask(nx, ny)
|
|
|
|
def get_curved_list(
|
|
self, nx: int, ny: int, nq: int,
|
|
nz: int = 1, ex=None, ey=None, ez=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. If ``hits_out`` is a
|
|
list, the true FP64 hit points (n, 2) are appended row-aligned.
|
|
|
|
Returns:
|
|
8-tuple matching CurvedLinkSoA.assign_host().
|
|
"""
|
|
from .coupling.soa_packer import pack_cut_links_to_soa
|
|
|
|
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):
|
|
"""Return compact sensor list (cells, obj_ids).
|
|
|
|
Returns:
|
|
cells (uint32), obj_ids (int32).
|
|
"""
|
|
if self._is_force_region:
|
|
from .coupling.soa_packer import pack_force_region_to_soa as packer
|
|
else:
|
|
from .coupling.soa_packer import pack_sensor_to_soa as packer
|
|
|
|
cells = self.geometry.build_sensor_cells(nx, ny)
|
|
for sc in cells:
|
|
sc.body_id = self.obj_id
|
|
return packer(cells)
|