Spaces:
Sleeping

File size: 12,747 Bytes
1f2a2cb
 
 
1c633be
1f2a2cb
 
 
 
 
 
1c633be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f2a2cb
 
 
 
 
 
 
 
 
 
 
869643e
 
1f2a2cb
 
 
 
 
 
 
 
 
 
 
869643e
1f2a2cb
 
 
 
 
 
 
 
 
869643e
 
 
1f2a2cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
869643e
 
1c633be
27fc6ec
1c633be
27fc6ec
 
1f2a2cb
 
 
 
 
 
 
1c633be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f2a2cb
 
 
 
 
 
 
 
 
 
 
869643e
 
1f2a2cb
 
 
 
 
 
 
1c633be
 
 
 
 
 
 
 
1f2a2cb
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import argparse
from pathlib import Path
import struct
import math
import numpy as np

DEFAULT_OBJ = Path("adaptive_mobius_unity.obj")
DEFAULT_STL = Path("adaptive_mobius_unity.stl")


def S_N(N, f):
    """HPF spectrum function: S_N(f) = |sin(πNf) / (N·sin(πf))|.
    Returns ~0 when f = 1/d and d | N (divisor signature).
    """
    f = f - math.floor(f)
    den = math.sin(math.pi * f)
    if abs(den) < 1e-15:
        return 1.0
    num = math.sin(math.pi * N * f)
    return abs(num / den) / N


def spectrum_kappas_from_N(N, D=16, kappa_max=0.10, tau=1e-12, gamma=1.0):
    """Map HPF spectrum to harmonic amplitudes.
    Large amplitude only when S_N(1/d) ≈ 0 (i.e., d | N).
    
    Args:
        N: Integer to fingerprint (composite shows divisor harmonics, prime is smooth)
        D: Max harmonic order (denominator) to probe
        kappa_max: Cap on amplitude
        tau: Softness parameter (≈1e-12 for zero-tuned, 0.02 for soft)
        gamma: Exponent for sharpening (1.0 = standard Gaussian)
    
    Returns:
        dict: {harmonic_order: amplitude}
    """
    ks = {}
    for d in range(2, D + 1):
        s = S_N(N, 1.0 / d)  # = 0 exactly when d | N
        a = kappa_max * math.exp(-((s / tau) ** 2) * gamma)
        ks[d] = a
    return ks


def adaptive_mobius_unity(
    radius_mm: float = 40.0,
    half_width_mm: float = 8.0,
    twists: float = 1.5,
    gamma: float = 0.25,
    samples_major: int = 480,
    samples_width: int = 48,
    tau: float = 0.5,
    proj_mode: str = "hybrid",
    thickness_mm: float = 2.0,
    kappa: float = 0.0,
    kappa2: float = 0.0,
    kappa3: float = 0.0,
):
    """
    Generate a (optionally thickened) adaptive Möbius band with π-adaptive curvature.

    Returns:
      vertices: (N,3) float32 array in mm
      faces: list[tuple[int,int,int]] wound CCW for outward normals
    Notes:
      - u is periodic; we wrap across the seam to avoid gaps.
      - thickness_mm=0.0 produces a single-sided sheet (non-manifold).
      - kappa=0.0 produces standard geometry; kappa>0 adds π-adaptive warping.
      - kappa2, kappa3: multi-frequency harmonics for richer field warping.
    """
    # Periodic along u; endpoint=False avoids duplicate seam column
    u = np.linspace(0.0, 2.0 * np.pi, samples_major, endpoint=False, dtype=np.float64)
    v = np.linspace(-half_width_mm, half_width_mm, samples_width, dtype=np.float64)
    uu, vv = np.meshgrid(u, v, indexing="ij")  # (M,N)

    # 4D time-like coordinate for projections
    t4 = gamma * np.sin(uu * twists / 2.0)

    # Multi-frequency π-adaptive radius modulation
    # Rₖ(u) = R₀(1 + κ₁·sin(u) + κ₂·sin(2u) + κ₃·sin(3u))
    Rk = radius_mm * (1.0 + kappa * np.sin(uu) + kappa2 * np.sin(2*uu) + kappa3 * np.sin(3*uu))

    # Euclidean base
    cos_tw = np.cos(twists * uu / 2.0)
    sin_tw = np.sin(twists * uu / 2.0)
    r_eff = Rk + vv * cos_tw
    x = r_eff * np.cos(uu)
    y = r_eff * np.sin(uu)
    z = vv * sin_tw

    # Projection blend
    if proj_mode == "euclidean":
        x3, y3, z3 = x, y, z
    elif proj_mode == "lorentz":
        # Simple Lorentz-like mixing between x and z (toy model)
        ch, sh = np.cosh(t4), np.sinh(t4)
        x3 = x * ch - z * sh
        y3 = y
        z3 = z * ch - x * sh
    elif proj_mode == "complex":
        phase = np.exp(1j * uu * twists)
        x3 = np.real(x + phase * 0.4)
        y3 = np.imag(y + phase * 0.4)
        z3 = z + np.real(phase) * 0.2
    else:
        # hybrid: blend Euclidean, Lorentz, Complex using tau in [0,1]
        phase = np.exp(1j * uu * twists)
        ch, sh = np.cosh(t4), np.sinh(t4)
        xE, yE, zE = x, y, z
        xL, yL, zL = x * ch - z * sh, y, z * ch - x * sh
        xC, yC, zC = np.real(x + phase * 0.4), np.imag(y + phase * 0.4), z + np.real(phase) * 0.2
        x3 = (1.0 - tau) * xE + tau * 0.5 * (xL + xC)
        y3 = (1.0 - tau) * yE + tau * 0.5 * (yL + yC)
        z3 = (1.0 - tau) * zE + tau * 0.5 * (zL + zC)

    M, N = samples_major, samples_width
    P = np.stack([x3, y3, z3], axis=-1)  # (M,N,3)

    # Compute per-vertex normals from param derivatives (periodic in u)
    def finite_diff_periodic(arr, axis):
        if axis == 0:  # along u, wrap
            return (np.roll(arr, -1, axis=0) - np.roll(arr, 1, axis=0)) * 0.5
        if axis == 1:  # along v, clamp ends (one-sided)
            result = np.zeros_like(arr)
            result[:, 1:-1, :] = (arr[:, 2:, :] - arr[:, :-2, :]) * 0.5
            result[:, 0, :] = arr[:, 1, :] - arr[:, 0, :]
            result[:, -1, :] = arr[:, -1, :] - arr[:, -2, :]
            return result
        raise ValueError

    Pu = finite_diff_periodic(P, axis=0)
    Pv = finite_diff_periodic(P, axis=1)
    Nrm = np.cross(Pu, Pv)  # (M,N,3)
    nlen = np.linalg.norm(Nrm, axis=-1, keepdims=True) + 1e-12
    Nn = Nrm / nlen  # unit normals

    verts = []
    faces = []

    def idx_outer(i, j):
        return i * N + j

    def idx_inner(i, j):
        return M * N + i * N + j

    if thickness_mm > 0.0:
        # Outer and inner shells
        outer = P + (0.5 * thickness_mm) * Nn
        inner = P - (0.5 * thickness_mm) * Nn
        verts = np.concatenate([outer.reshape(-1, 3), inner.reshape(-1, 3)], axis=0)

        # Surface quads -> triangles (wrap i+1 with modulo)
        for i in range(M):
            i2 = (i + 1) % M
            for j in range(N - 1):
                # Outer (CCW outward)
                a, b, c, d = idx_outer(i, j), idx_outer(i, j + 1), idx_outer(i2, j), idx_outer(i2, j + 1)
                faces.append((a, b, d))
                faces.append((a, d, c))
                # Inner (flip winding so outward is still exterior)
                a, b, c, d = idx_inner(i, j), idx_inner(i2, j), idx_inner(i, j + 1), idx_inner(i2, j + 1)
                faces.append((a, b, d))
                faces.append((a, d, c))

        # Side walls at v edges (j=0 and j=N-1)
        for i in range(M):
            i2 = (i + 1) % M

            # j = 0 side
            o_a, o_b = idx_outer(i, 0), idx_outer(i2, 0)
            i_a, i_b = idx_inner(i, 0), idx_inner(i2, 0)
            # two triangles, oriented outward
            faces.append((o_a, i_b, i_a))
            faces.append((o_a, o_b, i_b))

            # j = N-1 side
            o_a, o_b = idx_outer(i, N - 1), idx_outer(i2, N - 1)
            i_a, i_b = idx_inner(i, N - 1), idx_inner(i2, N - 1)
            faces.append((o_a, i_a, i_b))
            faces.append((o_a, i_b, o_b))
    else:
        # Single-sided (non-manifold) sheet
        verts = P.reshape(-1, 3)
        for i in range(M):
            i2 = (i + 1) % M
            for j in range(N - 1):
                a = i * N + j
                b = a + 1
                c = i2 * N + j
                d = c + 1
                faces.append((a, b, d))
                faces.append((a, d, c))

    return verts.astype(np.float32, copy=False), faces


def save_obj(path: Path, vertices: np.ndarray, faces: list[tuple[int, int, int]]):
    path = Path(path)
    with path.open("w", encoding="utf-8") as f:
        for vx, vy, vz in vertices:
            f.write(f"v {vx:.6f} {vy:.6f} {vz:.6f}\n")
        for a, b, c in faces:
            f.write(f"f {a+1} {b+1} {c+1}\n")


def write_binary_stl(path: Path, vertices: np.ndarray, faces: list[tuple[int, int, int]]):
    path = Path(path)
    with path.open("wb") as f:
        f.write(b"AdaptiveCAD Mobius".ljust(80, b"\0"))
        f.write(struct.pack("<I", len(faces)))
        V = vertices
        for a, b, c in faces:
            A, B, C = V[a], V[b], V[c]
            n = np.cross(B - A, C - A)
            nl = np.linalg.norm(n) + 1e-20
            n = n / nl
            f.write(struct.pack("<3f", float(n[0]), float(n[1]), float(n[2])))
            for P in (A, B, C):
                f.write(struct.pack("<3f", float(P[0]), float(P[1]), float(P[2])))
            f.write(struct.pack("<H", 0))


def parse_args():
    p = argparse.ArgumentParser(description="Adaptive π Möbius generator (OBJ/STL). Units: mm.")
    p.add_argument("--radius-mm", type=float, default=40.0)
    p.add_argument("--half-width-mm", type=float, default=8.0)
    p.add_argument("--twists", type=float, default=1.5)
    p.add_argument("--gamma", type=float, default=0.25)
    p.add_argument("--samples-major", type=int, default=480)
    p.add_argument("--samples-width", type=int, default=48)
    p.add_argument("--tau", type=float, default=0.5)
    p.add_argument("--proj-mode", choices=["euclidean", "lorentz", "complex", "hybrid"], default="hybrid")
    p.add_argument("--thickness-mm", type=float, default=2.0, help="0 for sheet; >0 for manifold band")
    p.add_argument("--kappa", type=float, default=0.0, help="π-adaptive curvature (0=standard, >0=warped)")
    p.add_argument("--kappa2", type=float, default=0.0, help="2nd harmonic warping (sin(2u) term)")
    p.add_argument("--kappa3", type=float, default=0.0, help="3rd harmonic warping (sin(3u) term)")
    p.add_argument("--from-spectrum", type=int, default=None, help="Derive kappa harmonics from HPF spectrum of N")
    p.add_argument("--tau-spectrum", type=float, default=1e-12, help="Softness for spectrum→kappa map (1e-12=zero-tuned, 0.02=soft)")
    p.add_argument("--kappa-max", type=float, default=0.10, help="Cap on |kappa_d| from spectrum mapping")
    p.add_argument("--D-spectrum", type=int, default=32, help="Max harmonic order (denominator) for spectrum mapping")
    p.add_argument("--gamma-spectrum", type=float, default=2.0, help="Exponent for spectrum transition sharpening (higher=harder gating)")
    p.add_argument("--format", choices=["obj", "stl", "both"], default="both")
    p.add_argument("--out", type=Path, default=None, help="Output basename without extension")
    return p.parse_args()


def main():
    args = parse_args()
    
    # HPF spectrum mapping (if enabled)
    spectrum_meta = None
    if args.from_spectrum is not None:
        tau_map = args.tau_spectrum if args.tau_spectrum is not None else args.tau
        if tau_map is None:
            tau_map = 1e-12  # Zero-tuned default
        
        ks = spectrum_kappas_from_N(
            args.from_spectrum,
            D=args.D_spectrum,
            kappa_max=args.kappa_max,
            tau=tau_map,
            gamma=args.gamma_spectrum
        )
        
        # Map top 3 harmonics to kappa, kappa2, kappa3
        top3 = sorted(ks.items(), key=lambda kv: kv[1], reverse=True)[:3]
        (h1, a1) = top3[0] if len(top3) > 0 else (1, 0.0)
        (h2, a2) = top3[1] if len(top3) > 1 else (2, 0.0)
        (h3, a3) = top3[2] if len(top3) > 2 else (3, 0.0)
        
        args.kappa = a1
        args.kappa2 = a2
        args.kappa3 = a3
        
        spectrum_meta = {
            "N": args.from_spectrum,
            "tau_spectrum": tau_map,
            "gamma_spectrum": args.gamma_spectrum,
            "D_spectrum": args.D_spectrum,
            "kappa_max": args.kappa_max,
            "harmonics": {int(h): float(a) for h, a in ks.items() if a > 1e-10},
            "top3": {"h1": h1, "a1": a1, "h2": h2, "a2": a2, "h3": h3, "a3": a3}
        }
        
        print(f"HPF spectrum mapping for N={args.from_spectrum}:")
        print(f"  Top harmonics: {h1}→{a1:.6f}, {h2}→{a2:.6f}, {h3}→{a3:.6f}")
        divisors = [d for d in range(2, args.D_spectrum+1) if args.from_spectrum % d == 0]
        if divisors:
            print(f"  Divisors found: {divisors}")
        else:
            print(f"  No divisors in range [2,{args.D_spectrum}] → likely prime")
    
    V, F = adaptive_mobius_unity(
        radius_mm=args.radius_mm,
        half_width_mm=args.half_width_mm,
        twists=args.twists,
        gamma=args.gamma,
        samples_major=args.samples_major,
        samples_width=args.samples_width,
        tau=args.tau,
        proj_mode=args.proj_mode,
        thickness_mm=args.thickness_mm,
        kappa=args.kappa,
        kappa2=args.kappa2,
        kappa3=args.kappa3,
    )
    base = args.out if args.out else (DEFAULT_OBJ.with_suffix(""))
    if args.format in ("obj", "both"):
        save_obj(base.with_suffix(".obj"), V, F)
    if args.format in ("stl", "both"):
        write_binary_stl(base.with_suffix(".stl"), V, F)
    print(f"Wrote: {', '.join(str(p) for p in [base.with_suffix('.obj') if args.format in ('obj','both') else None, base.with_suffix('.stl') if args.format in ('stl','both') else None] if p)}")
    
    # Write spectrum metadata if HPF mapping was used
    if spectrum_meta is not None:
        import json
        meta_path = Path(str(base) + "_spectrum.json")
        with open(meta_path, 'w') as f:
            json.dump(spectrum_meta, f, indent=2)
        print(f"Wrote: {meta_path}")


if __name__ == "__main__":
    main()