Skip to content

Commit a1ef9e6

Browse files
committed
Fix non-contiguous node tags in the Gmsh reader (#96)
- Gmsh reader: when node tags have gaps (max tag > number of nodes), map each tag to a compact 1-based index and remap element and boundary node references; meshes with contiguous tags are read as before - Previously each gap added a disconnected node with an all-zero matrix row, so Jacobi returned NaN and the LU solver failed - Tests: add gmshReader unit test (test meshes copied with gaps in their node tags give the same nodes, connectivity and solution)
1 parent f2b4bb7 commit a1ef9e6

3 files changed

Lines changed: 243 additions & 4 deletions

File tree

‎src/readers/gmshReader.js‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ const importGmshMesh = async (file) => {
5656
let nodeTagsCollected = 0;
5757
let nodeCoordinatesCollected = 0;
5858

59+
// Node tags with gaps are mapped to compact 1-based indices (null when tags are contiguous)
60+
let nodeTagToIndex = null;
61+
5962
// Elements
6063
let elementEntityBlocks = 0;
6164
let elementBlocksProcessed = 0;
@@ -178,6 +181,13 @@ const importGmshMesh = async (file) => {
178181
if (nodeEntityBlocks === 0) {
179182
nodeEntityBlocks = parseInt(parts[0], 10);
180183
totalNodes = parseInt(parts[1], 10);
184+
const maxNodeTag = parseInt(parts[3], 10);
185+
if (maxNodeTag !== totalNodes) {
186+
nodeTagToIndex = new Map();
187+
debugLog(
188+
`Gmsh node tags are not contiguous (max tag ${maxNodeTag}, ${totalNodes} nodes); renumbering`,
189+
);
190+
}
181191
result.nodesXCoordinates = new Array(totalNodes).fill(0);
182192
result.nodesYCoordinates = new Array(totalNodes).fill(0);
183193
} else if (nodeBlocksProcessed < nodeEntityBlocks && currentNodeBlock.numNodes === 0) {
@@ -197,9 +207,13 @@ const importGmshMesh = async (file) => {
197207
if (nodeTagsCollected === currentNodeBlock.numNodes) break;
198208
}
199209
} else if (nodeCoordinatesCollected < currentNodeBlock.numNodes) {
200-
const nodeTag = nodeTags[nodeCoordinatesCollected] - 1;
201-
result.nodesXCoordinates[nodeTag] = parseFloat(parts[0]);
202-
result.nodesYCoordinates[nodeTag] = parseFloat(parts[1]);
210+
let nodeIndex = nodeTags[nodeCoordinatesCollected] - 1;
211+
if (nodeTagToIndex) {
212+
nodeIndex = nodeTagToIndex.size;
213+
nodeTagToIndex.set(nodeTags[nodeCoordinatesCollected], nodeIndex + 1);
214+
}
215+
result.nodesXCoordinates[nodeIndex] = parseFloat(parts[0]);
216+
result.nodesYCoordinates[nodeIndex] = parseFloat(parts[1]);
203217
result.totalNodesX++;
204218
result.totalNodesY++;
205219
nodeCoordinatesCollected++;
@@ -227,7 +241,8 @@ const importGmshMesh = async (file) => {
227241

228242
elementsProcessedInBlock = 0;
229243
} else if (elementsProcessedInBlock < currentElementBlock.numElements) {
230-
const nodeIndices = parts.slice(1).map((n) => parseInt(n, 10));
244+
let nodeIndices = parts.slice(1).map((n) => parseInt(n, 10));
245+
if (nodeTagToIndex) nodeIndices = nodeIndices.map((tag) => nodeTagToIndex.get(tag));
231246

232247
// Resolve physical tag via entity → physical map
233248
let physicalTag = currentElementBlock.tag;

‎tests/unit/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ and utilities.
1717
| `elements2D.test.js` | Basis functions and quadrature rules of linear and quadratic quadrilaterals and triangles |
1818
| `plotInterpolation.test.js` | Point location and solution interpolation of the contour plot, for all 2D element types |
1919
| `solutionFormat.test.js` | Solution vector is a Float64Array for every model and solver method, with the same values and plots |
20+
| `gmshReader.test.js` | Gmsh reader, including meshes with non-contiguous node tags (same nodes, connectivity, solution) |
2021

2122
Run all unit, regression, and verification tests from the repository root with:
2223

‎tests/unit/gmshReader.test.js‎

Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,223 @@
1+
/**
2+
* ════════════════════════════════════════════════════════════════
3+
* FEAScript Core Library
4+
* Finite Element Simulation in JavaScript
5+
* Version: 0.3.0 (RC) | https://feascript.com
6+
* MIT License © 2023–2026 FEAScript
7+
* ════════════════════════════════════════════════════════════════
8+
*/
9+
10+
/**
11+
* Unit tests for the Gmsh reader (importGmshMesh)
12+
*
13+
* Uses the test meshes of linear and quadratic quadrilaterals and triangles
14+
*
15+
* Covers:
16+
* - Non-contiguous node tags: each mesh is copied with gaps in its node tags (same geometry and
17+
* connectivity) and compared against the original
18+
* - No extra (disconnected) nodes are created by the gaps
19+
* - Element and boundary node references point to the same coordinates
20+
* - The heat conduction solution (lusolve and jacobi) is the same at every element node
21+
*
22+
* Run: node tests/unit/gmshReader.test.js (or npm test)
23+
*/
24+
25+
import fs from "fs";
26+
import path from "path";
27+
import { fileURLToPath } from "url";
28+
import { FEAScriptModel } from "../../src/FEAScript.js";
29+
import { importGmshMesh } from "../../src/readers/gmshReader.js";
30+
import { basicLog, errorLog } from "../../src/utilities/logging.js";
31+
32+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
33+
const meshesDirectory = path.join(__dirname, "../meshes");
34+
35+
const TOLERANCE = 1e-8;
36+
37+
basicLog("");
38+
basicLog("================================");
39+
basicLog("Unit tests: Gmsh reader");
40+
41+
let passed = 0;
42+
let failed = 0;
43+
44+
function assert(condition, message) {
45+
if (!condition) {
46+
errorLog(`FAIL: ${message}`);
47+
failed++;
48+
} else {
49+
basicLog(`PASS: ${message}`);
50+
passed++;
51+
}
52+
}
53+
54+
const meshCases = [
55+
{
56+
meshFile: "rect_quad_linear.msh",
57+
elementOrder: "linear",
58+
solverMethods: ["lusolve"],
59+
},
60+
{
61+
meshFile: "rect_quad_quadratic.msh",
62+
elementOrder: "quadratic",
63+
solverMethods: ["lusolve"],
64+
},
65+
{
66+
meshFile: "rect_triang_linear.msh",
67+
elementOrder: "linear",
68+
solverMethods: ["lusolve", "jacobi"],
69+
},
70+
{
71+
meshFile: "rect_triang_quadratic.msh",
72+
elementOrder: "quadratic",
73+
solverMethods: ["lusolve"],
74+
},
75+
];
76+
77+
// Gmsh physical tags: 1 bottom, 2 right, 3 top, 4 left (stored as boundary keys 0-3)
78+
const boundaryConditions = {
79+
0: ["constantTemperature", 200],
80+
1: ["constantTemperature", 200],
81+
2: ["convection", 1, 20],
82+
3: ["symmetry"],
83+
};
84+
85+
const readMeshFile = (meshFile) => fs.readFileSync(path.join(meshesDirectory, meshFile), "utf8");
86+
87+
const parseMesh = (meshContent) => importGmshMesh({ text: async () => meshContent });
88+
89+
// Coordinates of the nodes referenced by a list of 1-based node numbers
90+
const nodeCoordinates = (mesh, nodeNumbers) =>
91+
nodeNumbers.map((node) => [mesh.nodesXCoordinates[node - 1], mesh.nodesYCoordinates[node - 1]]);
92+
93+
const largestDifference = (a, b) => {
94+
const flatB = b.flat(Infinity);
95+
return Math.max(0, ...a.flat(Infinity).map((value, i) => Math.abs(value - flatB[i])));
96+
};
97+
98+
function runSimulation(parsedMesh, elementOrder, solverMethod) {
99+
const model = new FEAScriptModel();
100+
model.setModelConfig("heatConductionScript");
101+
model.setMeshConfig({ parsedMesh, meshDimension: "2D", elementOrder });
102+
Object.entries(boundaryConditions).forEach(([boundaryKey, condition]) => {
103+
model.addBoundaryCondition(boundaryKey, condition);
104+
});
105+
model.setSolverMethod(solverMethod);
106+
return model.solve({ maxIterations: 200000, tolerance: 1e-10 });
107+
}
108+
109+
// ─── Non-contiguous node tags ───────────────────────────────────
110+
111+
// Node tags above TAG_GAP_START are shifted by TAG_GAP, leaving tags that no node uses
112+
const TAG_GAP_START = 10;
113+
const TAG_GAP = 100;
114+
115+
/**
116+
* Function to copy a Gmsh (.msh v4.1 ASCII) file with gaps in its node tags
117+
* @param {string} meshContent - Content of the original mesh file
118+
* @returns {string} Content of the mesh file with shifted node tags
119+
*/
120+
function addNodeTagGaps(meshContent) {
121+
const shiftTag = (tag) => (tag > TAG_GAP_START ? tag + TAG_GAP : tag);
122+
const lines = meshContent.split("\n");
123+
const output = [];
124+
let lineIndex = 0;
125+
const nextParts = () => lines[lineIndex++].trim().split(/\s+/).map(Number);
126+
127+
while (lineIndex < lines.length) {
128+
const line = lines[lineIndex++];
129+
output.push(line);
130+
131+
if (line.trim() === "$Nodes") {
132+
const [numBlocks, numNodes, minTag, maxTag] = nextParts();
133+
output.push(`${numBlocks} ${numNodes} ${minTag} ${shiftTag(maxTag)}`);
134+
for (let block = 0; block < numBlocks; block++) {
135+
const blockHeader = nextParts();
136+
output.push(blockHeader.join(" "));
137+
const numBlockNodes = blockHeader[3];
138+
for (let i = 0; i < numBlockNodes; i++) output.push(String(shiftTag(nextParts()[0])));
139+
for (let i = 0; i < numBlockNodes; i++) output.push(lines[lineIndex++]);
140+
}
141+
} else if (line.trim() === "$Elements") {
142+
const elementsHeader = nextParts();
143+
output.push(elementsHeader.join(" "));
144+
for (let block = 0; block < elementsHeader[0]; block++) {
145+
const blockHeader = nextParts();
146+
output.push(blockHeader.join(" "));
147+
for (let i = 0; i < blockHeader[3]; i++) {
148+
const [elementTag, ...nodeTags] = nextParts();
149+
output.push([elementTag, ...nodeTags.map(shiftTag)].join(" "));
150+
}
151+
}
152+
}
153+
}
154+
155+
return output.join("\n");
156+
}
157+
158+
for (const { meshFile, elementOrder, solverMethods } of meshCases) {
159+
const meshContent = readMeshFile(meshFile);
160+
const original = await parseMesh(meshContent);
161+
const gapped = await parseMesh(addNodeTagGaps(meshContent));
162+
163+
const originalElements = [
164+
...original.nodalNumbering.quadElements,
165+
...original.nodalNumbering.triangleElements,
166+
];
167+
const gappedElements = [...gapped.nodalNumbering.quadElements, ...gapped.nodalNumbering.triangleElements];
168+
169+
const numNodes = original.nodesXCoordinates.length;
170+
const definedNodes = gapped.nodesXCoordinates.filter((x) => x !== undefined).length;
171+
assert(
172+
gapped.nodesXCoordinates.length === numNodes && definedNodes === numNodes,
173+
`${meshFile}: ${numNodes} nodes with gapped tags (got ${gapped.nodesXCoordinates.length}, ${definedNodes} defined)`,
174+
);
175+
176+
const elementDifference = largestDifference(
177+
gappedElements.map((element) => nodeCoordinates(gapped, element)),
178+
originalElements.map((element) => nodeCoordinates(original, element)),
179+
);
180+
assert(
181+
elementDifference === 0,
182+
`${meshFile}: element nodes have the same coordinates (largest difference ${elementDifference})`,
183+
);
184+
185+
const boundaryTags = Object.keys(original.boundaryNodePairs);
186+
const boundaryDifference = largestDifference(
187+
boundaryTags.map((tag) => gapped.boundaryNodePairs[tag].map((pair) => nodeCoordinates(gapped, pair))),
188+
boundaryTags.map((tag) => original.boundaryNodePairs[tag].map((pair) => nodeCoordinates(original, pair))),
189+
);
190+
assert(
191+
boundaryDifference === 0,
192+
`${meshFile}: boundary nodes have the same coordinates (largest difference ${boundaryDifference})`,
193+
);
194+
195+
// The simulation modifies the parsed mesh, so each one parses its own copy
196+
for (const solverMethod of solverMethods) {
197+
const originalSolution = runSimulation(
198+
await parseMesh(meshContent),
199+
elementOrder,
200+
solverMethod,
201+
).solutionVector;
202+
const gappedSolution = runSimulation(
203+
await parseMesh(addNodeTagGaps(meshContent)),
204+
elementOrder,
205+
solverMethod,
206+
).solutionVector;
207+
208+
const allFinite = Array.from(gappedSolution).every(Number.isFinite);
209+
const solutionDifference = largestDifference(
210+
gappedElements.map((element) => element.map((node) => gappedSolution[node - 1])),
211+
originalElements.map((element) => element.map((node) => originalSolution[node - 1])),
212+
);
213+
assert(
214+
allFinite && gappedSolution.length === numNodes && solutionDifference < TOLERANCE,
215+
`${meshFile}, ${solverMethod}: same temperatures at the element nodes, largest difference ${solutionDifference.toExponential(
216+
3,
217+
)} (tolerance ${TOLERANCE})`,
218+
);
219+
}
220+
}
221+
222+
basicLog(`Gmsh reader tests: ${passed} passed, ${failed} failed`);
223+
if (failed > 0) process.exit(1);

0 commit comments

Comments
 (0)