|
| 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