npsolver / app.py
multimodalart's picture
multimodalart HF Staff
Upload app.py with huggingface_hub
7977564 verified
Raw History Blame Contribute Delete
13.2 kB
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)