#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Perendev REAL geometry (German video) -> Kraft-Winkel diagram via 2D FEM. Radial magnets, N-N repulsion, magnet axis along the approach line (alpha=0): 2D planar: x = tangential (rim direction), y = axial (along the gap). Magnet 25x22 mm: tangential width 25 mm, magnetization length 22 mm, out-of-plane depth Lz = 25 mm. Br = 1.2 T. Rotor R = 55 mm. Screen ("Abschirmung"): steel mur=1000, 2 mm strip, 3 mm LONGER than the magnet at each end (author: "Schirm etwas laenger als der Magnet"). Variants: none / half (one side) / full (U-cup: both sides + back, only the working pole face left open). Force straight from Maxwell stress tensor (contours in air), no co-energy. Reuses the parametrized core of ratchet_solver (assemble/solve/MST/grid). """ import json import sys import time import numpy as np sys.path.insert(0, '/Users/alchemist/Python_projects/magnetic-generator/cad/fem_cup_ratchet') import ratchet_solver as S MU0 = S.MU0 BR = 1.2 M0 = BR / MU0 MUR = 1000.0 BSAT = 1.6 MAG_W = 25e-3 # tangential width (x) MAG_L = 22e-3 # magnetization length (y, along gap) LZ = 25e-3 # out-of-plane depth ST = 2e-3 # screen strip thickness EXT = 3e-3 # screen longer than magnet by 3 mm at EACH end R = 0.055 # rotor radius G = 10e-3 # magnet-face to magnet-face gap (not given in brief; >6 mm # required so the 3 mm screen tips don't touch; 10 mm matches # the earlier cup-ratchet sweeps) H = S.H # 0.5 mm base grid # domain: magnets are 25 mm wide and sweep to +-50 mm -> old +-80 mm x-domain # would put the A=0 wall too close; use +-110 mm (bias spot-checked in main). XMIN, XMAX = -110e-3, 110e-3 YMIN, YMAX = -85e-3, 85e-3 N_HOLES = 12 # magnets per rotor disc PITCH_MM = 2 * np.pi * R * 1e3 / N_HOLES # 28.80 mm arc per 30 deg SHIFT_MM = PITCH_MM * 20.0 / 30.0 # 20 deg disc offset = 19.20 mm OUT_JSON = ('/private/tmp/claude-501/-Users-alchemist-Python-projects-' 'magnetic-generator/d0441e33-1c8a-451c-9ca1-5fbf45512f20/' 'scratchpad/perendev_results.json') def build(g, xr, screen, h=H, rotor_on=True, xmin=XMIN, xmax=XMAX, ymin=YMIN, ymax=YMAX): """screen in {'none','half','full'}. Rotor above gap (N down), stator below (N up): N-N facing. Half-screen: rotor +x (leading) side, stator -x side (shields the approach side, exposes the departure - the ratchet intent).""" Nx, Ny, xc, yc = S.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) if rotor_on: My[rect(xr - MAG_W / 2, xr + MAG_W / 2, g / 2, g / 2 + MAG_L)] = -M0 My[rect(-MAG_W / 2, MAG_W / 2, -(g / 2 + MAG_L), -g / 2)] = +M0 if screen == 'half': if rotor_on: mur[rect(xr + MAG_W / 2, xr + MAG_W / 2 + ST, g / 2 - EXT, g / 2 + MAG_L + EXT)] = MUR mur[rect(-MAG_W / 2 - ST, -MAG_W / 2, -(g / 2 + MAG_L + EXT), -(g / 2 - EXT))] = MUR elif screen == 'full': if rotor_on: mur[rect(xr + MAG_W / 2, xr + MAG_W / 2 + ST, g / 2 - EXT, g / 2 + MAG_L + ST)] = MUR mur[rect(xr - MAG_W / 2 - ST, xr - MAG_W / 2, g / 2 - EXT, g / 2 + MAG_L + ST)] = MUR mur[rect(xr - MAG_W / 2 - ST, xr + MAG_W / 2 + ST, g / 2 + MAG_L, g / 2 + MAG_L + ST)] = MUR mur[rect(-MAG_W / 2 - ST, -MAG_W / 2, -(g / 2 + MAG_L + ST), -(g / 2 - EXT))] = MUR mur[rect(MAG_W / 2, MAG_W / 2 + ST, -(g / 2 + MAG_L + ST), -(g / 2 - EXT))] = MUR mur[rect(-MAG_W / 2 - ST, MAG_W / 2 + ST, -(g / 2 + MAG_L + ST), -(g / 2 + MAG_L))] = MUR return mur, My, xc, yc def body_bbox(g, xr, which, screen): if which == 'rotor': x0b = xr - MAG_W / 2 - (ST if screen == 'full' else 0.0) x1b = xr + MAG_W / 2 + (ST if screen in ('half', 'full') else 0.0) y1b = g / 2 + MAG_L + (ST if screen == 'full' else (EXT if screen == 'half' else 0.0)) return x0b, x1b, None, y1b x0b = -MAG_W / 2 - (ST if screen in ('half', 'full') else 0.0) x1b = MAG_W / 2 + (ST if screen == 'full' else 0.0) y0b = -(g / 2 + MAG_L) - (ST if screen == 'full' else (EXT if screen == 'half' else 0.0)) return x0b, x1b, y0b, None def body_force(A2, g, xr, which, screen, h=H): """3 nested grid-aligned air contours; gap-side edge near mid-gap y=0 (screen tips reach y=+-(g/2-EXT)=+-2 mm, so >=1.5 mm air clearance).""" x0b, x1b, y0b, y1b = body_bbox(g, xr, which, screen) out = [] for c, dy in [(1.5e-3, 0.0), (2.5e-3, +h), (3.5e-3, -h)]: i0 = S._line(x0b - c, h, XMIN) i1 = S._line(x1b + c, h, XMIN) if which == 'rotor': j0 = S._line(dy, h, YMIN) j1 = S._line(y1b + c, h, YMIN) else: j0 = S._line(y0b - c, h, YMIN) j1 = S._line(dy, h, YMIN) out.append(S.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 solve_nl(mur0, My, h, max_it=40, relax=0.5, tol=1e-3): """Picard saturation: mur(B) = 1 + (mur0-1)/(1+(B/Bsat)^4).""" steel = mur0 > 1.5 mur_it = mur0.copy() A2 = None for it in range(max_it): A2 = S.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] = 1.0 + (MUR - 1.0) / (1.0 + (Bm[steel] / BSAT) ** 4) change = np.max(np.abs(mur_new[steel] - mur_it[steel]) / mur_it[steel]) mur_it[steel] = (1 - relax) * mur_it[steel] + relax * mur_new[steel] if change < tol: break return A2, mur_it, it + 1 def sweep_variant(screen, xs_mm, g=G, h=H, nl=False, tag=''): """nl=True: Picard saturation solve (mandatory for screened variants - linear mur=1000 drives the 2 mm strip to a fictitious 7-8 T).""" row = dict(x=[], Fx=[], Fy=[], Fstd=[], Fx_sta=[], Fy_sta=[], Bsteel=[]) t0 = time.time() for x_mm in xs_mm: xr = x_mm * 1e-3 mur, My, xc, yc = build(g, xr, screen, h) if nl and screen != 'none': A2, mur_eff, nit = solve_nl(mur, My, h) else: A2 = S.solve_field(mur, My, h) nit = 1 fx, fy, fstd = body_force(A2, g, xr, 'rotor', screen, h) fxs, fys, _ = body_force(A2, g, xr, 'stator', screen, h) if screen == 'none': bmax = 0.0 else: Bx = np.gradient(A2, h, axis=0) By = -np.gradient(A2, h, axis=1) bmax = float(np.percentile(np.hypot(Bx, By)[mur > 1.5], 95)) for k, v in zip(('x', 'Fx', 'Fy', 'Fstd', 'Fx_sta', 'Fy_sta', 'Bsteel'), (x_mm, fx, fy, fstd, fxs, fys, bmax)): row[k].append(v) print(f'{tag}{screen:>5} x={x_mm:+6.1f} mm Fx={fx:+8.3f} N ' f'Fy={fy:+8.3f} N it={nit:2d} [{time.time()-t0:6.1f} s]', flush=True) return {k: np.asarray(v) for k, v in row.items()} def metrics(r): x_m = r['x'] * 1e-3 T = r['Fx'] * R Jp = np.trapezoid(np.clip(T, 0, None), x_m) Jm = np.trapezoid(np.clip(T, None, 0), x_m) 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])) return dict(Tpeak_pos=float(T.max()), Tpeak_neg=float(T.min()), Jplus=float(Jp), Jminus=float(Jm), Jnet=float(Jp + Jm), asym=float(Jp / abs(Jm)) if Jm != 0 else float('inf'), newton=float(newton), Fy_peak=float(np.max(np.abs(r['Fy']))), Bsteel_max=float(r['Bsteel'].max()), Fstd_max=float(r['Fstd'].max()), T_end_left=float(T[0]), T_end_right=float(T[-1])) def stack_metrics(xs_mm, T): """Periodic magnet train (pitch 30 deg = 28.8 mm) x 3 discs offset 20 deg. Superposition of the single-pass curve (neighbor screen interaction and neighbor-magnet flux linkage on one disc are neglected - magnets sit only 3.8 mm apart at this pitch, so treat as first approximation).""" def T1(u): return np.interp(u, xs_mm, T, left=0.0, right=0.0) def Tdisc(u): return sum(T1(u - k * PITCH_MM) for k in range(-5, 6)) s = np.linspace(0.0, PITCH_MM, 721) Td = Tdisc(s) Tt = sum(Tdisc(s - m * SHIFT_MM) for m in range(3)) # honest mean of the true periodic waveform = Jnet / pitch; the windowed # sum mean also carries the zero-fill truncation of non-decayed tails x_m = np.asarray(xs_mm) * 1e-3 jnet_mean = float(np.trapezoid(np.interp( np.linspace(xs_mm[0], xs_mm[-1], 2001), xs_mm, T), np.linspace(xs_mm[0], xs_mm[-1], 2001) * 1e-3) / (PITCH_MM * 1e-3)) return dict( disc_mean=float(Td.mean()), disc_meanabs=float(np.abs(Td).mean()), disc_p2p=float(Td.max() - Td.min()), tot_mean=float(Tt.mean()), tot_meanabs=float(np.abs(Tt).mean()), tot_p2p=float(Tt.max() - Tt.min()), tot_std=float(Tt.std()), jnet_over_pitch=jnet_mean) def main(): global XMIN, XMAX # temporarily shrunk in the domain-size check quick = '--quick' in sys.argv t00 = time.time() print('=== sanity: B 1 mm above stator pole (single magnet) ===', flush=True) mur, My, xc, yc = build(G, 0.0, 'none', H, rotor_on=False) A2 = S.solve_field(mur, My, H) BxS, ByS, _, _ = S.field_splines(A2, xc, yc, H) yq = -G / 2 + 1e-3 B_fem = float(np.hypot(BxS.ev(yq, 0.0), ByS.ev(yq, 0.0))) # 2D charge-sheet anchor: B = (Br/pi)*[atan(w/2z) - atan(w/2(z+L))] z = 1e-3 B_ana = (BR / np.pi) * (np.arctan(MAG_W / (2 * z)) - np.arctan(MAG_W / (2 * (z + MAG_L)))) print(f'B_fem = {B_fem:.3f} T vs 2D sheet anchor {B_ana:.3f} T', flush=True) print('=== domain-size spot check (half screen, x=-10 mm) ===', flush=True) xmin_s, xmax_s = XMIN, XMAX fvals = {} for xm in (80e-3, xmax_s): XMIN, XMAX = -xm, xm # body_force uses module XMIN for indexing mur, My, xc, yc = build(G, -10e-3, 'half', H, xmin=-xm, xmax=xm) A2 = S.solve_field(mur, My, H) fx, fy, _ = body_force(A2, G, -10e-3, 'rotor', 'half', H) fvals[xm] = fx XMIN, XMAX = xmin_s, xmax_s print(f'x-domain +-{xm*1e3:.0f} mm : Fx = {fx:+.4f} N', flush=True) dom_bias = abs(fvals[80e-3] - fvals[xmax_s]) / abs(fvals[xmax_s]) print(f'80 mm vs 110 mm relative diff : {dom_bias*100:.2f} %', flush=True) conv = None if not quick: print('=== grid convergence (half screen, x=-10 mm) ===', flush=True) fg = {} for h in (H, H / 2): mur, My, xc, yc = build(G, -10e-3, 'half', h) A2 = S.solve_field(mur, My, h) fx, fy, _ = body_force(A2, G, -10e-3, 'rotor', 'half', h) fg[h] = fx print(f'h={h*1e3:.2f} mm : Fx = {fx:+.4f} N', flush=True) conv = abs(fg[H] - fg[H / 2]) / abs(fg[H / 2]) print(f'h vs h/2 relative diff : {conv*100:.2f} %', flush=True) xs = list(np.linspace(-50, 50, 11 if quick else 41)) cases = [('none', False), ('half', False), ('full', False), ('half', True), ('full', True)] if quick: cases = [('none', False), ('half', True), ('full', True)] res = {} for screen, nl in cases: key = screen + ('_nl' if nl else '') print(f'=== sweep {key} ===', flush=True) res[key] = sweep_variant(screen, xs, nl=nl) table = {k: metrics(r) for k, r in res.items()} stacks = {k: stack_metrics(r['x'], r['Fx'] * R) for k, r in res.items()} nl_conv = None if not quick: print('=== NL grid check (half screen, x=-10 mm, h vs h/2) ===', flush=True) fg = {} for h in (H, H / 2): mur, My, xc, yc = build(G, -10e-3, 'half', h) A2, _, nit = solve_nl(mur, My, h) fx, _, _ = body_force(A2, G, -10e-3, 'rotor', 'half', h) fg[h] = fx print(f'h={h*1e3:.2f} mm : Fx_NL = {fx:+.4f} N ({nit} it)', flush=True) nl_conv = abs(fg[H] - fg[H / 2]) / abs(fg[H / 2]) print(f'NL h vs h/2 relative diff : {nl_conv*100:.2f} %', flush=True) out = dict( meta=dict(h_mm=H * 1e3, Lz_mm=LZ * 1e3, R_m=R, Br=BR, g_mm=G * 1e3, mag_w_mm=MAG_W * 1e3, mag_l_mm=MAG_L * 1e3, steel_t_mm=ST * 1e3, ext_mm=EXT * 1e3, mur=MUR, pitch_mm=PITCH_MM, shift_mm=SHIFT_MM, B_pole_fem=B_fem, B_pole_anchor=B_ana, dom_bias=dom_bias, conv_rel=conv, nl_conv=nl_conv), table=table, stacks=stacks, curves={k: dict(x=list(map(float, r['x'])), T=list(map(float, r['Fx'] * R)), Fy=list(map(float, r['Fy']))) for k, 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() print(f'{"screen":>6} {"T_pk+":>8} {"T_pk-":>8} {"J+":>9} {"J-":>9} ' f'{"Jnet":>9} {"asym":>6} {"Nwt%":>6} {"Fy_pk":>7} {"Bst95":>6} ' f'{"T(-50)":>7} {"T(+50)":>7}') for sc, t in table.items(): print(f'{sc:>8} {t["Tpeak_pos"]*1e3:8.1f} {t["Tpeak_neg"]*1e3:8.1f} ' f'{t["Jplus"]*1e3:9.3f} {t["Jminus"]*1e3:9.3f} {t["Jnet"]*1e3:9.3f} ' f'{t["asym"]:6.3f} {t["newton"]*100:6.2f} {t["Fy_peak"]:7.2f} ' f'{t["Bsteel_max"]:6.2f} {t["T_end_left"]*1e3:7.1f} ' f'{t["T_end_right"]*1e3:7.1f}') print('(T mN*m; J = int T dx, 1e-3 N*m*m; Fy N; Bst95 T)') print() print(f'{"screen":>8} | disc mean|T| {"p2p":>8} | 3-disc mean {"mean|T|":>9} ' f'{"p2p":>8} {"std":>8} {"Jnet/P":>8} (mN*m)') for sc, st in stacks.items(): print(f'{sc:>8} | {st["disc_meanabs"]*1e3:12.1f} {st["disc_p2p"]*1e3:8.1f} ' f'| {st["tot_mean"]*1e3:11.2f} {st["tot_meanabs"]*1e3:9.1f} ' f'{st["tot_p2p"]*1e3:8.1f} {st["tot_std"]*1e3:8.1f} ' f'{st["jnet_over_pitch"]*1e3:8.2f}') print(f'total elapsed {time.time()-t00:7.1f} s', flush=True) if __name__ == '__main__': main()