Trying to add a SlipBC to my lbm code
import numpy as np
import warp as wp
import jax.numpy as jnp
from jax import jit
from functools import partial
from typing import Any
from xlb.velocity_set.velocity_set import VelocitySet
from xlb.precision_policy import PrecisionPolicy
from xlb.compute_backend import ComputeBackend
from xlb.operator.operator import Operator
from xlb.operator.boundary_condition.boundary_condition import (
ImplementationStep,
BoundaryCondition,
)
from xlb.operator.boundary_masker.mesh_voxelization_method import MeshVoxelizationMethod
The traceback tells us that SlipBC.init invokes
self._construct_neon() → self._construct_warp() before you attach self.mapping_np to the object, so when _construct_warp tries to use it the attribute does not yet exist:
BoundaryCondition.init(…) ← (inside this call, _construct_neon is executed)
└── SlipBC._construct_neon()
└── SlipBC._construct_warp()
└── uses self.mapping_np ← not created yet
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Args:
normal_axis (int): The axis normal to the slip surface (0 for x, 1 for y, 2 for z).
indices (array-like, optional): Indices where the BC applies.
mesh_vertices (array-like, optional): Mesh vertices for boundary definition.
voxelization_method (str, optional): Method for voxelizing mesh vertices.
"""
self.normal_axis = normal_axis
# Precompute mapping once on CPU
super().__init__(
ImplementationStep.STREAMING,
velocity_set,
precision_policy,
compute_backend,
indices,
mesh_vertices,
voxelization_method,
)
self.c = self.velocity_set.c # Warp matrix of shape (d, q)
self.q = self.velocity_set.q # Number of lattice directions
self.d = self.velocity_set.d # Number of dimensions
self.mapping_np = self._compute_mapping()
print(self.mapping_np)
def _compute_mapping(self):
"""Compute the mapping for specular reflection based on velocity_set.
Returns:
np.ndarray: Array mapping each lattice direction to its reflected direction.
"""
mapping = np.zeros(self.q, dtype=int)
for i in range(self.q):
# Extract the velocity vector for direction i
c_i = np.array([self.c[a, i] for a in range(self.d)])
# Reflect the velocity along the normal axis
c_j = c_i.copy()
c_j[self.normal_axis] = -c_j[self.normal_axis]
# Find the matching direction j
for j in range(self.q):
match = True
for a in range(self.d):
if self.c[a, j] != c_j[a]:
match = False
break
if match:
mapping[i] = j
break
else:
raise ValueError(f"No matching reflected direction found for i={i}")
return mapping
@Operator.register_backend(ComputeBackend.JAX)
@partial(jit, static_argnums=(0))
def jax_implementation(self, f_pre, f_post, bc_mask, missing_mask):
"""JAX implementation of the Slip boundary condition.
Args:
f_pre: Pre-collision distribution functions.
f_post: Post-collision distribution functions.
bc_mask: Mask identifying boundary nodes.
missing_mask: Mask for missing populations.
Returns:
Updated post-collision distribution functions.
"""
mapping = self._compute_mapping()
boundary = bc_mask == self.id # Shape: (1, nx, ny, nz)
boundary = jnp.broadcast_to(boundary, (self.velocity_set.q,) + boundary.shape[1:])
condition = boundary & missing_mask # Shape: (q, nx, ny, nz)
f_post_new = jnp.where(condition, f_post[mapping], f_post)
return f_post_new
def _construct_warp(self):
"""Construct the Warp kernel for the Slip boundary condition.
Returns:
tuple: Warp functional and kernel.
"""
_mapping_wp = wp.constant(wp.array(self.mapping_np.astype(np.int32)))
@wp.func
def functional(
index: Any,
timestep: Any,
missing_mask: Any,
f_0: Any,
f_1: Any,
f_pre: Any,
f_post: Any,
):
for l in range(self.velocity_set.q):
if missing_mask[l]:
f_post[l] = f_post[_mapping_wp[l]]
return f_post
kernel = self._construct_kernel(functional)
return functional, kernel
@Operator.register_backend(ComputeBackend.WARP)
def warp_implementation(self, f_pre, f_post, bc_mask, missing_mask):
# Launch the warp kernel
wp.launch(
self.warp_kernel,
inputs=[f_pre, f_post, bc_mask, missing_mask],
dim=f_pre.shape[1:],
)
return f_post
def _construct_neon(self):
functional, _ = self._construct_warp()
return functional, None
@Operator.register_backend(ComputeBackend.NEON)
def neon_implementation(self, f_pre, f_post, bc_mask, missing_mask):
# rise exception as this feature is not implemented yet
raise NotImplementedError("This feature is not implemented in XLB with the NEON backend yet.")
getting
self.neon_functional, self.neon_container = self._construct_neon()
File "/xlb/neon_warp_testing/XLB/xlb/operator/boundary_condition/bc_slip.py", line 148, in _construct_neon
functional, _ = self._construct_warp()
File "/xlb/neon_warp_testing/XLB/xlb/operator/boundary_condition/bc_slip.py", line 117, in _construct_warp
_mapping_wp = wp.constant(wp.array(self.mapping_np.astype(np.int32)))
AttributeError: 'SlipBC' object has no attribute 'mapping_np'
The fix is simply to create self.mapping_np (and everything it depends on) before the parent constructor (or to make _construct_warp compute the mapping on-the-fly). Re-ordering a few lines is enough:
python
class SlipBC(BoundaryCondition):
def __init__(
self,
velocity_set: VelocitySet = None,
precision_policy: PrecisionPolicy = None,
compute_backend: ComputeBackend = None,
indices=None,
mesh_vertices=None,
voxelization_method: MeshVoxelizationMethod = None,
normal_axis: int = 2,
):
self.normal_axis = normal_axis
# ---------- create the data needed by the base class ----------
self.velocity_set = velocity_set # so we can use it below
self.c = velocity_set.c
self.q = velocity_set.q
self.d = velocity_set.d
# mapping *must* exist before BoundaryCondition.__init__ runs
self.mapping_np = self._compute_mapping()
# ----------------------------------------------------------------
super().__init__(
ImplementationStep.STREAMING,
velocity_set,
precision_policy,
compute_backend,
indices,
mesh_vertices,
voxelization_method,
)
Nothing else has to change; now _construct_warp() (and therefore _construct_neon()) can safely access self.mapping_np while the base‐class constructor is executing.
Alternative (if you prefer not to touch the ordering):