"""Overshoot of the truncated series near the rim (Sec. 6.4, v2). Our own computation. Example: b=3, c=1, Omega={nu>0, mu<6}, V=V0=1 on nu=0, V=0 on mu=6; series Eq. (series), truncated at q_nm <= q_max. Uses series_Q960.json by default (built by build_series_par.py; its 118 roots with q<=240 equal those of series_Q240.json to 1.3e-12), evaluated with ModeN (Ce started at 1; same functions up to a scale absorbed by the coefficients). Key fact used for the peak search: every truncated sum is harmonic in Omega and continuous up to the boundary, and it vanishes on mu=6. By the maximum principle its largest value over Omega is therefore approached at the electrode nu=0. So the peak overshoot (the supremum of V/V0 over Omega) is the maximum of the sum over the electrode surface, a 2-D search in Arscott's (alpha, beta) on nu=0, alpha in [0, alpha0], beta in [0, pi/2] (the sum is even in x and y). """ import sys, json, time from pathlib import Path import numpy as np from scipy.optimize import minimize HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from pbvp import * from build_series_par import ModeN t0 = time.time() FILE = sys.argv[1] if len(sys.argv) > 1 else str(HERE / "series_Q960.json") info = json.load(open(FILE)) QS = [Q for Q in (30, 60, 120, 240, 480, 960) if Q <= max(o['q'] for o in info) + 1] print('series file:', FILE) modes = [ModeN(o['n2'], o['q']) for o in info] coef = np.array([o['coef'] for o in info]); qq = np.array([o['q'] for o in info]) NT = {Q: int((qq <= Q).sum()) for Q in QS} print('terms per truncation:', NT, f'(built in {time.time()-t0:.0f}s)') def xyz(mu, nu, la): x = np.sqrt(np.clip(4*(mu-b)*(b-nu)*(b-la)/(b-c), 0, None)) y = np.sqrt(np.clip(4*(mu-c)*(c-nu)*(la-c)/(b-c), 0, None)) return x, y, mu+nu+la-b-c def terms(mu, nu, la): """matrix (modes x points) of coef * mode value.""" mu, nu, la = [np.atleast_1d(np.asarray(t, float)).ravel() for t in np.broadcast_arrays(mu, nu, la)] return np.array([cf*M.V(mu, nu, la) for cf, M in zip(coef, modes)]) def V(mu, nu, la, Q): return terms(mu, nu, la)[qq <= Q].sum(0) # rim curve nu=0, mu=6, lambda in [c,b]; distance from a point to it lr = np.linspace(c, b, 4001); RX, RY, RZ = xyz(np.full_like(lr, mu0), 0*lr, lr) def dist_rim(x, y, z): return np.sqrt((np.abs(x)-RX)**2 + (np.abs(y)-RY)**2 + (z-RZ)**2).min() # ---- 0. consistency with the published series (series_Q240.json, original Mode) at the checks.py points ---- from solution import Series 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], [0, 0, 0.2], [4.0, 0, 2.0]]) old = Series(str(HERE / "series_Q240.json")).V(*pts.T) new = V(*coords(*pts.T), 240) print(f'0. max |V(this file, q<=240) - V(series_Q240.json)| at the 8 checks.py points: {np.abs(old-new).max():.1e}') print(' (4,0,2) and (0,0,0.2) at q_max=%g:' % QS[-1], ' '.join(f'{v:.6f}' for v in V(*coords(*pts[[7, 6]].T), QS[-1]))) # ---- 1. peak of the sum on the electrode nu=0 (= sup over Omega) ---- al = np.concatenate([np.linspace(0, 0.9*alpha0, 181, endpoint=False), np.linspace(0.9*alpha0, alpha0, 401)]) be = np.linspace(0, np.pi/2, 61) A_, B_ = np.meshgrid(al, be, indexing='ij') muE = b + cA*np.sinh(A_)**2; laE = c + cA*np.cos(B_)**2 TE = terms(muE, 0*muE, laE) def Vab(p, Q): a_, b_ = p; return V(b + cA*np.sinh(a_)**2, 0.0, c + cA*np.cos(b_)**2, Q)[0] peaks = {} print('\n1. Peak of V/V0 over Omega (attained at the electrode surface nu=0), refined from the grid maximum:') print(' q_max terms peak V/V0 alpha/alpha0 beta 6-mu dist. to rim grid max [max in plane y=0: value, 6-mu, dist]') for Q in QS: G = TE[qq <= Q].sum(0).reshape(muE.shape) # multi-start: refine from the 8 largest local maxima of the grid Gp_ = np.pad(G, 1, constant_values=-np.inf) loc = np.ones(G.shape, bool) for di in (-1, 0, 1): for dj in (-1, 0, 1): if di or dj: loc &= G >= Gp_[1+di:1+di+G.shape[0], 1+dj:1+dj+G.shape[1]] cand = sorted(zip(G[loc], *np.nonzero(loc)), reverse=True)[:8] best = None for _, i, j in cand: r = minimize(lambda p: -Vab(p, Q), [al[i], be[j]], method='L-BFGS-B', bounds=[(0, alpha0), (0, np.pi/2)], options=dict(ftol=1e-15, gtol=1e-11)) if best is None or r.fun < best.fun: best = r r = best; pa, pb = r.x; pk = -r.fun m_, l_ = b + cA*np.sinh(pa)**2, c + cA*np.cos(pb)**2; X = xyz(m_, 0.0, l_) # same in the plane y=0 (beta=0), 1-D r0 = minimize(lambda p: -Vab([p[0], 0.0], Q), [al[G[:, 0].argmax()]], method='L-BFGS-B', bounds=[(0, alpha0)]) m0 = b + cA*np.sinh(r0.x[0])**2; X0 = xyz(m0, 0.0, c) peaks[Q] = dict(terms=NT[Q], peak=pk, alpha_rel=pa/alpha0, beta=pb, mu=m_, d=dist_rim(*X), xyz=[float(t) for t in X], peak_y0=-r0.fun, mu_y0=m0, d_y0=dist_rim(*X0), x_y0=float(X0[0])) print(f' {Q:5d} {NT[Q]:5d} {pk:.4f} {pa/alpha0:.4f} {pb:.3f} {6-m_:.4f} {dist_rim(*X):.4f} {G.max():.4f}' f' [{-r0.fun:.4f}, {6-m0:.4f}, {dist_rim(*X0):.4f}]') json.dump(peaks, open(Path.cwd() / "rim_overshoot_peaks.json", "w"), indent=1) ks = sorted(peaks) print(' successive ratios of distance to rim:', ' '.join(f'{peaks[ks[k+1]]["d"]/peaks[ks[k]]["d"]:.3f}' for k in range(len(ks)-1))) print(' successive changes of peak height: ', ' '.join(f'{peaks[ks[k+1]]["peak"]-peaks[ks[k]]["peak"]:+.4f}' for k in range(len(ks)-1))) # cross-check: random interior points never exceed the electrode maximum (and reproduce checks.py's 1.1675 at 240) rng = np.random.default_rng(42) Gp = rng.uniform([-6, -4.5, 0], [6, 4.5, 6], (20000, 3)); m_, n_, l_ = coords(*Gp.T); ins = (n_ > nu0) & (m_ < mu0) TR = terms(m_[ins], n_[ins], l_[ins]) print(f' {ins.sum()} random interior points (seed 42, as in checks.py): max V/V0 =', ', '.join(f'{TR[qq <= Q].sum(0).max():.4f} (q<={Q})' for Q in QS)) norm1 = np.pi*np.sinh(2*alpha0) print(' relative L2 misfit of the data on nu=0 (Parseval, as in checks.py):', ', '.join(f'{np.sqrt(max(norm1-sum(o["coef"]**2*o["D"] for o in info if o["q"] <= Q), 0)/norm1):.3f} (q<={Q})' for Q in QS)) # ---- 2. profiles in the plane y=0 (lambda=c) along curves nu = nu_s, from mu=3 (x=0) to mu=6 (the rim) ---- print('\n2. Profiles in the plane y=0 along nu = nu_s (x from the axis to the rim). Max of V/V0 along each curve:') mug = np.concatenate([np.linspace(b, 5.0, 201, endpoint=False), np.linspace(5.0, mu0, 1001)]) prof = {} print(' nu_s ' + ' '.join(f'q<={Q:<4d}' for Q in QS) + ' (location of max, 6-mu, at the largest q)') for nus in (0.0, 0.001, 0.005, 0.02, 0.05, 0.1): T = terms(mug, np.full_like(mug, nus), np.full_like(mug, c)) rows = {Q: T[qq <= Q].sum(0) for Q in QS} prof[nus] = rows print(f' {nus:<7g} ' + ' '.join(f'{rows[Q].max():.4f} ' for Q in QS) + f' {6-mug[rows[QS[-1]].argmax()]:.4f}') X, _, Z = xyz(mug, 0*mug, np.full_like(mug, c)) np.save(Path.cwd() / "rim_profiles.npy", dict(mu=mug, QS=QS, NT=NT, prof=prof), allow_pickle=True) # ---- 3. FD cross-check: y=0 grid nodes of the Cartesian FD solution (fd_check.py) close to the electrode near the rim ---- fd_slice = Path.cwd() / "fd_rim_slice.npy" if not fd_slice.is_file(): fd_slice = HERE / "fd_rim_slice.npy" if not fd_slice.is_file(): print("\n3. FD slice fd_rim_slice.npy not found; skip this comparison. Run fd_rim_slice.py to generate it.") print(f"\ntotal {time.time()-t0:.0f}s") raise SystemExit(0) F = np.load(fd_slice, allow_pickle=True).item() U1, U2 = F[0.1], F[0.05] print(f'\n3. FD (fd_check.py solver, y=0 slice): max over the slice = {np.nanmax(U1):.4f} (h=0.1), {np.nanmax(U2):.4f} (h=0.05)') print(' node (x,0,z) nu 6-mu FD h=.1 FD h=.05 Richardson | series, q_max = ' + ' '.join(map(str, QS))) fdrows = [] for xn in (3.0, 4.0, 5.0, 5.5): i1 = int(round(xn/0.1)); i2 = 2*i1 for k1 in range(U1.shape[1]): if not np.isnan(U1[i1, k1]): mm, nn, ll = coords(xn, 0.0, k1*0.1) if nn > 0.04: break for dk in (0, 3): # first h=0.1 node with nu>0.04, and one 0.3 higher k = k1 + dk; z = k*0.1; mm, nn, ll = coords(xn, 0.0, z) f1, f2 = U1[i1, k], U2[i2, 2*k]; ri = (4*f2 - f1)/3 sv = [V(mm, nn, ll, Q)[0] for Q in QS] fdrows.append((xn, z, nn, mm, f1, f2, ri, sv)) print(f' ({xn:.1f},0,{z:.1f}) {nn:.4f} {6-mm:.4f} {f1:.5f} {f2:.5f} {ri:.5f} |', ' '.join(f'{v:.5f}' for v in sv)) # all common FD nodes (h=0.1 grid) in y=0 with 0.04 < nu < 0.5 and 6-mu < 2 (near the electrode, towards the rim) Ii, Kk = np.meshgrid(np.arange(U1.shape[0]), np.arange(U1.shape[1]), indexing='ij') xs, zs = Ii.ravel()*0.1, Kk.ravel()*0.1; m_, n_, l_ = coords(xs, 0*xs, zs) sel = (n_ > 0.04) & (n_ < 0.5) & (m_ > 4.0) & (m_ < mu0) & ~np.isnan(U1.ravel()) ri = (4*U2[2*Ii.ravel()[sel], 2*Kk.ravel()[sel]] - U1.ravel()[sel])/3 TS = terms(m_[sel], n_[sel], l_[sel]) print(f' {sel.sum()} FD nodes in y=0 with 0.04