Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

# Tolerance of the point-in-tetrahedron test, in barycentric units.
_BARYCENTRIC_TOLERANCE = 1e-10
# Points located per block: the lookup holds (n, 5, 4, 3) arrays, about 2.7 KB a point.
_LOCATION_CHUNK_SIZE = int(1e4)


class TetMesh(BaseStructuredSupport):
Expand Down Expand Up @@ -264,16 +266,6 @@ def evaluate_gradient(self, pos: np.ndarray, property_array: np.ndarray) -> np.n
# values[inside,:] /= length[:,None]
return values

def inside(self, pos: np.ndarray):
inside = np.ones(pos.shape[0]).astype(bool)
for i in range(3):
inside *= pos[:, i] > self.origin[None, i]
inside *= (
pos[:, i]
< self.origin[None, i] + self.step_vector[None, i] * self.nsteps_cells[None, i]
)
return inside

def get_element_for_location(self, pos: np.ndarray):
"""
Determine the tetrahedron from a numpy array of points
Expand All @@ -290,7 +282,15 @@ def get_element_for_location(self, pos: np.ndarray):
"""
pos = np.array(pos)
pos = pos[:, : self.dimension]
inside = self.inside(pos)
if pos.shape[0] <= _LOCATION_CHUNK_SIZE:
return self._get_element_for_location_block(pos)
blocks = [
self._get_element_for_location_block(pos[start : start + _LOCATION_CHUNK_SIZE])
for start in range(0, pos.shape[0], _LOCATION_CHUNK_SIZE)
]
return tuple(np.concatenate(parts) for parts in zip(*blocks))

def _get_element_for_location_block(self, pos: np.ndarray):
# initialise array for tetrahedron vertices
vertices = np.zeros((pos.shape[0], 5, 4, 3))
vertices[:] = np.nan
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -643,14 +643,3 @@ def tetra_global_index(self, indices, tetra_index):
+ self.nsteps_cells[0] * indices[:, 1] * 5
+ self.nsteps_cells[0] * self.nsteps_cells[1] * indices[:, 2] * 5
)

def inside(self, pos: np.ndarray):
"""Check if points are inside the mesh domain."""
inside = np.ones(pos.shape[0]).astype(bool)
for i in range(3):
inside *= pos[:, i] > self.origin[None, i]
inside *= (
pos[:, i]
< self.origin[None, i] + self.step_vector[None, i] * self.nsteps_cells[None, i]
)
return inside
20 changes: 10 additions & 10 deletions packages/loop_common/src/loop_common/supports/_support_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,24 +55,24 @@ def create_support_from_bbox(
if local_coordinates:
# Build the mesh in the bounding box's local (interpolation) frame
# rather than raw world coordinates -- keeps node coordinates
# numerically well-conditioned. Project origin/maximum directly
# (rather than all corners, which BoundingBox.corners only
# supports in 3D) -- exact for translation-only transforms, which
# is the only kind in use today (no code sets a non-identity
# rotation on a bounding box).
local_points = bounding_box.project(np.array([bounding_box.origin, bounding_box.maximum]))
origin = np.min(local_points, axis=0)
local_maximum = np.max(local_points, axis=0)
step_vector = (local_maximum - origin) / bounding_box.nsteps
# numerically well-conditioned. The local box encloses every
# projected corner, so a rotated frame gives a full support.
origin, local_maximum = bounding_box.local_enclosure()
# A rotated enclosure is longer than the world box: add cells so each
# axis keeps the world cell size (an unrotated box keeps its nsteps).
ratio = (local_maximum - origin) / (bounding_box.maximum - bounding_box.origin)
nsteps = np.maximum(np.ceil(bounding_box.nsteps * ratio - 1e-9).astype(int), 1)
step_vector = (local_maximum - origin) / nsteps
else:
origin = bounding_box.origin
step_vector = bounding_box.step_vector
nsteps = bounding_box.nsteps

nsteps_kwarg = (
"nsteps_cells" if support_type in SupportFactory._CELL_COUNT_SUPPORT_TYPES else "nsteps"
)
return support_map[support_type](
origin=origin,
step_vector=step_vector,
**{nsteps_kwarg: bounding_box.nsteps},
**{nsteps_kwarg: nsteps},
)
Binary file modified packages/loop_common/tests/data/structured_support_reference.npz
Binary file not shown.
50 changes: 50 additions & 0 deletions packages/loop_common/tests/test_bounding_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,53 @@ def test_structured_grid_local_coordinates_accounts_for_rotation():
# not just the two corners obtained by projecting origin/maximum alone.
assert np.all(grid.origin <= projected_corners.min(axis=0) + 1e-8)
assert np.all(grid.maximum >= projected_corners.max(axis=0) - 1e-8)


def test_support_factory_local_frame_encloses_rotated_box():
from loop_common.supports import SupportFactory

bbox = BoundingBox(origin=[0.0, 0.0, 0.0], maximum=[10.0, 10.0, 10.0], nsteps=[5, 5, 5])
angle = np.radians(45.0)
rotation = np.array(
[
[np.cos(angle), -np.sin(angle), 0.0],
[np.sin(angle), np.cos(angle), 0.0],
[0.0, 0.0, 1.0],
]
)
bbox.set_local_transform(local_origin=[0.0, 0.0, 0.0], rotation_matrix=rotation)
projected_corners = bbox.project(bbox.corners)

support = SupportFactory.create_support_from_bbox("StructuredGrid", bbox, nelements=None)

assert np.all(support.origin <= projected_corners.min(axis=0) + 1e-8)
assert np.all(support.maximum >= projected_corners.max(axis=0) - 1e-8)


@pytest.mark.parametrize("degrees", [0.0, 30.0])
def test_support_factory_local_frame_keeps_world_cell_size(degrees):
from loop_common.supports import SupportFactory

bbox = BoundingBox(origin=[0.0, 0.0, 0.0], maximum=[10.0, 10.0, 10.0], nsteps=[5, 5, 5])
angle = np.radians(degrees)
rotation = np.array(
[
[np.cos(angle), -np.sin(angle), 0.0],
[np.sin(angle), np.cos(angle), 0.0],
[0.0, 0.0, 1.0],
]
)
bbox.set_local_transform(local_origin=[0.0, 0.0, 0.0], rotation_matrix=rotation)
origin, maximum = bbox.local_enclosure()

support = SupportFactory.create_support_from_bbox("TetMesh", bbox, nelements=None)

# The world cell is 2 on each axis; the rotated enclosure gets more cells, not longer ones.
np.testing.assert_array_equal(support.nsteps_cells, np.ceil((maximum - origin) / 2.0 - 1e-9))
assert np.all(support.step_vector <= 2.0 + 1e-12)
assert np.all(support.step_vector > 2.0 * (support.nsteps_cells - 1) / support.nsteps_cells)
if degrees == 0.0:
np.testing.assert_array_equal(support.nsteps_cells, [5, 5, 5])
np.testing.assert_array_equal(support.step_vector, bbox.step_vector)
else:
np.testing.assert_array_equal(support.nsteps_cells, [7, 7, 5])
28 changes: 28 additions & 0 deletions packages/loop_common/tests/test_tetra_face_tolerance.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,31 @@ def test_points_outside_the_mesh_stay_outside():
)
inside = mesh.get_element_for_location(outside)[3]
assert not inside.any()


@pytest.mark.parametrize("name", ["TetMesh", "P2TetMesh"])
def test_points_on_the_mesh_boundary_are_inside(name):
origin, step = np.zeros(3), np.ones(3)
mesh = {
"TetMesh": TetMesh(origin=origin, nsteps_cells=[4, 4, 4], step_vector=step),
"P2TetMesh": P2TetMesh(origin=origin, nsteps=[4, 4, 4], step_vector=step),
}[name]
# origin corner, max corner, a point on the max face and on the min face
points = np.array([[0, 0, 0], [4, 4, 4], [4, 1.5, 1.5], [0, 1.5, 1.5]], dtype=float)
values = mesh.evaluate_value(points, mesh.nodes.sum(axis=1))
np.testing.assert_allclose(values, points.sum(axis=1), atol=1e-12)


def test_tetmesh_location_lookup_in_chunks_gives_the_same_result(monkeypatch):
from loop_common.supports import _3d_structured_tetra

meshes, origin, extent = _meshes()
mesh = meshes["TetMesh"]
rng = np.random.default_rng(2)
# some points outside, so the inside mask is mixed
points = origin + rng.uniform(-0.1, 1.1, size=(101, 3)) * extent
expected = mesh.get_element_for_location(points)
monkeypatch.setattr(_3d_structured_tetra, "_LOCATION_CHUNK_SIZE", 7)
chunked = mesh.get_element_for_location(points)
for a, b in zip(expected, chunked):
np.testing.assert_array_equal(a, b)
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@
},
"fold orientation": {
"A_fro": 156.7322557739791,
"A_rowmoment": -2.0979769033147022e-09,
"A_sum": -5.598160823794274e-13,
"A_rowmoment": -8.912479643186089e-10,
"A_sum": -5.870165464827437e-13,
"WA_fro": 1567.322557739791,
"b_norm": 0.0,
"b_sum": 0.0,
Expand Down Expand Up @@ -78,8 +78,8 @@
},
"fold regularisation 2": {
"A_fro": 156.41759486642567,
"A_rowmoment": -9.113136911764741e-10,
"A_sum": 1.9484414082171497e-13,
"A_rowmoment": -1.025910023599863e-09,
"A_sum": 1.6359136267851682e-13,
"WA_fro": 1.5641759486642568,
"b_norm": 0.0,
"b_sum": 0.0,
Expand Down Expand Up @@ -140,15 +140,15 @@
"dof": 5832,
"engine": "DFI",
"metrics": {
"angle_max": 16.09179039973764,
"angle_median": 2.4599700200430394,
"angle_max": 16.091790399738144,
"angle_median": 2.459970020043632,
"angle_p90": 10.362774495778687,
"data_normal_angle_max": 7.772696499624479,
"data_value_rms": 1.2257794538813684e-05,
"data_normal_angle_max": 7.7726964996243835,
"data_value_rms": 1.2257794538628517e-05,
"flipped_fraction": 0.0,
"grad_norm_ratio_median": 0.5387235948762048,
"grad_norm_ratio_median": 0.538723594876275,
"nan_fraction": 0.0,
"value_max": 0.22203421827165537,
"value_rms": 0.11191966434086847
"value_max": 0.22203421827228953,
"value_rms": 0.11191966434078293
}
}
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"metrics": {
"angle_max": 63.71962891191211,
"angle_median": 39.89865888624575,
"angle_p90": 61.061233254910015,
"angle_p90": 61.06123325491003,
"data_normal_angle_max": 1.5292416061637002,
"data_value_rms": 2.4699668150190985e-05,
"flipped_fraction": 0.0,
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
},
"fold axis": {
"A_fro": 156.7322557739791,
"A_rowmoment": -1.126508664128778e-09,
"A_sum": 1.2106982083537332e-13,
"A_rowmoment": -6.168505706227734e-10,
"A_sum": 1.3994361225400098e-13,
"WA_fro": 1567.322557739791,
"b_norm": 0.0,
"b_sum": 0.0,
Expand All @@ -33,10 +33,10 @@
},
"fold normalisation": {
"A_fro": 156.7322557739791,
"A_rowmoment": 3.2496103585799574e-09,
"A_sum": 1.5620837956475953e-13,
"A_rowmoment": 2.973521873173013e-09,
"A_sum": 7.627232179174825e-14,
"WA_fro": 156.7322557739791,
"b_norm": 7.925735547400374,
"b_norm": 7.925735547400375,
"b_sum": -1217.905634310967,
"nnz": 98260,
"shape": [
Expand All @@ -48,8 +48,8 @@
},
"fold orientation": {
"A_fro": 156.7322557739791,
"A_rowmoment": -1.8776713517354437e-10,
"A_sum": -5.995204332975845e-15,
"A_rowmoment": 6.50172360394663e-10,
"A_sum": 5.255518242819335e-14,
"WA_fro": 1567.322557739791,
"b_norm": 0.0,
"b_sum": 0.0,
Expand All @@ -63,9 +63,9 @@
},
"fold regularisation 1": {
"A_fro": 159.75825173199294,
"A_rowmoment": -9.576979209668934e-10,
"A_sum": 2.5868196473766147e-14,
"WA_fro": 15.975825173199295,
"A_rowmoment": -1.1214069672860205e-09,
"A_sum": 1.1157741397482823e-14,
"WA_fro": 15.975825173199294,
"b_norm": 0.0,
"b_sum": 0.0,
"nnz": 236980,
Expand All @@ -78,9 +78,9 @@
},
"fold regularisation 2": {
"A_fro": 158.73215032382961,
"A_rowmoment": -1.153239281848073e-09,
"A_sum": -1.006972283335017e-13,
"WA_fro": 1.5873215032382963,
"A_rowmoment": 3.092281986027956e-11,
"A_sum": -5.5011550870176507e-14,
"WA_fro": 1.5873215032382961,
"b_norm": 0.0,
"b_sum": 0.0,
"nnz": 236980,
Expand All @@ -93,8 +93,8 @@
},
"fold regularisation 3": {
"A_fro": 159.8699648597854,
"A_rowmoment": 3.71164787793532e-09,
"A_sum": 1.5876189252139739e-13,
"A_rowmoment": 3.5824996302835643e-09,
"A_sum": 1.255662240851052e-13,
"WA_fro": 1.598699648597854,
"b_norm": 0.0,
"b_sum": 0.0,
Expand Down Expand Up @@ -140,15 +140,15 @@
"dof": 5832,
"engine": "DFI",
"metrics": {
"angle_max": 19.179746886401613,
"angle_median": 5.031488876359824,
"angle_p90": 12.35885981396067,
"data_normal_angle_max": 14.150982349177252,
"data_value_rms": 0.0011218259985967124,
"angle_max": 19.1797468864033,
"angle_median": 5.031488876359679,
"angle_p90": 12.358859813960105,
"data_normal_angle_max": 14.150982349179255,
"data_value_rms": 0.001121825998965027,
"flipped_fraction": 0.0,
"grad_norm_ratio_median": 0.44254296534946697,
"grad_norm_ratio_median": 0.44254296534942067,
"nan_fraction": 0.0,
"value_max": 0.3090860459721929,
"value_rms": 0.1407901438131724
"value_max": 0.3090860459732059,
"value_rms": 0.14079014381319194
}
}
Binary file not shown.
Binary file not shown.
3 changes: 0 additions & 3 deletions packages/loop_interpolation/tests/golden/test_golden.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,6 @@ def test_p2_mesh_stores_its_geometry():
assert hasattr(mesh, "origin") # inside() and the setup diagnostics need it


@pytest.mark.xfail(
strict=True, reason="new finding F2: P1/DFI return NaN for points on the lower x/y/z faces"
)
@pytest.mark.parametrize("engine", ["P1", "DFI"])
def test_known_points_on_lower_boundary_are_finite(engine):
case = "fold_sparse"
Expand Down
Loading