File size: 13,195 Bytes
3ca49df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7977564
3ca49df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import spaces  # must be imported before torch

import io
import time
from functools import lru_cache

import gradio as gr
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from ba_transolver.Transolver_Irregular_Mesh import Model
from npsolver_core import (FIXED_VALUE, GEOMETRIES, MODEL_REPO, ZERO_GRADIENT, DATA_REPO, expr_source,
                           face_bc_types, fourier_source, load_mesh, mean_zero, reference_solve,
                           residual_rms, wall_patches)

# ----------------------------------------------------------------------------- models
CKPTS = {"dirichlet": 2, "neumann": 2, "random_bc": 4}  # name -> boundary token dim


def build_model(name, bdry_dim):
    m = Model(space_dim=2, n_layers=10, n_hidden=256, dropout=0.0, n_head=8, Time_Input=False, mlp_ratio=1,
              fun_dim=1, bdry_dim=bdry_dim, out_dim=1, slice_num=[64, 8], ref=8, unified_pos=False)
    path = hf_hub_download(MODEL_REPO, f"ba-transolver_{name}/ckpt_min/checkpoint.pth")
    sd = torch.load(path, map_location="cpu", weights_only=False)["model_state_dict"]
    m.load_state_dict(sd)
    return m.eval().to("cuda")


MODELS = {name: build_model(name, bd) for name, bd in CKPTS.items()}

# pre-fetch the authors' test meshes (geometry presets)
for _f, _ in GEOMETRIES.values():
    hf_hub_download(DATA_REPO, _f, repo_type="dataset")

BC_DIRICHLET = "All Dirichlet (u = 0)"
BC_NEUMANN = "All Neumann (∂u/∂n = 0)"
BC_MIXED = "Mixed (pick Neumann walls)"
SRC_FOURIER = "Random Fourier field (training distribution)"
SRC_EXPR = "Custom expression f(x, y)"
WALL_CHOICES = [str(i) for i in range(1, 13)]
DIR_COLOR, NEU_COLOR = "#1f4e9c", "#e08a00"


@lru_cache(maxsize=64)
def get_mesh(geometry, index):
    m = load_mesh(geometry, int(index))
    pos = m["pos"]
    tri = mtri.Triangulation(pos[:, 0], pos[:, 1])
    t = tri.triangles
    p = pos[t]
    edges = np.stack([np.linalg.norm(p[:, 0] - p[:, 1], axis=1), np.linalg.norm(p[:, 1] - p[:, 2], axis=1),
                      np.linalg.norm(p[:, 2] - p[:, 0], axis=1)], 1).max(1)
    h = 1.0 / float(np.median(m["deltaCoeff"]))  # cell spacing (volume includes z-depth)
    tri.set_mask(edges > 2.2 * h)
    m["tri"] = tri
    return m


def resolve_bc(m, bc_mode, neumann_walls):
    walls = wall_patches(m)
    chosen = {int(w) for w in (neumann_walls or [])}
    types = {}
    for k, p in enumerate(walls, start=1):
        if bc_mode == BC_DIRICHLET:
            types[p] = FIXED_VALUE
        elif bc_mode == BC_NEUMANN:
            types[p] = ZERO_GRADIENT
        else:
            types[p] = ZERO_GRADIENT if k in chosen else FIXED_VALUE
    return walls, types


def fig_to_pil(fig):
    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=110, bbox_inches="tight")
    plt.close(fig)
    buf.seek(0)
    return Image.open(buf).convert("RGB")


def _draw_walls(ax, m, walls, types, label=True):
    for k, p in enumerate(walls, start=1):
        o, s = m["patchOffset"][p], m["patchSize"][p]
        pts = m["pos_bd"][o:o + s]
        c = DIR_COLOR if types[p] == FIXED_VALUE else NEU_COLOR
        ax.scatter(pts[:, 0], pts[:, 1], s=6 if label else 3, color=c, zorder=3)
        if label:
            mid = pts[len(pts) // 2]
            ctr = np.array([np.pi, np.pi])
            d = mid - ctr
            d = d / (np.linalg.norm(d) + 1e-9)
            ax.text(*(mid + 0.35 * d), str(k), ha="center", va="center", fontsize=10, weight="bold",
                    bbox=dict(boxstyle="circle,pad=0.2", fc="white", ec=c, lw=1.5), zorder=4)


def preview(geometry, sample_index, bc_mode, neumann_walls):
    """Render the selected domain with numbered walls coloured by boundary-condition type."""
    m = get_mesh(geometry, sample_index)
    walls, types = resolve_bc(m, bc_mode, neumann_walls)
    fig, ax = plt.subplots(figsize=(4.6, 4.6))
    ax.tripcolor(m["tri"], np.ones(len(m["pos"])), cmap="Greys", vmin=0, vmax=4, shading="gouraud")
    _draw_walls(ax, m, walls, types)
    ax.set_xlim(-0.7, 2 * np.pi + 0.7)
    ax.set_ylim(-0.7, 2 * np.pi + 0.7)
    ax.set_aspect("equal")
    ax.axis("off")
    ax.scatter([], [], color=DIR_COLOR, label="Dirichlet  u = 0")
    ax.scatter([], [], color=NEU_COLOR, label="Neumann  ∂u/∂n = 0")
    ax.legend(loc="upper center", bbox_to_anchor=(0.5, 0.0), ncol=2, frameon=False, fontsize=9)
    ax.set_title(f"{geometry} · {len(m['pos']):,} cells · {len(walls)} walls", fontsize=10)
    return fig_to_pil(fig)


@spaces.GPU(duration=10)
def solve(geometry: str, sample_index: int = 0, bc_mode: str = BC_DIRICHLET, neumann_walls: list = None,
          source_type: str = SRC_FOURIER, seed: int = 0, expression: str = "sin(2*x) * cos(3*y)"):
    """Solve the Poisson equation ∇²u = f on an irregular 2D domain with NPSolver (BA-Transolver).

    Args:
        geometry: one of the domain presets (square with 0-4 corners removed), domain is [0, 2π]².
        sample_index: which of the authors' test meshes for that geometry (0-9).
        bc_mode: all Dirichlet (u=0), all Neumann (zero normal gradient), or mixed per wall.
        neumann_walls: wall numbers (1-12, see preview) that are Neumann in mixed mode; others are Dirichlet.
        source_type: random Fourier source (the training distribution) or a custom expression.
        seed: random seed for the Fourier source.
        expression: numpy expression in x, y for the custom source term, e.g. "sin(2*x)*cos(3*y)".

    Returns:
        A figure (source | NPSolver | FVM reference | |error|) and a markdown metrics table.
    """
    m = get_mesh(geometry, sample_index)
    walls, types = resolve_bc(m, bc_mode, neumann_walls)
    bc_faces = face_bc_types(m, types)
    n_dir = int(sum(t == FIXED_VALUE for t in types.values()))
    if n_dir == len(walls):
        name = "dirichlet"
    elif n_dir == 0:
        name = "neumann"
    else:
        name = "random_bc"

    pos = m["pos"]
    if source_type == SRC_FOURIER:
        f = fourier_source(pos, int(seed))
    else:
        try:
            f = expr_source(pos, expression)
        except Exception as e:  # noqa: BLE001
            raise gr.Error(f"Could not evaluate source expression: {e}")
    if name != "dirichlet":  # authors' norm_f=True: volume-weighted zero-mean source
        f = mean_zero(f, m["volume"])
    scale = float(np.abs(f).max())
    if scale < 1e-12:
        raise gr.Error("The source term is (numerically) zero on this domain; the solution is trivially u = 0.")
    f_in = f / scale  # the model was trained on max-normalised sources; Poisson is linear -> rescale after

    x_bd = m["pos_bd"]
    if name == "random_bc":
        x_bd = np.concatenate([x_bd, np.eye(2, dtype=np.float32)[bc_faces]], -1)

    model = MODELS[name]
    with torch.no_grad():
        x_t = torch.from_numpy(pos).float().cuda()[None]
        f_t = torch.from_numpy(f_in).float().cuda()[None, :, None]
        b_t = torch.from_numpy(np.ascontiguousarray(x_bd)).float().cuda()[None]
        model(x_t, f_t, b_t)  # warm-up
        torch.cuda.synchronize()
        t0 = time.perf_counter()
        p = model(x_t, f_t, b_t)[0, :, 0]
        torch.cuda.synchronize()
        t_model = time.perf_counter() - t0
        p = p.double().cpu().numpy() * scale
    if name == "neumann":
        p = p - p[0]  # reference cell, as in the authors' Neumann trainer

    t0 = time.perf_counter()
    p_ref, A, b = reference_solve(m, f, bc_faces)
    t_ref = time.perf_counter() - t0

    err = np.abs(p - p_ref)
    rel_l2 = float(np.linalg.norm(p - p_ref) / (np.linalg.norm(p_ref) + 1e-12))
    r_model, r_ref = residual_rms(A, b, p), residual_rms(A, b, p_ref)

    fig, axes = plt.subplots(1, 4, figsize=(17, 4.4))
    vmin, vmax = float(min(p.min(), p_ref.min())), float(max(p.max(), p_ref.max()))
    panels = [(f, "Source term f", "RdBu_r", None, None), (p, "NPSolver prediction", "viridis", vmin, vmax),
              (p_ref, "FVM reference (direct solve)", "viridis", vmin, vmax), (err, "|error|", "magma", 0, None)]
    for ax, (val, title, cmap, lo, hi) in zip(axes, panels):
        if cmap == "RdBu_r":
            a = float(np.abs(val).max())
            lo, hi = -a, a
        im = ax.tripcolor(m["tri"], val, cmap=cmap, vmin=lo, vmax=hi, shading="gouraud")
        _draw_walls(ax, m, walls, types, label=False)
        ax.set_aspect("equal")
        ax.set_title(title, fontsize=11)
        ax.set_xticks([])
        ax.set_yticks([])
        fig.colorbar(im, ax=ax, fraction=0.046, pad=0.03)
    fig.tight_layout()

    labels = {"dirichlet": "ba-transolver_dirichlet", "neumann": "ba-transolver_neumann",
              "random_bc": "ba-transolver_random_bc"}
    md = (
        f"| | |\n|---|---|\n"
        f"| Checkpoint | `{labels[name]}` |\n"
        f"| Mesh | {len(pos):,} cells, {len(walls)} walls ({n_dir} Dirichlet / {len(walls) - n_dir} Neumann) |\n"
        f"| Relative L2 error vs. FVM | **{rel_l2:.2%}** |\n"
        f"| Max abs error | {err.max():.3e} (solution range {p_ref.min():.3e} … {p_ref.max():.3e}) |\n"
        f"| FVM residual RMS (NPSolver / direct solve) | {r_model:.2e} / {r_ref:.2e} |\n"
        f"| Time: NPSolver forward (GPU) / sparse direct solve (CPU) | {t_model * 1000:.1f} ms / {t_ref * 1000:.1f} ms |\n"
    )
    if name != "dirichlet":
        md += "\n*The source was made zero-mean (volume-weighted), following the authors' setup for Neumann / mixed BCs.*"
    return fig_to_pil(fig), md


CSS = """
#col-container { max-width: 1250px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""

with gr.Blocks() as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(
            "# NPSolver: Neural Poisson Solver\n"
            "Solve **∇²u = f** on irregular 2D domains with homogeneous Dirichlet / Neumann / mixed walls using "
            "**NPSolver** (BA-Transolver trained label-free with iterative physics supervision, KDD 2026). "
            "Each prediction is compared with a direct sparse solve of the same finite-volume system.\n\n"
            "[Paper](https://huggingface.co/papers/2605.25786) · [Code](https://github.com/intell-sci-comput/NPSolver) · "
            "[Checkpoints](https://huggingface.co/bochengz/NPSolver_models) · "
            "[Data](https://huggingface.co/datasets/bochengz/NPSolver_datasets)"
        )
        with gr.Row():
            with gr.Column(scale=1):
                geometry = gr.Dropdown(list(GEOMETRIES.keys()), value="2 corners removed", label="Domain")
                sample_index = gr.Slider(0, 9, value=0, step=1, label="Mesh sample",
                                         info="Authors' test meshes (ignored for the square)")
                bc_mode = gr.Radio([BC_DIRICHLET, BC_NEUMANN, BC_MIXED], value=BC_DIRICHLET,
                                   label="Boundary conditions")
                neumann_walls = gr.CheckboxGroup(WALL_CHOICES, value=[], label="Neumann walls (mixed mode)",
                                                 info="Wall numbers from the preview; unchecked walls are Dirichlet")
                source_type = gr.Radio([SRC_FOURIER, SRC_EXPR], value=SRC_FOURIER, label="Source term f")
                with gr.Row():
                    seed = gr.Number(value=0, precision=0, label="Fourier seed")
                    expression = gr.Textbox(value="sin(2*x) * cos(3*y)", label="f(x, y), x, y ∈ [0, 2π]",
                                            info="numpy syntax: sin, cos, exp, sqrt, pi, ...")
                run = gr.Button("Solve", variant="primary")
            with gr.Column(scale=1):
                geo_preview = gr.Image(label="Domain & boundary conditions", type="pil", height=440)
        result = gr.Image(label="Result", type="pil")
        metrics = gr.Markdown()

        gr.Examples(
            examples=[
                ["2 corners removed", 3, BC_DIRICHLET, [], SRC_FOURIER, 7, "sin(2*x) * cos(3*y)"],
                ["4 corners removed", 0, BC_NEUMANN, [], SRC_FOURIER, 42, "sin(2*x) * cos(3*y)"],
                ["3 corners removed", 5, BC_MIXED, ["1", "3", "5", "7", "9"], SRC_FOURIER, 3, "sin(2*x) * cos(3*y)"],
                ["Square (no corners removed)", 0, BC_DIRICHLET, [], SRC_EXPR, 0, "sin(2*x) * cos(3*y)"],
                ["1 corner removed", 2, BC_MIXED, ["2", "4"], SRC_EXPR, 0, "exp(-((x-2)**2 + (y-4)**2))"],
            ],
            inputs=[geometry, sample_index, bc_mode, neumann_walls, source_type, seed, expression],
            outputs=[result, metrics],
            fn=solve,
            cache_examples=True,
            cache_mode="lazy",
        )

    prev_inputs = [geometry, sample_index, bc_mode, neumann_walls]
    for comp in prev_inputs:
        comp.change(preview, prev_inputs, geo_preview, api_visibility="private")
    demo.load(preview, prev_inputs, geo_preview, api_visibility="private")
    run.click(solve, [geometry, sample_index, bc_mode, neumann_walls, source_type, seed, expression],
              [result, metrics])

if __name__ == "__main__":
    demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)