multimodalart HF Staff commited on
Commit
3ca49df
·
verified ·
1 Parent(s): 7397c54

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,13 +1,26 @@
1
  ---
2
- title: Npsolver
3
- emoji: 📊
4
- colorFrom: red
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: NPSolver
3
+ emoji: 🌡️
4
+ colorFrom: blue
5
+ colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.32.0
 
8
  app_file: app.py
9
+ python_version: "3.12"
10
+ short_description: Neural Poisson solver on irregular 2D domains
11
+ startup_duration_timeout: 30m
12
+ models:
13
+ - bochengz/NPSolver_models
14
+ datasets:
15
+ - bochengz/NPSolver_datasets
16
  ---
17
 
18
+ # NPSolver: Neural Poisson Solver with Iterative Physics Supervision
19
+
20
+ Interactive demo of [NPSolver](https://huggingface.co/papers/2605.25786) (KDD 2026). It solves
21
+ ∇²u = f on corner-removed square domains with Dirichlet, Neumann or mixed walls using the authors'
22
+ pretrained BA-Transolver checkpoints ([bochengz/NPSolver_models](https://huggingface.co/bochengz/NPSolver_models)).
23
+ Each prediction is checked against a direct sparse solve of the same finite-volume system.
24
+
25
+ Domain meshes are the authors' test meshes from [bochengz/NPSolver_datasets](https://huggingface.co/datasets/bochengz/NPSolver_datasets), downloaded at runtime.
26
+ Model code is adapted from https://github.com/intell-sci-comput/NPSolver (MIT).
app.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces # must be imported before torch
2
+
3
+ import io
4
+ import time
5
+ from functools import lru_cache
6
+
7
+ import gradio as gr
8
+ import matplotlib
9
+
10
+ matplotlib.use("Agg")
11
+ import matplotlib.pyplot as plt
12
+ import matplotlib.tri as mtri
13
+ import numpy as np
14
+ import torch
15
+ from huggingface_hub import hf_hub_download
16
+ from PIL import Image
17
+
18
+ from ba_transolver.Transolver_Irregular_Mesh import Model
19
+ from npsolver_core import (FIXED_VALUE, GEOMETRIES, MODEL_REPO, ZERO_GRADIENT, DATA_REPO, expr_source,
20
+ face_bc_types, fourier_source, load_mesh, mean_zero, reference_solve,
21
+ residual_rms, wall_patches)
22
+
23
+ # ----------------------------------------------------------------------------- models
24
+ CKPTS = {"dirichlet": 2, "neumann": 2, "random_bc": 4} # name -> boundary token dim
25
+
26
+
27
+ def build_model(name, bdry_dim):
28
+ m = Model(space_dim=2, n_layers=10, n_hidden=256, dropout=0.0, n_head=8, Time_Input=False, mlp_ratio=1,
29
+ fun_dim=1, bdry_dim=bdry_dim, out_dim=1, slice_num=[64, 8], ref=8, unified_pos=False)
30
+ path = hf_hub_download(MODEL_REPO, f"ba-transolver_{name}/ckpt_min/checkpoint.pth")
31
+ sd = torch.load(path, map_location="cpu", weights_only=False)["model_state_dict"]
32
+ m.load_state_dict(sd)
33
+ return m.eval().to("cuda")
34
+
35
+
36
+ MODELS = {name: build_model(name, bd) for name, bd in CKPTS.items()}
37
+
38
+ # pre-fetch the authors' test meshes (geometry presets)
39
+ for _f, _ in GEOMETRIES.values():
40
+ hf_hub_download(DATA_REPO, _f, repo_type="dataset")
41
+
42
+ BC_DIRICHLET = "All Dirichlet (u = 0)"
43
+ BC_NEUMANN = "All Neumann (∂u/∂n = 0)"
44
+ BC_MIXED = "Mixed (pick Neumann walls)"
45
+ SRC_FOURIER = "Random Fourier field (training distribution)"
46
+ SRC_EXPR = "Custom expression f(x, y)"
47
+ WALL_CHOICES = [str(i) for i in range(1, 13)]
48
+ DIR_COLOR, NEU_COLOR = "#1f4e9c", "#e08a00"
49
+
50
+
51
+ @lru_cache(maxsize=64)
52
+ def get_mesh(geometry, index):
53
+ m = load_mesh(geometry, int(index))
54
+ pos = m["pos"]
55
+ tri = mtri.Triangulation(pos[:, 0], pos[:, 1])
56
+ t = tri.triangles
57
+ p = pos[t]
58
+ edges = np.stack([np.linalg.norm(p[:, 0] - p[:, 1], axis=1), np.linalg.norm(p[:, 1] - p[:, 2], axis=1),
59
+ np.linalg.norm(p[:, 2] - p[:, 0], axis=1)], 1).max(1)
60
+ h = 1.0 / float(np.median(m["deltaCoeff"])) # cell spacing (volume includes z-depth)
61
+ tri.set_mask(edges > 2.2 * h)
62
+ m["tri"] = tri
63
+ return m
64
+
65
+
66
+ def resolve_bc(m, bc_mode, neumann_walls):
67
+ walls = wall_patches(m)
68
+ chosen = {int(w) for w in (neumann_walls or [])}
69
+ types = {}
70
+ for k, p in enumerate(walls, start=1):
71
+ if bc_mode == BC_DIRICHLET:
72
+ types[p] = FIXED_VALUE
73
+ elif bc_mode == BC_NEUMANN:
74
+ types[p] = ZERO_GRADIENT
75
+ else:
76
+ types[p] = ZERO_GRADIENT if k in chosen else FIXED_VALUE
77
+ return walls, types
78
+
79
+
80
+ def fig_to_pil(fig):
81
+ buf = io.BytesIO()
82
+ fig.savefig(buf, format="png", dpi=110, bbox_inches="tight")
83
+ plt.close(fig)
84
+ buf.seek(0)
85
+ return Image.open(buf).convert("RGB")
86
+
87
+
88
+ def _draw_walls(ax, m, walls, types, label=True):
89
+ for k, p in enumerate(walls, start=1):
90
+ o, s = m["patchOffset"][p], m["patchSize"][p]
91
+ pts = m["pos_bd"][o:o + s]
92
+ c = DIR_COLOR if types[p] == FIXED_VALUE else NEU_COLOR
93
+ ax.scatter(pts[:, 0], pts[:, 1], s=6 if label else 3, color=c, zorder=3)
94
+ if label:
95
+ mid = pts[len(pts) // 2]
96
+ ctr = np.array([np.pi, np.pi])
97
+ d = mid - ctr
98
+ d = d / (np.linalg.norm(d) + 1e-9)
99
+ ax.text(*(mid + 0.35 * d), str(k), ha="center", va="center", fontsize=10, weight="bold",
100
+ bbox=dict(boxstyle="circle,pad=0.2", fc="white", ec=c, lw=1.5), zorder=4)
101
+
102
+
103
+ def preview(geometry, sample_index, bc_mode, neumann_walls):
104
+ """Render the selected domain with numbered walls coloured by boundary-condition type."""
105
+ m = get_mesh(geometry, sample_index)
106
+ walls, types = resolve_bc(m, bc_mode, neumann_walls)
107
+ fig, ax = plt.subplots(figsize=(4.6, 4.6))
108
+ ax.tripcolor(m["tri"], np.ones(len(m["pos"])), cmap="Greys", vmin=0, vmax=4, shading="gouraud")
109
+ _draw_walls(ax, m, walls, types)
110
+ ax.set_xlim(-0.7, 2 * np.pi + 0.7)
111
+ ax.set_ylim(-0.7, 2 * np.pi + 0.7)
112
+ ax.set_aspect("equal")
113
+ ax.axis("off")
114
+ ax.scatter([], [], color=DIR_COLOR, label="Dirichlet u = 0")
115
+ ax.scatter([], [], color=NEU_COLOR, label="Neumann ∂u/∂n = 0")
116
+ ax.legend(loc="upper center", bbox_to_anchor=(0.5, 0.0), ncol=2, frameon=False, fontsize=9)
117
+ ax.set_title(f"{geometry} · {len(m['pos']):,} cells · {len(walls)} walls", fontsize=10)
118
+ return fig_to_pil(fig)
119
+
120
+
121
+ @spaces.GPU(duration=20)
122
+ def solve(geometry: str, sample_index: int = 0, bc_mode: str = BC_DIRICHLET, neumann_walls: list = None,
123
+ source_type: str = SRC_FOURIER, seed: int = 0, expression: str = "sin(2*x) * cos(3*y)"):
124
+ """Solve the Poisson equation ∇²u = f on an irregular 2D domain with NPSolver (BA-Transolver).
125
+
126
+ Args:
127
+ geometry: one of the domain presets (square with 0-4 corners removed), domain is [0, 2π]².
128
+ sample_index: which of the authors' test meshes for that geometry (0-9).
129
+ bc_mode: all Dirichlet (u=0), all Neumann (zero normal gradient), or mixed per wall.
130
+ neumann_walls: wall numbers (1-12, see preview) that are Neumann in mixed mode; others are Dirichlet.
131
+ source_type: random Fourier source (the training distribution) or a custom expression.
132
+ seed: random seed for the Fourier source.
133
+ expression: numpy expression in x, y for the custom source term, e.g. "sin(2*x)*cos(3*y)".
134
+
135
+ Returns:
136
+ A figure (source | NPSolver | FVM reference | |error|) and a markdown metrics table.
137
+ """
138
+ m = get_mesh(geometry, sample_index)
139
+ walls, types = resolve_bc(m, bc_mode, neumann_walls)
140
+ bc_faces = face_bc_types(m, types)
141
+ n_dir = int(sum(t == FIXED_VALUE for t in types.values()))
142
+ if n_dir == len(walls):
143
+ name = "dirichlet"
144
+ elif n_dir == 0:
145
+ name = "neumann"
146
+ else:
147
+ name = "random_bc"
148
+
149
+ pos = m["pos"]
150
+ if source_type == SRC_FOURIER:
151
+ f = fourier_source(pos, int(seed))
152
+ else:
153
+ try:
154
+ f = expr_source(pos, expression)
155
+ except Exception as e: # noqa: BLE001
156
+ raise gr.Error(f"Could not evaluate source expression: {e}")
157
+ if name != "dirichlet": # authors' norm_f=True: volume-weighted zero-mean source
158
+ f = mean_zero(f, m["volume"])
159
+ scale = float(np.abs(f).max())
160
+ if scale < 1e-12:
161
+ raise gr.Error("The source term is (numerically) zero on this domain; the solution is trivially u = 0.")
162
+ f_in = f / scale # the model was trained on max-normalised sources; Poisson is linear -> rescale after
163
+
164
+ x_bd = m["pos_bd"]
165
+ if name == "random_bc":
166
+ x_bd = np.concatenate([x_bd, np.eye(2, dtype=np.float32)[bc_faces]], -1)
167
+
168
+ model = MODELS[name]
169
+ with torch.no_grad():
170
+ x_t = torch.from_numpy(pos).float().cuda()[None]
171
+ f_t = torch.from_numpy(f_in).float().cuda()[None, :, None]
172
+ b_t = torch.from_numpy(np.ascontiguousarray(x_bd)).float().cuda()[None]
173
+ model(x_t, f_t, b_t) # warm-up
174
+ torch.cuda.synchronize()
175
+ t0 = time.perf_counter()
176
+ p = model(x_t, f_t, b_t)[0, :, 0]
177
+ torch.cuda.synchronize()
178
+ t_model = time.perf_counter() - t0
179
+ p = p.double().cpu().numpy() * scale
180
+ if name == "neumann":
181
+ p = p - p[0] # reference cell, as in the authors' Neumann trainer
182
+
183
+ t0 = time.perf_counter()
184
+ p_ref, A, b = reference_solve(m, f, bc_faces)
185
+ t_ref = time.perf_counter() - t0
186
+
187
+ err = np.abs(p - p_ref)
188
+ rel_l2 = float(np.linalg.norm(p - p_ref) / (np.linalg.norm(p_ref) + 1e-12))
189
+ r_model, r_ref = residual_rms(A, b, p), residual_rms(A, b, p_ref)
190
+
191
+ fig, axes = plt.subplots(1, 4, figsize=(17, 4.4))
192
+ vmin, vmax = float(min(p.min(), p_ref.min())), float(max(p.max(), p_ref.max()))
193
+ panels = [(f, "Source term f", "RdBu_r", None, None), (p, "NPSolver prediction", "viridis", vmin, vmax),
194
+ (p_ref, "FVM reference (direct solve)", "viridis", vmin, vmax), (err, "|error|", "magma", 0, None)]
195
+ for ax, (val, title, cmap, lo, hi) in zip(axes, panels):
196
+ if cmap == "RdBu_r":
197
+ a = float(np.abs(val).max())
198
+ lo, hi = -a, a
199
+ im = ax.tripcolor(m["tri"], val, cmap=cmap, vmin=lo, vmax=hi, shading="gouraud")
200
+ _draw_walls(ax, m, walls, types, label=False)
201
+ ax.set_aspect("equal")
202
+ ax.set_title(title, fontsize=11)
203
+ ax.set_xticks([])
204
+ ax.set_yticks([])
205
+ fig.colorbar(im, ax=ax, fraction=0.046, pad=0.03)
206
+ fig.tight_layout()
207
+
208
+ labels = {"dirichlet": "ba-transolver_dirichlet", "neumann": "ba-transolver_neumann",
209
+ "random_bc": "ba-transolver_random_bc"}
210
+ md = (
211
+ f"| | |\n|---|---|\n"
212
+ f"| Checkpoint | `{labels[name]}` |\n"
213
+ f"| Mesh | {len(pos):,} cells, {len(walls)} walls ({n_dir} Dirichlet / {len(walls) - n_dir} Neumann) |\n"
214
+ f"| Relative L2 error vs. FVM | **{rel_l2:.2%}** |\n"
215
+ f"| Max abs error | {err.max():.3e} (solution range {p_ref.min():.3e} … {p_ref.max():.3e}) |\n"
216
+ f"| FVM residual RMS (NPSolver / direct solve) | {r_model:.2e} / {r_ref:.2e} |\n"
217
+ f"| Time: NPSolver forward (GPU) / sparse direct solve (CPU) | {t_model * 1000:.1f} ms / {t_ref * 1000:.1f} ms |\n"
218
+ )
219
+ if name != "dirichlet":
220
+ md += "\n*The source was made zero-mean (volume-weighted), following the authors' setup for Neumann / mixed BCs.*"
221
+ return fig_to_pil(fig), md
222
+
223
+
224
+ CSS = """
225
+ #col-container { max-width: 1250px; margin: 0 auto; }
226
+ .dark .gradio-container { color: var(--body-text-color); }
227
+ """
228
+
229
+ with gr.Blocks() as demo:
230
+ with gr.Column(elem_id="col-container"):
231
+ gr.Markdown(
232
+ "# NPSolver: Neural Poisson Solver\n"
233
+ "Solve **∇²u = f** on irregular 2D domains with homogeneous Dirichlet / Neumann / mixed walls using "
234
+ "**NPSolver** (BA-Transolver trained label-free with iterative physics supervision, KDD 2026). "
235
+ "Each prediction is compared with a direct sparse solve of the same finite-volume system.\n\n"
236
+ "[Paper](https://huggingface.co/papers/2605.25786) · [Code](https://github.com/intell-sci-comput/NPSolver) · "
237
+ "[Checkpoints](https://huggingface.co/bochengz/NPSolver_models) · "
238
+ "[Data](https://huggingface.co/datasets/bochengz/NPSolver_datasets)"
239
+ )
240
+ with gr.Row():
241
+ with gr.Column(scale=1):
242
+ geometry = gr.Dropdown(list(GEOMETRIES.keys()), value="2 corners removed", label="Domain")
243
+ sample_index = gr.Slider(0, 9, value=0, step=1, label="Mesh sample",
244
+ info="Authors' test meshes (ignored for the square)")
245
+ bc_mode = gr.Radio([BC_DIRICHLET, BC_NEUMANN, BC_MIXED], value=BC_DIRICHLET,
246
+ label="Boundary conditions")
247
+ neumann_walls = gr.CheckboxGroup(WALL_CHOICES, value=[], label="Neumann walls (mixed mode)",
248
+ info="Wall numbers from the preview; unchecked walls are Dirichlet")
249
+ source_type = gr.Radio([SRC_FOURIER, SRC_EXPR], value=SRC_FOURIER, label="Source term f")
250
+ with gr.Row():
251
+ seed = gr.Number(value=0, precision=0, label="Fourier seed")
252
+ expression = gr.Textbox(value="sin(2*x) * cos(3*y)", label="f(x, y), x, y ∈ [0, 2π]",
253
+ info="numpy syntax: sin, cos, exp, sqrt, pi, ...")
254
+ run = gr.Button("Solve", variant="primary")
255
+ with gr.Column(scale=1):
256
+ geo_preview = gr.Image(label="Domain & boundary conditions", type="pil", height=440)
257
+ result = gr.Image(label="Result", type="pil")
258
+ metrics = gr.Markdown()
259
+
260
+ gr.Examples(
261
+ examples=[
262
+ ["2 corners removed", 3, BC_DIRICHLET, [], SRC_FOURIER, 7, "sin(2*x) * cos(3*y)"],
263
+ ["4 corners removed", 0, BC_NEUMANN, [], SRC_FOURIER, 42, "sin(2*x) * cos(3*y)"],
264
+ ["3 corners removed", 5, BC_MIXED, ["1", "3", "5", "7", "9"], SRC_FOURIER, 3, "sin(2*x) * cos(3*y)"],
265
+ ["Square (no corners removed)", 0, BC_DIRICHLET, [], SRC_EXPR, 0, "sin(2*x) * cos(3*y)"],
266
+ ["1 corner removed", 2, BC_MIXED, ["2", "4"], SRC_EXPR, 0, "exp(-((x-2)**2 + (y-4)**2))"],
267
+ ],
268
+ inputs=[geometry, sample_index, bc_mode, neumann_walls, source_type, seed, expression],
269
+ outputs=[result, metrics],
270
+ fn=solve,
271
+ cache_examples=True,
272
+ cache_mode="lazy",
273
+ )
274
+
275
+ prev_inputs = [geometry, sample_index, bc_mode, neumann_walls]
276
+ for comp in prev_inputs:
277
+ comp.change(preview, prev_inputs, geo_preview, api_visibility="private")
278
+ demo.load(preview, prev_inputs, geo_preview, api_visibility="private")
279
+ run.click(solve, [geometry, sample_index, bc_mode, neumann_walls, source_type, seed, expression],
280
+ [result, metrics])
281
+
282
+ if __name__ == "__main__":
283
+ demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
ba_transolver/Embedding.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ from einops import rearrange
5
+
6
+
7
+ class RotaryEmbedding(nn.Module):
8
+ def __init__(self, dim, min_freq=1 / 2, scale=1.):
9
+ super().__init__()
10
+ inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim))
11
+ self.min_freq = min_freq
12
+ self.scale = scale
13
+ self.register_buffer('inv_freq', inv_freq)
14
+
15
+ def forward(self, coordinates, device):
16
+ # coordinates [b, n]
17
+ t = coordinates.to(device).type_as(self.inv_freq)
18
+ t = t * (self.scale / self.min_freq)
19
+ freqs = torch.einsum('... i , j -> ... i j', t, self.inv_freq) # [b, n, d//2]
20
+ return torch.cat((freqs, freqs), dim=-1) # [b, n, d]
21
+
22
+
23
+ def rotate_half(x):
24
+ x = rearrange(x, '... (j d) -> ... j d', j=2)
25
+ x1, x2 = x.unbind(dim=-2)
26
+ return torch.cat((-x2, x1), dim=-1)
27
+
28
+
29
+ def apply_rotary_pos_emb(t, freqs):
30
+ return (t * freqs.cos()) + (rotate_half(t) * freqs.sin())
31
+
32
+
33
+ def apply_2d_rotary_pos_emb(t, freqs_x, freqs_y):
34
+ # split t into first half and second half
35
+ # t: [b, h, n, d]
36
+ # freq_x/y: [b, n, d]
37
+ d = t.shape[-1]
38
+ t_x, t_y = t[..., :d // 2], t[..., d // 2:]
39
+
40
+ return torch.cat((apply_rotary_pos_emb(t_x, freqs_x),
41
+ apply_rotary_pos_emb(t_y, freqs_y)), dim=-1)
42
+
43
+
44
+ class PositionalEncoding(nn.Module):
45
+ "Implement the PE function."
46
+
47
+ def __init__(self, d_model, dropout, max_len=421 * 421):
48
+ super(PositionalEncoding, self).__init__()
49
+ self.dropout = nn.Dropout(p=dropout)
50
+
51
+ # Compute the positional encodings once in log space.
52
+ pe = torch.zeros(max_len, d_model)
53
+ position = torch.arange(0, max_len).unsqueeze(1)
54
+ div_term = torch.exp(
55
+ torch.arange(0, d_model, 2) * -(math.log(10000.0) / d_model)
56
+ )
57
+ pe[:, 0::2] = torch.sin(position * div_term)
58
+ pe[:, 1::2] = torch.cos(position * div_term)
59
+ pe = pe.unsqueeze(0)
60
+ self.register_buffer("pe", pe)
61
+
62
+ def forward(self, x):
63
+ x = x + self.pe[:, : x.size(1)].requires_grad_(False)
64
+ return self.dropout(x)
65
+
66
+
67
+ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
68
+ """
69
+ Create sinusoidal timestep embeddings.
70
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
71
+ These may be fractional.
72
+ :param dim: the dimension of the output.
73
+ :param max_period: controls the minimum frequency of the embeddings.
74
+ :return: an [N x dim] Tensor of positional embeddings.
75
+ """
76
+
77
+ half = dim // 2
78
+ freqs = torch.exp(
79
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
80
+ ).to(device=timesteps.device)
81
+ args = timesteps[:, None].float() * freqs[None]
82
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
83
+ if dim % 2:
84
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
85
+ return embedding
ba_transolver/Physics_Attention.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from einops import rearrange, repeat
5
+
6
+
7
+ class Physics_Attention_Irregular_Mesh(nn.Module):
8
+ """
9
+ Interior/Boundary 版本 Transolver-style Attention:
10
+
11
+ - 输入:
12
+ x_inter: (B, N_i_max, C)
13
+ x_bdry: (B, N_b_max, C) or None
14
+ mask_inter: (B, N_i_max) or None, True = 有效
15
+ mask_bdry: (B, N_b_max) or None, True = 有效
16
+ - 输出:
17
+ out_inter: (B, N_i_max, C) # 只更新 interior 节点
18
+ """
19
+ def __init__(
20
+ self,
21
+ dim,
22
+ heads=8,
23
+ dim_head=64,
24
+ dropout=0.,
25
+ slice_num=[64, 16],
26
+ ):
27
+ super().__init__()
28
+ inner_dim = dim_head * heads
29
+ self.dim_head = dim_head
30
+ self.heads = heads
31
+ self.scale = dim_head ** -0.5
32
+ self.softmax = nn.Softmax(dim=-1)
33
+ self.dropout = nn.Dropout(dropout)
34
+
35
+ # 温度:保持和原版一致的广播形状
36
+ self.temperature = nn.Parameter(torch.ones([1, heads, 1, 1]) * 0.5)
37
+
38
+ # 节点特征 -> head 维度
39
+ self.in_project_x = nn.Linear(dim, inner_dim)
40
+ self.in_project_fx = nn.Linear(dim, inner_dim)
41
+
42
+ # interior / boundary 各自 slice 数
43
+ self.slice_num_int = slice_num[0]
44
+ self.slice_num_bd = slice_num[1]
45
+
46
+ # interior 用的 slice projection
47
+ self.in_project_slice_int = nn.Linear(dim_head, self.slice_num_int)
48
+ torch.nn.init.orthogonal_(self.in_project_slice_int.weight)
49
+
50
+ # boundary 用的 slice projection
51
+ self.in_project_slice_bd = nn.Linear(dim_head, self.slice_num_bd)
52
+ torch.nn.init.orthogonal_(self.in_project_slice_bd.weight)
53
+
54
+ # 共用一套 q/k/v:既用于 interior self-attn,也用于 inter←bdry cross-attn
55
+ self.to_q = nn.Linear(dim_head, dim_head, bias=False)
56
+ self.to_k = nn.Linear(dim_head, dim_head, bias=False)
57
+ self.to_v = nn.Linear(dim_head, dim_head, bias=False)
58
+
59
+ self.to_out = nn.Sequential(
60
+ nn.Linear(inner_dim, dim),
61
+ nn.Dropout(dropout)
62
+ )
63
+
64
+ # 自注意力 / 交叉注意力的融合系数(可学习)
65
+ self.alpha_self = nn.Parameter(torch.tensor(1.0))
66
+ self.alpha_cross = nn.Parameter(torch.tensor(1.0))
67
+
68
+ def forward(self, x_inter, x_bdry, mask_inter=None, mask_bdry=None):
69
+ """
70
+ 只返回 interior 的输出 (B, N_i_max, C)
71
+ """
72
+
73
+ # ========= (1) interior / boundary 各自 slice ========= #
74
+ z_int, w_int, z_bd, _ = self.fast_slice_group(
75
+ x_inter, x_bdry,
76
+ mask_int=mask_inter,
77
+ mask_bd=mask_bdry
78
+ ) # z_int: (B,H,G_i,D), w_int: (B,H,N_i,G_i), z_bd: (B,H,G_b,D)
79
+
80
+ # ========= (2) token self-attn ========= #
81
+ # cat interior and boundary token
82
+ z_all = torch.cat([z_int, z_bd], dim=2) # (B,H,G_i+G_b,D)
83
+ # self-attention
84
+ q_all = self.to_q(z_all) # (B,H,G_i+G_b,D)
85
+ k_all = self.to_k(z_all)
86
+ v_all = self.to_v(z_all)
87
+
88
+ dots_self = torch.matmul(q_all, k_all.transpose(-1, -2)) * self.scale # (B,H,G_i+G_b,G_i+G_b)
89
+ attn_self = self.softmax(dots_self)
90
+ attn_self = self.dropout(attn_self)
91
+ z_all_out = torch.matmul(attn_self, v_all) # (B,H,G_i+G_b,D)
92
+
93
+
94
+ # ========= (3) Deslice:只回到 interior 节点 ========= #
95
+ z_int_out = z_all_out[:, :, :self.slice_num_int, :] # 取出 interior token 的输出部分
96
+ out_x_int = torch.einsum("bhgc,bhng->bhnc", z_int_out, w_int) # (B,H,N_i,D)
97
+
98
+ if mask_inter is not None:
99
+ node_mask_i = mask_inter[:, None, :, None].float()
100
+ out_x_int = out_x_int * node_mask_i
101
+
102
+ out_x_int = rearrange(out_x_int, "b h n d -> b n (h d)")
103
+ out_x_int = self.to_out(out_x_int) # (B, N_i_max, C)
104
+
105
+ return out_x_int
106
+
107
+ def fast_slice_group(self, x_int, x_bd, mask_int, mask_bd):
108
+ """
109
+ x: (B, N_max, C)
110
+ mask: (B, N_max) or None
111
+ 返回:
112
+ slice_token: (B, H, G, D)
113
+ slice_weights: (B, H, N_max, G)
114
+ """
115
+ B, N_int, _ = x_int.shape
116
+ _, N_bd, _ = x_bd.shape
117
+ H, D = self.heads, self.dim_head
118
+
119
+ if mask_int is not None:
120
+ node_mask_int = mask_int[:, None, :, None] # B 1 N 1
121
+ node_mask_f_int = node_mask_int.float()
122
+ node_mask_bd = mask_bd[:, None, :, None] # B 1 N 1
123
+ node_mask_f_bd = node_mask_bd.float()
124
+
125
+ x = torch.cat([x_int, x_bd], dim=1) # (B, N_total, C)
126
+ fx_mid = self.in_project_fx(x).reshape(B, N_int + N_bd, H, D) \
127
+ .permute(0, 2, 1, 3).contiguous() # B H N D
128
+ x_mid = self.in_project_x(x).reshape(B, N_int + N_bd, H, D) \
129
+ .permute(0, 2, 1, 3).contiguous() # B H N D
130
+
131
+ # padding 节点 feature 清零
132
+ fx_mid_int = fx_mid[:, :, :N_int, :]
133
+ x_mid_int = x_mid[:, :, :N_int, :]
134
+ fx_mid_bd = fx_mid[:, :, N_int:, :]
135
+ x_mid_bd = x_mid[:, :, N_int:, :]
136
+ if mask_int is not None:
137
+ fx_mid_int = fx_mid_int * node_mask_f_int
138
+ x_mid_int = x_mid_int * node_mask_f_int
139
+ fx_mid_bd = fx_mid_bd * node_mask_f_bd
140
+ x_mid_bd = x_mid_bd * node_mask_f_bd
141
+
142
+ # B H N G
143
+ slice_weights_int = self.softmax(self.in_project_slice_int(x_mid_int) / self.temperature) # softmax over G_i
144
+ slice_weights_bd = self.softmax(self.in_project_slice_bd(x_mid_bd) / self.temperature) # softmax over G_b
145
+ if mask_int is not None:
146
+ slice_weights_int = slice_weights_int * node_mask_f_int # padding 权重清零
147
+ slice_weights_bd = slice_weights_bd * node_mask_f_bd
148
+ slice_norm_int = slice_weights_int.sum(2) # B H G_i
149
+ slice_norm_bd = slice_weights_bd.sum(2) # B H G_b
150
+ slice_token_int = torch.einsum("bhnc,bhng->bhgc", fx_mid_int, slice_weights_int)
151
+ slice_token_int = slice_token_int / (slice_norm_int[..., None] + 1e-5) # B H G_i D
152
+ slice_token_bd = torch.einsum("bhnc,bhng->bhgc", fx_mid_bd, slice_weights_bd)
153
+ slice_token_bd = slice_token_bd / (slice_norm_bd[..., None] + 1e-5) # B H G_b D
154
+
155
+ return slice_token_int, slice_weights_int, slice_token_bd, slice_weights_bd
156
+
ba_transolver/Transolver_Irregular_Mesh.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn.init import trunc_normal_
4
+ from .Embedding import timestep_embedding
5
+ import numpy as np
6
+ from .Physics_Attention import Physics_Attention_Irregular_Mesh
7
+
8
+ ACTIVATION = {'gelu': nn.GELU, 'tanh': nn.Tanh, 'sigmoid': nn.Sigmoid, 'relu': nn.ReLU, 'leaky_relu': nn.LeakyReLU(0.1),
9
+ 'softplus': nn.Softplus, 'ELU': nn.ELU, 'silu': nn.SiLU}
10
+
11
+
12
+ class MLP(nn.Module):
13
+ def __init__(self, n_input, n_hidden, n_output, n_layers=1, act='gelu', res=True):
14
+ super(MLP, self).__init__()
15
+
16
+ if act in ACTIVATION.keys():
17
+ act = ACTIVATION[act]
18
+ else:
19
+ raise NotImplementedError
20
+ self.n_input = n_input
21
+ self.n_hidden = n_hidden
22
+ self.n_output = n_output
23
+ self.n_layers = n_layers
24
+ self.res = res
25
+ self.linear_pre = nn.Sequential(nn.Linear(n_input, n_hidden), act())
26
+ self.linear_post = nn.Linear(n_hidden, n_output)
27
+ self.linears = nn.ModuleList([nn.Sequential(nn.Linear(n_hidden, n_hidden), act()) for _ in range(n_layers)])
28
+
29
+ def forward(self, x):
30
+ x = self.linear_pre(x)
31
+ for i in range(self.n_layers):
32
+ if self.res:
33
+ x = self.linears[i](x) + x
34
+ else:
35
+ x = self.linears[i](x)
36
+ x = self.linear_post(x)
37
+ return x
38
+
39
+
40
+ class Transolver_block(nn.Module):
41
+ """Transformer encoder block."""
42
+
43
+ def __init__(
44
+ self,
45
+ num_heads: int,
46
+ hidden_dim: int,
47
+ dropout: float,
48
+ act='gelu',
49
+ mlp_ratio=4,
50
+ last_layer=False,
51
+ out_dim=1,
52
+ slice_num=32,
53
+ ):
54
+ super().__init__()
55
+ self.last_layer = last_layer
56
+ self.fx_ln_1 = nn.LayerNorm(hidden_dim)
57
+ self.fx_bd_ln_1 = nn.LayerNorm(hidden_dim)
58
+ self.Attn = Physics_Attention_Irregular_Mesh(hidden_dim, heads=num_heads, dim_head=hidden_dim // num_heads,
59
+ dropout=dropout, slice_num=slice_num)
60
+ self.fx_ln_2 = nn.LayerNorm(hidden_dim)
61
+ self.mlp = MLP(hidden_dim, hidden_dim * mlp_ratio, hidden_dim, n_layers=0, res=False, act=act)
62
+ if self.last_layer:
63
+ self.fx_ln_3 = nn.LayerNorm(hidden_dim)
64
+ self.mlp2 = nn.Linear(hidden_dim, out_dim)
65
+
66
+ def forward(self, fx, fx_bd, mask_inter, mask_bdry):
67
+ fx = self.fx_ln_1(fx)
68
+ fx_bd = self.fx_bd_ln_1(fx_bd)
69
+ fx = self.Attn(fx, fx_bd, mask_inter, mask_bdry) + fx
70
+ fx = self.mlp(self.fx_ln_2(fx)) + fx
71
+ if self.last_layer:
72
+ return self.mlp2(self.fx_ln_3(fx))
73
+ else:
74
+ return fx
75
+
76
+
77
+ class Model(nn.Module):
78
+ def __init__(self,
79
+ space_dim=1,
80
+ n_layers=5,
81
+ n_hidden=256,
82
+ dropout=0.0,
83
+ n_head=8,
84
+ Time_Input=False,
85
+ act='gelu',
86
+ mlp_ratio=1,
87
+ fun_dim=1,
88
+ out_dim=1,
89
+ bdry_dim=1,
90
+ slice_num=32,
91
+ ref=8,
92
+ unified_pos=False
93
+ ):
94
+ super(Model, self).__init__()
95
+ self.__name__ = 'Transolver_1D'
96
+ self.ref = ref
97
+ self.unified_pos = unified_pos
98
+ self.Time_Input = Time_Input
99
+ self.n_hidden = n_hidden
100
+ self.space_dim = space_dim
101
+ if self.unified_pos:
102
+ self.preprocess = MLP(fun_dim + self.ref * self.ref, n_hidden * 2, n_hidden, n_layers=0, res=False, act=act)
103
+ else:
104
+ self.preprocess = MLP(fun_dim + space_dim, n_hidden * 2, n_hidden, n_layers=0, res=False, act=act)
105
+ self.preprocess_bd = MLP(bdry_dim, n_hidden * 2, n_hidden, n_layers=0, res=False, act=act)
106
+ if Time_Input:
107
+ self.time_fc = nn.Sequential(nn.Linear(n_hidden, n_hidden), nn.SiLU(), nn.Linear(n_hidden, n_hidden))
108
+
109
+ self.blocks = nn.ModuleList([Transolver_block(num_heads=n_head, hidden_dim=n_hidden,
110
+ dropout=dropout,
111
+ act=act,
112
+ mlp_ratio=mlp_ratio,
113
+ out_dim=out_dim,
114
+ slice_num=slice_num,
115
+ last_layer=(_ == n_layers - 1))
116
+ for _ in range(n_layers)])
117
+ self.initialize_weights()
118
+ # self.placeholder = nn.Parameter((1 / (n_hidden)) * torch.rand(n_hidden, dtype=torch.float))
119
+
120
+ def initialize_weights(self):
121
+ self.apply(self._init_weights)
122
+
123
+ def _init_weights(self, m):
124
+ if isinstance(m, nn.Linear):
125
+ trunc_normal_(m.weight, std=0.02)
126
+ if isinstance(m, nn.Linear) and m.bias is not None:
127
+ nn.init.constant_(m.bias, 0)
128
+ elif isinstance(m, (nn.LayerNorm, nn.BatchNorm1d)):
129
+ nn.init.constant_(m.bias, 0)
130
+ nn.init.constant_(m.weight, 1.0)
131
+
132
+ def get_grid(self, x, batchsize=1):
133
+ # x: B N 2
134
+ # grid_ref
135
+ gridx = torch.tensor(np.linspace(0, 1, self.ref), dtype=torch.float)
136
+ gridx = gridx.reshape(1, self.ref, 1, 1).repeat([batchsize, 1, self.ref, 1])
137
+ gridy = torch.tensor(np.linspace(0, 1, self.ref), dtype=torch.float)
138
+ gridy = gridy.reshape(1, 1, self.ref, 1).repeat([batchsize, self.ref, 1, 1])
139
+ grid_ref = torch.cat((gridx, gridy), dim=-1).cuda().reshape(batchsize, self.ref * self.ref, 2) # B H W 8 8 2
140
+
141
+ pos = torch.sqrt(torch.sum((x[:, :, None, :] - grid_ref[:, None, :, :]) ** 2, dim=-1)). \
142
+ reshape(batchsize, x.shape[1], self.ref * self.ref).contiguous()
143
+ return pos
144
+
145
+ def forward(self, x, fx, x_bd, mask=None, mask_bd=None, T=None):
146
+ if self.unified_pos:
147
+ x = self.get_grid(x, x.shape[0])
148
+ if fx is not None:
149
+ fx = torch.cat((x, fx), -1)
150
+ fx = self.preprocess(fx)
151
+ fx_bd = self.preprocess_bd(x_bd)
152
+ else:
153
+ fx = self.preprocess(x)
154
+ # fx = fx + self.placeholder[None, None, :]
155
+
156
+ if T is not None:
157
+ Time_emb = timestep_embedding(T, self.n_hidden).repeat(1, x.shape[1], 1)
158
+ Time_emb = self.time_fc(Time_emb)
159
+ fx = fx + Time_emb
160
+
161
+ for block in self.blocks:
162
+ fx = block(fx, fx_bd, mask_inter=mask, mask_bdry=mask_bd)
163
+
164
+ return fx
ba_transolver/__init__.py ADDED
File without changes
npsolver_core.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core utilities for the NPSolver demo: mesh I/O, source terms, FVM reference solver."""
2
+ import h5py
3
+ import numpy as np
4
+ import scipy.sparse as sp
5
+ import scipy.sparse.linalg as spla
6
+ from huggingface_hub import hf_hub_download
7
+
8
+ DATA_REPO = "bochengz/NPSolver_datasets"
9
+ MODEL_REPO = "bochengz/NPSolver_models"
10
+
11
+ # PatchType enum from the original repo
12
+ ZERO_GRADIENT, FIXED_VALUE, EMPTY = 0, 1, 2
13
+
14
+ GEOMETRIES = {
15
+ "Square (no corners removed)": ("2d/mesh/test_corner0_mesh[N=1].h5", 1),
16
+ "1 corner removed": ("2d/mesh/test_corner1_mesh[N=10].h5", 10),
17
+ "2 corners removed": ("2d/mesh/test_corner2_mesh[N=10].h5", 10),
18
+ "3 corners removed": ("2d/mesh/test_corner3_mesh[N=10].h5", 10),
19
+ "4 corners removed": ("2d/mesh/test_corner4_mesh[N=10].h5", 10),
20
+ }
21
+
22
+ _KEYS = ["pos", "bou_faces_centroid", "volume", "lowerIndex", "upperIndex", "magSf", "deltaCoeff",
23
+ "bouMagSf", "bouDeltaCoeff", "face2cell", "patchSize", "patchOffset", "patchTypeP", "patchName"]
24
+
25
+
26
+ def load_mesh(geometry: str, index: int) -> dict:
27
+ fname, n = GEOMETRIES[geometry]
28
+ index = int(np.clip(index, 0, n - 1))
29
+ path = hf_hub_download(DATA_REPO, fname, repo_type="dataset")
30
+ with h5py.File(path, "r") as f:
31
+ g = f[str(index)]
32
+ m = {k: g[k][()] for k in _KEYS if k in g}
33
+ m["patchName"] = [p.decode() if isinstance(p, bytes) else str(p) for p in m.get("patchName", [])]
34
+ m["pos"] = m["pos"][:, :2].astype(np.float32)
35
+ m["pos_bd"] = m["bou_faces_centroid"][:, :2].astype(np.float32)
36
+ m["patchSize"] = m["patchSize"].reshape(-1)
37
+ m["patchOffset"] = m["patchOffset"].reshape(-1)
38
+ m["patchTypeP"] = m["patchTypeP"].reshape(-1)
39
+ return m
40
+
41
+
42
+ def wall_patches(m) -> list:
43
+ """Indices of non-empty (physical boundary) patches."""
44
+ return [i for i in range(len(m["patchSize"])) if m["patchTypeP"][i] != EMPTY and m["patchSize"][i] > 0]
45
+
46
+
47
+ def face_bc_types(m, patch_types: dict) -> np.ndarray:
48
+ """Per-boundary-face BC type (0 zeroGradient / 1 fixedValue)."""
49
+ nb = m["pos_bd"].shape[0]
50
+ bc = np.full(nb, FIXED_VALUE, dtype=np.int64)
51
+ for i, t in patch_types.items():
52
+ o, s = m["patchOffset"][i], m["patchSize"][i]
53
+ bc[o:o + s] = t
54
+ return bc
55
+
56
+
57
+ # ---------------------------------------------------------------- source terms
58
+ def fourier_source(pos: np.ndarray, seed: int, M: int = 10) -> np.ndarray:
59
+ """Random Fourier source exactly as in the authors' FourierGenerator (norm='max')."""
60
+ import torch
61
+ g = torch.Generator().manual_seed(int(seed))
62
+ xx = torch.tensor(pos[:, 0], dtype=torch.float32)
63
+ yy = torch.tensor(pos[:, 1], dtype=torch.float32)
64
+ alpha = torch.normal(0., 1., size=(M, M), generator=g)
65
+ beta = torch.normal(0., 1., size=(M, M), generator=g)
66
+ gamma = torch.normal(-1., 1., size=(1,), generator=g)
67
+ W = torch.zeros_like(xx)
68
+ for i in range(M):
69
+ for j in range(M):
70
+ phase = (i - M // 2) * xx + (j - M // 2) * yy
71
+ W = W + alpha[i, j] * torch.sin(phase) + beta[i, j] * torch.cos(phase)
72
+ U = W + gamma[0]
73
+ U = U / (U.abs().max() + 1e-8)
74
+ return U.numpy().astype(np.float64)
75
+
76
+
77
+ _SAFE = {k: getattr(np, k) for k in ["sin", "cos", "tan", "exp", "log", "sqrt", "abs", "tanh", "sinh",
78
+ "cosh", "arctan", "arctan2", "pi", "minimum", "maximum", "sign", "where"]}
79
+
80
+
81
+ def expr_source(pos: np.ndarray, expr: str) -> np.ndarray:
82
+ """Evaluate a user expression f(x, y) on cell centroids (domain is [0, 2π]²)."""
83
+ expr = (expr or "").strip().replace("^", "**")
84
+ if not expr:
85
+ raise ValueError("Empty source expression.")
86
+ if "__" in expr or "import" in expr or "lambda" in expr:
87
+ raise ValueError("Expression contains forbidden tokens.")
88
+ env = dict(_SAFE)
89
+ env.update(x=pos[:, 0].astype(np.float64), y=pos[:, 1].astype(np.float64), e=np.e)
90
+ val = eval(expr, {"__builtins__": {}}, env) # noqa: S307 (sandboxed namespace)
91
+ val = np.broadcast_to(np.asarray(val, dtype=np.float64), (pos.shape[0],)).copy()
92
+ if not np.all(np.isfinite(val)):
93
+ raise ValueError("Source expression produced NaN/Inf on the domain.")
94
+ return val
95
+
96
+
97
+ def mean_zero(f, volume):
98
+ v = volume.reshape(-1).astype(np.float64)
99
+ return f - np.sum(f * v) / np.sum(v)
100
+
101
+
102
+ # ---------------------------------------------------------------- FVM reference
103
+ def assemble(m, bc_faces: np.ndarray):
104
+ """Assemble the authors' FVM Laplacian (A p = f * vol) with homogeneous BCs as a scipy CSR."""
105
+ n = m["pos"].shape[0]
106
+ lo = m["lowerIndex"].astype(np.int64)
107
+ up = m["upperIndex"].astype(np.int64)
108
+ c = (m["deltaCoeff"] * m["magSf"]).reshape(-1).astype(np.float64)
109
+ diag = np.zeros(n)
110
+ np.add.at(diag, lo, -c)
111
+ np.add.at(diag, up, -c)
112
+ fixed = bc_faces == FIXED_VALUE
113
+ bcoef = -(m["bouDeltaCoeff"] * m["bouMagSf"]).reshape(-1).astype(np.float64)
114
+ np.add.at(diag, m["face2cell"][fixed], bcoef[fixed])
115
+ A = sp.coo_matrix((np.concatenate([c, c, diag]),
116
+ (np.concatenate([lo, up, np.arange(n)]), np.concatenate([up, lo, np.arange(n)]))),
117
+ shape=(n, n)).tocsr()
118
+ return A
119
+
120
+
121
+ def reference_solve(m, f, bc_faces):
122
+ A = assemble(m, bc_faces)
123
+ b = f * m["volume"].reshape(-1).astype(np.float64)
124
+ if not np.any(bc_faces == FIXED_VALUE):
125
+ # pure Neumann: pin reference cell 0 to zero (as in the authors' set_reference_pressure)
126
+ A = A.tolil()
127
+ A[0, :] = 0
128
+ A[:, 0] = 0
129
+ A[0, 0] = 1.0
130
+ A = A.tocsr()
131
+ b = b.copy()
132
+ b[0] = 0.0
133
+ p = spla.spsolve(A.tocsc(), b)
134
+ return p, A, b
135
+
136
+
137
+ def residual_rms(A, b, p):
138
+ return float(np.sqrt(np.mean((b - A @ p) ** 2)))
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ torch
2
+ numpy
3
+ scipy
4
+ h5py
5
+ einops
6
+ matplotlib
7
+ pillow