Skip to content

Commit 0818c1c

Browse files
committed
Decouple the frontal solver from physics models and restructure src
Frontal solver (#77): - runFrontalSolver(assembleFront, meshData, boundaryConditionsHandler) no longer imports any physics model; model-specific parameters are bound into the assembler by the caller - Boundary condition classes implement a common frontal interface: imposeDirichletBoundaryConditionsFront and the optional imposeRobinBoundaryConditionsFront (returns null off Robin boundaries) - newtonRaphson takes assembleFront and boundaryConditionsHandler via context instead of importing frontPropagation - Frontal convection now applies every side of an element on the same boundary, matching the matrix assembly Restructure: - elements/: basis functions, numerical integration, isoparametric mapping, element geometry and initializeFEA (split from meshUtils) - physics/: models together with their boundary condition classes (was models/) - linalg/: sparse matrix and BLAS utilities (was numerics/) - io/: Gmsh reader, now including the Gmsh-to-FEAScript conversion previously in Mesh.parseMeshFromGmsh - solvers/index.js exports every solver except WebGPUComputeEngine Deduplicate boundary conditions: - Add getBoundarySides() to replace the repeated side-node tables - Thermal and generic BCs share one node loop for the matrix and frontal Dirichlet paths - Thermal convection uses one per-side computation for both paths (thermalBoundaryConditions.js 989 -> 425 lines) Add Prettier config matching the existing code style
1 parent 578c281 commit 0818c1c

38 files changed

Lines changed: 1194 additions & 1932 deletions

‎.prettierignore‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Build output
2+
dist/
3+
4+
# Third-party bundles
5+
src/vendor/

‎.prettierrc‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"printWidth": 110,
3+
"trailingComma": "all"
4+
}

‎src/FEAScript.js‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ import { newtonRaphson } from "./solvers/newtonRaphson.js";
1212
import { solveLinearSystem } from "./solvers/linearSystemSolver.js";
1313
import { solveLinearSystemAsync } from "./solvers/linearSystemSolver.js";
1414
import { prepareMesh } from "./mesh/meshUtils.js";
15-
import { assembleFrontPropagationMat } from "./models/frontPropagation.js";
16-
import { assembleGeneralFormPDEMat, assembleGeneralFormPDENonlinearMat } from "./models/generalFormPDE.js";
17-
import { assembleHeatConductionMat, assembleHeatConductionFront } from "./models/heatConduction.js";
18-
import { assembleCreepingFlowMatrix } from "./models/creepingFlow.js";
19-
import { assembleEulerBernoulliBeamMat } from "./models/eulerBernoulliBeam.js";
15+
import { assembleFrontPropagationMat, assembleFrontPropagationFront } from "./physics/frontPropagation.js";
16+
import { assembleGeneralFormPDEMat, assembleGeneralFormPDENonlinearMat } from "./physics/generalFormPDE.js";
17+
import { assembleHeatConductionMat, assembleHeatConductionFront } from "./physics/heatConduction.js";
18+
import { ThermalBoundaryConditions } from "./physics/thermalBoundaryConditions.js";
19+
import { GenericBoundaryConditions } from "./physics/genericBoundaryConditions.js";
20+
import { assembleCreepingFlowMatrix } from "./physics/creepingFlow.js";
21+
import { assembleEulerBernoulliBeamMat } from "./physics/eulerBernoulliBeam.js";
2022
import { runFrontalSolver } from "./solvers/frontalSolver.js";
2123
import { basicLog, debugLog, warnLog, errorLog } from "./utilities/logging.js";
2224

@@ -141,11 +143,22 @@ export class FEAScriptModel {
141143
if (this.solverConfig === "heatConductionScript") {
142144
// Check if using frontal solver
143145
if (this.solverMethod === "frontal") {
146+
const thermalBoundaryConditions = new ThermalBoundaryConditions(
147+
this.boundaryConditions,
148+
meshData.boundaryElements,
149+
meshData.nop,
150+
meshData.meshDimension,
151+
meshData.elementOrder,
152+
meshData.elementShape,
153+
);
144154
const frontalResult = runFrontalSolver(
145-
assembleHeatConductionFront,
155+
(elementArgs) =>
156+
assembleHeatConductionFront({
157+
...elementArgs,
158+
coefficientFunctions: this.coefficientFunctions,
159+
}),
146160
meshData,
147-
this.boundaryConditions,
148-
{ coefficientFunctions: this.coefficientFunctions },
161+
thermalBoundaryConditions,
149162
);
150163
solutionVector = frontalResult.solutionVector;
151164
} else {
@@ -176,6 +189,20 @@ export class FEAScriptModel {
176189
// TODO: Consider using different maxIterations/tolerance for Newton-Raphson and linear solver
177190
maxIterations: options.maxIterations ?? this.maxIterations,
178191
tolerance: options.tolerance ?? this.tolerance,
192+
// Used only by the frontal solver
193+
assembleFront: (elementArgs) =>
194+
assembleFrontPropagationFront({
195+
...elementArgs,
196+
eikonalActivationFlag: context.eikonalActivationFlag,
197+
}),
198+
boundaryConditionsHandler: new GenericBoundaryConditions(
199+
this.boundaryConditions,
200+
meshData.boundaryElements,
201+
meshData.nop,
202+
meshData.meshDimension,
203+
meshData.elementOrder,
204+
meshData.elementShape,
205+
),
179206
};
180207

181208
// Count the incremental steps with an integer, so that the last step activates the eikonal equation

‎src/elements/basisFunctions.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,53 @@ export const triangleBoundarySides = {
2828
},
2929
};
3030

31+
/**
32+
* Local node indices on each side of the 1D reference element
33+
*/
34+
const lineBoundarySides = {
35+
linear: {
36+
0: [0], // Node at the left side of the reference element
37+
1: [1], // Node at the right side of the reference element
38+
},
39+
quadratic: {
40+
0: [0], // Node at the left side of the reference element
41+
1: [2], // Node at the right side of the reference element
42+
},
43+
};
44+
45+
/**
46+
* Local node indices on each side of the reference quadrilateral
47+
* (side 0: bottom, eta = 0; side 1: left, ksi = 0; side 2: top, eta = 1; side 3: right, ksi = 1)
48+
* Nodes are listed in order along each side
49+
*/
50+
const quadBoundarySides = {
51+
linear: {
52+
0: [0, 2], // Nodes at the bottom side of the reference element
53+
1: [0, 1], // Nodes at the left side of the reference element
54+
2: [1, 3], // Nodes at the top side of the reference element
55+
3: [2, 3], // Nodes at the right side of the reference element
56+
},
57+
quadratic: {
58+
0: [0, 3, 6], // Nodes at the bottom side of the reference element
59+
1: [0, 1, 2], // Nodes at the left side of the reference element
60+
2: [2, 5, 8], // Nodes at the top side of the reference element
61+
3: [6, 7, 8], // Nodes at the right side of the reference element
62+
},
63+
};
64+
65+
/**
66+
* Function to get the local node indices on each side of the reference element
67+
* @param {string} meshDimension - The dimension of the mesh, either '1D' or '2D'
68+
* @param {string} elementOrder - The order of elements, either 'linear' or 'quadratic'
69+
* @param {string} [elementShape='quad'] - The 2D element shape, either 'quad' or 'triangle'
70+
* @returns {object} Map from side index to the local node indices on that side
71+
*/
72+
export function getBoundarySides(meshDimension, elementOrder, elementShape = "quad") {
73+
if (meshDimension === "1D") return lineBoundarySides[elementOrder];
74+
if (elementShape === "triangle") return triangleBoundarySides[elementOrder];
75+
return quadBoundarySides[elementOrder];
76+
}
77+
3178
/**
3279
* Class to handle basis functions and their derivatives based on element configuration
3380
*/

‎src/elements/elementGeometry.js‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
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+
* Function to test if a point is inside a triangle using barycentric coordinates,
11+
* also returning the natural coordinates (ksi, eta)
12+
* @param {number} x - X-coordinate of the point
13+
* @param {number} y - Y-coordinate of the point
14+
* @param {array} vertices - Triangle vertices [[x0,y0],[x1,y1],[x2,y2]]
15+
* @returns {object} Object containing inside boolean and natural coordinates {inside, ksi, eta}
16+
*/
17+
export function pointInsideTriangle(x, y, vertices) {
18+
const tolerance = 1e-12;
19+
const [v0, v1, v2] = vertices;
20+
21+
const denom = (v1[1] - v2[1]) * (v0[0] - v2[0]) + (v2[0] - v1[0]) * (v0[1] - v2[1]);
22+
23+
const ksi = ((v1[1] - v2[1]) * (x - v2[0]) + (v2[0] - v1[0]) * (y - v2[1])) / denom;
24+
const eta = ((v2[1] - v0[1]) * (x - v2[0]) + (v0[0] - v2[0]) * (y - v2[1])) / denom;
25+
const gamma = 1 - ksi - eta;
26+
27+
const inside = ksi >= -tolerance && eta >= -tolerance && gamma >= -tolerance;
28+
return { inside, ksi, eta };
29+
}
30+
31+
/**
32+
* Function to test if a point is inside a triangular element, also returning the natural coordinates
33+
* (ksi, eta) of the FEAScript reference triangle
34+
* @param {number} x - X-coordinate of the point
35+
* @param {number} y - Y-coordinate of the point
36+
* @param {array} vertices - Triangle vertices in FEAScript order [[x0,y0],[x1,y1],[x2,y2]]
37+
* @returns {object} Object containing inside boolean and natural coordinates {inside, ksi, eta}
38+
*/
39+
export function pointInsideTriangularElement(x, y, vertices) {
40+
// Vertices order (reference coordinates):
41+
// 1 (0,1)
42+
// | \
43+
// | \
44+
// 0 --- 2 (1,0)
45+
// The barycentric weights of vertices 2 and 1 are the natural coordinates ksi and eta
46+
const { inside, ksi: weight0, eta: weight1 } = pointInsideTriangle(x, y, vertices);
47+
return { inside, ksi: 1 - weight0 - weight1, eta: weight1 };
48+
}
49+
50+
/**
51+
* Function to test if a point is inside a quadrilateral by spliting it into triangles and using barycentric coordinates
52+
* @param {number} x - X-coordinate of the point
53+
* @param {number} y - Y-coordinate of the point
54+
* @param {array} vertices - Quadrilateral vertices [[x0,y0],[x1,y1],[x2,y2],[x3,y3]]
55+
* @returns {object} Object containing inside boolean and natural coordinates {inside, ksi, eta}
56+
*/
57+
export function pointInsideQuadrilateral(x, y, vertices) {
58+
const [firstTriangleVertices, secondTriangleVertices] = splitQuadrilateral(vertices);
59+
const pointInsideFirstTriangle = pointInsideTriangle(x, y, firstTriangleVertices);
60+
const pointInsideSecondTriangle = pointInsideTriangle(x, y, secondTriangleVertices);
61+
62+
const inside = pointInsideFirstTriangle.inside || pointInsideSecondTriangle.inside;
63+
let ksi = 0;
64+
let eta = 0;
65+
66+
if (inside) {
67+
const [v0, v1, v2, v3] = vertices;
68+
69+
// Function to calculate distance from point to line segment
70+
const getDistanceFromLine = (p1, p2) => {
71+
const num = Math.abs((p2[0] - p1[0]) * (p1[1] - y) - (p1[0] - x) * (p2[1] - p1[1]));
72+
const den = Math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2);
73+
return num / den;
74+
};
75+
76+
// Calculate distances to edges based on vertex order:
77+
// 1 (v1) --- 3 (v3)
78+
// | |
79+
// 0 (v0) --- 2 (v2)
80+
81+
const distLeft = getDistanceFromLine(v0, v1);
82+
const distRight = getDistanceFromLine(v2, v3);
83+
const distBottom = getDistanceFromLine(v0, v2);
84+
const distTop = getDistanceFromLine(v1, v3);
85+
86+
ksi = distLeft / (distLeft + distRight);
87+
eta = distBottom / (distBottom + distTop);
88+
89+
// The distance ratios are exact only for parallelograms, so refine them with Newton iterations
90+
// on the bilinear mapping x(ksi, eta) = v0 (1-ksi)(1-eta) + v1 (1-ksi) eta + v2 ksi (1-eta) + v3 ksi eta
91+
for (let iteration = 0; iteration < 20; iteration++) {
92+
const mappedX =
93+
v0[0] * (1 - ksi) * (1 - eta) + v1[0] * (1 - ksi) * eta + v2[0] * ksi * (1 - eta) + v3[0] * ksi * eta;
94+
const mappedY =
95+
v0[1] * (1 - ksi) * (1 - eta) + v1[1] * (1 - ksi) * eta + v2[1] * ksi * (1 - eta) + v3[1] * ksi * eta;
96+
const ksiDerivX = (v2[0] - v0[0]) * (1 - eta) + (v3[0] - v1[0]) * eta;
97+
const ksiDerivY = (v2[1] - v0[1]) * (1 - eta) + (v3[1] - v1[1]) * eta;
98+
const etaDerivX = (v1[0] - v0[0]) * (1 - ksi) + (v3[0] - v2[0]) * ksi;
99+
const etaDerivY = (v1[1] - v0[1]) * (1 - ksi) + (v3[1] - v2[1]) * ksi;
100+
const detJacobian = ksiDerivX * etaDerivY - etaDerivX * ksiDerivY;
101+
const residualX = x - mappedX;
102+
const residualY = y - mappedY;
103+
const deltaKsi = (etaDerivY * residualX - etaDerivX * residualY) / detJacobian;
104+
const deltaEta = (ksiDerivX * residualY - ksiDerivY * residualX) / detJacobian;
105+
ksi += deltaKsi;
106+
eta += deltaEta;
107+
if (Math.abs(deltaKsi) + Math.abs(deltaEta) < 1e-14) break;
108+
}
109+
}
110+
111+
return { inside, ksi, eta };
112+
}
113+
114+
/**
115+
* Function to split the quadrilateral elements into two triangles
116+
* @param {array} vertices - Quadrilateral vertices [[x0,y0],[x1,y1],[x2,y2],[x3,y3]]
117+
* @returns {array} Array of triangle vertices: [[v0,v1,v3], [v0,v2,v3]]
118+
*/
119+
export function splitQuadrilateral(vertices) {
120+
const [v0, v1, v2, v3] = vertices;
121+
// Vertices order:
122+
// 1 --- 3
123+
// | |
124+
// 0 --- 2
125+
return [
126+
[v0, v1, v3],
127+
[v0, v2, v3],
128+
];
129+
}

‎src/elements/feaInitialization.js‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
// Internal imports
11+
import { BasisFunctions } from "./basisFunctions.js";
12+
import { NumericalIntegration } from "./numericalIntegration.js";
13+
import { getIntegrationPoints2D } from "./isoparametricMapping.js";
14+
import { SparseMatrix } from "../linalg/sparseMatrix.js";
15+
/**
16+
* Function to initialize the FEA matrices and numerical tools
17+
* @param {object} meshData - Object containing mesh data from prepareMesh()
18+
* @returns {object} An object containing initialized matrices and numerical tools
19+
*/
20+
export function initializeFEA(meshData) {
21+
const { totalNodes, nop, meshDimension, elementOrder, elementShape } = meshData;
22+
23+
// Initialize variables for matrix assembly
24+
let residualVector = new Array(totalNodes).fill(0);
25+
let jacobianMatrix = new SparseMatrix(totalNodes);
26+
let localToGlobalMap = [];
27+
28+
// Initialize the BasisFunctions class
29+
const basisFunctions = new BasisFunctions({
30+
meshDimension,
31+
elementOrder,
32+
elementShape,
33+
});
34+
35+
// Initialize the NumericalIntegration class
36+
const numericalIntegration = new NumericalIntegration({
37+
meshDimension,
38+
elementOrder,
39+
elementShape,
40+
});
41+
42+
// Calculate Gauss points and weights
43+
let gaussPointsAndWeights = numericalIntegration.getGaussPointsAndWeights();
44+
let gaussPoints = gaussPointsAndWeights.gaussPoints;
45+
let gaussWeights = gaussPointsAndWeights.gaussWeights;
46+
47+
// Integration points for 2D elements (tensor product for quads, collapsed rule for triangles)
48+
const integrationPoints2D =
49+
meshDimension === "2D" ? getIntegrationPoints2D(gaussPoints, gaussWeights, elementShape) : [];
50+
51+
// Basis functions on the reference element at each integration point (the same for every element)
52+
const referenceBasisFunctions =
53+
meshDimension === "1D"
54+
? gaussPoints.map((gaussPoint) => basisFunctions.getBasisFunctions(gaussPoint))
55+
: integrationPoints2D.map(([ksi, eta]) => basisFunctions.getBasisFunctions(ksi, eta));
56+
57+
// Determine the number of nodes in the reference element based on the first element in the nop array
58+
const nodesPerElement = nop[0].length;
59+
60+
return {
61+
residualVector,
62+
jacobianMatrix,
63+
localToGlobalMap,
64+
basisFunctions,
65+
gaussPoints,
66+
gaussWeights,
67+
integrationPoints2D,
68+
referenceBasisFunctions,
69+
nodesPerElement,
70+
};
71+
}

0 commit comments

Comments
 (0)