#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 2D magnetostatic solver (cell-centered finite volume on vector potential A_z) for a "half-cup ratchet": rotor magnet + steel half-cup passing a stator magnet + opposite-side steel half-cup, like poles facing (N-N). Force is computed DIRECTLY from the Maxwell stress tensor integrated over a closed contour in air around the body: F = (Lz/mu0) * closed_int [ (B.n)B - 0.5*B^2 n ] dl No energy / co-energy / virtual work anywhere. Geometry (2D planar, disc plane; y = axial direction of the pair, x = tangential): stator magnet : x in [-2, 2] mm, y in [-(g/2+25), -g/2] mm, M = +M0 y (N pole up) rotor magnet : x in [xr-2, xr+2] mm, y in [ g/2, g/2+25] mm, M = -M0 y (N pole down) rotor steel : x in [xr+2, xr+4] mm (leading side, +x), same y band as rotor magnet stator steel : x in [-4, -2] mm (opposite side, 180 deg), same y band as stator magnet N-N facing across axial gap g; rotor slides tangentially x = -25 .. +25 mm. Units SI internally; mm only at the interface. """ import json import sys import time import numpy as np import scipy.sparse as sp import scipy.sparse.linalg as spla from scipy.interpolate import RectBivariateSpline MU0 = 4e-7 * np.pi BR = 1.2 # T M0 = BR / MU0 # A/m MUR_STEEL = 1000.0 BSAT = 1.6 # T (optional saturation model) LZ = 4e-3 # out-of-plane depth = magnet diameter R_ROT = 0.055 # m, rotor radius for torque MAG_W = 4e-3 # magnet width (tangential) MAG_L = 25e-3 # magnet length (axial, magnetization axis) STEEL_T = 2e-3 # half-cup strip thickness # base grid; domain +-80 mm: at 48 mm the A=0 boundary still biased forces # by up to 17% at g=20 mm (domain study), at 80 mm the bias is <2%. H = 0.5e-3 XMIN, XMAX = -80e-3, 80e-3 YMIN, YMAX = -82e-3, 82e-3 def grid(h=H, xmin=XMIN, xmax=XMAX, ymin=YMIN, ymax=YMAX): Nx = int(round((xmax - xmin) / h)) Ny = int(round((ymax - ymin) / h)) xc = xmin + (np.arange(Nx) + 0.5) * h yc = ymin + (np.arange(Ny) + 0.5) * h return Nx, Ny, xc, yc def build_materials(g, xr, h=H, steel=True, stator=True, xmin=XMIN, xmax=XMAX, ymin=YMIN, ymax=YMAX): """Return (mur, My, xc, yc); arrays indexed [j(y), i(x)].""" Nx, Ny, xc, yc = grid(h, xmin, xmax, ymin, ymax) X, Y = np.meshgrid(xc, yc) mur = np.ones((Ny, Nx)) My = np.zeros((Ny, Nx)) def rect(x0, x1, y0, y1): return (X > x0) & (X < x1) & (Y > y0) & (Y < y1) # rotor magnet (N pole faces down toward stator -> M along -y) My[rect(xr - MAG_W / 2, xr + MAG_W / 2, g / 2, g / 2 + MAG_L)] = -M0 if steel: mur[rect(xr + MAG_W / 2, xr + MAG_W / 2 + STEEL_T, g / 2, g / 2 + MAG_L)] = MUR_STEEL if stator: # stator magnet (N pole faces up -> M along +y): N-N repulsion My[rect(-MAG_W / 2, MAG_W / 2, -(g / 2 + MAG_L), -g / 2)] = +M0 if steel: mur[rect(-MAG_W / 2 - STEEL_T, -MAG_W / 2, -(g / 2 + MAG_L), -g / 2)] = MUR_STEEL return mur, My, xc, yc def assemble(mur, My, h): """-div(nu grad A) = mu0 d/dx(nu My) (M has only y-component here). Cell-centered FV, harmonic-mean face reluctivity, Dirichlet A=0 outside.""" Ny, Nx = mur.shape nu = 1.0 / (MU0 * mur) N = Nx * Ny idx = np.arange(N).reshape(Ny, Nx) tx = 2.0 * nu[:, :-1] * nu[:, 1:] / (nu[:, :-1] + nu[:, 1:]) ty = 2.0 * nu[:-1, :] * nu[1:, :] / (nu[:-1, :] + nu[1:, :]) diag = np.zeros((Ny, Nx)) diag[:, :-1] += tx diag[:, 1:] += tx diag[:-1, :] += ty diag[1:, :] += ty # Dirichlet A=0 at domain edge (half-cell distance) diag[:, 0] += 2 * nu[:, 0] diag[:, -1] += 2 * nu[:, -1] diag[0, :] += 2 * nu[0, :] diag[-1, :] += 2 * nu[-1, :] rows = np.concatenate([idx[:, :-1].ravel(), idx[:, 1:].ravel(), idx[:-1, :].ravel(), idx[1:, :].ravel(), np.arange(N)]) cols = np.concatenate([idx[:, 1:].ravel(), idx[:, :-1].ravel(), idx[1:, :].ravel(), idx[:-1, :].ravel(), np.arange(N)]) vals = np.concatenate([-tx.ravel(), -tx.ravel(), -ty.ravel(), -ty.ravel(), diag.ravel()]) K = sp.csc_matrix((vals, (rows, cols)), shape=(N, N)) # Face source from magnetization: half-cell integration of H_t continuity # gives H_face = -nu_harm*[(dA/dx) + mu0*(My_L+My_R)/2], so the source term # carries the HARMONIC face reluctivity (tx), not an arithmetic average. # (Arithmetic averaging injects bound current into mur>>1 cells and blows # up the flux by ~mur - verified during debugging.) ff = tx * 0.5 * (My[:, :-1] + My[:, 1:]) # interior vertical faces b = np.zeros((Ny, Nx)) b[:, :-1] += MU0 * h * ff b[:, 1:] -= MU0 * h * ff # boundary faces: M=0 well inside the domain edge, no contribution return K, b.ravel() def solve_field(mur, My, h): K, b = assemble(mur, My, h) A = spla.spsolve(K, b) return A.reshape(mur.shape) def solve_field_nl(g, xr, h=H, max_it=40, relax=0.5, tol=1e-3): """Optional saturation: Picard iteration, mur(B)=1+(mur0-1)/(1+(B/Bsat)^4).""" mur, My, xc, yc = build_materials(g, xr, h) steel_mask = mur > 1.5 mur_it = mur.copy() A2 = None for it in range(max_it): A2 = solve_field(mur_it, My, h) Bx = np.gradient(A2, h, axis=0) By = -np.gradient(A2, h, axis=1) Bm = np.hypot(Bx, By) mur_new = mur_it.copy() mur_new[steel_mask] = 1.0 + (MUR_STEEL - 1.0) / (1.0 + (Bm[steel_mask] / BSAT) ** 4) change = np.max(np.abs(mur_new[steel_mask] - mur_it[steel_mask]) / mur_it[steel_mask]) mur_it[steel_mask] = (1 - relax) * mur_it[steel_mask] + relax * mur_new[steel_mask] if change < tol: break return A2, mur_it, xc, yc, it + 1 def field_splines(A2, xc, yc, h): Bx = np.gradient(A2, h, axis=0) # dA/dy By = -np.gradient(A2, h, axis=1) # -dA/dx BxS = RectBivariateSpline(yc, xc, Bx) ByS = RectBivariateSpline(yc, xc, By) return BxS, ByS, Bx, By def mst_rect_grid(A2, h, i0, i1, j0, j1): """Maxwell stress over a rectangle whose sides lie ON grid lines (line index i -> x = XMIN + i*h). B on each side is taken at face midpoints straight from finite differences of A (no interpolation, air cells only). Returns (Fx, Fy) per unit depth.""" q = 0.25 / h inv = 1.0 / h Fx = Fy = 0.0 # vertical edges (lines iL), cells j0..j1-1 for iL, sgn in ((i1, +1.0), (i0, -1.0)): By = -(A2[j0:j1, iL] - A2[j0:j1, iL - 1]) * inv Bx = (A2[j0 + 1:j1 + 1, iL - 1] + A2[j0 + 1:j1 + 1, iL] - A2[j0 - 1:j1 - 1, iL - 1] - A2[j0 - 1:j1 - 1, iL]) * q Fx += sgn * np.sum(0.5 * (Bx * Bx - By * By)) / MU0 * h Fy += sgn * np.sum(Bx * By) / MU0 * h # horizontal edges (lines jL), cells i0..i1-1 for jL, sgn in ((j1, +1.0), (j0, -1.0)): Bx = (A2[jL, i0:i1] - A2[jL - 1, i0:i1]) * inv By = -(A2[jL - 1, i0 + 1:i1 + 1] + A2[jL, i0 + 1:i1 + 1] - A2[jL - 1, i0 - 1:i1 - 1] - A2[jL, i0 - 1:i1 - 1]) * q Fx += sgn * np.sum(Bx * By) / MU0 * h Fy += sgn * np.sum(0.5 * (By * By - Bx * Bx)) / MU0 * h return Fx, Fy def _line(v, h, vmin): return int(round((v - vmin) / h)) def body_force(A2, g, xr, which, h=H): """Average over 3 nested grid-aligned air contours around rotor or stator (magnet+steel). The gap-side edge sits near mid-gap y=0.""" if which == 'rotor': x0b, x1b = xr - MAG_W / 2, xr + MAG_W / 2 + STEEL_T y1b = g / 2 + MAG_L else: x0b, x1b = -MAG_W / 2 - STEEL_T, MAG_W / 2 y0b = -(g / 2 + MAG_L) out = [] for c, dy in [(1.5e-3, 0.0), (2.5e-3, +h), (3.5e-3, -h)]: i0 = _line(x0b - c, h, XMIN) i1 = _line(x1b + c, h, XMIN) if which == 'rotor': j0 = _line(dy, h, YMIN) j1 = _line(y1b + c, h, YMIN) else: j0 = _line(y0b - c, h, YMIN) j1 = _line(dy, h, YMIN) out.append(mst_rect_grid(A2, h, i0, i1, j0, j1)) r = np.array(out) return (r[:, 0].mean() * LZ, r[:, 1].mean() * LZ, r[:, 0].std() * LZ) def dipole_check(): """Far field of a single magnet must fall off ~ 1/r^2 (2D dipole).""" h = 1e-3 lim = 0.12 mur, My, xc, yc = build_materials(g=0.0, xr=0.0, h=h, steel=False, stator=False, xmin=-lim, xmax=lim, ymin=-lim, ymax=lim) # recenter single magnet on origin: build put rotor at y in [0, 25] mm; shift ok A2 = solve_field(mur, My, h) BxS, ByS, Bx, By = field_splines(A2, xc, yc, h) # magnet center is at (0, 12.5 mm) cx, cy = 0.0, MAG_L / 2 th = np.deg2rad(40.0) rs = np.linspace(40e-3, 90e-3, 12) Bm = [] for r in rs: xq, yq = cx + r * np.cos(th), cy + r * np.sin(th) Bm.append(float(np.hypot(BxS.ev(yq, xq), ByS.ev(yq, xq)))) Bm = np.array(Bm) slope = np.polyfit(np.log(rs), np.log(Bm), 1)[0] # field at magnet center and at pole face (sanity anchors) B_c = float(np.hypot(BxS.ev(cy, cx), ByS.ev(cy, cx))) B_pole = float(np.hypot(BxS.ev(-1e-3, cx), ByS.ev(-1e-3, cx))) return slope, B_c, B_pole def sweep(gaps_mm, xs_mm, h=H, tag=''): res = {} t0 = time.time() for g_mm in gaps_mm: g = g_mm * 1e-3 row = dict(x=[], Fx=[], Fy=[], Fstd=[], Fx_sta=[], Fy_sta=[], Bsteel=[]) for x_mm in xs_mm: xr = x_mm * 1e-3 mur, My, xc, yc = build_materials(g, xr, h) A2 = solve_field(mur, My, h) fx, fy, fstd = body_force(A2, g, xr, 'rotor', h) fxs, fys, _ = body_force(A2, g, xr, 'stator', h) Bx = np.gradient(A2, h, axis=0) By = -np.gradient(A2, h, axis=1) steel = mur > 1.5 bmax = float(np.percentile(np.hypot(Bx, By)[steel], 95)) row['x'].append(x_mm) row['Fx'].append(fx) row['Fy'].append(fy) row['Fstd'].append(fstd) row['Fx_sta'].append(fxs) row['Fy_sta'].append(fys) row['Bsteel'].append(bmax) res[g_mm] = {k: np.asarray(v) for k, v in row.items()} print(f'{tag}g={g_mm:5.1f} mm done, elapsed {time.time()-t0:7.1f} s', flush=True) return res def postprocess(res): """Torque curves and impulse metrics per gap.""" table = [] for g_mm, r in sorted(res.items()): x_m = r['x'] * 1e-3 T = r['Fx'] * R_ROT # N*m Tp = np.clip(T, 0, None) Tm = np.clip(T, None, 0) Jp = np.trapezoid(Tp, x_m) # N*m*m Jm = np.trapezoid(Tm, x_m) net = Jp + Jm asym = Jp / abs(Jm) if Jm != 0 else np.inf # Newton check: worst |Fx_rot + Fx_sta| / |Fx_rot| where force significant Fmax = np.max(np.abs(r['Fx'])) mask = np.abs(r['Fx']) > 0.1 * Fmax newton = np.max(np.abs(r['Fx'][mask] + r['Fx_sta'][mask]) / np.abs(r['Fx'][mask])) table.append(dict(g=g_mm, Tpeak_pos=float(T.max()), Tpeak_neg=float(T.min()), Jplus=float(Jp), Jminus=float(Jm), Jnet=float(net), asym=float(asym), newton=float(newton), Bsteel_max=float(r['Bsteel'].max()), Fstd_max=float(r['Fstd'].max()), Fx_peak=float(np.max(np.abs(r['Fx']))), Fy_peak=float(np.max(np.abs(r['Fy']))))) return table def main(): quick = '--quick' in sys.argv print('=== dipole / far-field check (single magnet, big domain) ===', flush=True) slope, B_c, B_pole = dipole_check() print(f'log-log slope |B|(r), r=40..90 mm : {slope:+.3f} (2D dipole -> -2)') print(f'B at magnet center : {B_c:.3f} T') print(f'B on axis 1 mm outside pole : {B_pole:.3f} T', flush=True) print('=== grid convergence spot check (g=4 mm, x=-10 mm) ===', flush=True) fvals = {} for h in (H, H / 2): mur, My, xc, yc = build_materials(4e-3, -10e-3, h) A2 = solve_field(mur, My, h) fx, fy, fstd = body_force(A2, 4e-3, -10e-3, 'rotor', h) fvals[h] = fx print(f'h={h*1e3:.2f} mm : Fx_rotor = {fx:+.4f} N (contour std {fstd:.4f})', flush=True) conv = abs(fvals[H] - fvals[H / 2]) / abs(fvals[H / 2]) print(f'relative difference h vs h/2 : {conv*100:.2f} %', flush=True) gaps = [2, 3, 4, 6, 8, 10, 12, 15, 20] xs = list(np.linspace(-25, 25, 51)) if quick: gaps = [4] xs = list(np.linspace(-25, 25, 11)) h_sweep = H if quick else H / 2 # 0.25 mm for production accuracy print(f'=== main sweep (h={h_sweep*1e3:.2f} mm) ===', flush=True) res = sweep(gaps, xs, h_sweep) table = postprocess(res) out = { 'meta': dict(h_mm=h_sweep * 1e3, Lz_mm=LZ * 1e3, r_rot_m=R_ROT, Br=BR, mur_steel=MUR_STEEL, dipole_slope=slope, B_center=B_c, B_pole=B_pole, conv_rel=conv), 'table': table, 'curves': {str(g): dict(x=list(map(float, r['x'])), T=list(map(float, r['Fx'] * R_ROT)), Fy=list(map(float, r['Fy']))) for g, r in res.items()}, } with open(OUT_JSON, 'w') as f: json.dump(out, f, indent=1) print(f'saved {OUT_JSON}', flush=True) print() hdr = (f'{"g,mm":>5} {"T_peak+":>9} {"T_peak-":>9} {"J+":>10} {"J-":>10} ' f'{"J_net":>10} {"asym":>7} {"Newton%":>8} {"Bsteel":>7}') print(hdr) for t in table: print(f'{t["g"]:5.0f} {t["Tpeak_pos"]*1e3:9.1f} {t["Tpeak_neg"]*1e3:9.1f} ' f'{t["Jplus"]*1e3:10.3f} {t["Jminus"]*1e3:10.3f} {t["Jnet"]*1e3:10.3f} ' f'{t["asym"]:7.3f} {t["newton"]*100:8.2f} {t["Bsteel_max"]:7.2f}') print('(T mN*m; J = int T dx in mN*m*m = mJ*m/m ... units: 1e-3 N*m*m)') OUT_JSON = '/private/tmp/claude-501/-Users-alchemist-Python-projects-magnetic-generator/' \ 'f962ae49-2b54-4db3-b5d1-be50714c865b/scratchpad/ratchet_results.json' if __name__ == '__main__': main()