-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmeshUtilsScript.js
More file actions
436 lines (384 loc) · 15.6 KB
/
meshUtilsScript.js
File metadata and controls
436 lines (384 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/**
* ════════════════════════════════════════════════════════════════
* FEAScript Core Library
* Lightweight Finite Element Simulation in JavaScript
* Version: 0.2.0 (RC) | https://feascript.com
* MIT License © 2023–2026 FEAScript
* ════════════════════════════════════════════════════════════════
*/
// Internal imports
import { BasisFunctions } from "./basisFunctionsScript.js";
import { Mesh1D, Mesh2D } from "./meshGenerationScript.js";
import { NumericalIntegration } from "../methods/numericalIntegrationScript.js";
import { basicLog, debugLog, errorLog } from "../utilities/loggingScript.js";
/**
* Function to prepare the mesh for finite element analysis
* @param {object} meshConfig - Object containing computational mesh details
* @returns {object} An object containing all mesh-related data
*/
export function prepareMesh(meshConfig) {
const {
meshDimension,
numElementsX,
numElementsY,
maxX,
maxY,
elementOrder,
parsedMesh,
angleLeft,
angleRight,
} = meshConfig;
// Create a new instance of the Mesh class
let mesh;
if (meshDimension === "1D") {
mesh = new Mesh1D({ numElementsX, maxX, elementOrder, parsedMesh });
} else if (meshDimension === "2D") {
mesh = new Mesh2D({
numElementsX,
maxX,
numElementsY,
maxY,
elementOrder,
parsedMesh,
angleLeft,
angleRight,
});
} else {
errorLog("Mesh dimension must be either '1D' or '2D'");
}
// Use the parsed mesh (e.g., from a Gmsh .msh import) if provided. Otherwise, generate a structured mesh
const nodesCoordinatesAndNumbering = mesh.boundaryElementsProcessed ? mesh.parsedMesh : mesh.generateMesh();
// Extract nodes coordinates and nodal numbering (NOP) from the mesh data
let nodesXCoordinates = nodesCoordinatesAndNumbering.nodesXCoordinates;
let nodesYCoordinates = nodesCoordinatesAndNumbering.nodesYCoordinates;
let totalNodesX = nodesCoordinatesAndNumbering.totalNodesX;
let totalNodesY = nodesCoordinatesAndNumbering.totalNodesY;
let nop = nodesCoordinatesAndNumbering.nodalNumbering;
let boundaryElements = nodesCoordinatesAndNumbering.boundaryElements;
// Check the mesh type
const isParsedMesh = parsedMesh !== undefined && parsedMesh !== null;
// Calculate totalElements and totalNodes based on mesh type
let totalElements, totalNodes;
if (isParsedMesh) {
totalElements = nop.length; // Number of elements is the length of the nodal numbering array
totalNodes = nodesXCoordinates.length; // Number of nodes is the length of the coordinates array
debugLog(`Using parsed mesh with ${totalElements} elements and ${totalNodes} nodes`);
} else {
// For structured mesh, calculate based on dimensions
totalElements = numElementsX * (meshDimension === "2D" ? numElementsY : 1);
totalNodes = totalNodesX * (meshDimension === "2D" ? totalNodesY : 1);
debugLog(`Using mesh generated from geometry with ${totalElements} elements and ${totalNodes} nodes`);
}
return {
nodesXCoordinates,
nodesYCoordinates,
totalNodesX,
totalNodesY,
nop,
boundaryElements,
totalElements,
totalNodes,
meshDimension,
elementOrder,
};
}
/**
* Function to initialize the FEA matrices and numerical tools
* @param {object} meshData - Object containing mesh data from prepareMesh()
* @returns {object} An object containing initialized matrices and numerical tools
*/
export function initializeFEA(meshData) {
const { totalNodes, nop, meshDimension, elementOrder } = meshData;
// Initialize variables for matrix assembly
let residualVector = [];
let jacobianMatrix = [];
let localToGlobalMap = [];
// Initialize jacobianMatrix and residualVector arrays
for (let nodeIndex = 0; nodeIndex < totalNodes; nodeIndex++) {
residualVector[nodeIndex] = 0;
jacobianMatrix.push([]);
for (let colIndex = 0; colIndex < totalNodes; colIndex++) {
jacobianMatrix[nodeIndex][colIndex] = 0;
}
}
// Determine the number of nodes in the reference element based on the first element in the nop array
const nodesPerElement = nop[0].length;
// Initialize the BasisFunctions class
const basisFunctions = new BasisFunctions({
meshDimension,
elementOrder,
nodesPerElement,
});
// Initialize the NumericalIntegration class
const numericalIntegration = new NumericalIntegration({
meshDimension,
elementOrder,
nodesPerElement,
});
// Calculate Gauss points and weights
let gaussPointsAndWeights = numericalIntegration.getGaussPointsAndWeights();
let gaussPoints = gaussPointsAndWeights.gaussPoints;
let gaussWeights = gaussPointsAndWeights.gaussWeights;
return {
residualVector,
jacobianMatrix,
localToGlobalMap,
basisFunctions,
gaussPoints,
gaussWeights,
nodesPerElement,
};
}
/**
* Function to perform isoparametric mapping for 1D elements
* @param {object} mappingParams - Parameters for the mapping
* @returns {object} An object containing the mapped data
*/
export function performIsoparametricMapping1D(mappingParams) {
const { basisFunction, basisFunctionDerivKsi, nodesXCoordinates, localToGlobalMap, nodesPerElement } =
mappingParams;
let xCoordinates = 0;
let ksiDerivX = 0;
// Isoparametric mapping
for (let localNodeIndex = 0; localNodeIndex < nodesPerElement; localNodeIndex++) {
xCoordinates += nodesXCoordinates[localToGlobalMap[localNodeIndex]] * basisFunction[localNodeIndex];
ksiDerivX += nodesXCoordinates[localToGlobalMap[localNodeIndex]] * basisFunctionDerivKsi[localNodeIndex];
}
let detJacobian = ksiDerivX;
// Compute x-derivative of basis functions
let basisFunctionDerivX = [];
for (let localNodeIndex = 0; localNodeIndex < nodesPerElement; localNodeIndex++) {
basisFunctionDerivX[localNodeIndex] = basisFunctionDerivKsi[localNodeIndex] / detJacobian;
}
return {
xCoordinates,
detJacobian,
basisFunctionDerivX,
};
}
/**
* Function to perform isoparametric mapping for 2D elements
* @param {object} mappingParams - Parameters for the mapping
* @returns {object} An object containing the mapped data
*/
export function performIsoparametricMapping2D(mappingParams) {
const {
basisFunction,
basisFunctionDerivKsi,
basisFunctionDerivEta,
nodesXCoordinates,
nodesYCoordinates,
localToGlobalMap,
nodesPerElement,
} = mappingParams;
let xCoordinates = 0;
let yCoordinates = 0;
let ksiDerivX = 0;
let etaDerivX = 0;
let ksiDerivY = 0;
let etaDerivY = 0;
// Isoparametric mapping
for (let localNodeIndex = 0; localNodeIndex < nodesPerElement; localNodeIndex++) {
xCoordinates += nodesXCoordinates[localToGlobalMap[localNodeIndex]] * basisFunction[localNodeIndex];
yCoordinates += nodesYCoordinates[localToGlobalMap[localNodeIndex]] * basisFunction[localNodeIndex];
ksiDerivX += nodesXCoordinates[localToGlobalMap[localNodeIndex]] * basisFunctionDerivKsi[localNodeIndex];
etaDerivX += nodesXCoordinates[localToGlobalMap[localNodeIndex]] * basisFunctionDerivEta[localNodeIndex];
ksiDerivY += nodesYCoordinates[localToGlobalMap[localNodeIndex]] * basisFunctionDerivKsi[localNodeIndex];
etaDerivY += nodesYCoordinates[localToGlobalMap[localNodeIndex]] * basisFunctionDerivEta[localNodeIndex];
}
let detJacobian = ksiDerivX * etaDerivY - etaDerivX * ksiDerivY;
// Compute x-derivative and y-derivative of basis functions
let basisFunctionDerivX = [];
let basisFunctionDerivY = [];
for (let localNodeIndex = 0; localNodeIndex < nodesPerElement; localNodeIndex++) {
// The x-derivative of the n basis function
basisFunctionDerivX[localNodeIndex] =
(etaDerivY * basisFunctionDerivKsi[localNodeIndex] -
ksiDerivY * basisFunctionDerivEta[localNodeIndex]) /
detJacobian;
// The y-derivative of the n basis function
basisFunctionDerivY[localNodeIndex] =
(ksiDerivX * basisFunctionDerivEta[localNodeIndex] -
etaDerivX * basisFunctionDerivKsi[localNodeIndex]) /
detJacobian;
}
return {
xCoordinates,
yCoordinates,
detJacobian,
basisFunctionDerivX,
basisFunctionDerivY,
};
}
/**
* Function to test if a point is inside a triangle using barycentric coordinates,
* also returning the natural coordinates (ksi, eta).
* @param {number} x - X-coordinate of the point
* @param {number} y - Y-coordinate of the point
* @param {array} vertices - Triangle vertices [[x0,y0],[x1,y1],[x2,y2]]
* @returns {object} Object containing inside boolean and natural coordinates {inside, ksi, eta}
*/
export function pointInsideTriangle(x, y, vertices) {
const tolerance = 1e-12;
const [v0, v1, v2] = vertices;
const denom = (v1[1] - v2[1]) * (v0[0] - v2[0]) + (v2[0] - v1[0]) * (v0[1] - v2[1]);
const ksi = ((v1[1] - v2[1]) * (x - v2[0]) + (v2[0] - v1[0]) * (y - v2[1])) / denom;
const eta = ((v2[1] - v0[1]) * (x - v2[0]) + (v0[0] - v2[0]) * (y - v2[1])) / denom;
const gamma = 1 - ksi - eta;
const inside = ksi >= -tolerance && eta >= -tolerance && gamma >= -tolerance;
return { inside, ksi, eta };
}
/**
* Function to test if a point is inside a quadrilateral by spliting it into triangles and using barycentric coordinates
* @param {number} x - X-coordinate of the point
* @param {number} y - Y-coordinate of the point
* @param {array} vertices - Quadrilateral vertices [[x0,y0],[x1,y1],[x2,y2],[x3,y3]]
* @returns {object} Object containing inside boolean and natural coordinates {inside, ksi, eta}
*/
export function pointInsideQuadrilateral(x, y, vertices) {
const [firstTriangleVertices, secondTriangleVertices] = splitQuadrilateral(vertices);
const pointInsideFirstTriangle = pointInsideTriangle(x, y, firstTriangleVertices);
const pointInsideSecondTriangle = pointInsideTriangle(x, y, secondTriangleVertices);
const inside = pointInsideFirstTriangle.inside || pointInsideSecondTriangle.inside;
let ksi = 0;
let eta = 0;
if (inside) {
const [v0, v1, v2, v3] = vertices;
// Function to calculate distance from point to line segment
const getDistanceFromLine = (p1, p2) => {
const num = Math.abs((p2[0] - p1[0]) * (p1[1] - y) - (p1[0] - x) * (p2[1] - p1[1]));
const den = Math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2);
return num / den;
};
// Calculate distances to edges based on vertex order:
// 1 (v1) --- 3 (v3)
// | |
// 0 (v0) --- 2 (v2)
const distLeft = getDistanceFromLine(v0, v1);
const distRight = getDistanceFromLine(v2, v3);
const distBottom = getDistanceFromLine(v0, v2);
const distTop = getDistanceFromLine(v1, v3);
ksi = distLeft / (distLeft + distRight);
eta = distBottom / (distBottom + distTop);
}
return { inside, ksi, eta };
}
/**
* Function to split the quadrilateral elements into two triangles
* @param {array} vertices - Quadrilateral vertices [[x0,y0],[x1,y1],[x2,y2],[x3,y3]]
* @returns {array} Array of triangle vertices: [[v0,v1,v3], [v0,v2,v3]]
*/
export function splitQuadrilateral(vertices) {
const [v0, v1, v2, v3] = vertices;
// Vertices order:
// 1 --- 3
// | |
// 0 --- 2
return [
[v0, v1, v3],
[v0, v2, v3],
];
}
/**
* Function that finds the list of adjacent elements for each node in the mesh
* @param {object} meshData - Object containing nodal numbering (NOP)
* @returns {object} Object containing:
* - nodeNeighbors: Indices of neighboring elements per node
* - neighborCount: Total number of neighboring elements per node
*/
export function computeNodeNeighbors(meshData) {
const { nop, nodesXCoordinates } = meshData;
const totalNodes = nodesXCoordinates.length;
const nodesPerElement = nop[0].length;
// Initialize arrays
const nodeNeighbors = Array.from({ length: totalNodes }, () => []);
const neighborCount = Array(totalNodes).fill(0);
// Loop through all elements
for (let elemIndex = 0; elemIndex < nop.length; elemIndex++) {
for (let localNodeIndex = 0; localNodeIndex < nodesPerElement; localNodeIndex++) {
const nodeIndex = nop[elemIndex][localNodeIndex] - 1;
// Increment the total number of neighboring elements for this node
neighborCount[nodeIndex] = neighborCount[nodeIndex] + 1;
// Store the element index as a neighbor of this node
nodeNeighbors[nodeIndex].push(elemIndex);
}
}
return { nodeNeighbors, neighborCount };
}
/**
* Function to extracts boundary line segments for ray casting
* @param {object} meshData - Object containing mesh data
* @returns {array} Array of segments
*/
export function getBoundarySegments(meshData) {
let boundaryLineElements = [];
let boundaryNodesSegments = [];
let boundaryGlobalElementIndex = 0;
let boundarySides;
const { nodesXCoordinates, nodesYCoordinates, nop, boundaryElements, meshDimension, elementOrder } =
meshData;
if (meshDimension === "1D") {
if (elementOrder === "linear") {
boundarySides = {
0: [0], // Node at the left side of the reference element
1: [1], // Node at the right side of the reference element
};
} else if (elementOrder === "quadratic") {
boundarySides = {
0: [0], // Node at the left side of the reference element
1: [1], // Node at the right side of the reference element
};
}
} else if (meshDimension === "2D") {
if (elementOrder === "linear") {
boundarySides = {
0: [0, 2], // Nodes at the bottom side of the reference element
1: [0, 1], // Nodes at the left side of the reference element
2: [1, 3], // Nodes at the top side of the reference element
3: [2, 3], // Nodes at the right side of the reference element
};
} else if (elementOrder === "quadratic") {
boundarySides = {
0: [0, 3, 6], // Nodes at the bottom side of the reference element
1: [0, 1, 2], // Nodes at the left side of the reference element
2: [2, 5, 8], // Nodes at the top side of the reference element
3: [6, 7, 8], // Nodes at the right side of the reference element
};
}
}
// Iterate over all boundaries
for (let boundaryIndex = 0; boundaryIndex < boundaryElements.length; boundaryIndex++) {
// Iterate over all elements in the current boundary
for (
let boundaryLocalElementIndex = 0;
boundaryLocalElementIndex < boundaryElements[boundaryIndex].length;
boundaryLocalElementIndex++
) {
boundaryLineElements[boundaryGlobalElementIndex] =
boundaryElements[boundaryIndex][boundaryLocalElementIndex];
boundaryGlobalElementIndex++;
// Retrieve the element index and the side
const [elementIndex, side] = boundaryElements[boundaryIndex][boundaryLocalElementIndex];
let boundaryLocalNodeIndices = boundarySides[side];
let currentElementNodesX = [];
let currentElementNodesY = [];
for (
let boundaryLocalNodeIndex = 0;
boundaryLocalNodeIndex < boundaryLocalNodeIndices.length;
boundaryLocalNodeIndex++
) {
const globalNodeIndex = nop[elementIndex][boundaryLocalNodeIndices[boundaryLocalNodeIndex]] - 1;
currentElementNodesX.push(nodesXCoordinates[globalNodeIndex]);
currentElementNodesY.push(nodesYCoordinates[globalNodeIndex]);
}
// Create segments for this element
for (let k = 0; k < currentElementNodesX.length - 1; k++) {
boundaryNodesSegments.push([
[currentElementNodesX[k], currentElementNodesY[k]],
[currentElementNodesX[k + 1], currentElementNodesY[k + 1]],
]);
}
}
}
return boundaryNodesSegments;
}