Repository navigation
Expand file tree
/
Copy pathqs-worker.js
More file actions
185 lines (176 loc) · 6.83 KB
/
Copy pathqs-worker.js
File metadata and controls
185 lines (176 loc) · 6.83 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
// Live result of the home page example, worked out off the main thread so the sliders and the hole drag stay smooth.
// For each request the worker meshes the fin (again only when the hole has moved or changed size), solves the model,
// and samples the temperature on the plot grid; the page draws it with one Plotly.react.
//
// The field is sampled here rather than with plotInterpolatedSolution, which locates each grid point in the mesh and
// takes about ten times as long as the solve: walking each element over the grid points it covers gives the same
// values (the quadratic shape functions of the element) in well under a millisecond.
let core = null;
let mesh = null;
let meshKey = "";
let meshLines = null;
// The fin and the plot grid: 0.02 m between grid points, as in the contour plots of FEAScript
const W = 4;
const H = 2;
const NX = 201;
const NY = 101;
const SIZE = 0.25; // Element side of the mesh
const HOLE_POINTS = 48; // Sides of the polygon that stands for the round hole
// The geometry of the model, as the code of the Browser tab writes it
const geometryOf = (hole) => ({
shape: {
start: [0, 0],
boundaries: [
{ name: "bottom", to: [W, 0] },
{ name: "right", to: [W, H] },
{ name: "top", to: [0, H] },
{ name: "left" },
],
},
holes: [
{
name: "hole",
points: Array.from({ length: HOLE_POINTS }, (_, i) => {
const angle = (2 * Math.PI * i) / HOLE_POINTS;
return [hole.x + hole.r * Math.cos(angle), hole.y + hole.r * Math.sin(angle)];
}),
},
],
});
// Each element edge once, through its mid-side node, as one polyline with null gaps
const buildMeshLines = () => {
const xs = mesh.nodesXCoordinates;
const ys = mesh.nodesYCoordinates;
const x = [];
const y = [];
const seen = new Set();
for (const element of mesh.nodalNumbering) {
const [a, ac, c, ab, bc, b] = element.map((n) => n - 1);
for (const [p, m, q] of [
[a, ab, b],
[b, bc, c],
[c, ac, a],
]) {
const key = p < q ? `${p}-${q}` : `${q}-${p}`;
if (seen.has(key)) continue;
seen.add(key);
x.push(xs[p], xs[m], xs[q], null);
y.push(ys[p], ys[m], ys[q], null);
}
}
return { x, y };
};
/**
* Function to sample the solution on the plot grid: each 6-node triangle (FEAScript order: corners 0, 5 and 2,
* mid-sides 3, 4 and 1) gives the grid points inside it the value of its quadratic shape functions
* @returns {Array<number|null>} The values, row by row (y), null outside the domain
*/
const raster = (mesh, xs, ys, u) => {
const z = new Array(NX * NY).fill(null);
const dx = W / (NX - 1);
const dy = H / (NY - 1);
for (const element of mesh.nodalNumbering) {
const [a, ac, c, ab, bc, b] = element.map((n) => n - 1);
const [ax, ay, bx, by, cx, cy] = [xs[a], ys[a], xs[b], ys[b], xs[c], ys[c]];
const det = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
const i0 = Math.max(0, Math.ceil(Math.min(ax, bx, cx) / dx - 1e-9));
const i1 = Math.min(NX - 1, Math.floor(Math.max(ax, bx, cx) / dx + 1e-9));
const j0 = Math.max(0, Math.ceil(Math.min(ay, by, cy) / dy - 1e-9));
const j1 = Math.min(NY - 1, Math.floor(Math.max(ay, by, cy) / dy + 1e-9));
for (let j = j0; j <= j1; j++) {
const y = j * dy;
for (let i = i0; i <= i1; i++) {
const x = i * dx;
// Area coordinates of the point
const la = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / det;
const lb = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / det;
const lc = 1 - la - lb;
if (la < -1e-9 || lb < -1e-9 || lc < -1e-9) continue;
z[j * NX + i] =
u[a] * la * (2 * la - 1) +
u[b] * lb * (2 * lb - 1) +
u[c] * lc * (2 * lc - 1) +
4 * (u[ab] * la * lb + u[bc] * lb * lc + u[ac] * la * lc);
}
}
}
return z;
};
// Carry the field a few grid cells into the hole, from the nearest sampled points. Plotly leaves a whole grid cell
// blank where a corner has no value, which gives the hole a stepped edge; the page covers the hole with an exact
// circle instead, so the field has to reach under its edge
const fillHoleEdge = (field, passes = 4) => {
let z = field;
for (let pass = 0; pass < passes; pass++) {
const next = z.slice();
for (let j = 0; j < NY; j++) {
for (let i = 0; i < NX; i++) {
if (z[j * NX + i] !== null) continue;
let sum = 0;
let count = 0;
for (let dj = -1; dj <= 1; dj++) {
for (let di = -1; di <= 1; di++) {
const jj = j + dj;
const ii = i + di;
if (jj < 0 || jj >= NY || ii < 0 || ii >= NX) continue;
const value = z[jj * NX + ii];
if (value !== null) {
sum += value;
count++;
}
}
}
if (count > 0) next[j * NX + i] = sum / count;
}
}
z = next;
}
return z;
};
const solve = ({ temp, hk, ext, hole }) => {
const start = performance.now();
const key = `${hole.x},${hole.y},${hole.r}`;
if (key !== meshKey) {
mesh = core.generateTriangleMesh(geometryOf(hole), { size: SIZE, elementOrder: "quadratic" });
meshKey = key;
meshLines = buildMeshLines();
}
const meshed = performance.now();
const model = new core.FEAScriptModel();
model.setModelConfig("heatConduction", { solver: { method: "frontal" } });
model.setMesh(mesh);
model.addBoundaryCondition("bottom", { type: "constantTemperature", temperature: temp });
model.addBoundaryCondition("left", { type: "symmetry" });
model.addBoundaryCondition("top", { type: "convection", h: hk, ambientTemperature: ext });
model.addBoundaryCondition("right", { type: "constantTemperature", temperature: temp });
model.addBoundaryCondition("hole", { type: "convection", h: hk, ambientTemperature: ext });
const result = model.solve();
const solved = performance.now();
return { result, meshTime: meshed - start, solveTime: solved - meshed };
};
self.onmessage = async ({ data: message }) => {
try {
if (message.type === "init") {
core = await import(message.coreUrl);
core.logSystem?.("none");
self.postMessage({ type: "ready", version: core.version, grid: { W, H, NX, NY } });
return;
}
const { result, meshTime, solveTime } = solve(message.values);
const { nodesXCoordinates: xs, nodesYCoordinates: ys } = result.nodesCoordinates;
const u = Array.from(result.solutionVector, (value) => (Array.isArray(value) ? value[0] : value));
const z = fillHoleEdge(raster(mesh, xs, ys, u));
const rows = Array.from({ length: NY }, (_, j) => z.slice(j * NX, (j + 1) * NX));
self.postMessage({
type: "result",
meshTime,
solveTime,
nodes: xs.length,
range: [Math.min(...u), Math.max(...u)],
z: rows,
meshLines,
});
} catch (error) {
self.postMessage({ type: "error", message: String(error?.message || error) });
}
};