Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ All notable changes to FEAScript-core are documented in this file. The format is
flat faces of a 3D mesh can be solved this way. Nodes that no 2D element uses are removed. 2D elements that are
not in a plane, or a mesh with no usable element left, still throw `UNSUPPORTED_MESH`, naming what was left out

### Fixed

- The triangle mesh generator no longer leaves a triangle with two sides on the boundary, as it did in some corners
of a domain ([#147](https://github.com/FEAScript/FEAScript-core/issues/147)). With velocity set on both walls,
five of the six velocity nodes of such a quadratic triangle were fixed, and the creeping flow near the corner
was wrong: in the lid-driven cavity with `size` 0.35, 0.3 or 0.15, the strongest return flow moved into a lid
corner. A vertex in the middle of the triangle's inner side now splits it, and the halves are refined to
`minAngle` again. A triangle with three sides on the boundary is split at its centroid. A corner of less than
twice `minAngle` keeps its triangle, since its halves would have smaller angles. Meshes that had such triangles
get a few more elements

### Deprecated

- The mesh properties of 0.4: `nodesXCoordinates`, `nodesYCoordinates`, `nodalNumbering` (from 1),
Expand Down
65 changes: 63 additions & 2 deletions src/mesh/triangleMesh.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import { basicLog, debugLog } from "../utilities/logging.js";
* - At a small angle between two input segments, the segments are split at concentric shells (lengths in powers
* of two from the corner), and a skinny triangle whose short edge joins two shell vertices at the same distance
* from the corner is kept (Miller, Pav and Walkington), so that the refinement stops
* - A triangle with two or three sides on the boundary, as at a corner of the domain, is split, and the halves
* are refined again (see splitCornerTriangles)
* The vertices are inserted in passes, each rebuilding the triangulation. In a pass, a bad triangle gets its vertex
* only if no vertex accepted earlier in the pass lies in its circumcircle, i.e. only if the triangle would still
* exist after those vertices; the pass is then the same as inserting the vertices one by one in that order
Expand All @@ -59,7 +61,8 @@ const MAX_PASSES = 10000;
* of the element center for a mesh size that varies; the largest element area is that of the equilateral
* triangle of this side. Without it, only the angles are refined
* @param {number} [options.minAngle=20] - The smallest angle of the elements, in degrees. Ruppert's refinement
* always stops below 20.7 degrees, and usually up to about 33; above that, it may reach maxNodes
* always stops below 20.7 degrees, and usually up to about 33; above that, it may reach maxNodes. Every element
* has at most one side on the boundary, except at a corner of less than twice minAngle
* @param {"linear" | "quadratic"} [options.elementOrder="linear"] - "linear" (3-node) or "quadratic" (6-node)
* triangles
* @param {number} [options.maxNodes=100000] - The limit on the number of vertices (the corner nodes of the
Expand Down Expand Up @@ -94,7 +97,11 @@ export function generateTriangleMesh(
maxArea = areaOf(size);
}
const input = readInput(normalized, { maxArea, minAngle, elementOrder, maxNodes });
const triangulation = refine(input);
// Refine, split the triangles with two or three sides on the boundary, and refine the halves again
let triangulation = refine(input);
for (let round = 0; round < 10 && splitCornerTriangles(input, triangulation) > 0; round++) {
triangulation = refine(input);
}
const parsedMesh = toParsedMesh(input, triangulation);
const mesh = toMeshObject(parsedMesh);
mesh.aliases = { ...normalized.aliases };
Expand Down Expand Up @@ -650,6 +657,60 @@ function refinePass(input, triangulation, { cosMinAngle, offConstant, areaLimit
return accepted.length + toSplit.size;
}

/**
* Function to split the triangles with two or three sides on the boundary (#147). At a corner of the domain, the
* refinement can leave one triangle whose two sides lie on the two walls. With velocity set on the walls, five of
* the six velocity nodes of a quadratic (Taylor-Hood) triangle are then fixed, and the flow near the corner is
* wrong. A vertex at the middle of the side inside the domain splits it: the vertex lies inside the circumcircle of
* the triangle, so the Delaunay triangulation joins it to the corner, and each half has one side on the boundary.
* A triangle with all three sides on the boundary gets a vertex at its centroid. This is done for every element
* order, so that the mesh does not depend on it (FreeFem++'s splitpbedge is similar).
* The split roughly halves the angle at the corner, so a corner of less than twice minAngle is left as it is: its
* halves would have angles below minAngle, and refining them would never end
* @returns {number} The number of vertices added; the caller refines the triangulation again
*/
function splitCornerTriangles(input, triangulation) {
const { vertices, options } = input;
const { coords, triangles, halfedges, triangleCount, segmentOfHalfedge, inside } = triangulation;
const x = (v) => coords[2 * v];
const y = (v) => coords[2 * v + 1];
// Whether the angle at vertex c, between the sides to a and b, is at least twice minAngle
const cosLimit = Math.cos((2 * options.minAngle * Math.PI) / 180);
const wideAngle = (c, a, b) => {
const [ux, uy, vx, vy] = [x(a) - x(c), y(a) - y(c), x(b) - x(c), y(b) - y(c)];
return (ux * vx + uy * vy) / Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)) <= cosLimit;
};

const added = new Set();
const addVertex = (key, px, py) => {
if (added.has(key)) return;
added.add(key);
vertices.x.push(px);
vertices.y.push(py);
vertices.kind.push(FREE);
vertices.parent.push(-1);
};
for (let t = 0; t < triangleCount; t++) {
if (!inside[t]) continue;
const free = [0, 1, 2].map((k) => 3 * t + k).filter((e) => segmentOfHalfedge[e] === -1);
if (free.length === 1) {
const e = free[0];
const a = triangles[e];
const b = triangles[nextHalfedge(e)];
const corner = triangles[prevHalfedge(e)];
if (!wideAngle(corner, a, b)) continue;
// The triangles on both sides of the edge may be corner triangles: one vertex for the edge
addVertex(Math.min(e, halfedges[e] === -1 ? e : halfedges[e]), (x(a) + x(b)) / 2, (y(a) + y(b)) / 2);
} else if (free.length === 0) {
const [a, b, c] = [triangles[3 * t], triangles[3 * t + 1], triangles[3 * t + 2]];
if (!(wideAngle(a, b, c) && wideAngle(b, c, a) && wideAngle(c, a, b))) continue;
addVertex(-1 - t, (x(a) + x(b) + x(c)) / 3, (y(a) + y(b) + y(c)) / 3);
}
}
if (added.size > 0) debugLog(`Split ${added.size} triangles with two or three sides on the boundary`);
return added.size;
}

// ───────────────────────────────── Output ─────────────────────────────────

/**
Expand Down
10 changes: 9 additions & 1 deletion tests/regression/lidDrivenCavity2DCreepingFlow/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ changes to the Taylor-Hood creeping flow (Stokes) assembler or the flow boundary

It replicates the physical problem set up in
[`lidDrivenCavity2DCreepingFlow.js`](../../../examples/creepingFlow/lidDrivenCavity2DCreepingFlow/lidDrivenCavity2DCreepingFlow.js)
on structured and Gmsh quadrilaterals and on Gmsh triangles, and asserts known good values.
on structured and Gmsh quadrilaterals and on Gmsh and generated triangles, and asserts known good values.

## Problem setup

Expand All @@ -25,6 +25,7 @@ on structured and Gmsh quadrilaterals and on Gmsh triangles, and asserts known g
| 12 × 6 structured quadrilaterals | Q2-Q1 (9-node velocity, 4-node pressure) |
| Quadratic quadrilaterals, `tests/meshes/rect_quad_quadratic.msh` | Q2-Q1 (9-node velocity, 4-node pressure) |
| Quadratic triangles, `tests/meshes/rect_triang_quadratic.msh` | P2-P1 (6-node velocity, 3-node pressure) |
| Generated quadratic triangles, `size: 0.35`, `minAngle: 30` | P2-P1 (6-node velocity, 3-node pressure) |

Creeping flow requires quadratic elements (Taylor-Hood), and the saddle-point system is solved
with `lusolve` only: the frontal solver is not supported for this model, and the Jacobi method
Expand All @@ -37,11 +38,18 @@ does not converge for saddle-point systems.
| Q2-Q1, 12 × 6 structured | **−0.32446** | **0.03988** | **0** | **91** |
| Q2-Q1, `rect_quad_quadratic.msh` | **−0.31898** | **0.02027** | **−0.00013** | **41** |
| P2-P1, `rect_triang_quadratic.msh` | **−0.31768** | **0.04319** | **−0.00020** | **35** |
| P2-P1, generated, size 0.35 | **−0.32274** | **0.03030** | **0** | **157** |

The minimum x-velocity is the strongest return flow of the recirculation below the lid. The
pressure nodes are the element corners (13 × 7 for the structured mesh) or the triangle vertices.
Tolerance used in the assertions: `1e-4`.

On every mesh, the test also checks that the strongest return flow is away from the side walls (1 < x < 3).
The generated triangle mesh covers [#147](https://github.com/FEAScript/FEAScript-core/issues/147): at size 0.35,
the triangle generator used to leave a triangle in each corner with both sides on the walls. Five of its six
velocity nodes were then fixed, and the strongest return flow moved into a lid corner (u = −0.34549 at
(0.125, 1.875)). The generator now splits these triangles.

The values were updated when zero-velocity (no-slip) conditions started to take precedence at nodes shared with a
moving wall. Before, the condition applied last won, so one corner of the lid took the lid velocity and leaked
mass through a side wall; with the pressure pinned at one node, this produced a spurious flow near that node. The
Expand Down
27 changes: 23 additions & 4 deletions tests/regression/lidDrivenCavity2DCreepingFlow/regression.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
* Regression test for LidDrivenCavity2DCreepingFlow
*
* Replicates the physical setup from lidDrivenCavity2DCreepingFlow.js with Q2-Q1 quadrilaterals
* (structured and Gmsh meshes) and P2-P1 triangles (Gmsh mesh), and asserts the strongest return
* flow (minimum x-velocity), the nodal mean x-velocity and y-velocity and the number of pressure
* nodes against known good values. It also checks that a viscosity μ (constant or a function of
* (structured and Gmsh meshes) and P2-P1 triangles (Gmsh and generated meshes), and asserts the strongest
* return flow (minimum x-velocity) and that it lies away from the side walls, the nodal mean x-velocity and
* y-velocity and the number of pressure nodes against known good values. It also checks that a viscosity μ (constant or a function of
* position) leaves the velocity unchanged and scales the pressure by μ, as the Stokes equations
* with velocity boundary conditions require
*
Expand Down Expand Up @@ -64,6 +64,19 @@ const cases = [
expectedMeanV: -0.0002,
expectedPressureNodes: 35,
},
{
// Size 0.35 used to leave a triangle in each corner with both sides on the walls, which moved the strongest
// return flow into a lid corner (u = -0.34549 at (0.125, 1.875)); #147
label: "generated P2-P1 triangles (size 0.35, minAngle 30)",
mesh: {
geometry: { rectangle: [4, 2] },
meshConfig: { elements: "triangles", elementOrder: "quadratic", size: 0.35, minAngle: 30 },
},
expectedMinU: -0.32274,
expectedMeanU: 0.0303,
expectedMeanV: 0,
expectedPressureNodes: 157,
},
];

async function getMeshSource({ mesh, meshFile }) {
Expand Down Expand Up @@ -136,6 +149,12 @@ for (const testCase of cases) {
const yVelocities = solution.slice(totalNodesVelocity, 2 * totalNodesVelocity);

checkValue(label, "minimum u (return flow)", Math.min(...xVelocities), testCase.expectedMinU);
// The strongest return flow is in the recirculation below the lid, not in a corner of the cavity
const returnFlowX = nodesCoordinates.nodesXCoordinates[xVelocities.indexOf(Math.min(...xVelocities))];
assert(
returnFlowX > 1 && returnFlowX < 3,
`${label}: the strongest return flow is away from the side walls (at x = ${returnFlowX})`,
);
checkValue(label, "nodal mean u", mean(xVelocities), testCase.expectedMeanU);
checkValue(label, "nodal mean v", mean(yVelocities), testCase.expectedMeanV);

Expand All @@ -147,7 +166,7 @@ for (const testCase of cases) {

// The structured mesh is symmetric about x = maxX / 2, and so is the Stokes flow: u(x, y) = u(maxX - x, y)
// and v(x, y) = -v(maxX - x, y). A corner of the lid that leaks through a side wall breaks this symmetry
if (testCase.mesh) {
if (testCase.mesh?.width) {
const { nodesXCoordinates, nodesYCoordinates } = nodesCoordinates;
const nodeKey = (x, y) => `${x.toFixed(9)},${y.toFixed(9)}`;
const nodeIndices = new Map(nodesXCoordinates.map((x, i) => [nodeKey(x, nodesYCoordinates[i]), i]));
Expand Down
72 changes: 72 additions & 0 deletions tests/unit/triangleMesh.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
* - Holes: no element inside a hole, and the area of the mesh is the polygon area minus the holes
* - Points: embedded points become nodes; a point on an edge splits it
* - Small input angles: the refinement ends, and away from the corner the angle target holds
* - Corner triangles (#147): no element has two or three sides on the boundary, at the sizes that used to leave
* one in each corner of the cavity rectangle, and the angle target still holds; a corner of less than twice
* minAngle keeps its triangle
* - Solve: heat conduction with a linear exact solution is reproduced at every node, on linear and
* quadratic elements, with the boundary conditions keyed by name
* - Errors: a polygon that is not simple, a hole outside the shape or inside another hole, a point outside
Expand Down Expand Up @@ -392,6 +395,75 @@ assert(
"wedge: away from the tip, every element has angles of at least 20 degrees",
);

// ─────────────────────────── Corner triangles ───────────────────────────

basicLog("");
basicLog("--- Triangles with two sides on the boundary (#147) ---");

// The elements with two or more sides on the boundary, with their smallest angle
const cornerElements = (mesh) => {
const count = new Map();
Object.values(mesh.boundaryElements).forEach((sides) =>
sides.forEach(([element]) => count.set(element, (count.get(element) ?? 0) + 1)),
);
return [...count].filter(([, sides]) => sides >= 2).map(([element]) => element);
};

// The rectangle of the lid-driven cavity: these sizes left one such triangle in each corner
for (const size of [0.35, 0.3, 0.15]) {
for (const elementOrder of ["linear", "quadratic"]) {
const label = `rectangle 4 × 2, size ${size}, ${elementOrder}`;
const mesh = generateTriangleMesh({ rectangle: [4, 2] }, { size, minAngle: 30, elementOrder });
assert(cornerElements(mesh).length === 0, `${label}: no element has two sides on the boundary`);
checkQuality(label, mesh, { minAngle: 30, size, area: 8 });
}
}
const lshape = [
[0, 0],
[0.4, 0],
[0.4, 0.4],
[0.8, 0.4],
[0.8, 0.8],
[0, 0.8],
];
const lshapeMesh = generateTriangleMesh({ shape: lshape }, { size: 0.1, minAngle: 30 });
assert(cornerElements(lshapeMesh).length === 0, "L-shape: no element has two sides on the boundary");
checkQuality("L-shape", lshapeMesh, { minAngle: 30, size: 0.1, area: polygonArea(lshape) });

// Without a size, the square is two triangles, each with two sides on the boundary, and a triangle is one
// element with three; both are split, and the halves are refined to minAngle
const coarseSquare = generateTriangleMesh({ shape: square });
assert(
cornerElements(coarseSquare).length === 0,
"square without a size: no element has two sides on the boundary",
);
checkQuality("square without a size", coarseSquare, { minAngle: 20, size: Infinity, area: 1 });
const rightTriangle = [
[0, 0],
[1, 0],
[0, 1],
];
const coarseTriangle = generateTriangleMesh({ shape: rightTriangle });
assert(
cornerElements(coarseTriangle).length === 0,
"triangle without a size: no element has two sides on the boundary",
);
checkQuality("triangle without a size", coarseTriangle, { minAngle: 20, size: Infinity, area: 0.5 });

// A corner of less than twice minAngle is left: its halves would have angles below minAngle
const sharp = [
[0, 0],
[4, 0],
[4, 4 * Math.tan(Math.PI / 12)],
];
const sharpMesh = generateTriangleMesh({ shape: sharp }, { size: 0.4 });
const sharpCorners = cornerElements(sharpMesh);
const sharpTip = elementStats(sharpMesh)[sharpCorners[0]]?.centroid;
assert(
sharpCorners.length === 1 && sharpTip[0] < 1 && sharpTip[1] < 0.3,
"15 degree corner: its triangle is left, and it is the only one with two sides on the boundary",
);

// ─────────────────────────── Solve ───────────────────────────

basicLog("");
Expand Down