File size: 5,661 Bytes
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
"""Core utilities for the NPSolver demo: mesh I/O, source terms, FVM reference solver."""
import h5py
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla
from huggingface_hub import hf_hub_download

DATA_REPO = "bochengz/NPSolver_datasets"
MODEL_REPO = "bochengz/NPSolver_models"

# PatchType enum from the original repo
ZERO_GRADIENT, FIXED_VALUE, EMPTY = 0, 1, 2

GEOMETRIES = {
    "Square (no corners removed)": ("2d/mesh/test_corner0_mesh[N=1].h5", 1),
    "1 corner removed": ("2d/mesh/test_corner1_mesh[N=10].h5", 10),
    "2 corners removed": ("2d/mesh/test_corner2_mesh[N=10].h5", 10),
    "3 corners removed": ("2d/mesh/test_corner3_mesh[N=10].h5", 10),
    "4 corners removed": ("2d/mesh/test_corner4_mesh[N=10].h5", 10),
}

_KEYS = ["pos", "bou_faces_centroid", "volume", "lowerIndex", "upperIndex", "magSf", "deltaCoeff",
         "bouMagSf", "bouDeltaCoeff", "face2cell", "patchSize", "patchOffset", "patchTypeP", "patchName"]


def load_mesh(geometry: str, index: int) -> dict:
    fname, n = GEOMETRIES[geometry]
    index = int(np.clip(index, 0, n - 1))
    path = hf_hub_download(DATA_REPO, fname, repo_type="dataset")
    with h5py.File(path, "r") as f:
        g = f[str(index)]
        m = {k: g[k][()] for k in _KEYS if k in g}
    m["patchName"] = [p.decode() if isinstance(p, bytes) else str(p) for p in m.get("patchName", [])]
    m["pos"] = m["pos"][:, :2].astype(np.float32)
    m["pos_bd"] = m["bou_faces_centroid"][:, :2].astype(np.float32)
    m["patchSize"] = m["patchSize"].reshape(-1)
    m["patchOffset"] = m["patchOffset"].reshape(-1)
    m["patchTypeP"] = m["patchTypeP"].reshape(-1)
    return m


def wall_patches(m) -> list:
    """Indices of non-empty (physical boundary) patches."""
    return [i for i in range(len(m["patchSize"])) if m["patchTypeP"][i] != EMPTY and m["patchSize"][i] > 0]


def face_bc_types(m, patch_types: dict) -> np.ndarray:
    """Per-boundary-face BC type (0 zeroGradient / 1 fixedValue)."""
    nb = m["pos_bd"].shape[0]
    bc = np.full(nb, FIXED_VALUE, dtype=np.int64)
    for i, t in patch_types.items():
        o, s = m["patchOffset"][i], m["patchSize"][i]
        bc[o:o + s] = t
    return bc


# ---------------------------------------------------------------- source terms
def fourier_source(pos: np.ndarray, seed: int, M: int = 10) -> np.ndarray:
    """Random Fourier source exactly as in the authors' FourierGenerator (norm='max')."""
    import torch
    g = torch.Generator().manual_seed(int(seed))
    xx = torch.tensor(pos[:, 0], dtype=torch.float32)
    yy = torch.tensor(pos[:, 1], dtype=torch.float32)
    alpha = torch.normal(0., 1., size=(M, M), generator=g)
    beta = torch.normal(0., 1., size=(M, M), generator=g)
    gamma = torch.normal(-1., 1., size=(1,), generator=g)
    W = torch.zeros_like(xx)
    for i in range(M):
        for j in range(M):
            phase = (i - M // 2) * xx + (j - M // 2) * yy
            W = W + alpha[i, j] * torch.sin(phase) + beta[i, j] * torch.cos(phase)
    U = W + gamma[0]
    U = U / (U.abs().max() + 1e-8)
    return U.numpy().astype(np.float64)


_SAFE = {k: getattr(np, k) for k in ["sin", "cos", "tan", "exp", "log", "sqrt", "abs", "tanh", "sinh",
                                      "cosh", "arctan", "arctan2", "pi", "minimum", "maximum", "sign", "where"]}


def expr_source(pos: np.ndarray, expr: str) -> np.ndarray:
    """Evaluate a user expression f(x, y) on cell centroids (domain is [0, 2π]²)."""
    expr = (expr or "").strip().replace("^", "**")
    if not expr:
        raise ValueError("Empty source expression.")
    if "__" in expr or "import" in expr or "lambda" in expr:
        raise ValueError("Expression contains forbidden tokens.")
    env = dict(_SAFE)
    env.update(x=pos[:, 0].astype(np.float64), y=pos[:, 1].astype(np.float64), e=np.e)
    val = eval(expr, {"__builtins__": {}}, env)  # noqa: S307 (sandboxed namespace)
    val = np.broadcast_to(np.asarray(val, dtype=np.float64), (pos.shape[0],)).copy()
    if not np.all(np.isfinite(val)):
        raise ValueError("Source expression produced NaN/Inf on the domain.")
    return val


def mean_zero(f, volume):
    v = volume.reshape(-1).astype(np.float64)
    return f - np.sum(f * v) / np.sum(v)


# ---------------------------------------------------------------- FVM reference
def assemble(m, bc_faces: np.ndarray):
    """Assemble the authors' FVM Laplacian (A p = f * vol) with homogeneous BCs as a scipy CSR."""
    n = m["pos"].shape[0]
    lo = m["lowerIndex"].astype(np.int64)
    up = m["upperIndex"].astype(np.int64)
    c = (m["deltaCoeff"] * m["magSf"]).reshape(-1).astype(np.float64)
    diag = np.zeros(n)
    np.add.at(diag, lo, -c)
    np.add.at(diag, up, -c)
    fixed = bc_faces == FIXED_VALUE
    bcoef = -(m["bouDeltaCoeff"] * m["bouMagSf"]).reshape(-1).astype(np.float64)
    np.add.at(diag, m["face2cell"][fixed], bcoef[fixed])
    A = sp.coo_matrix((np.concatenate([c, c, diag]),
                       (np.concatenate([lo, up, np.arange(n)]), np.concatenate([up, lo, np.arange(n)]))),
                      shape=(n, n)).tocsr()
    return A


def reference_solve(m, f, bc_faces):
    A = assemble(m, bc_faces)
    b = f * m["volume"].reshape(-1).astype(np.float64)
    if not np.any(bc_faces == FIXED_VALUE):
        # pure Neumann: pin reference cell 0 to zero (as in the authors' set_reference_pressure)
        A = A.tolil()
        A[0, :] = 0
        A[:, 0] = 0
        A[0, 0] = 1.0
        A = A.tocsr()
        b = b.copy()
        b[0] = 0.0
    p = spla.spsolve(A.tocsc(), b)
    return p, A, b


def residual_rms(A, b, p):
    return float(np.sqrt(np.mean((b - A @ p) ** 2)))