"""Independent check of the series solution: 2nd-order finite differences (Shortley-Weller boundary treatment) in Cartesian coordinates on the quarter domain x>=0, y>=0 (mirror symmetry), no Mathieu functions used. Omega = {nu > 0, mu < 6}, V=1 on nu=0, V=0 on mu=6 (b=3, c=1).""" import sys, time, numpy as np, scipy.sparse as sps, scipy.sparse.linalg as spl from pathlib import Path HERE = Path(__file__).resolve().parent if "__file__" in globals() else Path.cwd() sys.path.insert(0, str(HERE)) from pbvp import coords, mu0, nu0 def inside(P): mu, nu, la = coords(P[..., 0], P[..., 1], P[..., 2]); return (nu > nu0) & (mu < mu0) def solve(h): t0 = time.time() nx, ny, nz = int(round(6.2/h))+1, int(round(4.6/h))+1, int(round(6.2/h))+1 X, Y, Z = np.meshgrid(np.arange(nx)*h, np.arange(ny)*h, np.arange(nz)*h, indexing='ij') P = np.stack([X, Y, Z], -1); ins = inside(P) idx = -np.ones(ins.shape, int); idx[ins] = np.arange(ins.sum()); n = ins.sum() I, J, K = np.nonzero(ins); p = P[I, J, K] rows, cols, vals = [], [], []; rhs = np.zeros(n); diag = np.zeros(n) for ax in range(3): coef_parts = {} nb = {} for sgn in (-1, 1): ii = [I.copy(), J.copy(), K.copy()]; ii[ax] = ii[ax] + sgn if ax < 2 and sgn == -1: ii[ax] = np.where(ii[ax] < 0, 1, ii[ax]) # mirror plane x=0 / y=0 dims = (nx, ny, nz) okr = (ii[ax] >= 0) & (ii[ax] < dims[ax]) jn = np.full(n, -1) jn[okr] = idx[ii[0][okr], ii[1][okr], ii[2][okr]] # boundary crossing distance for neighbours outside Omega frac = np.ones(n); bval = np.zeros(n); out = jn < 0 if out.any(): e = np.zeros(3); e[ax] = sgn*h lo = np.zeros(out.sum()); hi = np.ones(out.sum()); po = p[out] for _ in range(50): mid = (lo+hi)/2; inn = inside(po + mid[:, None]*e) lo = np.where(inn, mid, lo); hi = np.where(inn, hi, mid) t = (lo+hi)/2; mu, nu, la = coords(*(po + t[:, None]*e).T) bval[out] = np.where(np.abs(nu - nu0) < np.abs(mu - mu0), 1.0, 0.0); frac[out] = np.maximum(t, 1e-12) nb[sgn] = (jn, frac*h, bval) (jl, hl, bl), (jr, hr, br) = nb[-1], nb[1] f = 2/(hl+hr) for (jj, hh, bb) in ((jl, hl, bl), (jr, hr, br)): diag -= f/hh m = jj >= 0 rows.append(np.nonzero(m)[0]); cols.append(jj[m]); vals.append((f/hh)[m]) rhs[~m] -= (f/hh*bb)[~m] A = sps.csr_matrix((np.concatenate(vals + [diag]), (np.concatenate(rows + [np.arange(n)]), np.concatenate(cols + [np.arange(n)]))), shape=(n, n)) # Row (Jacobi) scaling: rows next to the boundary with small Shortley-Weller cut fractions have entries # ~1/(frac*h^2) and would dominate ||rhs||, so a relative-residual stopping test could be met while the # interior is unconverged. Scaling each row by 1/diag gives an equivalent system with a meaningful test. Dinv = sps.diags(1/A.diagonal()); A = (Dinv @ A).tocsr(); rhs = Dinv @ rhs print(f'h={h}: {n} unknowns, assembled in {time.time()-t0:.1f}s', flush=True) if n < 120000: u = spl.spsolve(A.tocsc(), rhs) else: ilu = spl.spilu(A.tocsc(), drop_tol=1e-4, fill_factor=10) u, info = spl.bicgstab(A, rhs, M=spl.LinearOperator(A.shape, ilu.solve), rtol=1e-11, maxiter=2000); assert info == 0, info print(f' solved in {time.time()-t0:.1f}s, scaled residual {np.linalg.norm(A@u-rhs)/np.linalg.norm(rhs):.1e} (max-norm {np.abs(A@u-rhs).max():.1e})', flush=True) U = np.full(ins.shape, np.nan); U[ins] = u return U, h if __name__ == '__main__': pts = np.array([[0, 0, 1.0], [0, 0, 3.0], [0, 0, 5.0], [2.0, 0, 2.5], [0, 2.0, 3.5], [1.5, 1.0, 3.0]]) res = {} for h in [float(a) for a in sys.argv[1:]] or [0.1, 0.05]: U, h = solve(h) vals = [] for p in pts: i, j, k = np.round(p/h).astype(int); assert np.allclose([i*h, j*h, k*h], p) vals.append(U[i, j, k]) res[h] = vals; print(' V at test points:', ' '.join(f'{v:.6f}' for v in vals), flush=True) np.save('fd_results.npy', {'pts': pts, 'res': res}, allow_pickle=True) if len(res) >= 2: hs = sorted(res); h1, h2 = hs[-1], hs[0] rich = [(h1**2*np.array(res[h2]) - h2**2*np.array(res[h1]))/(h1**2-h2**2)] print('Richardson (O(h^2)) extrapolation:', ' '.join(f'{v:.6f}' for v in rich[0]))