diff --git a/changelog.d/polyhedra-no-kernel.md b/changelog.d/polyhedra-no-kernel.md new file mode 100644 index 00000000..8b3e453e --- /dev/null +++ b/changelog.d/polyhedra-no-kernel.md @@ -0,0 +1,10 @@ +### Fixed + +- A polyhedron with no kernel (tangled, inside out, or with a face whose own fan + folds over, which no point inside sees whole) held no points: a point inside + one was found in a neighbour or nowhere, and a particle reaching one stopped, + with a warning. Such a cell now holds a point by its winding number (the + solid angles of its face triangles), and point data there is interpolated by + mean value coordinates, which are exact for a linear field, as VTK's + `vtkPolyhedron` interpolates. Probes, `CellLocator.find`, `advect` and + streamlines take it. On AhmedML's volume 12 of 21.5M cells are such (#334). diff --git a/docs/vis-guide/design/polyhedra.md b/docs/vis-guide/design/polyhedra.md index 952ac9af..9e1a78ee 100644 --- a/docs/vis-guide/design/polyhedra.md +++ b/docs/vis-guide/design/polyhedra.md @@ -796,19 +796,43 @@ the points from which every triangle of its face fans is seen from inside. evaluate with, and probe's evaluation from the cells (`_evaluate_in_moved_tets`, `tet_value_from`). - A mesh without such cells compiles the path out. -- **Cells with no kernel are skipped, with a warning.** These are tangled or - inside-out cells, cells with a face whose own fan folds over, and cells with - no volume. `starts` is -2 for them, and both searches leave them out. - - A point inside one is found in a neighbour it overlaps, or nowhere, and a - particle reaching one stops. - - On the AhmedML volume there were 12: wall cells 2–3 mm across at the - nose's four corners, which none of 338 streamlines aimed at those edges - entered. - - VTK's `vtkStreamTracer` traces through such cells without a word: in 9 of - the 12 its `FindCell` returns a neighbour for the cell's centroid. - - Locating in them properly would need a solid-angle (winding number) test - and another interpolant, mean value coordinates. That is on the roadmap - for 0.9. +- **Cells with no kernel hold points by their winding number.** These are + tangled or inside-out cells, and cells with a face whose own fan folds over. + `starts` is -2 for them (`_SKIPPED`), and their sub-tetrahedra overlap, so + neither the fan's locating nor its interpolant holds there (#334). + - **Inside test.** `locate_by_winding` sums the solid angles of the cell's + face triangles (each face fanned from its face point, as its neighbour fans + it, so the cells' surfaces meet) over 4π, by Van Oosterom and Strackee's + formula. A point is held where that is 1 or -1, so an inside-out cell holds + its points too; a cell with no volume winds round nothing. A point outside + but within the slack of a face triangle is near, as in other cells. + - **The location.** Its sub-tetrahedron is `views.NO_KERNEL_TET` (positive + and past any fan's, so callers testing `t >= 0` need no change), and its + `pc` is the point less the cell point (the mean). + - **Interpolant.** `mvc_value`: mean value coordinates over the same + triangles (Ju, Schaefer and Warren, 2005, in the robust form + `vtkMeanValueCoordinatesInterpolator` uses), defined in any closed + polyhedron and exact for a linear field. A face point takes the mean of + its face's values. A point on a triangle takes its barycentric weights; + the angle tolerance is VTK's 1e-8, since the arcs' shortfall from 2π + shrinks as the square of the distance (1e-5 snapped points 0.3% of a + triangle away onto it). + - **Who reads it.** The search from the cells (`_test_points_in_polyhedra`), + the by-id `_PolyhedralMesh` (`locate_held`, `tet_value_of`), which probe + and advection use, and probe's evaluation from the cells + (`_evaluate_in_moved_tets`). Advection's shortcut, a cell that holds the + particle well inside (`_well_inside`), does not stop at such a cell, which + may overlap its neighbours. + - **Not done.** Gradients there: nothing reads a polyhedral location's + gradient yet. + - **On the AhmedML volume** there are 12: wall cells 2–3 mm across at the + nose's four corners, 10 of them read as polyhedra. Until #334 they held no + points. Now each of those 10 holds its centre and the points a third of + the way from it to each of its points (80 in all), none found in a + neighbour, and every interpolated `UMean` is within the range of the + cell's own point values (2026-12-05). VTK's `vtkStreamTracer` traces + through such cells without a word: in 9 of the 12 its `FindCell` returns a + neighbour for the cell's centroid. **Tests, and why not VTK.** The proposal planned exact agreement with `vtkProbeFilter` and `vtkGradientFilter` on linear fields. On VTK 9.7.1 diff --git a/packages/tack-dataset/CLAUDE.md b/packages/tack-dataset/CLAUDE.md index 0b5e9bfa..5b5c6d8a 100644 --- a/packages/tack-dataset/CLAUDE.md +++ b/packages/tack-dataset/CLAUDE.md @@ -69,7 +69,7 @@ Advection on a GPU runs in launches of a bounded number of steps (`_advection._l ## Polyhedra, polygons and cell location -Polyhedra have no reference element, so values inside them are linear on *sub-tetrahedra*: each face fanned from its points' mean, the fans from the cell's points' mean (both in value too, so linear fields are exact; `docs/vis-guide/design/polyhedra.md` section 13). Cell gradients are Green-Gauss over the fanned faces (`_polyhedral_gradients`, one walk per face); `cell_centers`/`values_at_centers` give the points' mean. The cell view locates and the field view evaluates, since a field view has no positions and a device function cannot call another view's methods: `views._PolyhedralLocation` (`locate`/`locate_from` give `(t, pc, inside)`, a sub-tetrahedron, its coordinates and whether it holds the point, which callers rank first; `cell_point`, `face_point`, `tet_jacobian`) on polyhedral domain views, and `_PolyhedralPointField`/`_PolyhedralCellField` (`tet_value`, `tet_parametric_gradient`), which `Space.mixin_for(key, shape)` picks by shape (`_H1Field.value` names shape functions a `Polyhedron` lacks, and every method of a view is resolved). A `CellLocator` records its topology and geometry and the geometry's `_revision` (`serves(data)`); `probe` and advection take one for any dataset of that topology and geometry and refuse a stale one, and without one use the locator the topology keeps (`cached_locator`, `_Topology._locator`, one at a time), so repeated probes build the bins once; a geometry of the same positions (a temporal filter's copy of a step, new arrays of unchanged values) takes it rebound (`holds_positions_of`, compared on the device; `rebound`: boxes and bins shared, the search made again from its positions). `CellLocator.find` returns `Locations(cells, pcs, tets)` on every dataset (`tets` None except on polyhedra), searching from the points where `tack.dataset.by_id` can read cells by id (`_MeshSearch.find` over `cell_bins()`, a two-level grid as Viskores' `CellLocatorTwoLevel`: coarse bins of about `_CELLS_PER_BIN` (32) cells, each a uniform grid of leaves sized by its count, about `_CELLS_PER_LEAF` (8; Viskores' 2 entered each of the aneurysm's tetrahedra 34 times) a leaf, rounded (Viskores truncates, which left a small even mesh's bins one leaf each), `leaves()` their dims and first leaf; `CellLocator(data, levels=1)` is one uniform grid of about `density` bins a cell, every bin a leaf (Viskores' `CellLocatorUniformBins`), for small even meshes, a point's leaf found from its coarse coordinate by `by_id._leaf` as the build places cells, so a point within a cell's widened box is in one of its leaves; ranked as the cell-side search ranks; `_PointValues`/`_CellValues.value(mesh, e, kind, pc, tet)` for probe and advection, which share it; a curved geometry and fields of other spaces through each shape group's own view, `by_id._ByShape` with `local` each cell's index in its group (a structured grid's index vector): `_CurvedCells.locate` (round 1's `curved_to_parametric` and `position`, `_MeshSearch.CURVED`) and `_ViewValues`, with one-shape variants `_OneCurvedShape`/`_OneShapeValues` called directly, since the eight-way dispatch took minutes to compile) and from the cells elsewhere, or for a fresh locator's first query of fewer points than a quarter of its cells and moves the cell point of a polyhedron not star-shaped from it into the cell's kernel (`_not_star_shaped`, then `_kernel_points`: Newton on the soft minimum of the fan triangles' clearances; the point as weights on the cell's points, `w_j = 1/n + d_j . G^-1 q`, so linear fields stay exact; `moved_cell_points`, read by `_cell_point`, `_PolyhedralMesh.moved` and probe's `_evaluate_in_moved_tets`), skipping cells with no kernel (tangled, inside out, folded faces: `starts` -2, `_SKIPPED`, left out of both searches, with a warning) and refusing polygons not star-shaped from it; the advection kernel's `_PolyhedralMesh` is built from the same mixins. Advection first tries the cell a particle was last found in (`_MeshSearch.find_from`, `_well_inside`): a tetrahedron, hexahedron, wedge or voxel holding the point by `shapes.WELL_INSIDE` (1e-3 parametric, a hundred times `HOLD_TOLERANCE`) is the only cell of a non-overlapping mesh holding it, so the search would return it with the same coordinates; a polyhedron is tried in its sub-tetrahedra (`_well_inside_fan`, `FANNED`: the search's own `locate`, taken where the holding sub-tetrahedron's four weights are each at least `WELL_INSIDE`); anything else (pyramids, surfaces, polygons, polylines, points near a face) searches the bins. `_MeshSearch.PREVIOUS_CELL = 0` turns it off; `test_trying_the_last_cell_first_changes_nothing` holds the traces bit for bit. It made streamlines 4-5x faster on real meshes. `neighbors=True` on `advect`/`streamlines` (and over pieces) then tries the last cell's face neighbours by the same rule (`_MeshSearch.NEIGHBORS`, compiled in; `CellLocator.cell_neighbors()`, `_MAX_FACES` ids a cell from `faces().sides`, -1 for none, kept; `None` for surfaces and polyhedra): 1.5-2x faster streamlines on the aneurysm and the M6, bit for bit (`test_walking_to_the_last_cells_neighbours_changes_nothing`). Polygons locate in the triangles fanning them from their cell point (`views._PolygonLocation`, `t = 2k`, `pc = (0, w_a, w_b)`, so `_PolyhedralPointField.tet_value` reads them unchanged) and polylines on their segments (`_PolylineLocation`, `_PolylinePointField`); `by_id` has `_PolygonMesh` and `_PolylineMesh`, and every mesh says `NO_REFERENCE`, which the search and evaluation branch on. VTK 9.7.1's `vtkPolyhedron` is no reference for these (wrong `Derivatives` and `EvaluatePosition`; see section 13). See `test_polyhedra.py`, `test_probe.py`, `test_flow.py`, and `benchmarks/polyhedra_compare.py` for the cost against hexahedra. +Polyhedra have no reference element, so values inside them are linear on *sub-tetrahedra*: each face fanned from its points' mean, the fans from the cell's points' mean (both in value too, so linear fields are exact; `docs/vis-guide/design/polyhedra.md` section 13). Cell gradients are Green-Gauss over the fanned faces (`_polyhedral_gradients`, one walk per face); `cell_centers`/`values_at_centers` give the points' mean. The cell view locates and the field view evaluates, since a field view has no positions and a device function cannot call another view's methods: `views._PolyhedralLocation` (`locate`/`locate_from` give `(t, pc, inside)`, a sub-tetrahedron, its coordinates and whether it holds the point, which callers rank first; `cell_point`, `face_point`, `tet_jacobian`) on polyhedral domain views, and `_PolyhedralPointField`/`_PolyhedralCellField` (`tet_value`, `tet_parametric_gradient`), which `Space.mixin_for(key, shape)` picks by shape (`_H1Field.value` names shape functions a `Polyhedron` lacks, and every method of a view is resolved). A `CellLocator` records its topology and geometry and the geometry's `_revision` (`serves(data)`); `probe` and advection take one for any dataset of that topology and geometry and refuse a stale one, and without one use the locator the topology keeps (`cached_locator`, `_Topology._locator`, one at a time), so repeated probes build the bins once; a geometry of the same positions (a temporal filter's copy of a step, new arrays of unchanged values) takes it rebound (`holds_positions_of`, compared on the device; `rebound`: boxes and bins shared, the search made again from its positions). `CellLocator.find` returns `Locations(cells, pcs, tets)` on every dataset (`tets` None except on polyhedra), searching from the points where `tack.dataset.by_id` can read cells by id (`_MeshSearch.find` over `cell_bins()`, a two-level grid as Viskores' `CellLocatorTwoLevel`: coarse bins of about `_CELLS_PER_BIN` (32) cells, each a uniform grid of leaves sized by its count, about `_CELLS_PER_LEAF` (8; Viskores' 2 entered each of the aneurysm's tetrahedra 34 times) a leaf, rounded (Viskores truncates, which left a small even mesh's bins one leaf each), `leaves()` their dims and first leaf; `CellLocator(data, levels=1)` is one uniform grid of about `density` bins a cell, every bin a leaf (Viskores' `CellLocatorUniformBins`), for small even meshes, a point's leaf found from its coarse coordinate by `by_id._leaf` as the build places cells, so a point within a cell's widened box is in one of its leaves; ranked as the cell-side search ranks; `_PointValues`/`_CellValues.value(mesh, e, kind, pc, tet)` for probe and advection, which share it; a curved geometry and fields of other spaces through each shape group's own view, `by_id._ByShape` with `local` each cell's index in its group (a structured grid's index vector): `_CurvedCells.locate` (round 1's `curved_to_parametric` and `position`, `_MeshSearch.CURVED`) and `_ViewValues`, with one-shape variants `_OneCurvedShape`/`_OneShapeValues` called directly, since the eight-way dispatch took minutes to compile) and from the cells elsewhere, or for a fresh locator's first query of fewer points than a quarter of its cells and moves the cell point of a polyhedron not star-shaped from it into the cell's kernel (`_not_star_shaped`, then `_kernel_points`: Newton on the soft minimum of the fan triangles' clearances; the point as weights on the cell's points, `w_j = 1/n + d_j . G^-1 q`, so linear fields stay exact; `moved_cell_points`, read by `_cell_point`, `_PolyhedralMesh.moved` and probe's `_evaluate_in_moved_tets`), locating in cells with no kernel (tangled, inside out, folded faces: `starts` -2, `_SKIPPED`) by their winding number (`locate_by_winding`, solid angles of the face triangles) and evaluating point data there by mean value coordinates (`mvc_value`, Ju-Schaefer-Warren as VTK's interpolator), the location's tet `views.NO_KERNEL_TET` and `pc` the point less the mean (#334) and refusing polygons not star-shaped from it; the advection kernel's `_PolyhedralMesh` is built from the same mixins. Advection first tries the cell a particle was last found in (`_MeshSearch.find_from`, `_well_inside`): a tetrahedron, hexahedron, wedge or voxel holding the point by `shapes.WELL_INSIDE` (1e-3 parametric, a hundred times `HOLD_TOLERANCE`) is the only cell of a non-overlapping mesh holding it, so the search would return it with the same coordinates; a polyhedron is tried in its sub-tetrahedra (`_well_inside_fan`, `FANNED`: the search's own `locate`, taken where the holding sub-tetrahedron's four weights are each at least `WELL_INSIDE`); anything else (pyramids, surfaces, polygons, polylines, points near a face) searches the bins. `_MeshSearch.PREVIOUS_CELL = 0` turns it off; `test_trying_the_last_cell_first_changes_nothing` holds the traces bit for bit. It made streamlines 4-5x faster on real meshes. `neighbors=True` on `advect`/`streamlines` (and over pieces) then tries the last cell's face neighbours by the same rule (`_MeshSearch.NEIGHBORS`, compiled in; `CellLocator.cell_neighbors()`, `_MAX_FACES` ids a cell from `faces().sides`, -1 for none, kept; `None` for surfaces and polyhedra): 1.5-2x faster streamlines on the aneurysm and the M6, bit for bit (`test_walking_to_the_last_cells_neighbours_changes_nothing`). Polygons locate in the triangles fanning them from their cell point (`views._PolygonLocation`, `t = 2k`, `pc = (0, w_a, w_b)`, so `_PolyhedralPointField.tet_value` reads them unchanged) and polylines on their segments (`_PolylineLocation`, `_PolylinePointField`); `by_id` has `_PolygonMesh` and `_PolylineMesh`, and every mesh says `NO_REFERENCE`, which the search and evaluation branch on. VTK 9.7.1's `vtkPolyhedron` is no reference for these (wrong `Derivatives` and `EvaluatePosition`; see section 13). See `test_polyhedra.py`, `test_probe.py`, `test_flow.py`, and `benchmarks/polyhedra_compare.py` for the cost against hexahedra. **Mixed cells (#307, phase 1 of the wiki's Mixed cells plan).** An `UnstructuredTopology` may hold polyhedra (type 42) beside shaped cells: `polyhedra=(face_offsets, face_points, cell_face_offsets, cell_faces, cell_face_sides)`, laid out as a `PolyhedralTopology`'s but `cell_face_offsets` per cell (a shaped cell's range empty), a polyhedron's connectivity its distinct points (VTK's); `has_polyhedra`, `num_polyhedral_faces`, `_POLYHEDRAL` (the five names). `groups()` gives the polyhedra one group of kind `views._MixedPolyhedra` (`cell(c)` = `ids[c]`, the global id; `index(c)` the position in the group, as a shaped group's; subgroups `_SelectedMixedPolyhedra`). `Faces._derive_mixed`: the polyhedral faces keep their stored ids and their sides from `cell_faces`; a shaped cell's face with the points of a polyhedral face with one side takes the free side (side 0 walking it as stored, side 1 reversed; the other way is refused), the shaped cells' other faces numbered after; `side_face`/`side_slot`/`side_orientation` cover the shaped groups only (`group_starts`), a polyhedron's are its `cell_faces`/`cell_face_sides`; a polyhedral face of more than four points has kind `POLYGON`, no row, and a `Polygon` group (`_PolygonFaces`). `Edges` puts the polyhedral faces' edges after the shaped entries (`face_edge`, `face_edge_sign`, indexed like `face_points`). `Shape.REFERENCE` (false on `_NoReference`) is the per-group test that replaces `reference_cells` as algorithms are ported (threshold's flags use it). `_extract._mixed_keep_cells` keeps cells and their polyhedra's faces. `vtk_to_dataset` reads a grid with polyhedra this way by default (`_mixed_polyhedra`: the polyhedra's copies matched by `_match_rings`, inside-out ones found by signed volumes from the rings, `orient` through `from_cell_faces`); `polyhedral="all"` (`True` deprecated) is the old all-polyhedra reading, which the VTK algorithm wrappers keep (`algorithms._converted`). `test_mixed_cells.READY` lists the calls of `test_dataset_devices.CALLS` that take mixed meshes, each held to the shaped mesh's answer (`_mixed` turns chosen cells of a shaped topology into polyhedra of the same faces) or the all-polyhedra reading's; every other must refuse the mixed mesh and the same mesh as all polyhedra alike (only what needs a reference element in every cell: `H1` above order 1, `L2`, `shrink`, `subdivide`), and `READY_2D` the same against a surface of all polygons. A new algorithm must take mixed meshes, or refuse them for what a polyhedron lacks. Phase 2 (per-cell work) is ported: the topology's `reference_cells` is false with polyhedra (so `H1` above order 1, `L2` and cell nodes refuse, by `spaces.reference_cells`), and the algorithms that tested it for the whole topology test `has_polyhedra` first and then go group by group, `group.shape.REFERENCE` choosing the shape path or the polyhedral one: `gradients` (cells: Green-Gauss on the polyhedra; points: a polyhedron's cell gradient at each of its corners, `_links._cell_values_at_corners`), `cell_centers`, `values_at_centers` (`_own_values` for cell data), `integrate` (`_mixed_cell_values`: quadrature, sub-tetrahedra, or value times measure), `project` (`_polyhedral_means` writes the shapes' cells after `_divided`; cell values at a polyhedron's corners through the same kernel), `cell_quality`, `traces` (`_polyhedral_traces`, the face's row being its stored walk; refused where a polyhedron has a face of more than four points, which `SideTraces` cannot hold, as AhmedML's do), `jump` and `upwind_flux` (point data on a mixed mesh is continuous order-1 `H1`, so neither takes traces: no jump, and the upwind value the face's points' mean, `_mean_upwind`, polygons included), `divergence`, `flow_quantities`; `interpolate` takes point values as on polyhedra. `corner_layout` gives the polyhedral group its connectivity's points, at `start + corners[index(c)]` (`polyhedral_corners`, kept on the topology), and `point_links` keys them by `corner_keys`. `test_mixed_cells.PER_CELL` holds a per-cell answer to the shaped mesh's on the shapes and the all-polyhedra mesh's on the polyhedra (`_three_ways`, a distorted mesh and a field that is not linear). Polygons (type 7) may stand beside triangles and quads, a polygon's connectivity its loop: on grouping, `_polygon_edges` derives their edges (matched among polygons, refusing an edge of three or opposite windings) into the same five arrays polyhedra give (two points a face; `has_polygons`), so the polygon group is a `_MixedPolyhedra` view of shape `Polygon` and `_derive_mixed` matches a shape's edge to the free side of a polygon's (candidates of 2-4 points). `mixed` (polyhedra or polygons; a property that groups the cells) is what algorithms test, `has_polyhedra` only where the faces are stored (as_polyhedra, merge_points, clip, tetrahedralize, the VTK writer); `_mixed_keep_cells` copies faces only for polyhedra. Phase 3 (filters that build a topology): `clip` of a mixed mesh (`_clip_polyhedra.clip_mixed`) keeps whole shapes and makes every other kept cell a polyhedron (`clip_parts` over `as_polyhedra` of the cut cells and the polyhedra, extracted with their input ids as fields), joined on points named `(p, p)` or `(low, high)`; a shape's table pieces would not conform with a polyhedron's clipped face. `contour` (`_mixed_contour`) joins the shape path's triangles (`_triangle_parts`) and López's polygons over the polyhedral group (`_lopez_polygons(only=)`) by the name both give a point, `(low * nlevels + level, high)`; `slice` follows. `extract_surface` writes `POLYGON` faces from the face arrays (and skips `_fresh_boundary`). `tetrahedralize` cones each polyhedron from a point it adds (`_refine._polyhedral_tets`), quads split from the corner of smallest rank as the shapes split them, larger faces fanned from points they add, the added points `Interpolate` averages. `merge_points` re-matches the polyhedra's faces through `_merged_polyhedra` and drops face fields; `as_polyhedra`, `check_winding`, `as_polygons`, `triangulate` (`_mixed_triangles`: tables and ear cutting into one set of slots), `surface_normals` (`_loop_relations`, `_rewound_loops`, `_loop_corner_normals`) and `feature_edges` take mixed meshes. The 2D sweep (`test_an_algorithm_takes_polygons_beside_shapes_or_refuses_them`, `READY_2D`) runs every call on a flat surface of quads with some made polygons. `vtk_to_dataset` reads a grid (or `vtkPolyData`) with polygons this way too, beside its triangles and quads; `polyhedral="all"` (`True` deprecated) gives the old `PolygonalTopology` (the VTK algorithm wrappers keep the all-polyhedra reading only for polyhedra). Phase 4 (cells by id): `by_id`'s cell classes say how a cell is located by `NO_REFERENCE`, 0 by its shape, 1 in its fan, 2 by its type (`fanned(e)`, a mixed mesh's `_MixedPolyhedralMesh` or `_MixedPolygonMesh`, the topology's arrays read by cell id); `_MeshSearch.find_ranked`, `find_from` (a hint's type picks `_well_inside_fan` or `_well_inside`) and `_PointValues` branch on it, the per-cell test compiled in only for 2 (the optimized LLVM IR of the search and advection kernels on hexahedra and on polyhedra was unchanged, but for names). `CellLocator` runs its fan kernels (star-shapedness, moved cell points, boxes, the cells' search) on the groups without a reference element and the shape kernels on the rest (`locator._for_cells`); `tets` is -1 on a mixed mesh's shapes, `moved_cell_points`' starts -1 there (`_unmoved`), and `cell_neighbors` stays `None` with polyhedra. `probe`'s cell-side evaluation picks the tets path per group. So `probe`, `voxelize`, `advect` and `streamlines` take mixed meshes. Phase 5 (pieces): `polyhedra.outward_rings` (a polyhedral or mixed topology's cells as faces wound out of them) and `mixed_from_rings` (cells plus their polyhedra's rings, matched by point set, as a mixed `UnstructuredTopology`) are what pieces are rebuilt from: `ghost_cells` classes a piece with polyhedra beside shapes as kind 3, and once any piece is, every unstructured piece sends rings (none for a shape) and `_polyhedra_with(..., cells=)` rebuilds the receiving piece mixed, so one without polyhedra takes them as ghosts; `merge_pieces` sends owned cells' rings on global point ids (`_owned_rings`, `_merged_rings`) and `_described`/`_rebuilt` carry the face arrays to the root. `generate_global_ids._boundary_points` takes a mixed topology's stored polyhedral faces (its first `num_polyhedral_faces` face ids) from their points, since one of five points or more has no row; `connected_components` over pieces uses it. `test_mixed_cells.mixed_pieces_across` runs on threads and through `_mixed_pieces_mpi.py` on 2 and 3 ranks. `vtk_to_dataset(polyhedral="split")` warns (`tack.dataset._deprecations.SPLIT`, removed in 0.9); `test_polyhedra._split` expects it. Performance on AhmedML (the wiki's numbers): `integrate` sums point data against per-point weights (`_Weights`: `_corner_weights`, `_polyhedron_corner_weights`, `_polygon_corner_weights`, summed over `point_links`) and cell data against masked measures (`_weighted_sum`, chunks on the device, f64 where it has it, then the host); a straight hexahedron's corner gradients come from its edges (`gradients._hexahedron_corner`, chosen by `_by_edges` at launch) and a 3-vector's from one inverse a corner (`_vector_point_gradients`, `_vector_edge_gradients`); `cell_quality` takes `conditioning` and edge flags and a straight cell's corner edges from `_tables`' neighbours; union-find kernels test `changed[0]` before their atomic (one counter hammered by every hook cost a CPU most of a pass). A hexahedron-specific integral kernel (trilinear map by its edge combinations) ran 2.7x slower than the general quadrature and was dropped; so was sorting buckets on local key copies (10%: the cost is the keys' random reads, which a scatter of the keys themselves would remove). Phase 6 (the whole): `topology._refuse_mixed` is gone; `test_dataset_devices.MAKERS` adds `mixed` (`_mixed_hexes`) and `polygons` to the device sweeps, every call on the second device and the device without f64 (`_called` checks the refusals). `Set.from_sides` looks a mixed mesh's polyhedra and polygons up in `cell_face_offsets`/`cell_faces` and its shapes by masks over the reference groups. On AhmedML a mixed reading's point gradients are the shapes' at the corners of its 5,493 tangled hexahedra (scaled Jacobian <= 0), up to 2e9, as on the hexahedra alone; the all-polyhedra reading's Green-Gauss stays bounded. diff --git a/packages/tack-dataset/src/tack/dataset/algorithms/probe.py b/packages/tack-dataset/src/tack/dataset/algorithms/probe.py index a34ab7c6..1531d633 100644 --- a/packages/tack-dataset/src/tack/dataset/algorithms/probe.py +++ b/packages/tack-dataset/src/tack/dataset/algorithms/probe.py @@ -7,7 +7,7 @@ import tack from tack import arrays -from tack.dataset import ids, units +from tack.dataset import ids, units, views from tack.dataset.algorithms._common import _field, _stand_in from tack.dataset.algorithms._extract import _vertices from tack.dataset.buckets import bucket_groups @@ -42,7 +42,8 @@ def _evaluate_in_tets(cells, u, links, link_points, tets, pcs, out): def _evaluate_in_moved_tets(cells, u, starts, weights, links, link_points, tets, pcs, out): # As _evaluate_in_tets, point data in polyhedra whose cell points the locator # moved (CellLocator.moved_cell_points): there, the cell point's value is the - # sum of the points' values by its weights. + # sum of the points' values by its weights. In a cell with no kernel + # (views.NO_KERNEL_TET), the value is its mean value coordinates' sum. for c in cells: e = cells.entity_id(c) if links[e + 1] > links[e]: @@ -55,7 +56,10 @@ def _evaluate_in_moved_tets(cells, u, starts, weights, links, link_points, tets, u0 += (u.corner_value(c, j) - first) * weights[s + j] for n in range(links[e], links[e + 1]): q = link_points[n] - out[q] = u.tet_value_from(c, tets[q], pcs[q], u0) + if tets[q] == views.NO_KERNEL_TET: + out[q] = cells.mvc_value(c, cells.cell_point(c) + pcs[q], u) + else: + out[q] = u.tet_value_from(c, tets[q], pcs[q], u0) @tack.kernel diff --git a/packages/tack-dataset/src/tack/dataset/by_id.py b/packages/tack-dataset/src/tack/dataset/by_id.py index cb7ef5ce..183ca72d 100644 --- a/packages/tack-dataset/src/tack/dataset/by_id.py +++ b/packages/tack-dataset/src/tack/dataset/by_id.py @@ -184,19 +184,28 @@ def cell_type(self, e): @tack.func def locate(self, c, x, slack): - """``_PolyhedralLocation.locate`` from its cell point; a cell the locator found - no kernel for (``moved_cell_points``' -2) holds nothing.""" + """``_PolyhedralLocation.locate`` from its cell point; in a cell the locator + found no kernel for (``moved_cell_points``' -2), by its winding number + (``locate_by_winding``).""" t, pc, inside = self.locate_held(c, x, slack, 1) return t, pc, inside @tack.func def locate_held(self, c, x, slack, near): """``locate``, seeking the nearest sub-tetrahedron only where ``near`` is 1 - (``_PolyhedralLocation.locate_held_from``).""" - t, pc, inside = self.locate_held_from(c, self.cell_point(c), x, slack, near) + (``_PolyhedralLocation.locate_held_from``); in a cell with no kernel, one + within the slack only where ``near`` is 1.""" + p = self.cell_point(c) skipped = self.moved_starts[c] if self.MOVED == 1 else -1 + t = -1 + pc = x - x + inside = 0 if skipped == -2: - t = -1 + t, pc, inside = self.locate_by_winding(c, p, x, slack) + if inside == 0 and near == 0: + t = -1 + else: + t, pc, inside = self.locate_held_from(c, p, x, slack, near) return t, pc, inside @tack.func @@ -220,28 +229,37 @@ def cell_point(self, c): @tack.func def tet_value_of(self, field, e, t, pc): """Point data at ``pc`` in sub-tetrahedron ``t``: linear there, the cell point - taking its points' values as its position takes their positions.""" - k, j = self.tet_face(e, t) - n = self.side_num_points(e, k) - nxt = j + 1 if j + 1 < n else 0 - count = self.num_points(e) - s = self.moved_starts[e] if self.MOVED == 1 else -1 - v0 = field.values[self.point_id(e, 0)] - if s >= 0: - first = v0 - for i in range(1, count): - v0 += (field.values[self.point_id(e, i)] - first) * self.moved_weights[s + i] + taking its points' values as its position takes their positions. In a cell + with no kernel (``views.NO_KERNEL_TET``), ``pc`` is the point less the cell + point, and the value its mean value coordinates' sum (``mvc_value``).""" + result = field.values[self.point_id(e, 0)] + # MOVED is compiled in: a mesh whose cells all have kernels (most) compiles + # the mean value coordinates out. + if self.MOVED == 1 and t == views.NO_KERNEL_TET: + result = self.mvc_value(e, self.cell_point(e) + pc, field) else: - for i in range(1, count): - v0 += field.values[self.point_id(e, i)] - v0 = v0 / count - vf = field.values[self.side_point_id(e, k, 0)] - for i in range(1, n): - vf += field.values[self.side_point_id(e, k, i)] - vf = vf / n - return (v0 + pc[0] * (vf - v0) - + pc[1] * (field.values[self.side_point_id(e, k, j)] - v0) - + pc[2] * (field.values[self.side_point_id(e, k, nxt)] - v0)) + k, j = self.tet_face(e, t) + n = self.side_num_points(e, k) + nxt = j + 1 if j + 1 < n else 0 + count = self.num_points(e) + s = self.moved_starts[e] if self.MOVED == 1 else -1 + v0 = field.values[self.point_id(e, 0)] + if s >= 0: + first = v0 + for i in range(1, count): + v0 += (field.values[self.point_id(e, i)] - first) * self.moved_weights[s + i] + else: + for i in range(1, count): + v0 += field.values[self.point_id(e, i)] + v0 = v0 / count + vf = field.values[self.side_point_id(e, k, 0)] + for i in range(1, n): + vf += field.values[self.side_point_id(e, k, i)] + vf = vf / n + result = (v0 + pc[0] * (vf - v0) + + pc[1] * (field.values[self.side_point_id(e, k, j)] - v0) + + pc[2] * (field.values[self.side_point_id(e, k, nxt)] - v0)) + return result @tack.device_class @@ -737,7 +755,10 @@ def _well_inside_fan(self, p, e): kind = 0 pc = p - p t = -1 - if (held == 1 and tet >= 0 and min(tpc[0], tpc[1], tpc[2]) >= shapes.WELL_INSIDE + # A cell with no kernel (views.NO_KERNEL_TET) may overlap its neighbours, so + # holding p is not enough to stop the search there. + if (held == 1 and tet >= 0 and tet != views.NO_KERNEL_TET + and min(tpc[0], tpc[1], tpc[2]) >= shapes.WELL_INSIDE and tpc[0] + tpc[1] + tpc[2] <= 1.0 - shapes.WELL_INSIDE): found = e kind = self.cells.cell_type(e) @@ -1127,6 +1148,11 @@ class _PointValues: def __init__(self, values): self.values = values + @tack.func + def get(self, p): + """Point ``p``'s value (as a field view's ``get``, for ``mvc_value``).""" + return self.values[p] + @tack.func def value(self, mesh, e, kind, pc, tet): v = self.values[mesh.cells.point_id(e, 0)] diff --git a/packages/tack-dataset/src/tack/dataset/locator.py b/packages/tack-dataset/src/tack/dataset/locator.py index 19a60bd3..592c320a 100644 --- a/packages/tack-dataset/src/tack/dataset/locator.py +++ b/packages/tack-dataset/src/tack/dataset/locator.py @@ -40,7 +40,6 @@ """ import copy -import warnings from typing import NamedTuple import numpy as np @@ -77,8 +76,9 @@ class Locations(NamedTuple): _TOLERANCE = 1e-3 #: ``moved_cell_points``' start for a polyhedron with no kernel: no point inside it -#: sees all of its faces, so it holds no points (found, if anywhere, in a neighbour -#: it overlaps). +#: sees all of its faces, so its sub-tetrahedra overlap. It holds a point by its +#: winding number (``views._PolyhedralLocation.locate_by_winding``), the location's +#: sub-tetrahedron ``views.NO_KERNEL_TET``. _SKIPPED = tack.constant(-2) @@ -374,7 +374,7 @@ def _unmoved(cells, starts): @tack.kernel def _skip(bad, starts): - # A cell still not star-shaped from its point holds no points. + # A cell still not star-shaped from its point is located by its winding number. for e in range(bad.shape[0]): if bad[e] == 1: starts[e] = _SKIPPED @@ -416,8 +416,6 @@ def _test_points_in_polyhedra(cells, points, lo, hi, bin_offsets, bin_points, ox j1 = min(tack.i64(floor((b[1] + slack - oy) * iy)), ny - 1) k1 = min(tack.i64(floor((b[2] + slack - oz) * iz)), nz - 1) skipped = starts[e] if moved == 1 else -1 - if skipped == _SKIPPED: - k1 = k0 - 1 # no kernel: it holds no points if hidden == 1 and (tack.i32(marks[e]) & _MASKED) != 0: k1 = k0 - 1 # left out: it holds no points for k in range(k0, k1 + 1): @@ -430,7 +428,13 @@ def _test_points_in_polyhedra(cells, points, lo, hi, bin_offsets, bin_points, ox if (x[0] >= a[0] - slack and x[0] <= b[0] + slack and x[1] >= a[1] - slack and x[1] <= b[1] + slack and x[2] >= a[2] - slack and x[2] <= b[2] + slack): - t, pc, inside = cells.locate_from(c, middle, x, slack) + t = -1 + pc = x - x + inside = 0 + if skipped == _SKIPPED: + t, pc, inside = cells.locate_by_winding(c, middle, x, slack) + else: + t, pc, inside = cells.locate_from(c, middle, x, slack) if t >= 0: rank = e if inside == 1 else e + ncells if write == 0: @@ -694,10 +698,10 @@ def __init__(self, data, density=1.0, levels=None): #: sum of its points by ``weights[starts[c] + j]`` (``starts[c]`` -1 for a cell #: that keeps the mean). ``find``'s ``tets`` and ``pcs`` there are relative to #: that point; ``probe`` and advection evaluate there. A polyhedron with no - #: kernel (tangled, inside out, a face whose fan folds, no volume) has - #: ``starts[c]`` -2 and holds no points: one inside it is found in a - #: neighbour it overlaps, or nowhere, and a particle reaching it stops as at - #: the mesh's edge. Making it is warned about. + #: kernel (tangled, inside out, a face whose fan folds) has ``starts[c]`` -2: + #: it holds a point by its winding number, and point data there is + #: interpolated by mean value coordinates (``views.NO_KERNEL_TET``). One with + #: no volume winds round nothing, so holds nothing. self.moved_cell_points = None if n and self.polyhedral: bad = tack.zeros((n,), tack.i32) @@ -714,12 +718,6 @@ def __init__(self, data, density=1.0, levels=None): count = int(bad.numpy().sum()) if count and dimension == 3: _skip(bad, self.moved_cell_points[0]) - warnings.warn( - f"{count} of the {n} cells are not star-shaped from any point found " - "inside them -- none sees all of their faces (tangled or inside-out " - "cells) -- or have no volume: they hold no points. A point inside " - "one is found in a neighbour it overlaps, or nowhere; a particle " - "reaching one stops.", stacklevel=2) elif count: raise NotImplementedError( f"{count} of the {n} cells are not star-shaped from their cell point " diff --git a/packages/tack-dataset/src/tack/dataset/views.py b/packages/tack-dataset/src/tack/dataset/views.py index 2a69333c..0767a04a 100644 --- a/packages/tack-dataset/src/tack/dataset/views.py +++ b/packages/tack-dataset/src/tack/dataset/views.py @@ -33,6 +33,8 @@ the cell ``c`` the loop is at. """ +import math + import tack from tack.dataset.ghosts import _before from tack.dataset.shapes import HOLD_TOLERANCE, NEWTON_DIVERGED, NEWTON_TOLERANCE, _symmetric @@ -327,7 +329,8 @@ def tet_face(self, c, t): edge by edge, as ``side_point_id`` walks them.""" k = 0 j = t - while j >= self.side_num_points(c, k): + last = self.num_faces(c) - 1 + while j >= self.side_num_points(c, k) and k < last: j -= self.side_num_points(c, k) k += 1 return k, j @@ -391,6 +394,26 @@ def _closest_on_triangle(p, a, b, c): return w +#: A polyhedral location's sub-tetrahedron in a cell with no kernel, where no +#: point inside sees all of its faces (tangled, inside out, a face whose own fan +#: folds), so its sub-tetrahedra overlap: the cell holds a point by its winding +#: number (``locate_by_winding``), the location's ``pc`` is the point less the +#: cell point, and point data there is its mean value coordinates' sum +#: (``mvc_value``). Positive and past any cell's sub-tetrahedra, so callers that +#: test ``t >= 0`` for "found" need no change. +NO_KERNEL_TET = tack.constant(1 << 30, tack.i32) + +#: Mean value coordinates' tolerances: a point this close to a triangle's vertex +#: (a share of the triangle's farthest vertex) takes the vertex's value; one whose +#: triangle's arcs sum this close to 2 pi is on it, and takes its barycentric +#: weights; a triangle whose sines are this small is edge-on and skipped. The +#: angle's is VTK's (``vtkMeanValueCoordinatesInterpolator``): the arcs' shortfall +#: shrinks as the square of the distance to the triangle, so 1e-5 snapped points +#: 0.3% of a triangle away onto it. +_MVC_VERTEX = tack.constant(1e-6) +_MVC_ANGLE = tack.constant(1e-8) + + class _PolyhedralLocation: """Where a point is in a polyhedron, which has no parametric coordinates: in which of its *sub-tetrahedra*, and where in that one (``docs/vis-guide/design/polyhedra.md``, @@ -525,6 +548,137 @@ def _sweep(self, c, p, x, slack, nearest): k += 1 return tet, pc + @tack.func + def winding_number(self, c, x): + """How many times the cell's faces wind round ``x``: the sum of the solid + angles of its face triangles (each face fanned from its face point, as + its neighbour fans it, so the cells' surfaces meet) over 4 pi, by Van + Oosterom and Strackee's formula. 1 inside a cell wound outward, -1 inside + one wound inward, 0 outside, whatever the cell's shape.""" + total = x[0] - x[0] + for k in range(self.num_faces(c)): + n = self.side_num_points(c, k) + f = self.face_point(c, k) - x + lf = f.norm() + first = self.side_position(c, k, 0) - x + a = first + for j in range(n): + b = first + if j + 1 < n: + b = self.side_position(c, k, j + 1) - x + la = a.norm() + lb = b.norm() + num = f.dot(a.cross(b)) + den = lf * la * lb + f.dot(a) * lb + f.dot(b) * la + a.dot(b) * lf + total += 2.0 * atan2(num, den) + a = b + return total / (4.0 * math.pi) + + @tack.func + def locate_by_winding(self, c, p, x, slack): + """``(t, pc, inside)`` in a cell with no kernel: ``t`` `NO_KERNEL_TET` and + ``inside`` 1 where its winding number round ``x`` is 1 or -1; else, where a + face triangle is within ``slack`` of ``x``, ``inside`` 0; else ``t`` -1. + ``pc`` is ``x - p``, ``p`` the cell point, where `mvc_value` evaluates.""" + t = -1 + inside = 0 + if abs(self.winding_number(c, x)) > 0.5: + t = NO_KERNEL_TET + inside = 1 + else: + best = slack * slack + for k in range(self.num_faces(c)): + n = self.side_num_points(c, k) + f = self.face_point(c, k) - x + first = self.side_position(c, k, 0) - x + a = first + for j in range(n): + b = first + if j + 1 < n: + b = self.side_position(c, k, j + 1) - x + r = _closest_on_triangle(x - x, f, a, b) + e = r[0] * f + r[1] * a + r[2] * b + if e.dot(e) <= best: + t = NO_KERNEL_TET + a = b + return t, x - p, inside + + @tack.func + def mvc_value(self, c, x, u): + """Point data at ``x`` by mean value coordinates over the cell's face + triangles (Ju, Schaefer and Warren, 2005, in its robust form, as + ``vtkMeanValueCoordinatesInterpolator``): defined in any closed + polyhedron, convex or not, and exact for a linear field. A face point + takes the mean of its face's values, as its position is the mean of its + positions. ``u.get(p)`` is point ``p``'s value.""" + zero = u.get(self.point_id(c, 0)) + zero = zero - zero + acc = zero + weight = x[0] - x[0] + exact = 0 + result = zero + for k in range(self.num_faces(c)): + n = self.side_num_points(c, k) + fv = u.get(self.side_point_id(c, k, 0)) + for j in range(1, n): + fv += u.get(self.side_point_id(c, k, j)) + fv = fv / n + f = self.face_point(c, k) - x + for j in range(n): + nxt = j + 1 if j + 1 < n else 0 + if exact == 0: + a = self.side_position(c, k, j) - x + b = self.side_position(c, k, nxt) - x + av = u.get(self.side_point_id(c, k, j)) + bv = u.get(self.side_point_id(c, k, nxt)) + d0 = f.norm() + d1 = a.norm() + d2 = b.norm() + m = max(d0, d1, d2) * _MVC_VERTEX + if d0 <= m: + result = fv + exact = 1 + elif d1 <= m: + result = av + exact = 1 + elif d2 <= m: + result = bv + exact = 1 + else: + u0 = f / d0 + u1 = a / d1 + u2 = b / d2 + t0 = 2.0 * asin(min((u1 - u2).norm() * 0.5, 1.0)) + t1 = 2.0 * asin(min((u2 - u0).norm() * 0.5, 1.0)) + t2 = 2.0 * asin(min((u0 - u1).norm() * 0.5, 1.0)) + h = 0.5 * (t0 + t1 + t2) + if math.pi - h < _MVC_ANGLE: + # On the triangle: its barycentric weights. + w0 = sin(t0) * d1 * d2 + w1 = sin(t1) * d2 * d0 + w2 = sin(t2) * d0 * d1 + result = (w0 * fv + w1 * av + w2 * bv) / (w0 + w1 + w2) + exact = 1 + else: + sh = sin(h) + c0 = 2.0 * sh * sin(h - t0) / (sin(t1) * sin(t2)) - 1.0 + c1 = 2.0 * sh * sin(h - t1) / (sin(t2) * sin(t0)) - 1.0 + c2 = 2.0 * sh * sin(h - t2) / (sin(t0) * sin(t1)) - 1.0 + sign = 1.0 if u0.dot(u1.cross(u2)) >= 0.0 else -1.0 + s0 = sign * sqrt(max(1.0 - c0 * c0, 0.0)) + s1 = sign * sqrt(max(1.0 - c1 * c1, 0.0)) + s2 = sign * sqrt(max(1.0 - c2 * c2, 0.0)) + if (abs(s0) > _MVC_ANGLE and abs(s1) > _MVC_ANGLE + and abs(s2) > _MVC_ANGLE): + w0 = (t0 - c1 * t2 - c2 * t1) / (d0 * sin(t1) * s2) + w1 = (t1 - c2 * t0 - c0 * t2) / (d1 * sin(t2) * s0) + w2 = (t2 - c0 * t1 - c1 * t0) / (d2 * sin(t0) * s1) + acc += w0 * fv + w1 * av + w2 * bv + weight += w0 + w1 + w2 + if exact == 0: + result = acc / weight + return result + class _PolygonLocation: """Where a point is in a polygon, a 2D cell with no parametric coordinates: in @@ -547,6 +701,13 @@ def cell_point(self, c): x += self.point_position(self.point_id(c, j)) return x / n + @tack.func + def locate_by_winding(self, c, p, x, slack): + """``locate_from``: a polygon is never marked as having no kernel, but the + locator's search over polyhedra, which it shares, names this method.""" + t, pc, inside = self.locate_from(c, p, x, slack) + return t, pc, inside + @tack.func def locate(self, c, x, slack): """``(t, pc, inside)``, as ``_PolyhedralLocation.locate``.""" @@ -598,6 +759,13 @@ def cell_point(self, c): x += self.point_position(self.point_id(c, j)) return x / n + @tack.func + def locate_by_winding(self, c, p, x, slack): + """``locate_from``: a polyline is never marked as having no kernel, but the + locator's search over polyhedra, which it shares, names this method.""" + t, pc, inside = self.locate_from(c, p, x, slack) + return t, pc, inside + @tack.func def locate(self, c, x, slack): t, pc, inside = self.locate_from(c, self.cell_point(c), x, slack) diff --git a/packages/tack-dataset/tests/test_mixed_cells.py b/packages/tack-dataset/tests/test_mixed_cells.py index 46e4f556..eeeaca6f 100644 --- a/packages/tack-dataset/tests/test_mixed_cells.py +++ b/packages/tack-dataset/tests/test_mixed_cells.py @@ -1419,18 +1419,23 @@ def _l_prism_beside_a_hexahedron(): beside a hexahedron (a shape) where its cube was.""" from test_polyhedra import _l_prism - top, pts = _l_prism() + return _prism_beside_a_hexahedron(*_l_prism()) + + +def _prism_beside_a_hexahedron(top, pts): + """A polyhedral topology's first cell, beside a hexahedron (a shape) where its + second, a cube of the last eight points, was.""" first = top.cell_offsets.numpy()[:2] faces = top.cell_faces.numpy()[first[0]:first[1]] fo, fp = top.face_offsets.numpy(), top.face_points.numpy() face_points = np.concatenate([fp[fo[f]:fo[f + 1]] for f in faces]) face_offsets = np.r_[0, np.cumsum([fo[f + 1] - fo[f] for f in faces])] sides = top.cell_face_sides.numpy()[first[0]:first[1]] - c = 14 + c = len(pts) - 8 hexahedron = [c + 0, c + 1, c + 3, c + 2, c + 4, c + 5, c + 7, c + 6] topology = td.UnstructuredTopology( - np.array([POLYHEDRON, 12], np.uint8), np.array([0, 14, 22]), - np.r_[np.arange(14), hexahedron], num_points=len(pts), + np.array([POLYHEDRON, 12], np.uint8), np.array([0, c, c + 8]), + np.r_[np.arange(c), hexahedron], num_points=len(pts), polyhedra=(face_offsets, face_points, np.array([0, len(faces), len(faces)]), np.arange(len(faces)), sides)) return td.DataSet(topology, tack.array(pts, tack.vec3(tack.f64))) @@ -1455,6 +1460,25 @@ def test_a_mixed_meshs_concave_polyhedron_is_fanned_from_a_point_inside(many): want[valid == 1], rtol=1e-12) +@pytest.mark.parametrize("many", [False, True], ids=["from the cells", "from the points"]) +def test_a_mixed_meshs_polyhedron_with_no_kernel_holds_its_points(many): + """test_polyhedra's C-shaped prism, which has no kernel, beside a hexahedron: it + holds its points by its winding number, and mean value coordinates hold a linear + field there, as in a polyhedral topology.""" + from test_polyhedra import _C_HELD, _C_PROBES, _c_prism, _linear + + data = _prism_beside_a_hexahedron(*_c_prism()) + data.fields["u"] = td.Field(td.H1(data), tack.array(_linear(data.positions()))) + locator = td.CellLocator(data) + np.testing.assert_array_equal(locator.moved_cell_points[0].numpy(), [-2, -1]) + stride = 100 if many else 1 + out = td.probe(data, np.repeat(_C_PROBES, stride, axis=0), locator=locator) + valid = out.fields["valid"].values.numpy()[::stride] + np.testing.assert_array_equal(valid, _C_HELD) + np.testing.assert_allclose(out.fields["u"].values.numpy()[::stride][valid == 1], + _linear(_C_PROBES)[valid == 1], atol=1e-12) + + @pytest.mark.parametrize("neighbors", [False, True]) def test_particles_cross_a_mixed_mesh_as_the_shaped_one(neighbors): # A linear velocity, exact in a hexahedron and in a polyhedron's sub-tetrahedra: diff --git a/packages/tack-dataset/tests/test_polyhedra.py b/packages/tack-dataset/tests/test_polyhedra.py index b665e54a..d2f89656 100644 --- a/packages/tack-dataset/tests/test_polyhedra.py +++ b/packages/tack-dataset/tests/test_polyhedra.py @@ -14,6 +14,7 @@ import os import types +import warnings import numpy as np import pytest @@ -1257,35 +1258,92 @@ def test_sub_tetrahedra_reproduce_a_linear_field(backend, name): np.testing.assert_allclose(values[:, 0], values[:, 1], atol=1e-5) -def test_a_cell_not_star_shaped_from_any_point_holds_no_points(backend): +def _c_prism(): """A C-shaped prism whose top and bottom are each one face: their face points are in the notch, so their own fans fold over, and no cell point makes every - sub-tetrahedron positive. The locator warns and leaves it out -- a point inside - it is found nowhere, and a particle there stops -- rather than find points it - does not hold, or refuse the whole mesh. Beside it, a cube still holds its - points.""" + sub-tetrahedron positive -- it has no kernel. Beside it, a cube, which keeps its + mean.""" ring = np.array([[0, 0], [3, 0], [3, 1], [1, 1], [1, 2], [3, 2], [3, 3], [0, 3]], float) cube = np.array([[i & 1, (i >> 1) & 1, (i >> 2) & 1] for i in range(8)], float) cube[:, 0] += 5.0 - pts = np.r_[np.c_[ring, np.zeros(8)], np.c_[ring, np.ones(8)], cube].astype(np.float32) + pts = np.r_[np.c_[ring, np.zeros(8)], np.c_[ring, np.ones(8)], cube] faces = [list(range(8))[::-1], list(range(8, 16))] faces += [[j, (j + 1) % 8, 8 + (j + 1) % 8, 8 + j] for j in range(8)] cube_faces = [[16, 18, 19, 17], [20, 21, 23, 22], [16, 17, 21, 20], [18, 22, 23, 19], [16, 20, 22, 18], [17, 19, 23, 21]] - data = td.DataSet(td.PolyhedralTopology.from_cell_faces([faces, cube_faces], 24, pts, - orient=True), pts) - data.fields["v"] = td.Field(td.H1(data), tack.array(np.tile([1.0, 0.0, 0.0], (24, 1)) - .astype(np.float32), tack.vec3())) - with pytest.warns(UserWarning, match="1 of the 2 cells are not star-shaped"): + top = td.PolyhedralTopology.from_cell_faces([faces, cube_faces], 24, pts, orient=True) + return top, pts + + +#: Points in the C (its spine, both arms, a corner, its top face, the notch's wall), +#: one in the notch, outside it, and one in the cube. +_C_PROBES = np.array([[0.5, 1.5, 0.5], [2.5, 0.5, 0.3], [2.5, 2.5, 0.7], [0.2, 0.2, 0.9], + [0.5, 1.5, 1.0], [1.0, 1.5, 0.5], [2.0, 1.5, 0.5], [5.5, 0.5, 0.5]]) +_C_HELD = [1, 1, 1, 1, 1, 1, 0, 1] + + +def _linear(x): + return 2 * x[:, 0] + 3 * x[:, 1] - x[:, 2] + 1 + + +@pytest.mark.parametrize("many", [False, True], ids=["from the cells", "from the points"]) +def test_a_cell_with_no_kernel_holds_its_points_by_winding_number(backend, many): + """A cell with no kernel (``_c_prism``) holds a point where its faces wind round it + once, and point data there is interpolated by mean value coordinates, which are + exact for a linear field: probes find it in the C and not in the notch, and a + particle runs up its spine to the far end. No warning: the cell is handled.""" + top, pts = _c_prism() + data = td.DataSet(top, pts.astype(np.float32)) + x = data.positions().astype(np.float64) + data.fields["u"] = td.Field(td.H1(data), tack.array(_linear(x).astype(np.float32))) + data.fields["v"] = td.Field(td.H1(data), tack.array( + np.tile([0.0, 1.0, 0.0], (len(x), 1)).astype(np.float32), tack.vec3())) + with warnings.catch_warnings(): + warnings.simplefilter("error") locator = td.CellLocator(data) - starts = locator.moved_cell_points[0].numpy() - np.testing.assert_array_equal(starts, [-2, -1]) - for many in (1, 100): # from the cells, and from the points - where = np.repeat([[0.5, 1.5, 0.5], [5.5, 0.5, 0.5]], many, axis=0) - found = locator.find(where).cells.numpy()[::many] - np.testing.assert_array_equal(found, [-1, 1]) - end = td.advect(data, "v", np.array([[0.5, 1.5, 0.5]]), 0.1, 5, locator=locator) - assert not end.fields["status"].values.numpy()[0] & td.ParticleStatus.SUCCESS + np.testing.assert_array_equal(locator.moved_cell_points[0].numpy(), [-2, -1]) + stride = 100 if many else 1 # many: the points' search + out = td.probe(data, np.repeat(_C_PROBES, stride, axis=0), locator=locator) + valid = out.fields["valid"].values.numpy()[::stride] + np.testing.assert_array_equal(valid, _C_HELD) + got = out.fields["u"].values.numpy()[::stride] + np.testing.assert_allclose(got[valid == 1], _linear(_C_PROBES)[valid == 1], atol=1e-5) + end = td.advect(data, "v", np.array([[0.5, 0.5, 0.5]]), 0.05, 100, locator=locator) + assert end.fields["status"].values.numpy()[0] & td.ParticleStatus.SPATIAL_BOUNDS + p = end.positions()[0] + np.testing.assert_allclose(p[[0, 2]], [0.5, 0.5], atol=1e-5) + assert 3.0 <= p[1] < 3.06 + + +def test_mean_value_coordinates_are_exact_in_f64(f64_backend): + """Mean value coordinates hold a linear field, a vector one too, at points all over + a cell with no kernel, near and on its faces included, to rounding.""" + top, pts = _c_prism() + data = td.DataSet(top, pts, dtype=tack.f64) + x = data.positions() + data.fields["u"] = td.Field(td.H1(data), tack.array(_linear(x))) + data.fields["w"] = td.Field(td.H1(data), tack.array( + np.c_[x[:, 1] - x[:, 2], 2 * x[:, 0], x[:, 0] + x[:, 1] + x[:, 2]], tack.vec3(tack.f64))) + rng = np.random.default_rng(7) + where = rng.uniform([0, 0, 0], [3, 3, 1], (2000, 3)) + where[:20, 0] = 0.0 # on the spine's outer face + where[20:40, :2] = [[1.0, 1.5]] # on the notch's wall + out = td.probe(data, where) + held = out.fields["valid"].values.numpy() == 1 + notch = (where[:, 0] > 1) & (where[:, 1] > 1) & (where[:, 1] < 2) + # In the notch, a point within the locator's tolerance (0.1% of the diagonal) + # of the cell's faces is near enough to count: of the notch's walls, or of the + # top or bottom (fanned from its face point, in the notch, so over it). + slack = 1e-3 * np.sqrt(19.0) + depth = np.minimum.reduce([where[:, 0] - 1, where[:, 1] - 1, 2 - where[:, 1], + where[:, 2], 1 - where[:, 2]]) + assert held[~notch].all() + assert not held[notch & (depth > slack)].any() + np.testing.assert_allclose(out.fields["u"].values.numpy()[held], _linear(where)[held], + atol=1e-12) + w = where[held] + np.testing.assert_allclose(out.fields["w"].values.numpy()[held], + np.c_[w[:, 1] - w[:, 2], 2 * w[:, 0], w.sum(axis=1)], atol=1e-12) def _l_prism(): @@ -1359,16 +1417,23 @@ def test_a_moved_cell_point_is_exact_in_f64(f64_backend): 2 * probes[:, 0] + 3 * probes[:, 1] - probes[:, 2], atol=1e-13) -def test_an_inside_out_cell_has_no_kernel(backend): - """A cube wound inward: no point sees all of its faces from inside, so it holds no - points, with a warning that says why.""" +def test_an_inside_out_cell_holds_its_points(backend): + """A cube wound inward has no kernel (no point sees all of its faces from inside), + but its faces wind round its inside all the same, once the other way: it holds + its points, and a linear field there is exact.""" cube = np.array([[i & 1, (i >> 1) & 1, (i >> 2) & 1] for i in range(8)], np.float32) faces = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]] data = td.DataSet(td.PolyhedralTopology.from_cell_faces([faces], 8), cube) - with pytest.warns(UserWarning, match="no volume|none sees all"): - locator = td.CellLocator(data) - assert locator.find([[0.5, 0.5, 0.5]]).cells.numpy()[0] == -1 + data.fields["u"] = td.Field(td.H1(data), tack.array(_linear(cube.astype(np.float64)) + .astype(np.float32))) + locator = td.CellLocator(data) + assert locator.moved_cell_points[0].numpy()[0] == -2 + where = np.array([[0.5, 0.5, 0.5], [0.1, 0.8, 0.3], [1.5, 0.5, 0.5]]) + out = td.probe(data, where, locator=locator) + np.testing.assert_array_equal(out.fields["valid"].values.numpy(), [1, 1, 0]) + np.testing.assert_allclose(out.fields["u"].values.numpy()[:2], _linear(where)[:2], + atol=1e-5) def test_global_ids_over_polyhedral_and_shape_pieces():