Ears for coding agents: let AI hear, review and make sound. CPU-only, open source.
forge fit: translate a recording into code (analysis by synthesis)
Leonxlnx789c398d0023
diff --git a/docs/FIT.md b/docs/FIT.mdnew file mode 100644index 0000000..58c9a31--- /dev/null+++ b/docs/FIT.md@@ -0,0 +1,260 @@+# earshot fit: translate a recording into code++**Can an audio file be translated into code? Yes, within limits.** The method is *analysis by synthesis*. You pick a+small synthesis model with readable parameters and fit those parameters until the model's render matches the+recording. The fitted model is then written out as a Python module whose `render()` makes the sound. Examples of the+parameters: the frequency, decay and level of each ringing mode, a noise band's loudness over time, a partial's+pitch glide.++The code does not store the recording's samples. It stores the structure of the sound: modes, partials, band+envelopes. From that structure it can make new takes (fresh noise each seed), variations (knobs: size, damping,+pitch, brightness, decay, width, ...), and morphs between two recordings.++On 12 real references, the renders of the generated code sit close to the originals:+- median CLAP cosine 0.945 (minimum 0.881);+- spectrograms a median 0.75 dB further apart than two renders of the same model are from each other;+- `earshot describe` gives the same top tag for both in 10 of 12.++They are close but not identical: measured differences remain in onsets, tone balance and noise texture, listed+below. Whether ears can tell them apart is what the mini blind test is for (`out/fit/blind_fit/`, below).++## How it works++Three fitters, each analysis by synthesis, each producing a plain-JSON model:++| fitter | for | the model |+|---|---|---|+| `fit/modal.py` | struck, ringing sounds (clicks, taps, keys, impacts) | per strike, damped sinusoids `[Hz, decay, amplitude, phase]` (ESPRIT on sub-bands + least squares); the contact as fast modes; a sub-20 Hz pulse; band noise envelopes |+| `fit/sines.py` | tonal sounds (dings, chimes, pops with a pitch) | tracked partials with frequency and level breakpoints (McAulay-Quatieri / SMS; glides kept); strike atoms; 1/3-octave residual noise including the recording's own floor |+| `fit/spectral.py` | noisy sounds (whooshes, swishes, cloth) | a time-varying 48-band noise gesture, stereo per band group, flutter / crackle texture statistics, tonal ridges |++`fit/auto.py` is the engine on top of them.++1. **Measure the sound.** `character()` measures attack, decay, crest, tonal share, partial persistence, glide and+ flatness, and names a class (glide, ringing, struck, gesture, mixed). The class orders the candidates.+2. **Fit every candidate.** Under 1 s that is all six: modal, sines, spectral, and three hybrids. Longer sounds get+ the class's four.+ - In a **hybrid**, each layer but the last keeps only its deterministic part, and the next layer is fitted on+ what is left. Example: sines partials, then modal modes on the rest, then spectral noise on what remains.+ - So a pop becomes chirp + body + air, and a key press becomes body + air.+3. **Measure each candidate's post stage** from two renders (analysis by synthesis again):+ - a smooth third-octave EQ that moves the render's average balance onto the original's;+ - the level;+ - the original's attack envelope. Before the onset a render may not stand above it: band noise and window smear+ leak energy before a strike, which softens the attack. Over the first 6-25 ms after a sharp onset the render+ follows the original's contour within ±9 dB. This fixed a ding whose onset the sines fit had blunted from 60+ to 4 dB/ms, and noise up to 12 dB above the original in the 4 ms before a key's strike.+4. **Score each candidate's render against the original** and keep the lowest (`quality.score`, metrics below).+ `--clap` adds CLAP to the score; loading CLAP takes about 50 s.++`fit/codegen.py` then writes the model as a **forge recipe module**. It contains:+- `TARGET` / `ALTS`: from the refset category's recipe when the source is a refset file;+- `REFSET` / `REFS`;+- `SPACE`: the kind's knobs with search ranges around the identity;+- `DEFAULTS`: the identity, which re-renders the fit;+- `MODEL`: the fitted parameters as a readable literal, one mode, partial or keyframe per line;+- `render(p, r)` and `render_seed(seed, **knobs)`.++The module's render is **bitwise identical** to the engine's render of the model. This is tested, and true for all+12 validation fits.++Variation comes in three forms:+- **Knob perturbations:** the `SPACE` of the recipe, searched by the forge critic with `earshot fit --forge`.+- **`vary`:** seeded jitter of modes and partials, so each take sounds like a new take of the same object.+- **Morph:** two fits of the same kind.+ - Paired modes and partials interpolate: frequency, decay and level geometrically, phase circularly. Pairing is+ an optimal assignment on log frequency within one octave.+ - Unpaired ones fade with their side's weight.+ - Envelopes interpolate in dB on a time axis warped through the strikes or the loudness peak.+ - Hybrids morph layer by layer, and the post stages interpolate too.+ - A morph recipe has a `morph` knob (0.2-0.8 in `SPACE`), so a search explores sounds between two recordings,+ not copies of either.++## Commands++```+earshot fit click.wav -o made/click_fit.py # recipe + made/click_fit.wav + .png (side by side) + .json+earshot fit click.wav -o made/click_fit.py --report # + render-vs-render floor + CLAP cosine -> click_fit.report.json+earshot fit pop.wav --kind hybrid --layers sines,modal,spectral --render pop_fit.wav+earshot fit whoosh.wav --clap # let CLAP help choose the fit (loads CLAP, ~50 s)+earshot fit --morph a.wav b.wav --amount 0.5 -o made/ab_morph.py+earshot fit --forge made/click_fit.py --budget 96 --dir made/click_variations # critic-searched variations+python made/click_fit.py 3 take3.wav # the module renders on its own (seed 3)+```++`--forge` loads the recipe from its path and runs the forge search (pre-screen, robust re-renders, report.md,+compare.png, audition.wav). Alternatively, copy the file into `earshot/forge/recipes/` and run `earshot forge <name>`.+Picks of a recipe loaded from a path cannot be re-rendered by `earshot forge --check`, which needs an importable+module name.++```python+from earshot.forge import fit+from earshot.forge.fit.quality import quality+m = fit.fit('click.wav') # kind='auto' | 'modal' | 'sines' | 'spectral' | 'hybrid'+y = fit.render(m, seed=0, vary=0.3) # knobs: earshot.forge.fit.auto.knobs_of(m)+q = quality('click.wav', fit.render(m)) # the metrics below; clap=True / describe=True add the model checks+src = fit.to_recipe(m, name='click_fit', source='click.wav')+mm = fit.morph(m_a, m_b, 0.5)+```++## Quality metrics (`fit/quality.py`)++Both sounds are mono-summed. Both are cut at the original's onset, so a timing error still counts. Each is levelled+to its own loudest 50 ms; the level difference is reported separately.++| metric | what |+|---|---|+| `mel_db` | multi-resolution log-mel distance (64 bands, FFT 256 / 1024 / 4096), mean \|dB\| over cells within 60 dB of the top; 0 = the same spectrogram |+| `env_corr` | correlation of the 5 ms dB envelopes |+| `onset_err` | \|log2\| of the onset-sharpness ratio. Sharpness: 17 dB over the time the first onset takes from 20 to 3 dB under its local peak (0.125 ms frames, interpolated) |+| `tone_db` | RMS third-octave balance difference (`earshot.forge.tone`) |+| `excess_db` / `missing_db` | energy the resynthesis has where the recording is quiet, or the reverse. Mean dB beyond 6 dB over third-octave band x 10 ms cells, looking 100 dB deep. It catches hiss bands, noise floors and rings that outlive the original, where mel and envelope stop looking. It tracks CLAP's verdicts closely |+| `clap_cos`, `describe` | the model checks (optional) |++**floor**: `quality(render seed 11, render seed 12)`. A model with noise in it can never beat its own floor on+`mel_db`.++**score** = mel + 0.3 tone + 8 (1 - env r) + onset (capped at 2) + 1.5 excess + missing [+ 20 (1 - CLAP)].+- With excess and missing, the model-free score's choices had a mean CLAP of 0.927 on the 12 refs; without them,+ 0.856 (the worst choice 0.52). Measured on the same refs, so in-sample.+- The CLAP-including choice agreed with the model-free one on 11 of 12.++## Measured quality++The **12 forge-split refs** (never bench) are 2 each of click, typing_key, pop, impact, whoosh_fast and notify: the+first file of each category and the first from another source.++For each ref: every candidate was fitted, the engine chose (with `--clap`), the recipe module was written and+imported, and **its** render (seed 0) was measured. Results are in `out/fit/validation/` (`summary.md`,+`all_metrics.json`, `<category>/<stem>/pair.png`, the recipe modules, the WAVs).++| category | ref | chosen | mel dB (floor) | env r | tone dB | onset err | excess dB | CLAP (floor) |+|---|---|---|---|---|---|---|---|---|+| click | fs-167829_1 | sines | 3.15 (2.35) | 0.997 | 1.14 | 0.27 | 0.16 | 0.959 (0.967) |+| click | kit-ui_click_01 | sines + modal + spectral | 3.26 (2.69) | 0.993 | 1.38 | 0.03 | 0.06 | 0.948 (0.962) |+| typing_key | fs-561697_1 | modal | 4.65 (2.49) | 0.975 | 1.93 | 0.60 | 1.06 | 0.881 (0.976) |+| typing_key | kit-kb_thock_01 | modal | 4.25 (3.28) | 0.946 | 4.40 | 0.87 | 0.49 | 0.944 (0.984) |+| pop | kit-ui_pop_01 | sines + modal + spectral | 3.89 (2.50) | 0.970 | 2.05 | 0.03 | 0.79 | 0.959 (0.988) |+| pop | mk-3000_1 | sines | 6.12 (3.24) | 0.989 | 3.45 | 1.36 | 1.15 | 0.923 (0.989) |+| impact | kit-impact_01 | sines | 4.41 (3.92) | 0.964 | 1.99 | 1.12 | 0.68 | 0.910 (0.978) |+| impact | kit-impact_02 | sines | 4.32 (3.96) | 0.919 | 0.61 | 0.68 | 0.59 | 0.953 (0.991) |+| whoosh_fast | fs-719636_1 | modal | 3.31 (5.56) | 0.972 | 2.22 | 0.78 | 0.84 | 0.898 (0.948) |+| whoosh_fast | kit-whoosh_fast_01 | sines | 3.54 (3.40) | 0.984 | 2.45 | 1.49 | 1.25 | 0.947 (0.973) |+| notify | fs-681787_1 | sines + spectral | 2.03 (1.81) | 0.999 | 1.48 | 0.41 | 0.32 | 0.964 (0.982) |+| notify | kit-ui_notify_01 | sines | 1.87 (0.72) | 0.998 | 1.18 | 0.48 | 0.89 | 0.937 (0.985) |++Per category, the mean CLAP of the two refs:++| category | mean CLAP |+|---|---|+| notify | 0.95 |+| click | 0.95 |+| pop | 0.94 |+| impact | 0.93 |+| whoosh_fast | 0.92 |+| typing_key | 0.91 |++All 12:+- median CLAP 0.945; 4 of 12 reach 0.95;+- median mel 3.71 dB against a median floor of 2.96;+- median envelope r 0.98;+- median tone 2.0 dB;+- `earshot describe` top tag the same in 10 of 12. The two that differ: 'an enter key press' was heard as 'a soft+ UI button tap', and 'a cinematic hit with a long tail' as 'a deep cinematic whoosh'.++**Each fitter alone versus the engine.** The builders reported each fitter alone at a CLAP median of about 0.90.+The engine's choice per sound plus the post stage reaches 0.945. Two things carry that gain:+- The three-layer hybrid won on clicks and pops.+- The sines fitter won on impacts. The spectral and noise-heavy candidates of the impacts scored CLAP 0.47-0.65,+ caught by `excess_db`: a hiss band and a noise floor through the tail.++**Size and time:**+- Recipe modules are 24-274 KB; the biggest is a whoosh fitted as about 600 modes in 10 strikes.+- `earshot fit` on a 0.2 s pop takes 12 s (six candidates, model-free choice).+- Fitting all six candidates with CLAP scoring took 8-98 s for short sounds. The 4.5 / 6.5 s impacts took+ 250-340 s with four to six candidates.++## The mini blind test++`out/fit/blind_fit/` holds 12 trials. In each, one clip is the real recording and the other is the render of its+generated recipe module, in random order (the recording is A on exactly half).++The files:+- `blind_test.wav` (65 s), or `blind_test_trials/tNN_A.wav` + `tNN_B.wav` one trial at a time;+- `answer_sheet.txt`;+- `KEY_open_after.json`, the answers: do not open it first;+- `cleanliness.json`, safe to open: no answers;+- `score_answers.py`.++Trim, level and the cleanliness checks are the clean blind test's own: `out/fit/build_blind_fit.py` imports+`eval/forge/blind_v2.py`'s functions.+- Both clips are cut at the same onset and end levels above the recording's floor, so neither plays room noise.+- They are matched on the K-weighted loudest 100 / 400 ms, and true peaks stay at or under -1 dBTP.+- Cleanliness PASS: loudest moments 0.00 LU apart.+- 2 warnings: recording floors at -53 and -59 dBFS under the sound, 10 dB below where the clips start and end.++After listening: `.venv\Scripts\python.exe out\fit\blind_fit\score_answers.py A B ...` (12 letters). 10 or more+right is unlikely by luck (p = 0.019).++## Morph examples++`out/fit/morphs/` has three morphs:+- `click_morph` (hybrid);+- `key_morph` (modal, two key presses);+- `ding_morph` (sines, two dings).++Each comes with:+- the morph recipe;+- its render at 0.5;+- a side-by-side spectrogram (A | morph | B);+- `<name>_audition.wav`: A, morph 0.25, 0.5, 0.75, B, peak-matched.++The 0.5 morphs sit between their sources: CLAP 0.48-0.76 to each, so they are new sounds, not copies.++## Licence++A fit of a recording is a derivative of that recording: the parameters are measured from it. Keep the source's+attribution and licence with the generated recipe; its docstring names the source.+- Prefer CC0 sources for anything shipped as a seed.+- A morph across several sources is less derivative of any one of them. Keep every source's attribution anyway.+- The refsets' recordings are licensed and are not redistributed. The fitted models and recipes of them, under+ `out/`, stay local like the refs.++## Limits (honest)++**Close but not identical.**+- The CLAP target of about 0.95 is reached on 4 of 12.+- `mel_db` stays 0.1-2.9 dB above each model's own floor on 11 of 12; one whoosh sits under its own unusually high+ floor. The worst: the pop mk-3000_1 at 6.1 dB against a 3.2 dB floor, and the key fs-561697_1 at 4.7 against 2.5.++**Onsets.** Even with the attack match, the measured onset sharpness differs by 0.6-1.5 octaves on 6 of 12. The+metric itself is noisy on stochastic renders: different seeds of one model ranged 23-140 dB/ms on a key.++**Noise models.** A noise band is spectrally flat within its band, which fills valleys: the thock key's tone sits at+4.4 dB even after the EQ. The modal key fits have high floors (2.5-3.3 dB): their noise varies take to take more+than the recording suggests.++**Whooshes fitted as modes or partials.** The engine chose modal and sines for the two fast whooshes because they+re-render them closest. Such a model is a sinusoidal decomposition of noise, about 600 modes and a 274 KB recipe.+Its knob variations (size, pitch) may sound metallic. The spectral fitter is the generative choice for whooshes, but+it lost on these two refs.++**Morphs.**+- Strikes pair by index, so a key with 2 strikes and one with 4 pair crudely.+- Partials more than an octave apart do not pair, so they fade instead of gliding (the ding morph keeps both pitches+ at -6 dB).+- Exact pole copies that stop a ring in a later strike stop cancelling once morphed.++**The post stage pins the attack** to the original's contour, so the `hardness` knob changes the attack's colour+but not its envelope. The EQ is static under pitch knobs. An envelope calibration (fix the tail's level over time)+is in the code but off: it lowered mel and raised envelope r, but CLAP fell from 0.925 to 0.918. A cut-only+spectro-temporal ceiling was tried and left out: CLAP +0.004, mel -0.3 dB.++**Speed.** Default `earshot fit` takes 10-100 s for short sounds and minutes for long impacts. `--clap` adds about+50 s to load CLAP.++**Choosing.** The weights of `quality.score` were set on the same 12 refs they were checked on. The selection has+no held-out test yet.++**Not tested here:** zips and long glides (the sines fitter tracks chirps, but no zip ref exists), risers, swipes,+shimmers, stereo-heavy designed sounds, and anything from the bench split.diff --git a/earshot/cli.py b/earshot/cli.pyindex 2730952..cf9d625 100644--- a/earshot/cli.py+++ b/earshot/cli.py@@ -26,6 +26,7 @@ COMMANDS = {'critique': 'critique', # launch-video sound scorecard against a profile of professional references'profile': 'profile', # build a reference profile from your own reference films'forge': 'forge', # make sounds in code and improve them by listening+ 'fit': 'forge.fit', # translate a recording into code (analysis by synthesis) and vary it'gallery': 'gallery', # one static HTML page of forge results: players, spectrograms, numbers'measure': 'features', # objective measurements only (no models)'llm': 'llm', # optional audio-LLM critique (only with your own API key + consent)diff --git a/earshot/forge/fit/__init__.py b/earshot/forge/fit/__init__.pynew file mode 100644index 0000000..33c38c1--- /dev/null+++ b/earshot/forge/fit/__init__.py@@ -0,0 +1,230 @@+"""earshot fit: translate a real recording into code (analysis by synthesis), then vary it.++ from earshot.forge import fit+ m = fit.fit('click.wav') # kind='auto' | 'modal' | 'spectral' | 'sines' | 'hybrid'+ y = fit.render(m, seed=0) # the resynthesis (seeds change only noise / jitter); knobs vary it+ from earshot.forge.fit.quality import quality+ q = quality('click.wav', y) # mel dB, envelope r, tone dB, onset error, ... (clap=True: CLAP cos)+ src = fit.to_recipe(m, name='click_fit', source='click.wav') # a forge recipe module (Python source)+ mm = fit.morph(m_a, m_b, 0.5) # a new model between two fits of the same kind++ earshot fit click.wav -o made/click_fit.py --report # recipe + resynthesis WAV + spectrogram PNG + metrics+ earshot fit --morph a.wav b.wav --amount 0.5 -o made/ab_morph.py+ earshot fit --forge made/click_fit.py --budget 96 --dir made/click_variations # critic-searched variations++The fitters (one module each, plain-JSON models, deterministic per seed, pure numpy / scipy):+ modal.py struck / ringing sounds -> strikes of damped sinusoids (ESPRIT + least squares) + band noise+ sines.py tonal sounds -> tracked partials (McAulay-Quatieri / SMS) + strike atoms + 1/3-octave noise+ spectral.py noisy sounds -> a time-varying 48-band noise gesture + stereo + texture + tonal ridges+ auto.py the engine: character -> candidates -> fit, render, score, keep the best; hybrids; morph+ quality.py the metrics every fit is judged by (and the side-by-side spectrogram picture)+ codegen.py model -> a forge recipe module (TARGET / SPACE / DEFAULTS / MODEL / render(p, r))+docs/FIT.md has how it works, the measured quality and the limits.+"""+import os+++def fit(x, kind='auto', **kw):+ from . import auto+ return auto.fit(x, kind=kind, **kw)+++def render(model, seed=0, **knobs):+ from . import auto+ return auto.render(model, seed=seed, **knobs)+++def morph(a, b, amount=0.5):+ from . import auto+ return auto.morph(a, b, amount)+++def to_recipe(model, **kw):+ from . import codegen+ return codegen.to_recipe(model, **kw)+++# ------------------------------------------------------------------------------------------------------- CLI+def _paths(a, stem):+ """output paths: -o recipe.py names the folder and stem, else --dir (default '.') and <stem>_fit"""+ if a.output:+ d = os.path.dirname(os.path.abspath(a.output))+ base = os.path.splitext(os.path.basename(a.output))[0]+ else:+ d = os.path.abspath(a.dir or '.')+ base = f'{stem}_fit'+ os.makedirs(d, exist_ok=True)+ j = lambda ext: os.path.join(d, base + ext).replace(chr(92), '/')+ return {'recipe': j('.py'), 'wav': (a.render or j('.wav')).replace(chr(92), '/'), 'png': j('.png'),+ 'model': j('.json'), 'report': j('.report.json'), 'name': base}+++def _write_wav(path, y):+ import numpy as np+ import soundfile as sf+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)+ sf.write(path, np.asarray(y, np.float32), 48000, subtype='FLOAT')+ return path+++def run_fit(path, kind='auto', layers=None, output=None, out_dir=None, render_path=None, report=False, clap=False,+ describe=False, seed=0, target=None, fast=False, verbose=True, log=print):+ """the `earshot fit <file>` pipeline as a function: fit, write the recipe / WAV / PNG / model JSON, measure.+ Returns the result dict (paths, quality, floor, chosen kind, timings)."""+ import time++ import numpy as np++ from . import auto, codegen+ from . import quality as Q++ class A:+ pass+ a = A()+ a.output, a.dir, a.render = output, out_dir, render_path+ stem = os.path.splitext(os.path.basename(path))[0]+ P = _paths(a, stem)+ t0 = time.time()+ X = Q.load(path)+ m = auto.fit(X, kind=kind, layers=layers, clap=clap, fast=fast, name=os.path.basename(path),+ verbose=verbose and kind == 'auto')+ t_fit = time.time() - t0+ codegen.write_recipe(P['recipe'], m, name=P['name'], source=path, target=target)+ rec = codegen.load_recipe(P['recipe'])+ y = rec.render_seed(seed) # the code's render, not the model's: what the file really does+ _write_wav(P['wav'], y)+ q = Q.quality(X, y, clap=report or clap, describe=describe)+ fl = Q.floor(lambda s: rec.render_seed(s), clap=False) if report else None+ codegen.write_recipe(P['recipe'], m, name=P['name'], source=path, target=target, quality=q, floor=fl)+ rec = codegen.load_recipe(P['recipe'])+ y2 = rec.render_seed(seed)+ same = bool(np.array_equal(np.asarray(y2), np.asarray(auto.render(m, seed=seed))) and np.array_equal(y2, y))+ auto.save(m, P['model'])+ Q.pair_png(P['png'], X, y, title=f"{os.path.basename(path)} -> {P['name']}.py ({auto.kind_of(m)}"+ + (f", auto: {m['fit_engine']['chosen']}" if m.get('fit_engine', {}).get('kind') == 'auto' else '')+ + ')')+ res = {'source': path.replace(chr(92), '/'), 'kind': auto.kind_of(m),+ 'chosen': (m.get('fit_engine') or {}).get('chosen', kind), 'quality': q, 'floor': fl,+ 'files': {k: P[k] for k in ('recipe', 'wav', 'png', 'model')}, 'code_renders_fit': same,+ 'seconds': {'fit': round(t_fit, 2), 'total': round(time.time() - t0, 2)},+ 'candidates': [{k: r.get(k) for k in ('candidate', 'score', 'fit_s', 'error')}+ for r in (m.get('fit_engine') or {}).get('candidates', [])]}+ if report:+ import json+ with open(P['report'], 'w', encoding='utf-8') as fh:+ json.dump({**res, 'fit_engine': m.get('fit_engine'), 'summary': auto.summary(m)}, fh, indent=1,+ default=float)+ res['files']['report'] = P['report']+ return res+++def run_morph(path_a, path_b, amount=0.5, output=None, out_dir=None, render_path=None, clap=False, seed=0,+ fast=False, verbose=True):+ """`earshot fit --morph a b`: both fitted with one kind, a morph recipe (knob 'morph' in SPACE) + its render"""+ import numpy as np++ from . import auto, codegen+ from . import quality as Q++ class A:+ pass+ a = A()+ a.output, a.dir, a.render = output, out_dir, render_path+ sa = os.path.splitext(os.path.basename(path_a))[0]+ sb = os.path.splitext(os.path.basename(path_b))[0]+ P = _paths(a, f'{sa}__{sb}_morph'.replace('_fit', ''))+ if not output:+ P = {k: (v.replace('_morph_fit', '_morph') if isinstance(v, str) else v) for k, v in P.items()}+ ma, mb, kinds = auto.fit_pair(path_a, path_b, clap=clap, fast=fast, verbose=verbose)+ mm = auto.morph_model(ma, mb, amount)+ src = codegen.to_recipe(mm, name=P['name'], source=None, licence=(+ f'Licence: a morph of two recordings ({os.path.basename(path_a)}, {os.path.basename(path_b)}); keep both '+ 'sources\' attribution / licence;'))+ os.makedirs(os.path.dirname(P['recipe']), exist_ok=True)+ with open(P['recipe'], 'w', encoding='utf-8') as fh:+ fh.write(src)+ rec = codegen.load_recipe(P['recipe'])+ y = rec.render_seed(seed)+ _write_wav(P['wav'], y)+ Xa, Xb = Q.load(path_a), Q.load(path_b)+ qa, qb = Q.quality(Xa, y, clap=clap), Q.quality(Xb, y, clap=clap)+ n = max(len(Xa), len(Xb), len(y))+ padt = lambda v: np.pad(Q.mono(v), (0, n - len(Q.mono(v))))+ Q.pair_png(P['png'], padt(Xa), padt(y), title=f'morph {amount:.2f}: {os.path.basename(path_a)} | morph | '+ f'{os.path.basename(path_b)}', extra=(os.path.basename(path_b), padt(Xb)))+ auto.save(mm, P['model'])+ return {'a': path_a, 'b': path_b, 'amount': amount, 'kind': auto.kind_of(ma), 'kinds_tried': kinds,+ 'vs_a': qa, 'vs_b': qb, 'files': {k: P[k] for k in ('recipe', 'wav', 'png', 'model')}}+++def add_cli(sub):+ from ...cli import common+ p = common(sub.add_parser('fit', help='translate a recording into code: fit a model, write a forge recipe, '+ 'resynthesis + spectrogram + quality (analysis by synthesis)'))+ p.add_argument('file', nargs='?', help='the recording to fit')+ p.add_argument('-o', '--output', help='recipe path (.py); the WAV / PNG / model JSON go next to it')+ p.add_argument('--dir', help='output folder when -o is not given (default: current folder)')+ p.add_argument('--kind', default='auto', choices=('auto', 'modal', 'spectral', 'sines', 'hybrid'))+ p.add_argument('--layers', help='hybrid layers, e.g. sines,modal,spectral (default modal,spectral)')+ p.add_argument('--render', help='resynthesis WAV path (default next to the recipe)')+ p.add_argument('--report', action='store_true',+ help='also measure the render-vs-render floor and CLAP cosine and write <name>.report.json')+ p.add_argument('--clap', action='store_true', help='let CLAP cosine take part in choosing the fit (loads CLAP)')+ p.add_argument('--describe', action='store_true', help='run earshot describe on the original and the resynthesis')+ p.add_argument('--target', help='critic description for the recipe (default: from the refset category / sound)')+ p.add_argument('--seed', type=int, default=0)+ p.add_argument('--fast', action='store_true', help='cheaper fitter settings (previews)')+ p.add_argument('--morph', nargs=2, metavar=('A', 'B'),+ help='fit two recordings with one kind and write a morph recipe')+ p.add_argument('--amount', type=float, default=0.5, help='with --morph: 0 = A, 1 = B (default 0.5)')+ p.add_argument('--forge', metavar='RECIPE_PY',+ help='search variations of a fitted recipe file with the forge critic')+ p.add_argument('--budget', type=int, default=96, help='with --forge: candidates the critic scores')+ p.add_argument('--pop', type=int, default=16, help='with --forge: population per generation')+ p.add_argument('--variants', type=int, default=4, help='with --forge: diverse sounds to keep')+ p.add_argument('--refset', help="with --forge: the critic's refset category (default the recipe's REFSET)")+ p.add_argument('--quiet', action='store_true', help='do not print the candidates while fitting')++ def run(a):+ from ...report import emit+ from . import quality as Q+ if a.forge:+ from .. import forge+ from . import codegen+ rec = codegen.load_recipe(a.forge)+ refset = a.refset or getattr(rec, 'REFSET', None)+ refs = None if refset else (getattr(rec, 'REFS', None) or None)+ out = a.dir or os.path.splitext(a.forge)[0] + '_forge'+ r = forge(rec, refs=refs, refset=refset, budget=a.budget, pop=a.pop, keep=a.variants, seed=a.seed, out=out,+ robust=3, prescreen=3 * a.pop, shortlist=2, strategy='es')+ lines = [r['summary']] + [f" {p['name']}: {p['score'].get('summary')}" for p in r['picks']]+ lines.append(f'wrote {out}: WAVs, report.json, report.md, compare.png, audition.wav')+ emit({k: v for k, v in r.items() if k != 'history'}, a, text='\n'.join(lines))+ return 0+ if a.morph:+ r = run_morph(a.morph[0], a.morph[1], a.amount, a.output, a.dir, a.render, clap=a.clap, seed=a.seed,+ fast=a.fast, verbose=not a.quiet)+ lines = [f"morph {a.amount:.2f} of {os.path.basename(a.morph[0])} and {os.path.basename(a.morph[1])} "+ f"({r['kind']} models)",+ f" vs A: {Q.text(r['vs_a'])}", f" vs B: {Q.text(r['vs_b'])}"]+ lines += [f' wrote {k}: {v}' for k, v in r['files'].items()]+ emit(r, a, text='\n'.join(lines))+ return 0+ if not a.file:+ print('usage: earshot fit <file> [-o recipe.py] [--kind auto] [--render out.wav] [--report] | '+ '--morph A B [-o morph.py] | --forge recipe.py [--dir out]')+ return 2+ layers = tuple(a.layers.split(',')) if a.layers else None+ r = run_fit(a.file, a.kind, layers, a.output, a.dir, a.render, a.report, a.clap, a.describe, a.seed, a.target,+ a.fast, verbose=not a.quiet and not a.json)+ lines = [f"{os.path.basename(a.file)} -> {r['kind']} model" + (f" (auto chose {r['chosen']})"+ if a.kind == 'auto' else '')+ + f" in {r['seconds']['fit']:.1f} s",+ ' ' + Q.text(r['quality'], r['floor'])]+ if r['floor'] and r['floor'].get('mel_db') is not None:+ lines.append(f" floor = two renders of the model with different seeds (a noise model cannot beat it)")+ lines.append(f" the recipe's own render equals the fit render: {r['code_renders_fit']}")+ lines += [f' wrote {k}: {v}' for k, v in r['files'].items()]+ emit(r, a, text='\n'.join(lines))+ return 0+ p.set_defaults(func=run)diff --git a/earshot/forge/fit/auto.py b/earshot/forge/fit/auto.pynew file mode 100644index 0000000..c63dfc8--- /dev/null+++ b/earshot/forge/fit/auto.py@@ -0,0 +1,1092 @@+"""The fit engine: one entry point that turns a recording into a model (and back), whatever kind of sound it is.++ from earshot.forge.fit import auto+ m = auto.fit('click.wav') # kind='auto': measure the sound, try the fitters, keep the best+ m = auto.fit('pop.wav', kind='hybrid', layers=('sines', 'modal', 'spectral'))+ y = auto.render(m, seed=0) # the resynthesis; seeds change only the noise / jitter+ y = auto.render(m, seed=3, vary=0.4) # knobs: knobs_of(m) (a fitted recipe's SPACE)+ mm = auto.morph(m_a, m_b, 0.5) # a new model between two fits of the same kind+ auto.character('x.wav') # the measurements the candidates are chosen from+ print(auto.summary(m))++Kinds (each a fitter in this package, all analysis by synthesis, all plain JSON models):+ modal struck / ringing sounds: strikes of damped sinusoids + band noise (fit/modal.py)+ sines tonal sounds: tracked partials (glides kept) + strike atoms + 1/3-octave noise (fit/sines.py)+ spectral noisy sounds: a time-varying 48-band noise gesture + stereo + texture + ridges (fit/spectral.py)+ hybrid layers fitted one after another on what the previous layers leave: every layer but the last keeps only+ its deterministic part (sines partials + atoms, or modal modes + contact + sub), the last (spectral)+ models the rest. A pop = chirp (sines) + body (modal) + air (spectral); a key press = modal + spectral.+ morph {'kind': 'morph', 'a': model, 'b': model, 'amount': w}: rendered as morph(a, b, w) (the recipe knob+ 'morph' moves w), so a variation sits between two recordings instead of copying one.++kind='auto' (fit):+ 1. character() measures attack, decay, crest, tonal share (energy in spectral peaks 12 dB over the local median),+ partial persistence, the glide of the strongest partial and flatness, and names a class (glide, ringing,+ struck, gesture, mixed); plan() orders the candidates by class. Under 1 s every candidate is fitted (each fit+ takes 0.5-4 s); longer sounds get the class's four.+ 2. every candidate is fitted, then its post stage (fit_post) is measured from two renders: a smooth third-octave+ EQ onto the original's balance, the level, and the attack: the original's 0.25 ms envelope before the onset+ (renders may not stand above it: band noise and window smear leak energy before a strike) and over the first+ 6-25 ms after a sharp onset (renders follow its contour within +-9 dB). render() always applies it.+ 3. each candidate is rendered (seed 0) and scored against the original (quality.score: mel dB, tone, envelope,+ onset, excess / missing energy, + CLAP with clap=True); the lowest score wins. Hybrids reuse the single-kind+ fits as their first layer. The model gets a 'fit_engine' entry: the character, every candidate's metrics, the+ choice.+Pure numpy / scipy (CLAP only with clap=True). Deterministic: render(model, seed, knobs) is a pure function.+"""+import copy+import json+import time++import numpy as np++from . import quality as Q++SR = 48000+KINDS = ('modal', 'spectral', 'sines', 'hybrid')+ROLE = {'sines': 'tone', 'modal': 'body', 'spectral': 'air'}+HYBRIDS = {'modal+spectral': ('modal', 'spectral'), 'sines+spectral': ('sines', 'spectral'),+ 'sines+modal+spectral': ('sines', 'modal', 'spectral')}+VERSION = 1++# knobs per kind: name -> (search range spec for a forge SPACE, identity value, what it does)+KNOBS = {+ 'modal': {+ 'size': ((0.8, 1.25, 'log'), 1.0, 'object size: mode frequencies / size, decays x size'),+ 'damping': ((0.7, 1.43, 'log'), 1.0, 'decays / damping'),+ 'brightness': ((-3.0, 3.0), 0.0, 'dB / octave about 1 kHz on modes and noise'),+ 'hardness': ((0.7, 1.43, 'log'), 1.0, 'contact: shorter and brighter attack above 1'),+ 'noise': ((-6.0, 4.0), 0.0, 'dB on the noise bands'),+ 'width': ((0.5, 1.5), 1.0, 'x the side signal'),+ 'room': ((0.0, 0.25), 0.0, 'wet of a small stochastic room'),+ 'vary': ((0.0, 0.6), 0.0, 'seeded jitter of modes, timing and noise: new takes of the same object'),+ 'spacing': ((0.8, 1.25, 'log'), 1.0, 'x the time between strikes'),+ },+ 'sines': {+ 'transpose': ((-3.0, 3.0), 0.0, 'semitones (partials and the residual spectrum together)'),+ 'stretch': ((0.85, 1.18, 'log'), 1.0, 'time factor about the first strike'),+ 'decay': ((0.7, 1.43, 'log'), 1.0, 'factor on every decay after its peak'),+ 'brightness': ((-3.0, 3.0), 0.0, 'dB / octave about the partial centroid'),+ 'vibrato': ((0.0, 20.0), 0.0, 'cents of vibrato'),+ 'drift': ((0.0, 10.0), 0.0, 'cents of slow random wander'),+ 'residual': ((0.5, 2.0, 'log'), 1.0, 'gain on the noise'),+ 'transient': ((0.5, 2.0, 'log'), 1.0, 'gain on the strike noise (first 15 ms)'),+ 'vary': ((0.0, 0.6), 0.0, 'seeded per-partial detune / level / decay jitter'),+ 'inharm': ((-0.03, 0.03), 0.0, 'stretch of the partial ratios'),+ },+ 'spectral': {+ 'length': ((0.8, 1.25, 'log'), 1.0, 'time-stretch of the gesture'),+ 'speed': ((0.8, 1.25, 'log'), 1.0, 'movement speed: shorter and higher above 1'),+ 'sweep': ((0.7, 1.43, 'log'), 1.0, 'x the spectral centroid excursion'),+ 'shift': ((-0.4, 0.4), 0.0, 'octaves'),+ 'tilt': ((-2.5, 2.5), 0.0, 'dB / octave about 1 kHz'),+ 'roughness': ((0.5, 1.5), 1.0, 'texture depth (flutter, crackle)'),+ 'width': ((0.5, 1.5), 1.0, 'side / pan amount'),+ 'ridges': ((0.5, 1.5), 1.0, 'tonal ridge gain'),+ },+ 'hybrid': {+ 'pitch': ((-3.0, 3.0), 0.0, 'semitones on every layer (modal size, sines transpose, spectral shift)'),+ 'decay': ((0.7, 1.43, 'log'), 1.0, 'decay factor of the tonal / body layers'),+ 'bright': ((-3.0, 3.0), 0.0, 'dB / octave on every layer'),+ 'vary': ((0.0, 0.6), 0.0, 'seeded jitter of the tonal / body layers'),+ 'width': ((0.5, 1.5), 1.0, 'stereo width of the air layer'),+ 'tone_db': ((-6.0, 6.0), 0.0, 'level of the tonal (sines) layer'),+ 'body_db': ((-6.0, 6.0), 0.0, 'level of the body (modal) layer'),+ 'air_db': ((-6.0, 6.0), 0.0, 'level of the air (spectral) layer'),+ },+}+++def _fitters():+ from . import modal, sines, spectral+ return {'modal': modal, 'sines': sines, 'spectral': spectral}+++def kind_of(model):+ """'modal' | 'sines' | 'spectral' | 'hybrid' | 'morph'"""+ k = model.get('kind') if isinstance(model, dict) else None+ if k == 'spectral_noise':+ return 'spectral'+ if k not in ('modal', 'sines', 'hybrid', 'morph'):+ raise ValueError(f'not a fit model (kind {k!r})')+ return k+++def knobs_of(model):+ """the knob table (KNOBS entry) of a model; a morph adds 'morph' (0..1) to its kind's"""+ k = kind_of(model)+ if k == 'morph':+ kn = dict(knobs_of(model['a']))+ kn['morph'] = ((0.2, 0.8), float(model.get('amount', 0.5)), 'where between the two recordings (0 = a, 1 = b)')+ return kn+ if k == 'hybrid':+ roles = {L['role'] for L in model['layers']}+ return {n: v for n, v in KNOBS['hybrid'].items()+ if not n.endswith('_db') or n[:-3] in roles}+ return KNOBS[k]+++def channels_of(x_or_model):+ if isinstance(x_or_model, dict):+ m = x_or_model+ k = kind_of(m)+ if k == 'morph':+ return max(channels_of(m['a']), channels_of(m['b']))+ if k == 'spectral':+ return 2 if m.get('stereo') else int(m.get('channels', 1))+ if k == 'sines':+ return int(m.get('channels', 2 if m.get('width', -120.0) > -50.0 else 1))+ return int(m.get('channels', 1))+ x = np.asarray(x_or_model)+ return 1 if x.ndim == 1 or x.shape[1] == 1 or np.allclose(x[:, 0], x[:, 1]) else 2+++# ================================================================================================ character+def character(x):+ """measurements that decide which fitter suits a sound (mono sum): duration, attack / t40 (ms), crest (dB),+ tonal share (0..1, energy in peaks 12 dB over the local median), persistence (0..1, peaks that continue into+ the next frame), glide (octaves the strongest partial moves), flatness (0..1, geometric / arithmetic mean+ power), strikes (onsets), and the class flags impulsive / tonal / noisy / gliding"""+ from scipy.ndimage import maximum_filter1d, median_filter+ X = Q.load(x)+ m = Q.mono(X)+ n = len(m)+ e = Q.env_db(m, 1.0)+ pk = int(np.argmax(e))+ top = float(e[pk])+ on = int(np.argmax(e > top - 30))+ below = np.nonzero(e[pk:] < top - 40)[0]+ t40 = float(below[0] if len(below) else len(e) - pk)+ act = e > top - 40+ eh = Q.env_db(m, 0.5) # the steepest rise anywhere loud (dB per 2 ms): a strike's onset+ loud = eh > eh.max() - 40+ rise = float(np.max(np.where(loud[4:], eh[4:] - eh[:-4], 0.0))) if len(eh) > 4 else 0.0+ crest = float(20 * np.log10(np.abs(m).max() + 1e-12) - 10 * np.log10(np.mean(10 ** (e[act] / 10)) + 1e-20))+ nfft, hop = 2048, 256+ T = max(1, (n + hop - 1) // hop)+ xp = np.zeros(T * hop + nfft)+ xp[nfft // 2:nfft // 2 + n] = m+ fr = np.lib.stride_tricks.sliding_window_view(xp, nfft)[::hop][:T]+ P = np.abs(np.fft.rfft(fr * np.hanning(nfft + 2)[1:-1], axis=1)) ** 2+ f = np.fft.rfftfreq(nfft, 1 / SR)+ band = (f >= 60) & (f <= 16000)+ P = P[:, band]+ fb = f[band]+ fe = P.sum(1)+ af = fe > fe.max() * 10 ** -3.5+ L = 10 * np.log10(P + 1e-20)+ med = median_filter(L, size=(1, 21), mode='nearest')+ lmax = maximum_filter1d(L, 3, axis=1)+ peaks = (L >= lmax) & (L - med > 12) & (L > L.max(1, keepdims=True) - 50)+ mask = maximum_filter1d(peaks.astype(np.uint8), 5, axis=1).astype(bool)+ share = (P * mask).sum(1) / (fe + 1e-30)+ w = fe * af+ tonal = float((share * w).sum() / (w.sum() + 1e-30))+ flat = np.exp(np.mean(np.log(P + 1e-30), 1)) / (P.mean(1) + 1e-30)+ flatness = float(np.exp((np.log(flat + 1e-12) * w).sum() / (w.sum() + 1e-30)))+ num = den = 0.0+ idx = np.nonzero(af)[0]+ for a, b in zip(idx[:-1], idx[1:]):+ if b != a + 1 or not peaks[a].any():+ continue+ pw = P[a][peaks[a]]+ num += float((pw * mask[b][peaks[a]]).sum())+ den += float(pw.sum())+ persist = num / den if den > 0 else 0.0+ # glide: the strongest partial's frequency over the frames where it stands out+ tr = []+ for t in idx:+ if not peaks[t].any():+ continue+ j = int(np.argmax(np.where(peaks[t], L[t], -1e9)))+ if L[t, j] - med[t, j] < 15:+ continue+ a, b, c = L[t, max(j - 1, 0)], L[t, j], L[t, min(j + 1, len(fb) - 1)]+ d = 0.5 * (a - c) / (a - 2 * b + c) if (a - 2 * b + c) < 0 else 0.0+ tr.append((t * hop / SR, np.log2(max(fb[j] + d * (fb[1] - fb[0]), 20.0)), b))+ glide = 0.0+ track_ms = 0.0+ if len(tr) >= 4:+ tt, lf, lv = map(np.asarray, zip(*tr))+ strong = lv > lv.max() - 15+ tt, lf = tt[strong], lf[strong]+ if len(tt) >= 4:+ jumps = np.abs(np.diff(lf))+ run = np.concatenate([[True], jumps < 1 / 6]) # a continuous track: < 2 semitones per frame+ k0 = int(np.argmax(run))+ seg = slice(k0, k0 + max(1, int(np.argmin(run[k0:])) if not run[k0:].all() else len(run) - k0))+ st, sl = tt[seg], lf[seg]+ track_ms = float((st[-1] - st[0]) * 1000) if len(st) > 1 else 0.0+ if len(st) >= 4:+ q = max(1, len(st) // 5)+ glide = float(np.median(sl[-q:]) - np.median(sl[:q]))+ from .modal import onsets+ strikes = len(onsets(m))+ c = {'dur_s': round(n / SR, 4), 'attack_ms': float(pk - on), 'rise_db': round(rise, 1), 't40_ms': t40,+ 'crest_db': round(crest, 2),+ 'tonal_share': round(tonal, 3), 'persistence': round(persist, 3), 'glide_oct': round(glide, 3),+ 'track_ms': round(track_ms, 1), 'flatness': round(flatness, 4), 'strikes': strikes,+ 'channels': channels_of(X)}+ c['impulsive'] = c['attack_ms'] <= 40.0 and (c['t40_ms'] <= 400.0 or c['crest_db'] >= 18.0)+ c['tonal'] = c['tonal_share'] >= 0.45 and c['persistence'] >= 0.5+ c['noisy'] = c['tonal_share'] < 0.25+ c['gliding'] = abs(c['glide_oct']) >= 0.3 and c['track_ms'] >= 25 and c['tonal_share'] >= 0.25+ if c['gliding']:+ c['class'] = 'glide'+ elif c['tonal_share'] >= 0.8 and c['persistence'] >= 0.9 and c['t40_ms'] > 300:+ c['class'] = 'ringing'+ elif c['impulsive']:+ c['class'] = 'struck'+ elif c['attack_ms'] > 40.0 and c['crest_db'] < 18.0:+ c['class'] = 'gesture'+ else:+ c['class'] = 'mixed'+ return c+++PLANS = { # class -> candidates, expected best first+ 'glide': ['sines', 'hybrid:sines+modal+spectral', 'hybrid:sines+spectral', 'modal'],+ 'ringing': ['sines', 'modal', 'hybrid:sines+spectral', 'spectral'],+ 'struck': ['modal', 'hybrid:sines+modal+spectral', 'hybrid:modal+spectral', 'sines'],+ 'gesture': ['spectral', 'hybrid:sines+spectral', 'modal', 'sines'],+ 'mixed': ['modal', 'spectral', 'hybrid:modal+spectral', 'sines'],+}+ALL = ('modal', 'sines', 'spectral', 'hybrid:modal+spectral', 'hybrid:sines+spectral', 'hybrid:sines+modal+spectral')+++def plan(c, max_candidates=None):+ """ordered candidate kinds for a character (first = the expected best); hybrids as 'hybrid:<a>+<b>[+<c>]'.+ The measured quality decides among them; the class orders them and prunes the slow fits of long sounds: under+ 1 s every candidate is tried (each fit takes 0.5-4 s), longer sounds the class's four (a long struck sound:+ modal, sines, modal + spectral, spectral; the three-layer hybrid alone took 147 s on a 4.5 s impact)."""+ order = list(PLANS[c['class']])+ if c['dur_s'] >= 1.0 and c['class'] == 'struck':+ order = ['modal', 'sines', 'hybrid:modal+spectral', 'spectral']+ order += [k for k in ALL if k not in order]+ if max_candidates is None:+ max_candidates = len(ALL) if c['dur_s'] < 1.0 else 4+ return order[:max_candidates]+++# ================================================================================================ fitting+def fit_kind(x, kind, fast=False, name=None, **opts):+ """one fitter on x ((n,) / (n, 2) 48 kHz array or path); fast=True uses cheaper settings (tests, previews)"""+ F = _fitters()+ X = Q.load(x)+ if kind == 'modal':+ kw = dict(passes=1) if fast else {}+ kw.update(opts)+ m = F['modal'].fit(X, **kw)+ elif kind == 'sines':+ kw = dict(windows=(1024,)) if fast else {}+ kw.update(opts)+ m = F['sines'].fit(X, **kw)+ m['channels'] = channels_of(X)+ elif kind == 'spectral':+ kw = dict(texture=False, iters=1, seeds=(1,)) if fast else {}+ kw.update(opts)+ m = F['spectral'].fit(X, name=name, **kw)+ m['channels'] = channels_of(X)+ else:+ raise ValueError(f'unknown fitter {kind!r} (modal, sines, spectral; hybrids via fit_hybrid)')+ if name:+ m['source'] = name+ return m+++def deterministic(model):+ """a copy of a modal / sines model that renders only its deterministic part (no noise): a hybrid layer"""+ k = kind_of(model)+ m = copy.deepcopy(model)+ if k == 'modal':+ L = float(m['length_s'])+ m['noise'] = dict(m['noise'], env=[[[0.0, -240.0], [L, -240.0]] for _ in m['noise']['env']])+ m['side'] = None+ m['channels'] = 1+ elif k == 'sines':+ m['residual'] = {'bands': [1000.0], 'times': [0.0, float(m['duration'])], 'db': [[-150.0, -150.0]]}+ m['width'] = -120.0+ m['channels'] = 1+ else:+ raise ValueError(f'a {k} model has no deterministic part')+ m.pop('post', None)+ m.pop('fit_engine', None)+ m['layer'] = 'deterministic'+ return m+++def _fit_n(X, y):+ """y (mono or stereo) as (len(X), channels of X)"""+ y = np.asarray(y, np.float64)+ if y.ndim == 1:+ y = y[:, None]+ if y.shape[1] != X.shape[1]:+ y = np.repeat(y.mean(1, keepdims=True), X.shape[1], 1)+ out = np.zeros_like(X)+ k = min(len(X), len(y))+ out[:k] = y[:k]+ return out+++def fit_hybrid(x, layers=('modal', 'spectral'), fast=False, base=None, name=None):+ """layers fitted in turn on what the previous ones leave (module doc). base: {kind: model} single-kind fits of+ the same x to reuse for the first layer"""+ X = Q.load(x)+ if X.ndim == 1:+ X = X[:, None]+ layers = tuple(layers)+ if len(layers) < 2 or layers[-1] == 'sines' or any(k not in ROLE for k in layers):+ raise ValueError(f'bad hybrid layers {layers}: 2-3 of modal / sines / spectral, deterministic ones first')+ resid = X.copy()+ out = []+ for i, k in enumerate(layers):+ last = i == len(layers) - 1+ if i == 0 and base and k in base:+ m = base[k]+ else:+ m = fit_kind(resid, k, fast=fast)+ if not last:+ m = deterministic(m)+ resid = resid - _fit_n(X, render(m, seed=0))+ out.append({'role': ROLE[k], 'gain_db': 0.0, 'model': m})+ return {'kind': 'hybrid', 'version': VERSION, 'sr': SR, 'length_s': round(len(X) / SR, 6),+ 'channels': channels_of(X), 'layers': out, 'source': name}+++def _cand_fit(X, cand, fast, base, name):+ if cand.startswith('hybrid'):+ layers = HYBRIDS[cand.split(':', 1)[1]] if ':' in cand else ('modal', 'spectral')+ return fit_hybrid(X, layers, fast=fast, base=base, name=name)+ m = fit_kind(X, cand, fast=fast, name=name)+ base[cand] = m+ return m+++PRE_HOP = 0.00025 # s: the attack envelope grid of the post stage+ATTACK_S = 0.006 # s: the attack window after the onset whose contour the post stage follows, at least,+ATTACK_MAX_S = 0.025 # or up to 4 ms past the loudest frame within this much after the onset (a later main strike)+++def _env_frames(m, hop):+ k = max(1, int(round(hop * SR)))+ nb = len(m) // k+ return 10 * np.log10((m[:nb * k].reshape(nb, k) ** 2).mean(1) + 1e-20) if nb else np.zeros(0)+++def fit_post(X, renders, iters=2, max_db=12.0, envelope=False):+ """the post stage of a model, measured by analysis by synthesis (renders = a few seeds of the model):+ eq_db a smooth third-octave EQ (minimum phase, forge.fx.eq_bands; 28 gains at tone.CEN) that moves the+ renders' mean balance onto the original's+ gain_db the gain that matches the loudest 50 ms+ pre the original's 0.25 ms envelope (dB) before its first onset (the first frame within 20 dB of the+ loudest) and, for a sharp onset (>= 15 dB/ms, quality.attack), over the ATTACK_S after it (or to+ 4 ms past the loudest frame of the next ATTACK_MAX_S: a key's bottom-out after its first touch):+ {'t_on' s, 'db' [...], 'attack_db' [...]}. Band noise and window smear leak energy before a strike+ and soften it (a pre-echoed, blunt attack); _pre_clamp keeps the attack as clean as the recording's+ env (envelope=True only) after the attack: the renders' mean 5 ms envelope error as a gain curve ({'hop',+ 'db'}, -12..+6 dB, smoothed): a tail that rings too long, a fade-out the model missed. Off by default:+ on the 10 short validation refs it lowered mel dB 3.69 -> 3.62 and raised envelope r 0.977 -> 0.986,+ but CLAP fell 0.925 -> 0.918 (a key press 0.955 -> 0.905)"""+ from ..fx import eq_bands+ from ..tone import profile+ xm = Q.mono(X)+ target = profile(xm)+ ys = [Q.mono(y) for y in renders]+ tot = np.zeros(len(target))+ for _ in range(iters):+ cur = 10 * np.log10(np.mean([10 ** (profile(eq_bands(y, tot) if tot.any() else y) / 10) for y in ys], 0))+ d = target - cur+ w = 10 ** (cur / 10)+ d -= np.sum(w * d) / np.sum(w) # level-neutral: centred on the loud bands+ d = np.where(cur < -50, np.minimum(d, 6.0), d) # EQ cannot create what is not there+ d = np.convolve(np.pad(d, 1, mode='edge'), [0.25, 0.5, 0.25], 'valid')+ tot = np.clip(tot + d, -max_db, max_db)+ g = Q.peak_rms_db(xm) - float(np.mean([Q.peak_rms_db(eq_bands(y, tot)) for y in ys])) # mono vs mono+ post = {'eq_db': [round(float(v), 2) for v in tot], 'gain_db': round(float(g), 2)}+ e = _env_frames(xm, PRE_HOP)+ if len(e) > 4:+ on = int(np.argmax(e > e.max() - 20))+ pk = on + int(np.argmax(e[on:on + int(round(ATTACK_MAX_S / PRE_HOP))])) # the main strike, if it is later+ n_att = max(int(round(ATTACK_S / PRE_HOP)), pk - on + int(round(0.004 / PRE_HOP)))+ struck = Q.attack(xm)[1] >= 15.0 # a sharp onset (dB/ms): its contour is worth keeping+ if on >= 2 or (struck and len(e) > on + 4):+ post['pre'] = {'t_on': round(on * PRE_HOP, 6), 'db': [round(float(v), 1) for v in e[:on]],+ 'attack_db': [round(float(v), 1) for v in e[on:on + n_att]] if struck else []}+ # the clamp pins the attack to the original's contour: re-level what it leaves+ g2 = Q.peak_rms_db(xm) - float(np.mean([Q.peak_rms_db(apply_post(y, post)) for y in ys]))+ post['gain_db'] = round(float(g + g2), 2)+ if envelope:+ post['env'] = _fit_env(xm, [apply_post(y, post) for y in ys], post)+ # the gain curve moves the balance (tail and attack differ in colour): one more EQ + level pass on top+ cur = 10 * np.log10(np.mean([10 ** (profile(apply_post(y, post)) / 10) for y in ys], 0))+ d = target - cur+ w = 10 ** (cur / 10)+ d -= np.sum(w * d) / np.sum(w)+ d = np.where(cur < -50, np.minimum(d, 6.0), d)+ d = np.convolve(np.pad(d, 1, mode='edge'), [0.25, 0.5, 0.25], 'valid')+ post['eq_db'] = [round(float(v), 2) for v in np.clip(np.asarray(post['eq_db']) + d, -max_db, max_db)]+ g3 = Q.peak_rms_db(xm) - float(np.mean([Q.peak_rms_db(apply_post(y, post)) for y in ys]))+ post['gain_db'] = round(float(post['gain_db'] + g3), 2)+ return post+++ENV_HOP = 0.005 # s: the envelope calibration grid+++def _fit_env(xm, ys, post):+ """the seed-averaged envelope error left after the attack (5 ms frames, dB, smoothed, -12..+6): a tail that+ rings too long or too loud, a missing fade-out. Applied as a gain curve (time-scaled with the decay knobs)"""+ eo = Q.env_db(xm, ENV_HOP * 1000)+ er = 10 * np.log10(np.mean([10 ** (Q.env_db(Q.mono(y), ENV_HOP * 1000)[:len(eo)] / 10) for y in ys+ if len(y) >= len(xm)], 0) + 1e-20)+ n = min(len(eo), len(er))+ d = np.clip(eo[:n] - er[:n], -12.0, 6.0)+ top = max(eo.max(), er.max())+ d = np.where((eo[:n] < top - 70) & (er[:n] < top - 70), 0.0, d) # both inaudible: leave it+ pre = post.get('pre') or {}+ t_start = float(pre.get('t_on', 0.0)) + PRE_HOP * len(pre.get('attack_db') or []) + 0.002+ i0 = int(np.ceil(t_start / ENV_HOP))+ d[:i0] = 0.0+ for _ in range(2):+ d = np.convolve(np.pad(d, 1, mode='edge'), [0.25, 0.5, 0.25], 'valid')+ d[:i0] = 0.0+ d[i0:i0 + 2] *= [0.33, 0.67][:len(d[i0:i0 + 2])] # fade the correction in+ return {'hop': ENV_HOP, 'db': [round(float(v), 2) for v in d]}+++def _env_gain(n, env, scale=1.0):+ d = np.asarray(env['db'], float)+ hop = float(env['hop']) * scale+ tc = (np.arange(len(d)) + 0.5) * hop * SR+ return 10 ** (np.interp(np.arange(n), tc, d, left=0.0, right=float(d[-1]) if len(d) else 0.0) / 20)+++def _pre_clamp(y, pre, scale=1.0):+ """the attack through the original's envelope (0.25 ms frames): before the onset y may not stand above the+ original (+1.5 dB; only cut), over the ATTACK_S after it y follows the original's contour (+-9 dB, the correction+ fading out over the last 2 ms), so a smeared or pre-echoed attack comes back as sharp as the recording's.+ scale: time factor of the render (spectral length / speed)"""+ k = int(round(PRE_HOP * SR))+ ref_pre = np.asarray(pre.get('db') or [], float)+ ref_att = np.asarray(pre.get('attack_db') or [], float)+ n_pre = int(round(float(pre['t_on']) * scale / PRE_HOP))+ n_att = len(ref_att) if scale == 1.0 else int(round(len(ref_att) * scale))+ nb = min(len(y) // k, n_pre + n_att)+ if nb < 2:+ return y+ m = y.mean(1) if y.ndim == 2 else y+ e = _env_frames(m[:nb * k], PRE_HOP)+ gdb = np.zeros(nb)+ if n_pre > 0 and len(ref_pre):+ want = np.interp(np.arange(min(n_pre, nb)) / max(n_pre - 1, 1), np.linspace(0, 1, len(ref_pre)), ref_pre)+ gdb[:len(want)] = np.minimum(0.0, want + 1.5 - e[:len(want)])+ if n_att > 0 and len(ref_att) and nb > n_pre:+ j = np.arange(n_pre, nb)+ want = np.interp((j - n_pre) / max(n_att - 1, 1), np.linspace(0, 1, len(ref_att)), ref_att)+ fade = np.clip((n_pre + n_att - 1 - j) / max(1, int(round(0.002 / PRE_HOP))), 0.0, 1.0)+ gdb[n_pre:] = np.clip(want - e[n_pre:nb], -9.0, 9.0) * fade+ neg = np.minimum(gdb, 0.0) # widen each cut by a frame (smooth edges)+ neg = np.minimum(neg, np.minimum(np.r_[neg[1:], 0.0], np.r_[0.0, neg[:-1]]))+ gdb = np.where(gdb < 0, neg, gdb)+ gdb = np.convolve(np.pad(gdb, 1, mode='edge'), [0.25, 0.5, 0.25], 'valid')+ n_end = nb * k+ tt = (np.arange(nb) + 0.5) * k+ gs = 10 ** (np.interp(np.arange(n_end), np.r_[tt, n_end], np.r_[gdb, 0.0]) / 20)+ y = np.array(y, copy=True)+ if y.ndim == 2:+ y[:n_end] *= gs[:, None]+ else:+ y[:n_end] *= gs+ return y+++def apply_post(y, post, scale=1.0, tail=1.0):+ """a render through a model's post stage (EQ, gain, attack clamp, envelope calibration). scale: the render's+ time factor (spectral length / speed); tail: the decay knobs' factor on the envelope after the attack"""+ if not post:+ return y+ from ..fx import eq_bands+ if any(post.get('eq_db') or ()):+ y = eq_bands(y, post['eq_db'])+ y = y * 10 ** (float(post.get('gain_db', 0.0)) / 20)+ if post.get('pre'):+ y = _pre_clamp(y, post['pre'], scale)+ if post.get('env') and post['env'].get('db'):+ g = _env_gain(len(y), post['env'], scale * tail)+ y = y * (g[:, None] if y.ndim == 2 else g)+ return y+++def fit(x, kind='auto', layers=None, candidates=None, clap=False, fast=False, seeds=(0,), name=None, verbose=False,+ collect=None, post=True):+ """a model of x (path or 48 kHz array). kind: 'auto' | 'modal' | 'sines' | 'spectral' | 'hybrid' (layers=+ ('modal', 'spectral') by default). auto: candidates (default plan(character(x))) are all fitted, rendered with+ `seeds` and scored (quality.score; clap=True adds CLAP), the best is returned with a 'fit_engine' entry.+ collect: a dict that receives every candidate's model ({candidate: model})"""+ import os+ if name is None and isinstance(x, (str, os.PathLike)):+ name = os.path.basename(str(x))+ X = Q.load(x)+ t0 = time.time()+ if kind != 'auto':+ if kind == 'hybrid':+ m = fit_hybrid(X, layers or ('modal', 'spectral'), fast=fast, name=name)+ else:+ m = fit_kind(X, kind, fast=fast, name=name)+ if post:+ m['post'] = fit_post(X, [render(m, seed=s) for s in (0, 1)])+ m['fit_engine'] = {'kind': kind, 'seconds': round(time.time() - t0, 2)}+ return m+ c = character(X)+ cands = list(candidates or plan(c))+ base, rows, best = {}, [], None+ clap_e = None+ if clap:+ clap_e = Q.clap_embed([X])[0]+ for cand in cands:+ t1 = time.time()+ try:+ m = _cand_fit(X, cand, fast, base, name)+ except Exception as e: # one fitter failing must not stop the others+ rows.append({'candidate': cand, 'error': f'{type(e).__name__}: {e}'})+ if verbose:+ print(f' {cand}: failed ({type(e).__name__}: {e})')+ continue+ tf = time.time() - t1+ if collect is not None:+ collect[cand] = m+ qs = []+ if post:+ r0 = [render(m, seed=s) for s in (0, 1)]+ m['post'] = fit_post(X, r0)+ for s in seeds:+ y = render(m, seed=s)+ q = Q.quality(X, y)+ if clap_e is not None:+ q['clap_cos'] = round(float(clap_e @ Q.clap_embed([y])[0]), 4)+ qs.append(q)+ sc = float(np.mean([Q.score(q) for q in qs]))+ row = {'candidate': cand, 'score': round(sc, 3), 'fit_s': round(tf, 2), 'quality': qs[0]}+ rows.append(row)+ if verbose:+ print(f' {cand}: score {sc:.2f} ({Q.text(qs[0])}) in {tf:.1f} s')+ if best is None or sc < best[0]:+ best = (sc, cand, m)+ if best is None:+ raise RuntimeError('every fitter failed: ' + '; '.join(r.get('error', '') for r in rows))+ m = best[2]+ m['fit_engine'] = {'kind': 'auto', 'chosen': best[1], 'character': c, 'candidates': rows,+ 'seconds': round(time.time() - t0, 2)}+ return m+++# ================================================================================================ rendering+def _layer_render(m, seed, two, **kn):+ F = _fitters()+ k = kind_of(m)+ if k == 'sines':+ y = F['sines'].render(m, seed, knobs=kn)+ elif k == 'modal':+ y = F['modal'].render(m, seed, **kn)+ else:+ y = np.asarray(F['spectral'].render(m, seed, **kn), np.float64)+ y = np.asarray(y, np.float64)+ if y.ndim == 1:+ y = y[:, None]+ if two and y.shape[1] == 1:+ y = np.repeat(y, 2, 1)+ if not two and y.shape[1] == 2:+ y = y.mean(1, keepdims=True)+ return y+++def _render_hybrid(model, seed=0, pitch=0.0, decay=1.0, bright=0.0, vary=0.0, width=1.0, tone_db=0.0,+ body_db=0.0, air_db=0.0, stereo=None):+ two = (model.get('channels', 1) == 2) if stereo is None else bool(stereo)+ gains = {'tone': tone_db, 'body': body_db, 'air': air_db}+ ys = []+ for i, L in enumerate(model['layers']):+ m = L['model']+ k = kind_of(m)+ s = (int(seed) * 7 + 101 * (i + 1)) & 0x7FFFFFFF+ if k == 'sines':+ kn = {'transpose': pitch, 'decay': decay, 'brightness': bright, 'vary': vary}+ elif k == 'modal':+ size = 2.0 ** (-pitch / 12.0)+ kn = {'size': size, 'damping': size / max(decay, 1e-3), 'brightness': bright, 'vary': vary,+ 'stereo': False if m.get('side') is None else two, 'width': width}+ else:+ kn = {'shift': pitch / 12.0, 'tilt': bright, 'width': width}+ y = _layer_render(m, s, two, **kn) * 10 ** ((float(L.get('gain_db', 0.0)) + gains[L['role']]) / 20)+ ys.append(y)+ n = max(len(y) for y in ys)+ out = np.zeros((n, ys[0].shape[1]))+ for y in ys:+ out[:len(y)] += y+ return out if two else out[:, 0]+++def _render_raw(model, seed=0, **knobs):+ """the sound of a model (float64, 48 kHz): (n, 2) when the source was stereo, else (n,). knobs: knobs_of(model)+ names (identity values re-render the fit); unknown names raise"""+ k = kind_of(model)+ if k == 'morph':+ w = knobs.pop('morph', model.get('amount', 0.5))+ return render(morph(model['a'], model['b'], w), seed, **knobs)+ allowed = set(knobs_of(model)) | {'stereo', 'gain', 'gain_db'}+ bad = set(knobs) - allowed+ if bad:+ raise ValueError(f'unknown knobs for a {k} model: {sorted(bad)} (known: {sorted(allowed)})')+ F = _fitters()+ two = channels_of(model) == 2+ if k == 'hybrid':+ g = knobs.pop('gain_db', knobs.pop('gain', 0.0))+ return _render_hybrid(model, seed, **knobs) * 10 ** (g / 20)+ if k == 'modal':+ if 'gain_db' in knobs:+ knobs['gain'] = knobs.pop('gain_db')+ y = F['modal'].render(model, seed, **knobs)+ elif k == 'sines':+ if 'gain' in knobs:+ knobs['gain_db'] = knobs.pop('gain')+ knobs.setdefault('stereo', two)+ y = F['sines'].render(model, seed, knobs=knobs)+ else:+ if 'gain' in knobs:+ knobs['gain_db'] = knobs.pop('gain')+ y = np.asarray(F['spectral'].render(model, seed, **knobs), np.float64)+ if not two:+ y = y.mean(1)+ return np.asarray(y, np.float64)+++def render(model, seed=0, **knobs):+ """the sound of a model (float64, 48 kHz): (n, 2) when the source was stereo, else (n,), through the model's post+ stage (fitted EQ + gain) when it has one. knobs: knobs_of(model) names (identity values re-render the fit);+ unknown names raise"""+ y = _render_raw(model, seed, **dict(knobs))+ if kind_of(model) == 'morph':+ return y+ k = kind_of(model)+ scale = float(knobs.get('length', 1.0)) / float(knobs.get('speed', 1.0)) if k == 'spectral' else 1.0+ tail = {'modal': lambda: float(knobs.get('size', 1.0)) / float(knobs.get('damping', 1.0)),+ 'sines': lambda: float(knobs.get('stretch', 1.0)) * float(knobs.get('decay', 1.0)),+ 'hybrid': lambda: float(knobs.get('decay', 1.0))}.get(k, lambda: 1.0)()+ return apply_post(y, model.get('post'), scale, tail)+++def identity(model):+ """the knob values that re-render the fit (a recipe's DEFAULTS)"""+ return {n: v[1] for n, v in knobs_of(model).items()}+++# ================================================================================================ morph+def _assign(fa, ea, fb, eb, max_oct=1.0):+ """pairs (i, j) of a-rows and b-rows by log-frequency distance (optimal assignment; pairs further apart than+ max_oct octaves stay unpaired), plus the unpaired a and b indices"""+ from scipy.optimize import linear_sum_assignment+ fa, fb = np.asarray(fa, float), np.asarray(fb, float)+ if not len(fa) or not len(fb):+ return [], list(range(len(fa))), list(range(len(fb)))+ C = np.abs(np.log2(np.maximum(fa, 1.0))[:, None] - np.log2(np.maximum(fb, 1.0))[None, :])+ da = 10 * np.log10(np.asarray(ea, float) / (np.max(ea) + 1e-30) + 1e-12)+ db = 10 * np.log10(np.asarray(eb, float) / (np.max(eb) + 1e-30) + 1e-12)+ cost = C + 0.003 * np.abs(da[:, None] - db[None, :])+ cost = np.where(C > max_oct, 1e6, cost)+ r, c = linear_sum_assignment(cost)+ pairs = [(int(i), int(j)) for i, j in zip(r, c) if C[i, j] <= max_oct]+ pa, pb = {i for i, _ in pairs}, {j for _, j in pairs}+ return pairs, [i for i in range(len(fa)) if i not in pa], [j for j in range(len(fb)) if j not in pb]+++def _geo(a, b, w):+ return float(np.exp((1 - w) * np.log(max(a, 1e-30)) + w * np.log(max(b, 1e-30))))+++def _circ(pa, pb, w):+ return float(np.angle((1 - w) * np.exp(1j * pa) + w * np.exp(1j * pb)))+++def _mix_rows(ra, rb, w):+ """damped-sinusoid rows [f, tau, amp, phase] of two sounds -> rows between them: paired rows interpolate+ (frequency, decay, amplitude geometric; phase circular), unpaired rows fade with their side's weight"""+ a = np.array(ra, float).reshape(-1, 4)+ b = np.array(rb, float).reshape(-1, 4)+ for q in (a, b): # a negative amplitude is a phase of pi+ neg = q[:, 2] < 0+ q[neg, 2] *= -1+ q[neg, 3] += np.pi+ pairs, ua, ub = _assign(a[:, 0], a[:, 2] ** 2 * a[:, 1], b[:, 0], b[:, 2] ** 2 * b[:, 1])+ out = []+ for i, j in pairs:+ out.append([_geo(a[i, 0], b[j, 0], w), _geo(a[i, 1], b[j, 1], w), _geo(a[i, 2], b[j, 2], w),+ _circ(a[i, 3], b[j, 3], w)])+ if w < 1:+ out += [[float(a[i, 0]), float(a[i, 1]), float(a[i, 2] * (1 - w)), float(a[i, 3])] for i in ua]+ if w > 0:+ out += [[float(b[j, 0]), float(b[j, 1]), float(b[j, 2] * w), float(b[j, 3])] for j in ub]+ return out+++def _anchors(ta, tb, w):+ """piecewise-linear time maps a -> morph and b -> morph through paired anchor times"""+ ta, tb = np.asarray(ta, float), np.asarray(tb, float)+ tm = (1 - w) * ta + w * tb+ for t in (ta, tb, tm): # strictly increasing+ for i in range(1, len(t)):+ t[i] = max(t[i], t[i - 1] + 1e-6)++ def mk(src):+ def f(t):+ t = np.asarray(t, float)+ y = np.interp(t, src, tm)+ return np.where(t > src[-1], tm[-1] + (t - src[-1]), np.where(t < src[0], tm[0] + (t - src[0]), y))+ return f+ return mk(ta), mk(tb), tm+++def _mix_curves(ta, va, tb, vb, w):+ """two piecewise-linear curves (already on the morph time axis) -> their weighted mix on the union grid"""+ ta, va, tb, vb = (np.asarray(v, float) for v in (ta, va, tb, vb))+ g = np.unique(np.round(np.concatenate([ta, tb]), 6))+ return g, (1 - w) * np.interp(g, ta, va) + w * np.interp(g, tb, vb)+++def _morph_modal(A, B, w):+ from .modal import _rdp+ SA, SB = A['strikes'], B['strikes']+ k = min(len(SA), len(SB))+ wa, wb, tm = _anchors([0.0] + [s['t'] for s in SA[:k]] + [A['length_s']],+ [0.0] + [s['t'] for s in SB[:k]] + [B['length_s']], w)+ strikes = []+ for i in range(k):+ strikes.append({'t': round(float(tm[i + 1]), 6),+ 'ramp_ms': round((1 - w) * SA[i]['ramp_ms'] + w * SB[i]['ramp_ms'], 4),+ 'modes': _mix_rows(SA[i]['modes'], SB[i]['modes'], w),+ 'attack': _mix_rows(SA[i].get('attack', []), SB[i].get('attack', []), w)})+ for S, wt, wf in ((SA[k:], 1 - w, wa), (SB[k:], w, wb)):+ for s in S:+ if wt <= 0:+ continue+ strikes.append({'t': round(float(wf(s['t'])), 6), 'ramp_ms': s['ramp_ms'],+ 'modes': [[q[0], q[1], q[2] * wt, q[3]] for q in s['modes']],+ 'attack': [[q[0], q[1], q[2] * wt, q[3]] for q in s.get('attack', [])]})+ strikes.sort(key=lambda s: s['t'])+ na, nb = A['noise'], B['noise']+ if list(na['edges']) != list(nb['edges']):+ raise ValueError('modal models with different noise bands cannot be morphed')+ env = []+ for ea, eb in zip(na['env'], nb['env']):+ ea, eb = np.asarray(ea, float), np.asarray(eb, float)+ g, v = _mix_curves(wa(ea[:, 0]), ea[:, 1], wb(eb[:, 0]), eb[:, 1], w)+ keep = _rdp(g, v, 0.25)+ env.append([[round(float(g[j]), 6), round(float(v[j]), 3)] for j in keep])+ sub = None+ xa = (A.get('sub') or {}).get('x')+ xb = (B.get('sub') or {}).get('x')+ if xa or xb:+ xa, xb = np.asarray(xa or [0.0], float) * (1 - w), np.asarray(xb or [0.0], float) * w+ n = max(len(xa), len(xb))+ sx = np.pad(xa, (0, n - len(xa))) + np.pad(xb, (0, n - len(xb)))+ if np.abs(sx).max() > 0:+ sub = {'rate': (A.get('sub') or B.get('sub'))['rate'], 'x': [float(v) for v in sx]}+ side = None+ if A.get('side') or B.get('side'):+ sa = np.asarray(A.get('side') or np.zeros(len(B['side'])), float)+ sb = np.asarray(B.get('side') or np.zeros(len(A['side'])), float)+ side = [round(float(v), 4) for v in (1 - w) * sa + w * sb]+ return {'kind': 'modal', 'version': max(A['version'], B['version']), 'sr': SR,+ 'length_s': round(float(tm[-1]), 6), 'channels': max(A.get('channels', 1), B.get('channels', 1)),+ 'fade_out_s': (1 - w) * float(A.get('fade_out_s', 0.0)) + w * float(B.get('fade_out_s', 0.0)),+ 'strikes': strikes, 'sub': sub, 'noise': {'edges': list(na['edges']), 'h_erb': na['h_erb'], 'env': env},+ 'side': side, 'fit': {'modes': int(sum(len(s['modes']) for s in strikes))}}+++def _morph_partial(p, q, w, wa, wb):+ t0p, t1p = float(wa(p['t0'])), float(wa(p['t1']))+ t0q, t1q = float(wb(q['t0'])), float(wb(q['t1']))+ t0, t1 = (1 - w) * t0p + w * t0q, (1 - w) * t1p + w * t1q+ t1 = max(t1, t0 + 1e-4)++ def u(pts, warp, a, b):+ pts = np.asarray(pts, float)+ return (warp(pts[:, 0]) - a) / max(b - a, 1e-6), pts[:, 1]++ out = {}+ for key, tf in (('freq', np.log2), ('amp', lambda v: v)):+ up, vp = u(p[key], wa, t0p, t1p)+ uq, vq = u(q[key], wb, t0q, t1q)+ g, v = _mix_curves(up, tf(vp), uq, tf(vq), w)+ if key == 'freq':+ v = 2.0 ** v+ out[key] = [[round(float(t0 + gg * (t1 - t0)), 6), round(float(vv), 4)] for gg, vv in zip(g, v)]+ return {'t0': round(t0, 6), 'rise': (1 - w) * p['rise'] + w * q['rise'], 't1': round(t1, 6),+ 'rel': (1 - w) * p['rel'] + w * q['rel'], 'ph': _circ(p['ph'], q['ph'], w), **out}+++def _shift_partial(p, warp, gain_db):+ return {'t0': float(warp(p['t0'])), 'rise': p['rise'], 't1': float(warp(p['t1'])), 'rel': p['rel'], 'ph': p['ph'],+ 'freq': [[float(warp(t)), f] for t, f in p['freq']],+ 'amp': [[float(warp(t)), a + gain_db] for t, a in p['amp']]}+++def _morph_sines(A, B, w):+ from .sines import partial_freq, summary+ oa = list(A.get('onsets') or [A.get('onset', 0.0)])+ ob = list(B.get('onsets') or [B.get('onset', 0.0)])+ k = min(len(oa), len(ob))+ wa, wb, tm = _anchors([0.0] + oa[:k] + [A['duration']], [0.0] + ob[:k] + [B['duration']], w)+ PA, PB = A['partials'], B['partials']+ en = lambda p: 10 ** (max(v for _, v in p['amp']) / 10) * (p['t1'] - p['t0'] + 0.01)+ pairs, ua, ub = _assign([partial_freq(p) for p in PA], [en(p) for p in PA],+ [partial_freq(p) for p in PB], [en(p) for p in PB])+ parts = [_morph_partial(PA[i], PB[j], w, wa, wb) for i, j in pairs]+ if w < 1:+ parts += [_shift_partial(PA[i], wa, 20 * np.log10(1 - w)) for i in ua]+ if w > 0:+ parts += [_shift_partial(PB[j], wb, 20 * np.log10(w)) for j in ub]+ parts.sort(key=lambda p: -max(v for _, v in p['amp']))+ TA, TB = A.get('transients', []), B.get('transients', [])+ kt = min(len(TA), len(TB))+ trans = [{'t': (1 - w) * float(wa(TA[i]['t'])) + w * float(wb(TB[i]['t'])),+ 'atoms': _mix_rows(TA[i]['atoms'], TB[i]['atoms'], w)} for i in range(kt)]+ for T, wt, wf in ((TA[kt:], 1 - w, wa), (TB[kt:], w, wb)):+ trans += [{'t': float(wf(tr['t'])), 'atoms': [[f, tau, a * wt, ph] for f, tau, a, ph in tr['atoms']]}+ for tr in T if wt > 0]+ ra, rb = A['residual'], B['residual']+ if list(ra['bands']) != list(rb['bands']):+ raise ValueError('sines models with different residual bands cannot be morphed')+ ga = wa(np.asarray(ra['times'], float))+ gb = wb(np.asarray(rb['times'], float))+ g = np.unique(np.round(np.concatenate([ga, gb]), 6))+ da, dbb = np.asarray(ra['db'], float), np.asarray(rb['db'], float)+ lev = np.array([(1 - w) * np.interp(g, ga, da[i]) + w * np.interp(g, gb, dbb[i]) for i in range(len(da))])+ ons = sorted([(1 - w) * oa[i] + w * ob[i] for i in range(k)]+ + ([float(wa(o)) for o in oa[k:]] if w < 1 else [])+ + ([float(wb(o)) for o in ob[k:]] if w > 0 else []))+ m = {'kind': 'sines', 'version': max(A['version'], B['version']), 'sr': SR, 'duration': round(float(tm[-1]), 6),+ 'onset': float(ons[0]) if ons else 0.0, 'onsets': ons, 'partials': parts, 'transients': trans,+ 'residual': {'bands': list(ra['bands']), 'times': [float(v) for v in g],+ 'db': [[round(float(v), 2) for v in row] for row in lev]},+ 'width': (1 - w) * float(A.get('width', -120.0)) + w * float(B.get('width', -120.0)),+ 'channels': max(int(A.get('channels', 1)), int(B.get('channels', 1))), 'analysis': {}}+ m['summary'] = summary(m)+ return m+++def _morph_spectral(A, B, w):+ if A['bands'] != B['bands']:+ raise ValueError('spectral models with different bands cannot be morphed')++ def peak(M):+ E = 10 ** (np.asarray(M['env']['db'], float) / 10)+ return float(M['env']['t'][int(np.argmax(E.sum(1)))])+ wa, wb, tm = _anchors([0.0, peak(A), A['dur']], [0.0, peak(B), B['dur']], w)+ ta, tb = wa(np.asarray(A['env']['t'], float)), wb(np.asarray(B['env']['t'], float))+ g = np.unique(np.round(np.concatenate([ta, tb]), 5))+ Ea, Eb = np.asarray(A['env']['db'], float), np.asarray(B['env']['db'], float)+ E = np.stack([(1 - w) * np.interp(g, ta, Ea[:, j]) + w * np.interp(g, tb, Eb[:, j]) for j in range(Ea.shape[1])], 1)+ stereo = None+ if A.get('stereo') or B.get('stereo'):+ def st(M, tt):+ s = M.get('stereo')+ if not s:+ G = len((A.get('stereo') or B.get('stereo'))['groups']) - 1+ z = np.zeros((len(g), G))+ return z, z + 1.0+ ild, icc = np.asarray(s['ild'], float), np.asarray(s['icc'], float)+ return (np.stack([np.interp(g, tt, ild[:, j]) for j in range(ild.shape[1])], 1),+ np.stack([np.interp(g, tt, icc[:, j]) for j in range(icc.shape[1])], 1))+ (ia, ca), (ib, cb) = st(A, ta), st(B, tb)+ stereo = {'groups': list((A.get('stereo') or B.get('stereo'))['groups']),+ 'ild': [[round(float(v), 2) for v in r] for r in (1 - w) * ia + w * ib],+ 'icc': [[round(float(v), 3) for v in r] for r in (1 - w) * ca + w * cb]}+ ridges = []+ for M, wt, wf in ((A, 1 - w, wa), (B, w, wb)):+ if wt <= 0:+ continue+ for rd in M.get('ridges') or []:+ ridges.append(dict(rd, t=[float(v) for v in wf(np.asarray(rd['t'], float))],+ db=[float(v) + 20 * np.log10(wt) for v in rd['db']]))+ tex = _mix_texture(A.get('texture'), B.get('texture'), w)+ fine = None+ if A.get('fine') and B.get('fine'):+ fa, fb = A['fine'], B['fine']+ try:+ fine = dict(fa, db=[(1 - w) * u + w * v for u, v in zip(fa['db'], fb['db'])])+ except (KeyError, TypeError):+ fine = fa if w < 0.5 else fb+ return {'kind': 'spectral_noise', 'version': max(A['version'], B['version']), 'source': None, 'sr': SR,+ 'dur': round(float(tm[-1]), 4), 'level_db': round((1 - w) * A['level_db'] + w * B['level_db'], 2),+ 'bands': A['bands'], 'fit': {}, 'env': {'t': [float(v) for v in g],+ 'db': [[round(float(v), 2) for v in r] for r in E]},+ 'stereo': stereo, 'fine': fine, 'texture': tex, 'ridges': ridges,+ 'channels': max(int(A.get('channels', 1)), int(B.get('channels', 1)))}+++def _mix_texture(ta, tb, w):+ if not ta and not tb:+ return None+ dom = copy.deepcopy(ta if (w < 0.5 and ta) or not tb else tb)+ ga, gb = (ta or {}).get('grains'), (tb or {}).get('grains')+ if ga and gb:+ dom['grains'] = dict(ga, density=_geo(ga['density'], gb['density'], w))+ elif ga or gb:+ dom['grains'] = (ga if (1 - w) >= 0.5 else None) if ga else (gb if w >= 0.5 else None)+ aa, ab = (ta or {}).get('am'), (tb or {}).get('am')+ if aa and ab and len(aa.get('depth', [])) == len(ab.get('depth', [])):+ am = copy.deepcopy(aa if w < 0.5 else ab)+ am['depth'] = [(1 - w) * u + w * v for u, v in zip(aa['depth'], ab['depth'])]+ dom['am'] = am+ elif aa or ab:+ am = copy.deepcopy(aa or ab)+ wt = (1 - w) if aa else w+ am['depth'] = [v * wt for v in am.get('depth', [])]+ dom['am'] = am+ return dom+++def _mix_post(pa, pb, w):+ if not pa and not pb:+ return None+ za = {'eq_db': [0.0] * 28, 'gain_db': 0.0}+ pa, pb = pa or za, pb or za+ out = {'eq_db': [round((1 - w) * u + w * v, 3) for u, v in zip(pa['eq_db'], pb['eq_db'])],+ 'gain_db': round((1 - w) * pa.get('gain_db', 0.0) + w * pb.get('gain_db', 0.0), 3)}+ if pa.get('pre') and pb.get('pre'): # the pre-onset envelopes on a common normalised time axis+ ra, rb = np.asarray(pa['pre']['db'], float), np.asarray(pb['pre']['db'], float)+ t_on = (1 - w) * pa['pre']['t_on'] + w * pb['pre']['t_on']+ nb = max(1, int(round(t_on / PRE_HOP)))+ u = np.linspace(0, 1, nb)+ mix = (1 - w) * np.interp(u, np.linspace(0, 1, len(ra)), ra) + w * np.interp(u, np.linspace(0, 1, len(rb)), rb)+ out['pre'] = {'t_on': round(t_on, 6), 'db': [round(float(v), 1) for v in mix], 'attack_db': []}+ aa = np.asarray(pa['pre'].get('attack_db') or [], float)+ ab = np.asarray(pb['pre'].get('attack_db') or [], float)+ if len(aa) and len(ab):+ na = max(2, int(round((1 - w) * len(aa) + w * len(ab))))+ u = np.linspace(0, 1, na)+ mix = ((1 - w) * np.interp(u, np.linspace(0, 1, len(aa)), aa)+ + w * np.interp(u, np.linspace(0, 1, len(ab)), ab))+ out['pre']['attack_db'] = [round(float(v), 1) for v in mix]+ return out+++def morph(a, b, amount=0.5):+ """a model between two fits (see _morph); the post stages (EQ, gain) interpolate too"""+ w = float(np.clip(amount, 0.0, 1.0))+ if w in (0.0, 1.0) and kind_of(a) == kind_of(b) != 'morph': # the endpoints are the sources, exactly+ return copy.deepcopy({k: v for k, v in (a if w == 0.0 else b).items() if k != 'fit_engine'})+ m = _morph(a, b, amount)+ p = _mix_post(a.get('post'), b.get('post'), w)+ if p:+ m['post'] = p+ return m+++def _morph(a, b, amount=0.5):+ """a model between two fitted models of the same kind (0 = a, 1 = b): paired modes / partials interpolate+ (frequency, decay, level geometric), unpaired ones fade with their side's weight, envelopes interpolate in dB on+ a time axis warped through the strikes (modal, sines) or the loudness peak (spectral); hybrids morph layer by+ layer (a role only one side has fades)"""+ w = float(np.clip(amount, 0.0, 1.0))+ ka, kb = kind_of(a), kind_of(b)+ if ka != kb:+ raise ValueError(f'cannot morph a {ka} model with a {kb} model: refit one with kind={ka!r}')+ if ka == 'morph':+ raise ValueError('morph the source models, not a morph')+ if ka == 'modal':+ return _morph_modal(a, b, w)+ if ka == 'sines':+ return _morph_sines(a, b, w)+ if ka == 'spectral':+ return _morph_spectral(a, b, w)+ la = {L['role']: L for L in a['layers']}+ lb = {L['role']: L for L in b['layers']}+ layers = []+ for role in [r for r in ('tone', 'body', 'air') if r in la or r in lb]:+ A, B = la.get(role), lb.get(role)+ if A and B:+ layers.append({'role': role, 'gain_db': (1 - w) * A.get('gain_db', 0.0) + w * B.get('gain_db', 0.0),+ 'model': morph(A['model'], B['model'], w)})+ else:+ L, wt = (A, 1 - w) if A else (B, w)+ if wt > 0:+ layers.append(dict(L, gain_db=L.get('gain_db', 0.0) + 20 * np.log10(wt)))+ return {'kind': 'hybrid', 'version': VERSION, 'sr': SR,+ 'length_s': round((1 - w) * a['length_s'] + w * b['length_s'], 6),+ 'channels': max(a.get('channels', 1), b.get('channels', 1)), 'layers': layers}+++def morph_model(a, b, amount=0.5):+ """a 'morph' model: both sources kept, rendered as morph(a, b, amount) (the 'morph' knob moves amount)"""+ if kind_of(a) != kind_of(b):+ raise ValueError(f'cannot morph a {kind_of(a)} model with a {kind_of(b)} model')+ strip = lambda m: {k: v for k, v in m.items() if k != 'fit_engine'}+ return {'kind': 'morph', 'version': VERSION, 'amount': float(amount), 'a': strip(a), 'b': strip(b)}+++def fit_pair(xa, xb, clap=False, fast=False, verbose=False):+ """two recordings fitted with ONE kind (so they can be morphed): each is fitted with kind='auto', and if the+ winners differ, both are fitted with each winning kind and the kind with the lower summed score is kept.+ Returns (model a, model b, {kind: (score a, score b)})"""+ import os+ ma = fit(xa, clap=clap, fast=fast, verbose=verbose)+ mb = fit(xb, clap=clap, fast=fast, verbose=verbose)+ ka, kb = ma['fit_engine']['chosen'], mb['fit_engine']['chosen']+ if ka == kb:+ return ma, mb, {ka: (ma['fit_engine']['candidates'], mb['fit_engine']['candidates'])}+ Xa, Xb = Q.load(xa), Q.load(xb)+ out = {}+ names = [os.path.basename(str(v)) if isinstance(v, (str, os.PathLike)) else None for v in (xa, xb)]+ for kd in (ka, kb):+ pair = []+ for X, m, nm in ((Xa, ma, names[0]), (Xb, mb, names[1])):+ if m['fit_engine']['chosen'] == kd:+ pair.append((m, next(r['score'] for r in m['fit_engine']['candidates'] if r['candidate'] == kd)))+ continue+ mm = fit(X, candidates=[kd], clap=clap, fast=fast, name=nm)+ pair.append((mm, mm['fit_engine']['candidates'][0].get('score', 1e9)))+ out[kd] = pair+ kd = min(out, key=lambda k: out[k][0][1] + out[k][1][1])+ return out[kd][0][0], out[kd][1][0], {k: (v[0][1], v[1][1]) for k, v in out.items()}+++# ================================================================================================ io+def save(model, path):+ with open(path, 'w', encoding='utf-8') as fh:+ json.dump(model, fh, separators=(',', ':'))+ return path+++def load(path):+ with open(path, encoding='utf-8') as fh:+ m = json.load(fh)+ kind_of(m)+ return m+++def summary(model):+ """a few readable lines on a model"""+ F = _fitters()+ k = kind_of(model)+ fe = model.get('fit_engine') or {}+ head = ''+ if fe.get('kind') == 'auto':+ head = f"auto chose {fe['chosen']} of " + ', '.join(+ f"{r['candidate']} ({r['score']:.2f})" if 'score' in r else f"{r['candidate']} (failed)"+ for r in fe['candidates']) + '\n'+ if k == 'modal':+ return head + F['modal'].summary(model)+ if k == 'sines':+ return head + F['sines'].describe(model)+ if k == 'spectral':+ return head + F['spectral'].summary(model)+ if k == 'morph':+ ind = lambda t: t.replace('\n', '\n ')+ return (f"morph {model['amount']:.2f} between two {kind_of(model['a'])} models:\n a: "+ + ind(summary(model['a'])) + '\n b: ' + ind(summary(model['b'])))+ lines = [head + f"hybrid of {len(model['layers'])} layers ({model['length_s'] * 1000:.0f} ms):"]+ for L in model['layers']:+ lines.append(f" {L['role']} ({kind_of(L['model'])}{', deterministic part' if L['model'].get('layer') else ''}"+ f", {L.get('gain_db', 0.0):+.1f} dB): " + summary(L['model']).replace('\n', '\n '))+ return '\n'.join(lines)diff --git a/earshot/forge/fit/codegen.py b/earshot/forge/fit/codegen.pynew file mode 100644index 0000000..ff6a42a--- /dev/null+++ b/earshot/forge/fit/codegen.py@@ -0,0 +1,248 @@+"""Fitted model -> a readable, self-contained forge recipe module (Python source).++ from earshot.forge.fit import auto, codegen+ m = auto.fit('click.wav')+ src = codegen.to_recipe(m, name='click_fit', source='click.wav', quality=q) # q: quality dict (optional)+ open('click_fit.py', 'w').write(src)+ rec = codegen.load_recipe('click_fit.py') # a module: TARGET, ALTS, SPACE, DEFAULTS, MODEL, render(p, r)+ y = rec.render(rec.DEFAULTS, dsp.rng(0)) # DEFAULTS re-render the fit; the knobs in SPACE vary it+ # search variations with the forge critic: earshot fit --forge click_fit.py --budget 96 --dir made/click_fit+ # (or copy the file into earshot/forge/recipes/ and run `earshot forge click_fit`)++The module holds: a docstring (what the fit found, the source and its licence note, the measured fit quality, how to+use it), TARGET / ALTS (the critic's description: the refset category's recipe when the source is a refset file,+else the category or a description from the measured character), REFSET / REFS (the critic's real references),+SPACE (the model kind's knobs with search ranges around the identity: auto.KNOBS), DEFAULTS (the identity: the+fit itself), MODEL (the fitted parameters as a readable Python literal, one mode / partial / keyframe per line), and+render(p, r) / render_seed(seed, **knobs), which call earshot.forge.fit.auto.render (the fitters' renderers: numpy /+scipy). A morph model makes a recipe whose SPACE has a 'morph' knob (where between the two sources), so a search+explores sounds between two recordings rather than copies of one.+"""+import importlib.util+import os+import re++import numpy as np++from . import auto++COMMENTS = {+ 'strikes': 'one per onset: time s, contact ramp ms, modes, contact (attack) modes',+ 'modes': '[Hz, decay time constant s, amplitude, phase rad] referenced at the strike',+ 'attack': 'the contact: fast modes from the onset [Hz, tau s, amp, phase]',+ 'noise': 'band noise: ERB-spaced bands (edges Hz), per band an envelope [[t s, dB], ...]',+ 'sub': 'the residual under 20 Hz as a 100 Hz waveform (a pressure pulse) or None',+ 'side': 'per noise band, side / mid amplitude ratio of the stereo original',+ 'partials': 'strongest first: birth t0 s, rise s, last breakpoint t1 s, release s, phase, [t, Hz], [t, dBFS]',+ 'transients': 'per strike: damped sinusoid atoms [Hz, tau s, amplitude, phase]',+ 'residual': 'noise in 1/3-octave bands (Hz centres): dB envelopes at `times`',+ 'env': 'the gesture: keyframe times s -> 48-band power density dB (re full-scale white noise)',+ 'stereo': 'per band group and keyframe: L/R level difference dB, inter-channel correlation',+ 'texture': 'what the smooth gesture does not hold: flutter (am) and crackle (grains)',+ 'ridges': 'tonal ridges: keyframes of frequency Hz and level dB',+ 'layers': 'fitted one after another on what the previous layers leave',+ 'fit_engine': None,+}+DROP = ('fit_engine',)+++def _scalar(v):+ if isinstance(v, (bool, np.bool_)):+ return repr(bool(v))+ if isinstance(v, (int, np.integer)):+ return repr(int(v))+ if isinstance(v, (float, np.floating)):+ v = float(v)+ if v != v or v in (float('inf'), float('-inf')):+ return f"float('{v}')"+ return repr(v)+ return repr(v)+++def _is_scalar(v):+ return v is None or isinstance(v, (bool, int, float, str, np.integer, np.floating, np.bool_))+++def _lit(v, ind, width=116):+ pad = ' ' * ind+ if isinstance(v, dict):+ if not v:+ return '{}'+ out = ['{']+ for k, x in v.items():+ s = _lit(x, ind + 4, width)+ c = COMMENTS.get(k)+ if c and '\n' in s:+ out.append(f'{pad} # {c}')+ out.append(f'{pad} {k!r}: {s},' + (f' # {c}' if c and '\n' not in s else ''))+ out.append(pad + '}')+ return '\n'.join(out)+ if isinstance(v, (list, tuple)):+ if not v:+ return '[]'+ if all(_is_scalar(x) for x in v):+ items = [_scalar(x) for x in v]+ one = '[' + ', '.join(items) + ']'+ if len(one) + ind <= width:+ return one+ lines, cur = [], ''+ for it in items:+ if cur and len(cur) + len(it) + ind + 6 > width:+ lines.append(cur)+ cur = ''+ cur += it + ', '+ lines.append(cur)+ return '[\n' + '\n'.join(pad + ' ' + ln.rstrip() for ln in lines) + '\n' + pad + ']'+ return '[\n' + '\n'.join(pad + ' ' + _lit(x, ind + 4, width) + ',' for x in v) + '\n' + pad + ']'+ return _scalar(v)+++def literal(model, name='MODEL'):+ """`name = {...}`: the model as a readable Python literal that evaluates to an equal dict (fit diagnostics left+ out)"""+ m = {k: v for k, v in model.items() if k not in DROP}+ return f'{name} = ' + _lit(m, 0)+++def _category_of(path):+ """(refset category, split) of a registry file, else (None, None)"""+ if not path:+ return None, None+ try:+ from ..refsets import load+ reg = load()+ except Exception:+ return None, None+ p = os.path.normcase(os.path.abspath(path))+ for c, e in reg.get('categories', {}).items():+ for s in ('forge', 'bench'):+ if any(os.path.normcase(os.path.abspath(q)) == p for q in e.get(s, [])):+ return c, s+ return None, None+++def critic_words(source=None, category=None, character=None):+ """(TARGET, ALTS, REFSET) for a fitted recipe: a forge recipe of the same refset category lends its TARGET /+ ALTS; else the category's description; else a description from the measured character"""+ if category is None:+ category, _ = _category_of(source)+ if category:+ try:+ from .. import load_recipe, recipes+ for nm in recipes():+ try:+ r = load_recipe(nm)+ except Exception:+ continue+ if getattr(r, 'REFSET', None) == category:+ t = (getattr(r, 'TARGETS', None) or {}).get(category, r.TARGET)+ return t, list(getattr(r, 'ALTS', []) or []), category+ except Exception:+ pass+ from ..refsets import CATEGORIES+ if category in CATEGORIES:+ return re.sub(r'\s*\(.*?\)\s*$', '', CATEGORIES[category]), [], category+ c = character or {}+ if c.get('gliding'):+ t = 'a short round pop with a pitch glide'+ elif c.get('tonal'):+ t = 'a bright ringing chime' if c.get('t40_ms', 0) > 400 else 'a short pitched ding'+ elif c.get('impulsive') and c.get('dur_s', 1) < 0.5:+ t = 'a short crisp click'+ elif c.get('impulsive'):+ t = 'a deep hit with a long tail'+ elif c.get('noisy'):+ t = 'an air whoosh'+ else:+ t = 'a sound effect'+ return t, [], None+++def _space_lines(knobs):+ lines = ['SPACE = {']+ for n, (spec, ident, doc) in knobs.items():+ lines.append(f' {n!r}: {tuple(spec)!r}, # {doc}')+ lines.append('}')+ return lines+++def to_recipe(model, name='fitted', source=None, quality=None, floor=None, target=None, alts=None, refset=None,+ refs=None, licence=None):+ """the recipe module source (module doc). source: the recording's path (for the critic refs and the docstring);+ quality / floor: quality dicts measured on this model's render (written into the docstring)"""+ kind = auto.kind_of(model)+ knobs = auto.knobs_of(model)+ fe = model.get('fit_engine') or {}+ t, a, cat = critic_words(source, refset, fe.get('character'))+ target = target or t+ alts = a if alts is None else list(alts)+ refset = refset or cat+ if refs is None:+ refs = [os.path.abspath(source).replace(chr(92), '/')] if source and os.path.exists(source) else []+ from .quality import text as qtext+ summ = auto.summary(model)+ src_name = os.path.basename(source) if source else (model.get('source') or 'unknown')+ doc = [f'{name}: a forge recipe fitted from a real recording by `earshot fit` ({kind} model).', '']+ doc += [ln.rstrip() for ln in summ.splitlines()]+ doc += ['', f'Source: {src_name}' + (f' (refset {refset})' if refset else '') + '.',+ licence or ('Licence: a fit of a recording is a derivative of it. Keep the source\'s attribution / licence '+ 'with this file;'), 'prefer CC0 sources for shipped seeds (a morph of several sources is less '+ 'derivative of any one).']+ if quality:+ doc += ['', 'Fit quality (original vs this recipe at DEFAULTS, seed 0):', ' ' + qtext(quality, floor)]+ doc += ['', 'Use:',+ ' from earshot.forge import dsp',+ ' y = render(DEFAULTS, dsp.rng(0)) # one take of the fit (r = the take\'s noise)',+ ' y = render_seed(0) # the fit as measured (seed 0)',+ f" y = render(dict(DEFAULTS, {next(iter(knobs))}=...), dsp.rng(3)) # a variation",+ f' earshot fit --forge {name}.py --budget 96 --dir made/{name} # variations searched with the critic',+ f' (or copy this file into earshot/forge/recipes/ and run `earshot forge {name}`)',+ 'Knobs: SPACE (search ranges); DEFAULTS = the identity (the fit itself).']+ body = ['"""' + '\n'.join(doc).replace('"""', "'''").replace('\\', '/') + '\n"""',+ 'import numpy as np', '', 'from earshot.forge.fit import auto as _engine', '',+ f'TARGET = {target!r}', f'ALTS = {alts!r}']+ if refset:+ body.append(f'REFSET = {refset!r} # the critic\'s default refs: this refsets category (forge split)')+ body.append(f'REFS = {refs!r}')+ body.append(f'KIND = {kind!r}')+ body += [''] + _space_lines(knobs)+ body.append('DEFAULTS = ' + repr({n: v[1] for n, v in knobs.items()}) + ' # the identity: re-renders the fit')+ body += ['', literal(model), '', '',+ 'def render(p, r):',+ ' """one take: p = knob values (missing keys take DEFAULTS), r = numpy Generator (noise / jitter)"""',+ ' q = dict(DEFAULTS)',+ ' q.update({k: v for k, v in p.items() if k in DEFAULTS})',+ ' return _engine.render(MODEL, seed=int(r.integers(0, 2 ** 31 - 1)), **q)', '', '',+ 'def render_seed(seed=0, **knobs):',+ ' """render with an explicit seed: render_seed(0) is the fit as measured"""',+ ' q = dict(DEFAULTS)',+ ' q.update(knobs)',+ ' return _engine.render(MODEL, seed=seed, **q)', '', '',+ "if __name__ == '__main__':",+ ' import sys',+ ' import soundfile as sf',+ ' seed = int(sys.argv[1]) if len(sys.argv) > 1 else 0',+ f" out = sys.argv[2] if len(sys.argv) > 2 else '{name}.wav'",+ " sf.write(out, np.asarray(render_seed(seed), np.float32), 48000, subtype='FLOAT')",+ ' print(out)', '']+ return '\n'.join(body)+++def write_recipe(path, model, **kw):+ """to_recipe() written to `path` (the module name defaults to the file stem); returns the path"""+ kw.setdefault('name', re.sub(r'\W', '_', os.path.splitext(os.path.basename(path))[0]))+ d = os.path.dirname(os.path.abspath(path))+ os.makedirs(d, exist_ok=True)+ with open(path, 'w', encoding='utf-8') as fh:+ fh.write(to_recipe(model, **kw))+ return path+++def load_recipe(path):+ """import a recipe module from a file path (a fitted recipe outside earshot/forge/recipes/)"""+ name = re.sub(r'\W', '_', os.path.splitext(os.path.basename(path))[0])+ spec = importlib.util.spec_from_file_location(f'earshot_fit_recipe_{name}', path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ mod.__name__ = name+ return moddiff --git a/earshot/forge/fit/modal.py b/earshot/forge/fit/modal.pynew file mode 100644index 0000000..0d636d5--- /dev/null+++ b/earshot/forge/fit/modal.py@@ -0,0 +1,1094 @@+"""Modal fitter: a struck / ringing recording -> a small physical model that re-renders it (analysis by synthesis).++ from earshot.forge.fit import modal+ model = modal.fit('click.wav') # or a 48 kHz array (n,) / (n, 2)+ y = modal.render(model, seed=0) # the resynthesis, same length and channels+ y2 = modal.render(model, seed=3, size=1.3, damping=0.8, brightness=-2, hardness=1.5, vary=0.5)+ src = modal.to_code(model) # a standalone numpy script that renders it (same samples as render)+ modal.mel_distance(x, y) # multi-resolution log-mel distance (dB), the fit's own check++What the model holds (a plain JSON-serialisable dict, kind 'modal', version 1):+- strikes: one per detected onset (a click, a toggle's two contacts, a key's press + bottom-out + release): its+ time `t` (s), an attack ramp `ramp_ms` (the modes rise over it), its modes, rows [freq Hz, decay time constant s,+ amplitude, phase rad] referenced at the onset (amp * exp(-t / tau) * cos(2 pi f t + phase) * ramp(t)), and its+ `attack`: the contact as fast modes (tau <= 2 ms, same row format, no ramp) that keep the first ms coherent.+ A later strike also holds exact copies of earlier poles that still ring at its onset, so it can re-excite or stop+ them (a finger that lifts or holds).+- sub: the residual under 20 Hz as a 100 Hz waveform (a pressure pulse / bump), or None.+- noise: what the deterministic part does not carry, as band envelopes: 28 power-complementary bands (cosine+ crossovers on the ERB-rate axis, `edges` Hz) x breakpoints [t s, dB] (power, linear in dB between breakpoints).+ Each band's power is the original's minus the deterministic part's, so modes + noise keep the band energy.+- fade_out_s: the recording's linear fade-out (estimated; the modes are fitted un-faded and faded at render).+- side: per noise band, the side / mid amplitude ratio of a stereo original (None for mono).+- fit: diagnostics (mode count, the modes' energy share, the residual's level).++How it fits (`fit`):+1. onsets: peaks of a capped log-spectral flux (broadband rises count, a beating pair of modes or a glide's few bins+ barely do), refined to the first sample over 10 % of the local peak, or to the first step of the signal's+ difference when an earlier strike still rings; a fade-out estimate, and the signal un-faded for the modes;+2. per strike, damped-sinusoid candidates by ESPRIT on complex-demodulated, decimated sub-bands (15 bands, 20 Hz to+ 21.5 kHz; long windows for the low modes, short ones for the high), two overlapping windows per band merged,+ the order by MDL on the Hankel singular values (capped by a dynamic-range floor); poles outside the band's core,+ growing, or with Q < 2 are dropped;+3. amplitudes + phases by least squares on the full-band signal from `skip_ms` after each onset (closed-form Gram+ matrix of damped exponentials: many modes over a long file stay cheap; ridge raised while near-duplicates of+ one strike, or a pile of strikes, cancel each other), modes under -50 dB of their strike pruned, clusters of+ cancelling near-duplicates cut to the one that alone explains the most (matching pursuit), a second pass on the+ residual adds what the first missed, then one joint fit of every strike's modes;+4. per strike the attack ramp that leaves the least residual in the first ms; the sub wave; the contact modes+ (full-rate ESPRIT on the first 2.5 ms of the residual);+5. band envelopes (analytic-signal power; 0.5 ms smoothing from 8 ms before to 15 ms after onsets, 6 ms after,+ 30 ms in long tails), simplified to breakpoints (Ramer-Douglas-Peucker, 1 dB near strikes, 2 dB in tails).++render(model, seed, knobs): size (x: mode frequencies / size, decays * size, the noise spectrum shifted with them),+damping (decays / damping, noise tails shortened), brightness (dB / octave around 1 kHz on modes and noise),+hardness (x: a shorter contact and +4 dB / octave per doubling on the modes and the attack noise), noise (dB on+the noise bands), width (x side), room (0..1 wet of a small stochastic room), vary (0..1: seeded jitter of mode+frequencies / decays / amplitudes, strike timing and noise bands: new takes of the same object), spacing (x the+time between strikes), gain (dB). seed changes only the noise (and, with vary > 0, the jitter). The side of a+stereo render is the mid's Hilbert transform shaped per band by `side`.+What it is not for: glides / chirps (a rising pop, a zip) split into many false strikes; designed impacts with long+reverb tails fit, but the tail is mostly noise bands.+Pure numpy / scipy.+"""+import inspect+import json++import numpy as np+from scipy import fft as sfft+from scipy import signal++SR = 48000+KIND = 'modal'+VERSION = 1++MODE_BANDS = (20, 60, 120, 200, 320, 500, 750, 1100, 1600, 2300, 3300, 4700, 6600, 9300, 13000, 21500)+NOISE_EDGES = (50, 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, 3700,+ 4400, 5300, 6400, 7700, 9500, 12000, 14000, 16000, 18500) # critical bands + low / top splits: 28+NOISE_H = 0.4 # crossover half-width, ERB-rate units+GRID = 0.0005 # dense envelope grid, s+SUB_HZ = 20.0 # below this the residual is kept as a decimated waveform (a pressure pulse)+SUB_DEC = 480 # its decimation (100 Hz)+++# ------------------------------------------------------------------------------------------------ helpers+def _load(x):+ if isinstance(x, str):+ from ... import audio+ x = audio.load(x)+ x = np.asarray(x, np.float64)+ return x[:, None] if x.ndim == 1 else x+++def _mono(x):+ x = np.asarray(x, np.float64)+ return x.mean(axis=1) if x.ndim == 2 else x+++def _sig(v, n=5):+ """round to n significant digits (JSON-stable)"""+ v = float(v)+ if v == 0 or not np.isfinite(v):+ return 0.0+ return float(f'{v:.{n}g}')+++def _env_db(m, hop=12, win=24):+ """energy envelope in dB at `hop` samples (window `win`), and the frame centres"""+ p = np.convolve(m * m, np.ones(win) / win, mode='same')+ e = p[hop // 2::hop]+ return 10 * np.log10(e + 1e-20), np.arange(len(e)) * hop + hop // 2+++# ------------------------------------------------------------------------------------------------ onsets+def onset_strength(m, nper=256, hop=32, cap=1.5):+ """log-spectral flux (half-wave rectified rise of log(1 + |X| / ref) summed over bins, 2-frame lag) and the+ frame energy in dB, at `hop` samples; broadband rises count, a beating pair of modes barely does"""+ f, t, X = signal.stft(m, SR, nperseg=nper, noverlap=nper - hop, boundary='zeros', padded=True)+ A = np.abs(X)+ ref = A.max() * 1e-3 + 1e-12+ Sl = np.log1p(A / ref)+ flux = np.zeros(Sl.shape[1])+ flux[2:] = np.minimum(np.maximum(Sl[:, 2:] - Sl[:, :-2], 0.0), cap).sum(axis=0) # capped: a glide's few bins+ # cannot outvote a strike+ e = 10 * np.log10((A ** 2).sum(axis=0) + 1e-20)+ centre = (np.arange(Sl.shape[1]) * hop).astype(int)+ return flux, e, centre+++def onsets(x, rel=0.2, floor_db=-36.0, min_gap_ms=12.0, max_n=10):+ """strike onsets (samples): peaks of the capped log-spectral flux >= rel x its maximum whose frame energy lies+ within floor_db of the loudest frame and rises >= 3 dB (1 dB for a flux peak over half the maximum: a+ second contact over a loud ring), each refined to the first sample above 10 % of the+ local peak amplitude (from near silence) or to the first step of the signal's difference (over a ringing+ strike)"""+ m = _mono(x)+ if not len(m) or np.abs(m).max() <= 0:+ return [0]+ flux, e, c = onset_strength(m)+ top = e.max()+ w = 6 # +-4 ms local maximum+ fp = np.pad(flux, w, mode='constant')+ locmax = flux >= np.lib.stride_tricks.sliding_window_view(fp, 2 * w + 1).max(axis=1)+ emax = np.lib.stride_tricks.sliding_window_view(np.pad(e, (0, 8), mode='edge'), 9).max(axis=1)[:len(e)]+ emin = np.lib.stride_tricks.sliding_window_view(np.pad(e, (8, 0), mode='edge'), 9).min(axis=1)[:len(e)]+ cand = np.nonzero(locmax & (flux >= rel * flux.max()) & (emax >= top + floor_db) & ((emax - emin >= 3.0) | ((flux >= 0.5 * flux.max()) & (emax - emin >= 1.0))))[0]+ out = []+ early = np.abs(m[:int(0.005 * SR)]).max() >= 0.25 * np.abs(m).max()+ for i in cand:+ if (c[i] < 128 and not early) or c[i] > len(m) - 192: # the STFT's zero padding, not a strike+ continue+ s = int(c[i])+ a, b = max(0, s - 240), min(len(m), s + 240)+ loc = np.abs(m[a:b])+ if len(loc) < 100 or loc.max() <= 0:+ continue+ pre = np.sqrt(np.mean(m[a:a + 96] ** 2))+ if pre < 0.05 * loc.max(): # from near silence: 10 % of the local peak+ o = a + int(np.nonzero(loc >= 0.1 * loc.max())[0][0])+ else: # over a ringing strike: the new contact's step+ d = np.abs(np.diff(m[a:b]))+ thr = min(max(0.3 * d.max(), 4.0 * np.median(d[:96])), d.max())+ o = a + int(np.nonzero(d >= thr)[0][0])+ if out and o - out[-1][0] < min_gap_ms * SR / 1000:+ if flux[i] > out[-1][1] * 2.5: # a much stronger rise right after: that is the strike+ out[-1] = (out[-1][0], flux[i])+ continue+ out.append((o, float(flux[i])))+ if not out:+ return [int(np.argmax(np.abs(m) > np.abs(m).max() * 0.1))]+ if len(out) > max_n:+ out = sorted(sorted(out, key=lambda q: -q[1])[:max_n])+ return [o for o, _ in out]+++def fade_out(x, cands=(0.005, 0.01, 0.02, 0.03, 0.05, 0.1, 0.25), gain_db=0.5):+ """length (s) of a linear fade-out at the end of x (a trimmed recording), 0.0 when none fits: on one common end+ window, the 1 ms dB envelope is fitted by a line + 20 log10 of each candidate ramp (and by a line alone); the+ best ramp must beat the line alone by gain_db (mean absolute dB)"""+ m = _mono(x)+ h = int(0.001 * SR)+ k = len(m) // h+ if k < 20:+ return 0.0+ w = np.hanning(8 * h + 2)[1:-1] # 8 ms: low modes' ripple must not look like a fade+ e = 10 * np.log10(np.convolve(m[:k * h] ** 2, w / w.sum(), mode='same')[h // 2::h][:k] + 1e-20)+ t = (np.arange(k) + 0.5) * h / SR+ T = k * h / SR+ W = min(0.45 * T, 0.6)+ win = (t >= T - W) & (e > e.max() - 80)+ if win.sum() < 10:+ return 0.0+ tw, ew = t[win], e[win]+ def err(L):+ r = 20 * np.log10(np.clip((T - tw) / L, 1e-3, 1.0)) if L > 0 else np.zeros(len(tw))+ a, b = np.polyfit(tw, ew - r, 1)+ return float(np.mean(np.abs(ew - (a * tw + b + r))))+ e0 = err(0.0)+ best, bl = e0 - gain_db, 0.0+ for L in cands:+ if L > W / 2:+ break+ v = err(L)+ if v < best:+ best, bl = v, L+ return bl+++# ------------------------------------------------------------------------------------------------ ESPRIT+def _order(sv, M, kmax, dyn_db):+ lam = sv.astype(np.float64) ** 2 + 1e-300+ p = len(lam)+ kcap = int(min(kmax, p - 2, np.count_nonzero(sv > sv[0] * 10 ** (-dyn_db / 20))))+ if kcap <= 0:+ return 0+ best, kb = np.inf, 0+ for k in range(kcap + 1):+ tail = lam[k:]+ g = np.exp(np.mean(np.log(tail)))+ a = np.mean(tail)+ mdl = -M * (p - k) * np.log(g / a) + 0.5 * k * (2 * p - k) * np.log(M)+ if mdl < best:+ best, kb = mdl, k+ return kb+++def esprit(s, kmax=16, dyn_db=60.0):+ """poles z of the damped exponentials in the (complex) sequence s, model order by MDL; (z, order)"""+ s = np.asarray(s)+ N = len(s)+ if N < 12:+ return np.zeros(0, complex), 0+ L = max(4, N // 3)+ M = N - L + 1+ H = np.lib.stride_tricks.sliding_window_view(s, M)[:L]+ try:+ U, sv, _ = np.linalg.svd(H, full_matrices=False)+ except np.linalg.LinAlgError:+ return np.zeros(0, complex), 0+ k = _order(sv, M, kmax, dyn_db)+ if k == 0:+ return np.zeros(0, complex), 0+ Us = U[:, :k]+ Phi = np.linalg.lstsq(Us[:-1], Us[1:], rcond=None)[0]+ return np.linalg.eigvals(Phi), k+++def _band_candidates(seg, kmax=16, nmax=384, min_n=16):+ """(freq, tau) candidates in each MODE_BANDS core from a real segment that starts just after an onset"""+ Ns = len(seg)+ if Ns < 32:+ return []+ n_fft = sfft.next_fast_len(2 * Ns)+ X = np.fft.fft(seg, n_fft)+ f = np.fft.fftfreq(n_fft, 1 / SR)+ n = np.arange(Ns)+ out = []+ for lo, hi in zip(MODE_BANDS[:-1], MODE_BANDS[1:]):+ B = hi - lo+ tw = max(0.15 * B, 8.0)+ a0, a1, b1, b0 = lo - 2 * tw, lo - tw, hi + tw, hi + 2 * tw+ mask = np.zeros(n_fft)+ up = (f > a0) & (f < a1)+ mask[up] = 0.5 - 0.5 * np.cos(np.pi * (f[up] - a0) / tw)+ mask[(f >= a1) & (f <= b1)] = 1.0+ dn = (f > b1) & (f < b0)+ mask[dn] = 0.5 + 0.5 * np.cos(np.pi * (f[dn] - b1) / tw)+ span = B + 4 * tw+ D = max(1, min(int(SR / (1.15 * span)), Ns // 48))+ if Ns // D < min_n:+ continue+ fc = 0.5 * (lo + hi)+ y = np.fft.ifft(X * mask)[:Ns] * np.exp(-2j * np.pi * fc * n / SR)+ yd = y[::D]+ fs = SR / D+ wins = [yd[:nmax]]+ o2 = (nmax * 3) // 4+ if len(yd) > o2 + nmax // 2:+ w1 = yd[o2:o2 + nmax]+ if np.mean(np.abs(w1) ** 2) > 1e-4 * np.mean(np.abs(wins[0]) ** 2):+ wins.append(w1)+ for w in wins:+ z, _ = esprit(w, kmax)+ if not len(z):+ continue+ r = np.abs(z)+ ok = (r < 0.99999) & (r > 1e-6)+ z = z[ok]+ fk = fc + np.angle(z) * fs / (2 * np.pi)+ tau = -1.0 / (np.log(np.abs(z)) * fs)+ good = (fk >= lo) & (fk < hi) & (tau >= 3e-4) & (np.pi * fk * tau >= 2.0) & (tau < 30.0)+ out += [(float(a), float(b)) for a, b in zip(fk[good], tau[good])]+ return out+++def _dedupe(cands, existing=()):+ """drop candidates that duplicate an existing mode or an earlier candidate (same freq within its bandwidth / 4)"""+ keep = list(existing)+ new = []+ for fk, tk in cands:+ dup = False+ for fe, te in keep:+ tol = max(0.3, 0.0015 * fk, 0.25 / (np.pi * np.sqrt(tk * te)))+ if abs(fk - fe) < tol and abs(np.log(tk / te)) < 1.2:+ dup = True+ break+ if not dup:+ keep.append((fk, tk))+ new.append((fk, tk))+ return new+++# ------------------------------------------------------------------------------------------------ least squares+def _poles(freqs, taus):+ freqs, taus = np.asarray(freqs, float), np.asarray(taus, float)+ return np.exp((-1.0 / (taus * SR)) + 2j * np.pi * freqs / SR)+++def _geo(w, L):+ """sum_{n<L} w^n (complex, elementwise)"""+ d = 1.0 - w+ small = np.abs(d) < 1e-12+ with np.errstate(over='ignore', invalid='ignore', divide='ignore', under='ignore'):+ v = (1.0 - np.exp(L * np.log(w + 0j))) / np.where(small, 1.0, d)+ return np.where(small, L, v)+++def _gram(starts, Z, end):+ A = starts[:, None].astype(np.float64)+ B = starts[None, :].astype(np.float64)+ mx = np.maximum(A, B)+ L = np.maximum(end - mx, 0.0)+ lz = np.log(Z)+ with np.errstate(under='ignore'):+ pi = np.exp((mx - A) * lz[:, None])+ pj = np.exp((mx - B) * lz[None, :])+ S1 = pi * pj * _geo(Z[:, None] * Z[None, :], L)+ S2 = pi * np.conj(pj) * _geo(Z[:, None] * np.conj(Z)[None, :], L)+ RR = 0.5 * (S1 + S2).real+ II = 0.5 * (S2 - S1).real+ RI = 0.5 * (S1 - S2).imag+ IR = 0.5 * (S1 + S2).imag+ return np.block([[RR, RI], [IR, II]])+++def _project(m, starts, Z, end, chunk=8192):+ K = len(Z)+ bR, bI = np.zeros(K), np.zeros(K)+ lz = np.log(Z)+ for a in np.unique(starts):+ idx = np.nonzero(starts == a)[0]+ taus = -1.0 / (np.log(np.abs(Z[idx])) * SR)+ T = int(min(end - a, np.ceil(16 * taus.max() * SR) + 1))+ if T <= 0:+ continue+ B = min(chunk, T)+ with np.errstate(under='ignore'):+ base = np.exp(np.arange(B)[:, None] * lz[idx][None, :]) # z^0 .. z^(B-1), scaled per chunk+ for c0 in range(0, T, B):+ k = min(B, T - c0)+ v = (m[a + c0:a + c0 + k] @ base[:k]) * np.exp(c0 * lz[idx])+ bR[idx] += v.real+ bI[idx] += v.imag+ return np.concatenate([bR, bI])+++def ls_modes(m, starts, freqs, taus, end=None, ridge=1e-5, cross=10.0):+ """complex amplitudes c (mode_k[n] = Re(c_k z_k^(n - start_k)) for start_k <= n < end) by least squares on m"""+ starts = np.asarray(starts, np.int64)+ K = len(starts)+ if K == 0:+ return np.zeros(0, complex)+ end = len(m) if end is None else int(end)+ Z = _poles(freqs, taus)+ G = _gram(starts, Z, end)+ b = _project(m, starts, Z, end)+ dg = np.maximum(np.diag(G), 1e-30)+ lam = ridge+ for _ in range(5):+ Gr = G + lam * np.diag(dg)+ try:+ x = np.linalg.solve(Gr, b)+ except np.linalg.LinAlgError:+ x = np.linalg.lstsq(Gr, b, rcond=None)[0]+ bad = False # heavy cancellation between near-duplicates of one strike+ strike_e = 0.0+ for a in np.unique(starts):+ g = np.nonzero(starts == a)[0]+ gg = np.concatenate([g, g + K])+ tot = float(x[gg] @ G[np.ix_(gg, gg)] @ x[gg])+ strike_e += max(tot, 0.0)+ parts = float(sum(x[[k, k + K]] @ G[np.ix_([k, k + K], [k, k + K])] @ x[[k, k + K]] for k in g))+ if tot > 0 and parts > 2.0 * tot:+ bad = True+ break+ # ... or between strikes: a stopped ring cancels its own tail (ratio < ~6), a pile of close strikes+ # building the sound from huge opposite rings does not+ if not bad and strike_e > cross * max(float(x @ G @ x), 1e-30):+ bad = True+ if not bad:+ break+ lam *= 10.0+ return x[:K] - 1j * x[K:]+++def _cancelling(m, starts, freqs, taus, c, ratio=2.0):+ """indices of modes to drop: in each cluster of one strike's modes whose bandwidths overlap, when the modes'+ separate energies add up to more than `ratio` x the energy of their sum (they cancel), all but the one that+ alone explains the most of the signal m (a matching-pursuit choice: not the longest, loudest ring)"""+ n = len(m)+ starts, freqs, taus = np.asarray(starts), np.asarray(freqs), np.asarray(taus)+ E = _mode_energy(c, taus)+ drop = []+ for a in np.unique(starts):+ g = np.nonzero(starts == a)[0]+ g = g[np.argsort(freqs[g])]+ bw = 1.0 / (np.pi * taus[g])+ clusters, cur = [], [g[0]]+ for k in range(1, len(g)):+ if freqs[g[k]] - freqs[g[k - 1]] < max(2.0, 0.5 * (bw[k] + bw[k - 1])):+ cur.append(g[k])+ else:+ clusters.append(cur)+ cur = [g[k]]+ clusters.append(cur)+ for cl in clusters:+ if len(cl) < 2:+ continue+ cl = np.array(cl)+ Zc = _poles(freqs[cl], taus[cl])+ G = _gram(starts[cl], Zc, n)+ x = np.concatenate([c[cl].real, -c[cl].imag])+ tot = float(x @ G @ x)+ if E[cl].sum() > ratio * max(tot, 1e-30):+ b = _project(m, starts[cl], Zc, n)+ L = len(cl)+ expl = []+ for k in range(L):+ ix = [k, k + L]+ Gk = G[np.ix_(ix, ix)] + 1e-12 * np.eye(2) * max(G[k, k], 1e-30)+ expl.append(float(b[ix] @ np.linalg.solve(Gk, b[ix])))+ best = cl[int(np.argmax(expl))]+ drop += [int(k) for k in cl if k != best]+ return drop+++def _mode_energy(c, taus):+ r2 = np.exp(-2.0 / (np.asarray(taus) * SR))+ return 0.5 * np.abs(c) ** 2 / (1.0 - r2)+++def _synth_strike(n, o, freqs, taus, amps, phases, ramp_s=0.0, start=None):+ """the summed modes of one strike over n samples: onset o (samples); start (samples, default o) = first sample"""+ y = np.zeros(n)+ s0 = o if start is None else start+ if s0 >= n:+ return y+ for f, tau, a, ph in zip(freqs, taus, amps, phases):+ L = int(min(n - s0, np.ceil(14 * tau * SR) + 1))+ if L <= 0 or a == 0:+ continue+ t = (np.arange(L) + (s0 - o)) / SR+ y[s0:s0 + L] += a * np.exp(-t / tau) * np.cos(2 * np.pi * f * t + ph)+ if ramp_s > 0 and start is None:+ R = int(round(ramp_s * SR))+ if R > 1:+ k = min(R, n - o)+ y[o:o + k] *= 0.5 - 0.5 * np.cos(np.pi * np.arange(k) / R)+ return y+++def _attack_modes(r, o, end, kmax=24, tau_max=0.002):+ """the contact transient as fast damped sinusoids: full-rate ESPRIT on r[o:end] (real: conjugate pairs), poles+ with tau <= tau_max, amplitudes by least squares over the window; rows [f, tau, amp, phase] at the onset"""+ seg = r[o:end]+ if len(seg) < 24 or not np.any(seg):+ return []+ z, k = esprit(seg, kmax=kmax, dyn_db=50.0)+ if not len(z):+ return []+ z = z[(np.abs(z) < 0.9999) & (np.abs(z) > 1e-4) & (np.angle(z) >= 0)]+ f = np.angle(z) * SR / (2 * np.pi)+ tau = -1.0 / (np.log(np.abs(z)) * SR)+ ok = (tau >= 1e-5) & (tau <= tau_max) & (f < 0.47 * SR)+ f, tau = f[ok], tau[ok]+ if not len(f):+ return []+ c = ls_modes(r, np.full(len(f), o), f, tau, end=min(len(r), o + int(3 * tau_max * SR)))+ rows = [[round(float(a), 2), _sig(b, 5), _sig(abs(cc), 5), round(float(np.angle(cc)), 4)]+ for a, b, cc in zip(f, tau, c) if abs(cc) > 0]+ return sorted(rows, key=lambda q: q[0])+++def _sub_wave(xs, n):+ y = signal.resample_poly(np.asarray(xs, float), SUB_DEC, 1)[:n]+ return np.pad(y, (0, max(0, n - len(y))))+++# ------------------------------------------------------------------------------------------------ noise bands+def band_masks(n_fft, edges=NOISE_EDGES, h=NOISE_H):+ """power-complementary zero-phase masks on the rfft bins (sum of squares = 1): (bands, bins)"""+ return _masks(n_fft, edges, h)+++def band_centres(edges=NOISE_EDGES, top=22000.0):+ e = np.asarray(edges, float)+ return np.concatenate([[e[0] / np.sqrt(2)], np.sqrt(e[:-1] * e[1:]), [np.sqrt(e[-1] * top)]])+++def _rdp(t, v, tol):+ """indices kept by Ramer-Douglas-Peucker on the polyline (t, v) with tolerance tol (v units; scalar or per point)"""+ n = len(t)+ if n <= 2:+ return np.arange(n)+ tol = np.broadcast_to(np.asarray(tol, float), (n,))+ keep = np.zeros(n, bool)+ keep[0] = keep[-1] = True+ stack = [(0, n - 1)]+ while stack:+ a, b = stack.pop()+ if b - a < 2:+ continue+ tt = t[a + 1:b]+ line = v[a] + (v[b] - v[a]) * (tt - t[a]) / (t[b] - t[a])+ d = np.abs(v[a + 1:b] - line) / tol[a + 1:b]+ i = int(np.argmax(d))+ if d[i] > 1.0:+ k = a + 1 + i+ keep[k] = True+ stack.append((a, k))+ stack.append((k, b))+ return np.nonzero(keep)[0]+++def _fit_noise(m, det, ons, tol_db=1.0, edges=NOISE_EDGES, h=NOISE_H):+ """band envelopes of the stochastic part: per band, the original's power minus the deterministic part's power+ (analytic-signal power, 0.5 ms smoothing from 8 ms before to 15 ms after onsets, 6 ms elsewhere), so the+ rendered modes + noise keep the original's band energy even where the modes misfit; a list per band of [t, dB]+ breakpoints"""+ n = len(m)+ n_fft = sfft.next_fast_len(n + 16384)+ W = _masks(n_fft, edges, h)+ R = np.fft.rfft(m, n_fft)+ Rd = np.fft.rfft(det, n_fft)+ grid = np.arange(0, n, int(GRID * SR))+ tg = grid / SR+ near = np.zeros(len(grid))+ since = np.full(len(grid), 10.0) # s since the latest onset (tails get longer smoothing)+ for o in ons:+ d = (grid - o) / SR+ w = np.where((d >= -0.008) & (d <= 0.015), 1.0,+ np.where((d > 0.015) & (d < 0.03), 1.0 - (d - 0.015) / 0.015, 0.0))+ near = np.maximum(near, w)+ since = np.where(d >= 0, np.minimum(since, d), since)+ far = np.clip((since - 0.15) / 0.15, 0.0, 1.0)+ hs, hl = np.hanning(int(0.0005 * SR) + 2)[1:-1], np.hanning(int(0.006 * SR) + 2)[1:-1]+ hf = np.hanning(int(0.03 * SR) + 2)[1:-1]+ hs, hl, hf = hs / hs.sum(), hl / hl.sum(), hf / hf.sum()+ def bandpow(Rx, b):+ Xa = np.zeros(n_fft, complex)+ Xa[:len(Rx)] = Rx * W[b]+ Xa[1:len(Rx) - 1] *= 2.0+ p2 = 0.5 * np.abs(np.fft.ifft(Xa)[:n]) ** 2+ ps = np.maximum(signal.oaconvolve(p2, hs, mode='same')[grid], 0.0)+ pl = np.maximum(signal.oaconvolve(p2, hl, mode='same')[grid], 0.0)+ pf = np.maximum(signal.oaconvolve(p2, hf, mode='same')[grid], 0.0)+ return near * ps + (1 - near) * ((1 - far) * pl + far * pf)+ P_all = []+ for b in range(len(W)):+ po, pd = bandpow(R, b), bandpow(Rd, b)+ P_all.append(np.maximum(po - pd, 1e-6 * po))+ P_all = np.array(P_all)+ fl = 10 * np.log10(P_all.max() + 1e-30) - 100.0+ env = []+ for b in range(len(W)):+ dB = np.maximum(10 * np.log10(P_all[b] + 1e-30), fl)+ k = _rdp(tg, dB, tol_db * (1.0 + far)) # 1 dB near the strikes, 2 dB in long tails+ env.append([[round(float(tg[i]), 5), round(float(dB[i]), 2)] for i in k])+ return env+++# ------------------------------------------------------------------------------------------------ fit+def fit(x, *args, **kw):+ """fit a modal model to a struck / ringing recording (path or 48 kHz array); returns the model dict. Options:+ max_strikes, kmax (ESPRIT order cap per band), nmax (window, decimated samples), passes, skip_ms (the LS starts+ this long after each onset), prune_db, max_modes (per strike), onset_rel, noise_tol_db, analysis_s, verbose"""+ try: # small matrices: one BLAS thread is ~5x faster than a contended pool+ from threadpoolctl import threadpool_limits+ except ImportError:+ return _fit(x, *args, **kw)+ with threadpool_limits(1):+ return _fit(x, *args, **kw)+++def _fit(x, max_strikes=10, kmax=16, nmax=384, passes=2, skip_ms=0.5, prune_db=-50.0, max_modes=80, onset_rel=0.2,+ noise_tol_db=1.0, analysis_s=3.0, attack_ms=2.5, verbose=False):+ X = _load(x)+ m_orig = X.mean(axis=1)+ n = len(m_orig)+ ons = onsets(m_orig, rel=onset_rel, max_n=max_strikes)+ fo = fade_out(m_orig)+ m = m_orig.copy() # the modes are fitted on the un-faded signal+ n_fit = n+ if fo > 0:+ nf = int(round(fo * SR))+ ramp = np.clip((n - np.arange(n - nf, n)) / nf, 0.0, 1.0)+ m[n - nf:] /= np.maximum(ramp, 0.25)+ n_fit = n - int(0.25 * nf)+ skip = int(round(skip_ms * SR / 1000))+ skip_b = skip + int(round(0.0005 * SR))+ e, c = _env_db(m_orig)+ act = np.nonzero(e >= e.max() - 75)[0]+ act_end = int(min(n_fit, c[act[-1]] + 12)) if len(act) else n_fit+ seg_end = [min(ons[i + 1], act_end) if i + 1 < len(ons) else act_end for i in range(len(ons))]+ cap = int(analysis_s * SR)+ S = len(ons)+ modes = [[] for _ in range(S)] # per strike: list of (f, tau)+ work = m.copy()+ for p in range(passes):+ for i, o in enumerate(ons):+ a = o + skip_b+ e_ = min(seg_end[i], a + cap)+ if e_ - a < 48:+ continue+ cands = _band_candidates(work[a:e_], kmax=kmax, nmax=nmax)+ new = _dedupe(cands, modes[i])+ if not new:+ continue+ fr = np.array([q[0] for q in new])+ ta = np.array([q[1] for q in new])+ st = np.full(len(new), o + skip)+ cc = ls_modes(work, st, fr, ta, end=min(seg_end[i], o + skip + cap) if i + 1 < S else n_fit)+ E = _mode_energy(cc, ta)+ ref = max(E.sum(), 1e-30)+ order = np.argsort(-E)+ room_left = max_modes - len(modes[i])+ keep = [j for j in order[:max(room_left, 0)] if E[j] >= ref * 10 ** (prune_db / 10)]+ for j in keep:+ modes[i].append((float(fr[j]), float(ta[j])))+ if keep:+ amps, phs = np.abs(cc[keep]), np.angle(cc[keep])+ work -= _synth_strike(n, o + skip, fr[keep], ta[keep], amps, phs)+ # a later strike may re-excite or stop (a finger lifts, a second contact damps) an earlier one's modes: it+ # gets copies of the earlier poles that still ring at its onset, the joint fit picks their amplitudes+ for i in range(1, S):+ prev = [(fk, tk) for j in range(i) for fk, tk in modes[j]+ if np.exp(-(ons[i] - ons[j]) / (tk * SR)) > 1e-2]+ prev = _dedupe(sorted(prev, key=lambda q: -q[1])[:40])+ own = [q for q in modes[i] if q not in prev]+ modes[i] = prev + _dedupe(own, prev)+ # one joint fit of every strike's modes on the original+ starts, fr, ta, owner = [], [], [], []+ for i, o in enumerate(ons):+ for fk, tk in modes[i]:+ starts.append(o + skip)+ fr.append(fk)+ ta.append(tk)+ owner.append(i)+ if not starts:+ break+ starts, fr, ta, owner = map(np.asarray, (starts, fr, ta, owner))+ cc = ls_modes(m, starts, fr, ta, end=n_fit)+ E = _mode_energy(cc, ta)+ keep = np.zeros(len(E), bool)+ for i in range(S):+ sel = owner == i+ if sel.any():+ keep[sel] = E[sel] >= E[sel].sum() * 10 ** (prune_db / 10)+ if not keep.all():+ starts, fr, ta, owner = starts[keep], fr[keep], ta[keep], owner[keep]+ cc = ls_modes(m, starts, fr, ta, end=n_fit)+ for _ in range(3): # clusters of near-duplicates that cancel: keep their strongest+ drop = _cancelling(m[:n_fit], starts, fr, ta, cc)+ if not drop:+ break+ keep = np.ones(len(fr), bool)+ keep[drop] = False+ starts, fr, ta, owner = starts[keep], fr[keep], ta[keep], owner[keep]+ cc = ls_modes(m, starts, fr, ta, end=n_fit)+ modes = [[(float(a), float(b)) for a, b in zip(fr[owner == i], ta[owner == i])] for i in range(S)]+ work = m - sum((_synth_strike(n, ons[i] + skip, fr[owner == i], ta[owner == i], np.abs(cc[owner == i]),+ np.angle(cc[owner == i])) for i in range(S) if (owner == i).any()),+ np.zeros(n))+ if verbose:+ print(f'pass {p}: {len(fr)} modes, residual {10 * np.log10(np.sum(work ** 2) / np.sum(m ** 2) + 1e-30):.1f} dB')+ # per strike: modes referenced at the onset, and the attack ramp that leaves the least residual+ strikes = []+ mode_sig = np.zeros(n)+ have = len(starts) if isinstance(starts, np.ndarray) else 0+ for i, o in enumerate(ons):+ if have and (owner == i).any():+ sel = owner == i+ f_i, t_i, c_i = fr[sel], ta[sel], cc[sel]+ else:+ f_i, t_i, c_i = np.zeros(0), np.zeros(0), np.zeros(0, complex)+ amp0 = np.abs(c_i) * np.exp(skip / (t_i * SR)) if len(t_i) else np.zeros(0)+ ph0 = np.angle(c_i) - 2 * np.pi * f_i * skip / SR if len(t_i) else np.zeros(0)+ rows = sorted([[round(float(a), 2), _sig(b, 5), _sig(c_, 5), round(float(np.angle(np.exp(1j * d))), 4)]+ for a, b, c_, d in zip(f_i, t_i, amp0, ph0)], key=lambda q: q[0])+ rows = [q for q in rows if q[2] > 0 and q[1] > 0]+ fq, tq, aq, pq = (np.array([q[j] for q in rows]) for j in range(4)) if rows else (np.zeros(0),) * 4+ base = m - mode_sig+ w0, w1 = o, min(n, o + skip + int(0.0015 * SR))+ best, rb = np.inf, 0.0+ for rms in (0.0, 0.05, 0.1, 0.2, 0.35, 0.5, 0.8, 1.2):+ y = _synth_strike(w1 + int(0.002 * SR), o, fq, tq, aq, pq, rms / 1000) if rows else None+ err = np.sum((base[w0:w1] - (y[w0:w1] if y is not None else 0)) ** 2)+ if err < best * (1 - 1e-9):+ best, rb = err, rms+ mode_sig += _synth_strike(n, o, fq, tq, aq, pq, rb / 1000) if rows else 0+ strikes.append({'t': round(o / SR, 6), 'ramp_ms': rb, 'modes': rows})+ resid = m - mode_sig+ sub = None+ if n > 4 * SUB_DEC: # a slow pressure pulse under 20 Hz (thump, bump): its waveform+ lo = signal.sosfiltfilt(signal.butter(4, SUB_HZ, 'low', fs=SR, output='sos'), resid)+ if np.sum(lo ** 2) > 1e-3 * np.sum(m ** 2):+ xs = signal.resample_poly(lo, 1, SUB_DEC)+ sub = {'rate': SR // SUB_DEC, 'x': [_sig(v, 4) for v in xs]}+ resid = resid - _sub_wave(sub['x'], n)+ for i, o in enumerate(ons): # the contact: fast coherent modes in the first ms+ end_a = min(n, o + int(attack_ms * SR / 1000), ons[i + 1] if i + 1 < S else n)+ rows = _attack_modes(resid, o, end_a)+ strikes[i]['attack'] = rows+ if rows:+ q = np.array(rows)+ resid -= _synth_strike(n, o, q[:, 0], q[:, 1], q[:, 2], q[:, 3])+ det = m - resid # modes + sub + contact, un-faded+ if fo > 0:+ nf = int(round(fo * SR))+ det[n - nf:] *= np.clip((n - np.arange(n - nf, n)) / nf, 0.0, 1.0)+ resid = m_orig - det+ model = {'kind': KIND, 'version': VERSION, 'sr': SR, 'length_s': round(n / SR, 6), 'channels': int(X.shape[1]),+ 'fade_out_s': fo, 'strikes': strikes, 'sub': sub,+ 'noise': {'edges': list(NOISE_EDGES), 'h_erb': NOISE_H,+ 'env': _fit_noise(m_orig, det, ons, noise_tol_db)},+ 'side': None}+ if X.shape[1] == 2:+ side = 0.5 * (X[:, 0] - X[:, 1])+ n_fft = sfft.next_fast_len(n)+ W = band_masks(n_fft)+ Ms, Ss = np.abs(np.fft.rfft(m_orig, n_fft)) ** 2, np.abs(np.fft.rfft(side, n_fft)) ** 2+ rho = np.sqrt(((W ** 2) @ Ss + 1e-30) / ((W ** 2) @ Ms + 1e-30))+ model['side'] = [round(float(min(v, 1.5)), 4) for v in rho]+ pm = float(np.sum(m_orig ** 2)) + 1e-30+ model['fit'] = {'skip_ms': skip_ms, 'modes': int(sum(len(s['modes']) for s in strikes)),+ 'mode_share_db': round(float(10 * np.log10(np.sum(mode_sig ** 2) / pm + 1e-30)), 2),+ 'resid_db': round(float(10 * np.log10(np.sum(resid ** 2) / pm + 1e-30)), 2)}+ return model+++# ------------------------------------------------------------------------------------------------ render+# Everything below `render_model` uses only numpy / scipy and the constants SR, GRID: to_code() copies these+# functions verbatim into a standalone script, so the script renders the same samples as render().+def _plan(model, seed, size, damping, brightness, hardness, noise, vary, spacing):+ """the model with the knobs applied: strikes (onset s, ramp s, f, tau, amp, phase arrays), the dense noise+ envelope (bands x grid, dB) on a GRID-second grid, the band centres and the output length (samples)"""+ rv = np.random.default_rng([int(seed) & 0xFFFFFFFF, 1])+ st = model['strikes']+ t0 = [s['t'] for s in st]+ tn = []+ for i, t in enumerate(t0):+ if i == 0:+ tn.append(t)+ else:+ gap = (t - t0[i - 1]) * spacing + vary * 0.002 * rv.standard_normal()+ tn.append(tn[-1] + max(0.003, gap))+ stretch = max(size / damping, 1e-3)+ tilt = brightness + 4.0 * np.log2(max(hardness, 1e-3))+ strikes = []+ for i, s in enumerate(st):+ md = np.array(s['modes'], float).reshape(-1, 4)+ k = len(md)+ f = md[:, 0] / size * (1 + 0.006 * vary * rv.standard_normal(k))+ tau = md[:, 1] * stretch * np.exp(0.12 * vary * rv.standard_normal(k))+ a = md[:, 2] * 10 ** ((tilt * np.log2(np.maximum(f, 20.0) / 1000.0) + 1.5 * vary * rv.standard_normal(k)) / 20)+ keep = f < 0.47 * SR+ at = np.array(s.get('attack', []), float).reshape(-1, 4)+ fa = at[:, 0] / size+ ta = at[:, 1] * size / np.sqrt(max(hardness, 1e-3))+ aa = at[:, 2] * 10 ** ((tilt * np.log2(np.maximum(fa, 20.0) / 1000.0)) / 20)+ ka = fa < 0.47 * SR+ strikes.append((tn[i], s['ramp_ms'] / 1000.0 / max(hardness, 1e-3), f[keep], tau[keep], a[keep],+ md[keep, 3], fa[ka], ta[ka], aa[ka], at[ka, 3]))+ L0 = model['length_s']+ t_last0, t_last = t0[-1], tn[-1]+ length = t_last + (L0 - t_last0) * max(1.0, stretch)+ n_out = int(round(length * SR))+ # dense noise envelope on the original's time axis+ nz = model['noise']+ edges = np.asarray(nz['edges'], float)+ cen = np.concatenate([[edges[0] / np.sqrt(2)], np.sqrt(edges[:-1] * edges[1:]), [np.sqrt(edges[-1] * 22000.0)]])+ g_old = np.arange(0.0, L0 + GRID, GRID)+ E0 = np.array([np.interp(g_old, [p[0] for p in env], [p[1] for p in env]) for env in nz['env']])+ # time map: new grid -> old time (per strike segment: shift, tails stretched by size / damping)+ g_new = np.arange(0.0, n_out / SR + GRID, GRID)+ tn_a, t0_a = np.asarray(tn), np.asarray(t0)+ seg = np.clip(np.searchsorted(tn_a, g_new, side='right') - 1, 0, len(tn_a) - 1)+ hold = 0.002+ rel = g_new - tn_a[seg]+ rel_old = np.where(rel < hold, rel, hold + (rel - hold) / stretch)+ told = t0_a[seg] + rel_old+ end = np.append(t0_a[1:], L0)[seg]+ new_len = np.append(tn_a[1:] - tn_a[:-1], 1e9)[seg]+ old_len = np.append(t0_a[1:] - t0_a[:-1], 1e9)[seg]+ moved = (stretch != 1.0) | (np.abs(new_len - old_len) > 1e-9)+ cut = np.where(moved, end - GRID, end)+ extra = np.maximum(told - cut, 0.0)+ told = np.clip(np.minimum(told, cut), 0.0, L0)+ E = np.array([np.interp(told, g_old, row) for row in E0])+ if np.any(extra > 0): # past the old segment: keep falling at its last slope+ back = np.array([np.interp(np.maximum(told - 0.01, 0.0), g_old, row) for row in E0])+ E = E + np.clip((E - back) / 0.01, -3000.0, 0.0) * extra[None, :]+ if size != 1.0: # shift the noise spectrum with the modes+ lc = np.log2(cen)+ q = np.interp(lc + np.log2(size), lc, np.arange(len(cen)))+ i0 = np.clip(np.floor(q).astype(int), 0, len(cen) - 2)+ fr = (q - i0)[:, None]+ E = E[i0] * (1 - fr) + E[i0 + 1] * fr+ E = E + (brightness * np.log2(cen / 1000.0))[:, None] + noise+ if hardness != 1.0: # the contact's noise follows the hardness tilt+ hw = np.zeros(len(g_new))+ for t in tn:+ d = g_new - t+ hw = np.maximum(hw, np.where((d >= -0.001) & (d <= 0.004), 1.0,+ np.where((d > 0.004) & (d < 0.008), 1.0 - (d - 0.004) / 0.004, 0.0)))+ E = E + (4.0 * np.log2(hardness) * np.log2(cen / 1000.0))[:, None] * hw[None, :]+ if vary > 0:+ E = E + (1.5 * vary * rv.standard_normal(len(cen)))[:, None]+ sub = model.get('sub')+ sub = (int(round((tn[0] - t0[0]) * SR)), sub['x']) if sub else None+ return {'strikes': strikes, 'E': E, 'cen': cen, 'edges': edges, 'h': nz['h_erb'], 'n': n_out, 'sub': sub,+ 'fade': float(model.get('fade_out_s', 0.0))}+++def _masks(n_fft, edges, h):+ """power-complementary zero-phase band masks on the rfft bins: cosine crossovers of half-width h on the ERB-rate+ axis (21.4 log10(1 + 0.00437 f))"""+ erb = lambda v: 21.4 * np.log10(1.0 + 0.00437 * v)+ f = np.fft.rfftfreq(n_fft, 1 / SR)+ u = erb(f)+ le = erb(np.asarray(edges, float))+ s = np.clip((u[None, :] - le[:, None] + h) / (2 * h), 0.0, 1.0)+ nb = len(edges) + 1+ W = np.ones((nb, len(f)))+ for b in range(nb):+ if b > 0:+ W[b] *= np.sin(0.5 * np.pi * s[b - 1])+ if b < nb - 1:+ W[b] *= np.cos(0.5 * np.pi * s[b])+ return W+++def _ring(L, f, tau, a, ph, block=4096):+ """sum of a * exp(-t / tau) * cos(2 pi f t + ph) over L samples: blocks of z^n times each block's start power"""+ y = np.zeros(L)+ if not len(f) or L <= 0:+ return y+ lz = -1.0 / (np.asarray(tau) * SR) + 2j * np.pi * np.asarray(f) / SR+ C = np.asarray(a) * np.exp(1j * np.asarray(ph))+ T = int(min(L, np.ceil(14 * np.max(tau) * SR) + 1))+ B = min(block, T)+ with np.errstate(under='ignore'):+ base = np.exp(np.arange(B)[:, None] * lz[None, :])+ for c0 in range(0, T, B):+ k = min(B, T - c0)+ y[c0:c0 + k] = (base[:k] @ (C * np.exp(c0 * lz))).real+ return y+++def _modes(plan, n):+ """the strikes' modes (with their contact ramps and contact modes) and the sub wave, summed, faded"""+ y = np.zeros(n)+ for t, ramp, f, tau, a, ph, fa, ta, aa, pa in plan['strikes']:+ o = int(round(t * SR))+ if o >= n:+ continue+ ys = _ring(n - o, f, tau, a, ph)+ R = int(round(ramp * SR))+ if R > 1:+ k = min(R, len(ys))+ ys[:k] *= 0.5 - 0.5 * np.cos(np.pi * np.arange(k) / R)+ ys += _ring(n - o, fa, ta, aa, pa) # the contact: fast modes from the onset, no ramp+ y[o:] += ys+ if plan.get('sub'): # the slow pressure pulse (decimated waveform)+ shift, xs = plan['sub']+ w = signal.resample_poly(np.asarray(xs, float), SUB_DEC, 1)+ a0 = max(0, shift)+ w = w[max(0, -shift):][:max(0, n - a0)]+ y[a0:a0 + len(w)] += w+ nf = min(n, int(round(plan.get('fade', 0.0) * SR)))+ if nf > 0: # the recording's fade-out (the noise bands carry it)+ y[n - nf:] *= np.clip((n - np.arange(n - nf, n)) / nf, 0.0, 1.0)+ return y+++def _noise(plan, n, rng):+ """band noise: per band, white noise x the band's envelope, then the band's zero-phase mask"""+ n_fft = sfft.next_fast_len(n + 16384)+ W = _masks(n_fft, plan['edges'], plan['h'])+ g = np.mean(W ** 2, axis=1)+ ts = np.arange(n) / SR+ grid = np.arange(plan['E'].shape[1]) * GRID+ Y = np.zeros(W.shape[1], complex)+ for b in range(len(W)):+ amp = 10 ** (np.interp(ts, grid, plan['E'][b]) / 20) / np.sqrt(g[b])+ Y += np.fft.rfft(rng.standard_normal(n) * amp, n_fft) * W[b]+ return np.fft.irfft(Y, n_fft)[:n]+++def _room(y, rng, wet, rt60=0.35):+ """a small stochastic room: exponentially decaying, slowly darkening noise per channel, unit energy"""+ L = int(rt60 * SR)+ t = np.arange(L) / SR+ out = y.copy()+ for c in range(y.shape[1]):+ ir = rng.standard_normal(L) * np.exp(-6.9 * t / rt60)+ ir = signal.lfilter([0.35], [1, -0.65], ir)+ ir[:int(0.004 * SR)] = 0.0+ ir /= np.sqrt(np.sum(ir ** 2)) + 1e-12+ out[:, c] += wet * signal.fftconvolve(y[:, c], ir)[:len(y)]+ return out+++def render_model(model, seed=0, size=1.0, damping=1.0, brightness=0.0, hardness=1.0, noise=0.0, width=1.0,+ room=0.0, vary=0.0, spacing=1.0, gain=0.0, stereo=None):+ plan = _plan(model, seed, size, damping, brightness, hardness, noise, vary, spacing)+ n = plan['n']+ s = int(seed) & 0xFFFFFFFF+ mid = _modes(plan, n) + _noise(plan, n, np.random.default_rng([s, 2]))+ two = (model.get('channels', 1) == 2) if stereo is None else bool(stereo)+ if two:+ side = np.zeros(n)+ rho = model.get('side')+ if rho and width > 0: # the side: the mid's Hilbert transform (uncorrelated with it at zero lag, same+ n_fft = sfft.next_fast_len(n + 16384) # envelope), shaped per band by the original's+ W = _masks(n_fft, plan['edges'], plan['h']) # side / mid ratio+ gain_f = np.sqrt(((np.asarray(rho) ** 2)[:, None] * W ** 2).sum(0)) * width+ sign = -1.0 if np.random.default_rng([s, 3]).uniform() < 0.5 else 1.0+ H = np.fft.rfft(mid, n_fft) * gain_f * (-1j * sign)+ H[0] = 0.0+ side = np.fft.irfft(H, n_fft)[:n]+ y = np.stack([mid + side, mid - side], axis=1)+ else:+ y = mid[:, None]+ if room > 0:+ y = _room(y, np.random.default_rng([s, 5]), room, 0.25 + 0.15 * size)+ k = min(n, int(0.001 * SR))+ y[n - k:] *= np.linspace(1.0, 0.0, k)[:, None]+ y *= 10 ** (gain / 20)+ return y if two else y[:, 0]+++def render(model, seed=0, **knobs):+ """re-synthesise a modal model: (n, 2) for a stereo original (or stereo=True), else (n,); knobs: size, damping,+ brightness, hardness, noise, width, room, vary, spacing, gain, stereo (see the module doc)"""+ check(model)+ return render_model(model, seed, **knobs)+++def check(model):+ if not isinstance(model, dict) or model.get('kind') != KIND:+ raise ValueError(f"not a modal model (kind {model.get('kind') if isinstance(model, dict) else type(model)})")+ if int(model.get('version', 0)) > VERSION:+ raise ValueError(f"modal model version {model.get('version')} is newer than this code ({VERSION})")+++# ------------------------------------------------------------------------------------------------ io, code, checks+def save(model, path):+ with open(path, 'w', encoding='utf-8') as fh:+ json.dump(model, fh, separators=(',', ':'))+ return path+++def load(path):+ with open(path, encoding='utf-8') as fh:+ model = json.load(fh)+ check(model)+ return model+++def summary(model):+ """a few lines on what the fit found"""+ lines = [f"modal v{model['version']}: {model['length_s'] * 1000:.0f} ms, {len(model['strikes'])} strike(s), "+ f"{model.get('fit', {}).get('modes', '?')} modes, modes carry "+ f"{model.get('fit', {}).get('mode_share_db', '?')} dB of the energy, residual "+ f"{model.get('fit', {}).get('resid_db', '?')} dB"]+ for s in model['strikes']:+ md = sorted(s['modes'], key=lambda q: -q[2] ** 2 * q[1])[:5]+ top = ', '.join(f'{q[0]:.0f} Hz / {q[1] * 1000:.1f} ms' for q in md)+ lines.append(f" strike at {s['t'] * 1000:.1f} ms, contact {s['ramp_ms']} ms, {len(s['modes'])} modes; "+ f"strongest: {top}")+ return '\n'.join(lines)+++_CODE_FUNCS = (_plan, _masks, _ring, _modes, _noise, _room, render_model)+++def _literal(model):+ """the model as a readable Python literal (one mode per line)"""+ out = ['MODEL = {', f" 'kind': {model['kind']!r}, 'version': {model['version']}, 'sr': {model['sr']},",+ f" 'length_s': {model['length_s']!r}, 'channels': {model['channels']}, "+ f"'fade_out_s': {model.get('fade_out_s', 0.0)!r},", " 'strikes': ["]+ for s in model['strikes']:+ out.append(f" {{'t': {s['t']!r}, 'ramp_ms': {s['ramp_ms']!r}, 'modes': [ # [Hz, decay s, amp, phase]")+ for q in s['modes']:+ out.append(f' [{q[0]!r}, {q[1]!r}, {q[2]!r}, {q[3]!r}],')+ out.append(" ], 'attack': [ # the contact: fast modes from the onset")+ for q in s.get('attack', []):+ out.append(f' [{q[0]!r}, {q[1]!r}, {q[2]!r}, {q[3]!r}],')+ out.append(' ]},')+ out.append(' ],')+ nz = model['noise']+ out.append(f" 'noise': {{'edges': {nz['edges']!r}, 'h_erb': {nz['h_erb']!r}, 'env': [ # per band: [t s, dB]")+ for env in nz['env']:+ out.append(f' {json.dumps(env, separators=(",", ":"))},')+ out.append(' ]},')+ out.append(f" 'side': {model['side']!r},")+ sub = model.get('sub')+ out.append(f" 'sub': {json.dumps(sub, separators=(',', ':')) if sub else None}, # waveform under 20 Hz")+ out.append('}')+ return '\n'.join(out)+++def to_code(model, name='sound'):+ """a standalone Python script (numpy + scipy) that renders the model: `python <file> [seed] [out.wav]`; its+ render(seed, **knobs) returns the same samples as modal.render(model, seed, **knobs)"""+ check(model)+ head = (f'"""{name}: a modal model fitted by earshot.forge.fit.modal (kind {model["kind"]!r}, version '+ f'{model["version"]}).\n\n{summary(model)}\n\nrender(seed, size=, damping=, brightness=, hardness=, '+ f'noise=, width=, room=, vary=, spacing=, gain=) -> float array at 48 kHz.\n"""\n')+ body = [head, 'import sys', '', 'import numpy as np', 'from scipy import fft as sfft', 'from scipy import signal', '',+ f'SR = {SR}', f'GRID = {GRID!r}', f'SUB_DEC = {SUB_DEC}', '', _literal(model), '', '']+ for fn in _CODE_FUNCS:+ body.append(inspect.getsource(fn))+ body.append('')+ body.append('def render(seed=0, **knobs):\n return render_model(MODEL, seed, **knobs)\n\n')+ body.append("if __name__ == '__main__':\n from scipy.io import wavfile\n"+ " seed = int(sys.argv[1]) if len(sys.argv) > 1 else 0\n"+ f" out = sys.argv[2] if len(sys.argv) > 2 else '{name}.wav'\n"+ " wavfile.write(out, SR, render(seed).astype(np.float32))\n")+ return '\n'.join(body)+++def _melbank(n_fft, n_mels, fmin=30.0, fmax=20000.0):+ f = np.fft.rfftfreq(n_fft, 1 / SR)+ mel = lambda v: 2595 * np.log10(1 + v / 700.0)+ imel = lambda v: 700 * (10 ** (v / 2595) - 1)+ pts = imel(np.linspace(mel(fmin), mel(min(fmax, SR / 2)), n_mels + 2))+ fb = np.zeros((n_mels, len(f)))+ for i in range(n_mels):+ a, c, b = pts[i], pts[i + 1], pts[i + 2]+ fb[i] = np.maximum(0, np.minimum((f - a) / (c - a), (b - f) / (b - c)))+ return fb[fb.sum(1) > 0]+++def mel_distance(x, y, frames=(256, 1024, 4096), floor_db=80.0):+ """multi-resolution log-mel distance (dB): per frame size (hop = frame / 4; 32 / 64 / 96 mel bands), the mean+ |dB difference| over the cells where either sound is within floor_db of x's loudest cell; returns+ (mean over sizes, [per size])"""+ a, b = _mono(x), _mono(y)+ n = max(len(a), len(b))+ a, b = np.pad(a, (0, n - len(a))), np.pad(b, (0, n - len(b)))+ out = []+ for nf, nm in zip(frames, (32, 64, 96)):+ hop = nf // 4+ _, _, A = signal.stft(a, SR, nperseg=nf, noverlap=nf - hop, boundary='zeros', padded=True)+ _, _, B = signal.stft(b, SR, nperseg=nf, noverlap=nf - hop, boundary='zeros', padded=True)+ fb = _melbank(nf, nm)+ dA = 10 * np.log10(fb @ np.abs(A) ** 2 + 1e-20)+ dB = 10 * np.log10(fb @ np.abs(B) ** 2 + 1e-20)+ fl = dA.max() - floor_db+ dA, dB = np.maximum(dA, fl), np.maximum(dB, fl)+ act = (dA > fl) | (dB > fl)+ out.append(float(np.mean(np.abs(dA - dB)[act])) if act.any() else 0.0)+ return float(np.mean(out)), out+++def env_corr(x, y, hop_ms=2.0, floor_db=60.0):+ """Pearson correlation of the two dB envelopes (hop_ms RMS, floored floor_db under x's peak)"""+ a, b = _mono(x), _mono(y)+ n = max(len(a), len(b))+ a, b = np.pad(a, (0, n - len(a))), np.pad(b, (0, n - len(b)))+ h = int(SR * hop_ms / 1000)+ k = n // h+ ea = 10 * np.log10((a[:k * h].reshape(k, h) ** 2).mean(1) + 1e-20)+ eb = 10 * np.log10((b[:k * h].reshape(k, h) ** 2).mean(1) + 1e-20)+ fl = ea.max() - floor_db+ ea, eb = np.maximum(ea, fl), np.maximum(eb, fl)+ if ea.std() < 1e-9 or eb.std() < 1e-9:+ return 0.0+ return float(np.corrcoef(ea, eb)[0, 1])+++def rise_ms(x):+ """onset sharpness: ms from 10 % to 90 % of the loudest peak of a 1 ms RMS envelope (0.125 ms hop), searched+ back over 30 ms"""+ m = _mono(x)+ w, h = 48, 6+ p = np.sqrt(np.convolve(m * m, np.ones(w) / w, mode='same'))[::h]+ i = int(np.argmax(p))+ lo = int(max(0, i - int(0.03 * SR / h)))+ seg = p[lo:i + 1]+ a = np.nonzero(seg >= 0.1 * p[i])[0]+ b = np.nonzero(seg >= 0.9 * p[i])[0]+ return float((b[0] - a[0]) * h / SR * 1000) if len(a) and len(b) else 0.0diff --git a/earshot/forge/fit/quality.py b/earshot/forge/fit/quality.pynew file mode 100644index 0000000..2645ebe--- /dev/null+++ b/earshot/forge/fit/quality.py@@ -0,0 +1,370 @@+"""How close is a resynthesis to its recording? One set of fit-quality metrics for every fitter.++ from earshot.forge.fit.quality import quality, floor, score, pair_png+ q = quality(original, resynth) # paths or 48 kHz arrays (mono or (n, 2))+ q['mel_db'], q['env_corr'], q['tone_db'], q['onset_err']+ q = quality(original, resynth, clap=True) # + q['clap_cos'] (loads the CLAP model once)+ fl = floor(lambda s: render(model, seed=s)) # quality(render seed 11, render seed 12): the noise floor+ pair_png('pair.png', original, resynth) # side-by-side spectrograms + envelopes + 1/3-octave balance++Metrics (both sounds mono-summed; the ORIGINAL's onset trims both by the same amount, so a timing error still counts;+each is levelled to its own loudest 50 ms RMS, so a level offset is reported apart as `level_db`):+ mel_db multi-resolution log-mel distance: 64 mel bands 30 Hz - 20 kHz, FFT frames 256 / 1024 / 4096 (hop 1/4),+ mean |dB| over the cells within 60 dB of the louder sound's top (floored 80 dB down), averaged over+ the three resolutions (mel_256 / mel_1024 / mel_4096 are reported too). 0 = identical spectrograms.+ env_corr correlation of the 5 ms dB envelopes over the active span (1 = the same loudness contour)+ attack_ms (original, resynth): the first onset (first 0.125 ms frame within 20 dB of the loudest) to its local+ peak (loudest frame in the next 10 ms)+ sharp_db_ms (original, resynth): onset sharpness, 17 dB / the time the first onset takes to rise from 20 dB to 3 dB+ under its local peak (independent of a floor or fade-in under the sound)+ onset_err |log2| of the sharpness ratio (octaves; 0 = the same onset, 1 = twice as sharp or blunt)+ tone_db earshot.forge.tone: RMS over 28 third-octave bands of the balance difference (dB)+ excess_db energy the resynthesis has where the recording is quiet (hiss, a noise floor, a ring that outlives it):+ mean dB above the original beyond 6 dB over third-octave band x 10 ms cells, looking 100 dB deep+ missing_db the same the other way (the original has it, the resynthesis does not)+ t40_ms (original, resynth): peak until the 5 ms envelope first falls 40 dB+ level_db resynth minus original, loudest 50 ms RMS (dB)+ clap_cos (clap=True) cosine of the two CLAP embeddings (1 = the same to CLAP; same-category real refs sit at+ 0.4-0.95 to each other)+ describe (describe=True) the top tag of `earshot describe` of each sound+`score(q)` folds them into one number for choosing between fits (lower is better). `floor(render_fn)` measures two+renders of one model with different seeds: a stochastic model can never beat that floor on mel_db.+Pure numpy (matplotlib only for pair_png; the CLAP / describe models only when asked).+"""+import os++import numpy as np++SR = 48000+FRAMES = (256, 1024, 4096)+N_MEL = 64+++def load(x):+ """a path -> (n, 2) float64 at 48 kHz (earshot.audio.load); an array is returned as float64 unchanged"""+ if isinstance(x, (str, os.PathLike)):+ from ... import audio+ return np.asarray(audio.load(str(x)), np.float64)+ return np.asarray(x, np.float64)+++def mono(x):+ x = np.asarray(x, np.float64)+ return x.mean(axis=1) if x.ndim == 2 else x+++def _db(p, floor=1e-20):+ return 10 * np.log10(np.maximum(p, floor))+++def peak_rms_db(x, win_s=0.05):+ """loudest `win_s` RMS (channel-mean power) in dB"""+ x = np.asarray(x, np.float64)+ p = (x ** 2).mean(1) if x.ndim == 2 else x ** 2+ k = max(1, int(win_s * SR))+ if len(p) < k:+ return float(_db(p.mean() if len(p) else 0.0))+ c = np.concatenate([[0.0], np.cumsum(p)])+ return float(_db(((c[k:] - c[:-k]) / k).max()))+++def onset_index(m, db=-30.0, hop=48):+ """first 1 ms frame within |db| of the loudest frame (sample index)"""+ nb = len(m) // hop+ if nb < 2:+ return 0+ e = _db((m[:nb * hop].reshape(nb, hop) ** 2).mean(1))+ return int(np.argmax(e > e.max() + db)) * hop+++_FB = {}+++def _mel_fb(n_fft, n_mel=N_MEL, f_lo=30.0, f_hi=20000.0):+ key = (n_fft, n_mel)+ if key not in _FB:+ mel = lambda f: 2595 * np.log10(1 + f / 700)+ imel = lambda m: 700 * (10 ** (m / 2595) - 1)+ pts = imel(np.linspace(mel(f_lo), mel(f_hi), n_mel + 2))+ f = np.fft.rfftfreq(n_fft, 1 / SR)+ fb = np.zeros((n_mel, len(f)))+ for i in range(n_mel):+ a, c, b = pts[i], pts[i + 1], pts[i + 2]+ fb[i] = np.clip(np.minimum((f - a) / (c - a), (b - f) / (b - c)), 0, None)+ if fb[i].sum() == 0:+ fb[i, int(np.argmin(np.abs(f - c)))] = 1.0+ _FB[key] = fb+ return _FB[key]+++def melspec(m, n_fft):+ """log-mel power (dB), frames x 64, hop n_fft / 4, Hann, centred"""+ hop = n_fft // 4+ T = max(1, (len(m) + hop - 1) // hop)+ win = np.hanning(n_fft + 2)[1:-1]+ xp = np.zeros(T * hop + n_fft)+ xp[n_fft // 2:n_fft // 2 + len(m)] = m+ fr = np.lib.stride_tricks.sliding_window_view(xp, n_fft)[::hop][:T]+ P = np.abs(np.fft.rfft(fr * win, axis=1)) ** 2+ return _db(P @ _mel_fb(n_fft).T + 1e-20)+++def env_db(m, ms=5.0):+ k = max(1, int(SR * ms / 1000))+ nb = max(1, len(m) // k)+ seg = m[:nb * k] if len(m) >= k else np.pad(m, (0, k - len(m)))+ return _db((seg.reshape(nb, k) ** 2).mean(1) + 1e-20)+++def attack(m):+ """(attack ms, sharpness dB/ms) of the FIRST onset on a 0.125 ms envelope: the onset = the first frame within 20 dB+ of the loudest; its local peak = the loudest frame in the 10 ms after; attack = onset -> local peak; sharpness =+ 17 dB / the time the rise takes from 20 dB to 3 dB under the local peak (a recording floor or a fade-in under the+ sound does not change it)"""+ fm = 0.125 # frame ms (6 samples); crossings interpolated inside frames+ e = env_db(m, fm)+ if len(e) < 4:+ return 0.0, 1.0+ on = int(np.argmax(e > e.max() - 20))+ p = on + int(np.argmax(e[on:on + int(10 / fm) + 1]))+ j = p+ while j > 0 and e[j] > e[p] - 20:+ j -= 1++ def cross(level): # first time (frames) after j the envelope reaches `level`+ k = j + int(np.argmax(e[j:p + 1] >= level))+ if k == j or e[k] == e[k - 1]:+ return float(k)+ return k - 1 + (level - e[k - 1]) / (e[k] - e[k - 1])+ rise_ms = max((cross(e[p] - 3) - cross(e[p] - 20)) * fm, 0.02)+ return float(fm * (p - on)), float(17.0 / rise_ms)+++def t40(m, db=40.0):+ e = env_db(m, 5.0)+ pk = int(np.argmax(e))+ below = np.nonzero(e[pk:] < e[pk] - db)[0]+ return float(5.0 * (below[0] if len(below) else len(e) - pk))+++def tone_db(a, b):+ from ..tone import profile+ return float(np.sqrt(np.mean((profile(a) - profile(b)) ** 2)))+++def _align(a, b):+ """mono a, b trimmed at a's onset (5 ms lead), each levelled to its loudest 50 ms RMS, zero-padded to one length"""+ A, B = mono(a), mono(b)+ on = max(0, onset_index(A) - int(0.005 * SR))+ A, B = A[on:], B[on:]+ A = A * 10 ** (-peak_rms_db(A) / 20)+ B = B * 10 ** (-peak_rms_db(B) / 20)+ n = max(len(A), len(B))+ return np.pad(A, (0, n - len(A))), np.pad(B, (0, n - len(B)))+++def mel_distance(a, b, frames=FRAMES, detail=False):+ A, B = _align(a, b)+ ds = {}+ for nf in frames:+ MA, MB = melspec(A, nf), melspec(B, nf)+ top = max(MA.max(), MB.max())+ MA, MB = np.maximum(MA, top - 80), np.maximum(MB, top - 80)+ act = np.maximum(MA, MB) > top - 60+ ds[nf] = float(np.abs(MA - MB)[act].mean()) if act.any() else 0.0+ d = float(np.mean(list(ds.values())))+ return (d, ds) if detail else d+++def env_corr(a, b):+ A, B = _align(a, b)+ ea, eb = env_db(A), env_db(B)+ top = max(ea.max(), eb.max())+ ea, eb = np.maximum(ea, top - 60), np.maximum(eb, top - 60)+ act = np.maximum(ea, eb) > top - 60+ if act.sum() <= 3 or np.std(ea[act]) < 1e-9 or np.std(eb[act]) < 1e-9:+ return 0.0+ return float(np.corrcoef(ea[act], eb[act])[0, 1])+++_BM = {}+++def bandgram(m, nfft=1024, hop=512):+ """third-octave band power (dB) per frame: the tone.CEN bands, the three lowest merged into 22-112 Hz"""+ from ..tone import CEN+ if nfft not in _BM:+ f = np.fft.rfftfreq(nfft, 1 / SR)+ M = np.stack([(f >= c / 2 ** (1 / 6)) & (f < c * 2 ** (1 / 6)) for c in CEN], 1).astype(float)+ M[:, :3] = 0.0+ M[(f >= 22) & (f < 112), 2] = 1.0+ _BM[nfft] = M+ T = max(1, (len(m) + hop - 1) // hop)+ xp = np.zeros(T * hop + nfft)+ xp[nfft // 2:nfft // 2 + len(m)] = m+ fr = np.lib.stride_tricks.sliding_window_view(xp, nfft)[::hop][:T]+ P = np.abs(np.fft.rfft(fr * np.hanning(nfft + 2)[1:-1], axis=1)) ** 2+ return _db(P @ _BM[nfft] + 1e-20)+++def excess(a, b, tol=6.0, depth=100.0):+ """(excess dB, missing dB): mean over the band x frame cells within `depth` - 10 dB of the top of how far b stands+ above a (excess) or below it (missing) beyond `tol` dB, both floored `depth` dB down. Excess is energy where the+ recording is quiet: a hiss band, a noise floor, a ring that outlives the original, 60-100 dB down where the mel+ and envelope measures stop looking; it tracks CLAP's verdicts on fits closely"""+ A, B = _align(a, b)+ EA, EB = bandgram(A), bandgram(B)+ top = max(EA.max(), EB.max())+ EA, EB = np.maximum(EA, top - depth), np.maximum(EB, top - depth)+ act = np.maximum(EA, EB) > top - depth + 10+ if not act.any():+ return 0.0, 0.0+ return (float(np.maximum(0.0, EB - EA - tol)[act].mean()), float(np.maximum(0.0, EA - EB - tol)[act].mean()))+++def quality(original, resynth, clap=False, describe=False):+ """the fit-quality metrics dict of a resynthesis against its original (module doc)"""+ xa, xb = load(original), load(resynth)+ a, b = mono(xa), mono(xb)+ d, ds = mel_distance(a, b, detail=True)+ q = {'mel_db': round(d, 3)}+ q.update({f'mel_{k}': round(v, 2) for k, v in ds.items()})+ q['env_corr'] = round(env_corr(a, b), 4)+ (aa, sa), (ab, sb) = attack(a), attack(b)+ q['attack_ms'] = (round(aa, 2), round(ab, 2))+ q['sharp_db_ms'] = (round(sa, 2), round(sb, 2))+ q['onset_err'] = round(abs(float(np.log2(sb / sa))), 3)+ q['tone_db'] = round(tone_db(a, b), 3)+ ex, mi = excess(a, b)+ q['excess_db'], q['missing_db'] = round(ex, 3), round(mi, 3)+ q['t40_ms'] = (round(t40(a), 1), round(t40(b), 1))+ q['level_db'] = round(peak_rms_db(xb) - peak_rms_db(xa), 2)+ q['len_s'] = (round(len(a) / SR, 4), round(len(b) / SR, 4))+ if clap:+ q['clap_cos'] = round(clap_cos(xa, xb), 4)+ if describe:+ q['describe'] = describe_pair(xa, xb)+ return q+++def score(q):+ """one number to choose between fits of one recording (lower is better): mel dB + 0.3 x tone dB+ + 8 x (1 - envelope r) + 1 x onset error (octaves, capped at 2) + 1.5 x excess dB + 1 x missing dB+ [+ 20 x (1 - CLAP cos) when measured]. On the 12 validation refs (in-sample) the model-free part alone chose fits+ with a mean CLAP cos of 0.927 (the best candidates: 0.944); without excess / missing it chose 0.856"""+ s = (q['mel_db'] + 0.3 * q['tone_db'] + 8.0 * (1.0 - q['env_corr']) + 1.0 * min(q['onset_err'], 2.0)+ + 1.5 * q.get('excess_db', 0.0) + 1.0 * q.get('missing_db', 0.0))+ if q.get('clap_cos') is not None:+ s += 20.0 * (1.0 - q['clap_cos'])+ return float(s)+++def floor(render_fn, seeds=(11, 12), clap=False):+ """quality(render_fn(seeds[0]), render_fn(seeds[1])): what two takes of one stochastic model differ by"""+ return quality(render_fn(seeds[0]), render_fn(seeds[1]), clap=clap)+++# ----------------------------------------------------------------------------------------- model-based checks+def clap_embed(arrays):+ from ...models import clap as _clap+ return _clap.get().embed_audio([mono(load(x)).astype(np.float32) for x in arrays])+++def clap_cos(a, b):+ E = clap_embed([a, b])+ return float(E[0] @ E[1])+++def describe_pair(a, b):+ """the top `earshot describe` tag (term, z) and AudioSet label of each sound (writes temp WAVs)"""+ import tempfile++ import soundfile as sf++ from ...describe import describe as _describe+ out = {}+ with tempfile.TemporaryDirectory() as td:+ for key, x in (('original', a), ('resynth', b)):+ p = os.path.join(td, f'{key}.wav')+ sf.write(p, np.asarray(load(x), np.float32), SR, subtype='FLOAT')+ r = _describe(p)+ top = (r.get('top_tags') or [{}])[0]+ ast = (r.get('audioset') or [{}])[0]+ out[key] = {'tag': top.get('term'), 'z': None if top.get('z') is None else round(float(top['z']), 2),+ 'audioset': ast.get('label'), 'p': None if ast.get('p') is None else round(float(ast['p']), 2),+ 'tags3': [t.get('term') for t in (r.get('top_tags') or [])[:3]]}+ return out+++def text(q, fl=None):+ """one readable line of a quality dict (and its floor)"""+ s = (f"mel {q['mel_db']:.2f} dB" + (f" (floor {fl['mel_db']:.2f})" if fl else '')+ + f", env r {q['env_corr']:.3f}, tone {q['tone_db']:.2f} dB, onset err {q['onset_err']:.2f} oct "+ f"(sharpness {q['sharp_db_ms'][0]:.1f} vs {q['sharp_db_ms'][1]:.1f} dB/ms), "+ f"excess {q.get('excess_db', 0):.2f} / missing {q.get('missing_db', 0):.2f} dB, "+ f"t40 {q['t40_ms'][0]:.0f} vs {q['t40_ms'][1]:.0f} ms, level {q['level_db']:+.2f} dB")+ if q.get('clap_cos') is not None:+ s += f", CLAP cos {q['clap_cos']:.3f}"+ if q.get('describe'):+ d = q['describe']+ s += f"; describe: '{d['original']['tag']}' vs '{d['resynth']['tag']}'"+ return s+++# -------------------------------------------------------------------------------------------------- picture+def _spec_db(m, n_fft=1024, hop=128):+ T = max(1, (len(m) + hop - 1) // hop)+ win = np.hanning(n_fft + 2)[1:-1]+ xp = np.zeros(T * hop + n_fft)+ xp[n_fft // 2:n_fft // 2 + len(m)] = m+ fr = np.lib.stride_tricks.sliding_window_view(xp, n_fft)[::hop][:T]+ return _db(np.abs(np.fft.rfft(fr * win, axis=1)) ** 2).T+++def pair_png(path, original, resynth, title=None, q=None, extra=None):+ """side-by-side picture: spectrogram of the original | the resynthesis (| `extra` = (label, array)), same dB+ range, log frequency; below, both 5 ms envelopes and both third-octave balances"""+ import matplotlib+ matplotlib.use('Agg')+ import matplotlib.pyplot as plt+ from ..tone import CEN, profile+ a, b = mono(load(original)), mono(load(resynth))+ cols = [('original', a), ('resynthesis', b)] + ([(extra[0], mono(load(extra[1])))] if extra else [])+ n = max(len(c[1]) for c in cols)+ fig = plt.figure(figsize=(4.4 * len(cols), 6.2))+ gs = fig.add_gridspec(2, len(cols), height_ratios=[2.2, 1.0])+ S = [_spec_db(np.pad(c[1], (0, n - len(c[1])))) for c in cols]+ top = max(s.max() for s in S)+ f = np.fft.rfftfreq(1024, 1 / SR)+ t = np.arange(S[0].shape[1]) * 128 / SR+ for i, ((lab, _), s) in enumerate(zip(cols, S)):+ ax = fig.add_subplot(gs[0, i])+ ax.pcolormesh(t, np.maximum(f, 20), s, vmin=top - 90, vmax=top, cmap='magma', shading='auto')+ ax.set_yscale('log')+ ax.set_ylim(40, 22000)+ ax.set_title(lab, fontsize=9)+ ax.set_xlabel('s', fontsize=8)+ ax.tick_params(labelsize=7)+ ax = fig.add_subplot(gs[1, :max(1, len(cols) - 1)])+ for lab, c in cols:+ e = env_db(np.pad(c, (0, n - len(c))))+ ax.plot(np.arange(len(e)) * 0.005, e, lw=0.9, label=lab)+ ax.set_ylim(max(-120, ax.get_ylim()[1] - 80), ax.get_ylim()[1] + 3)+ ax.set_xlabel('s', fontsize=8)+ ax.set_ylabel('dB (5 ms)', fontsize=8)+ ax.legend(fontsize=7)+ ax.tick_params(labelsize=7)+ ax2 = fig.add_subplot(gs[1, -1])+ for lab, c in cols:+ ax2.semilogx(CEN, profile(c), lw=0.9, label=lab)+ ax2.set_xlabel('Hz (1/3 octave)', fontsize=8)+ ax2.set_ylabel('dB of total', fontsize=8)+ ax2.tick_params(labelsize=7)+ if q is not None:+ title = (title + '\n' if title else '') + text(q)+ if title:+ fig.suptitle(title, fontsize=8)+ fig.tight_layout()+ fig.savefig(path, dpi=110)+ plt.close(fig)+ return pathdiff --git a/earshot/forge/fit/sines.py b/earshot/forge/fit/sines.pynew file mode 100644index 0000000..e3641ee--- /dev/null+++ b/earshot/forge/fit/sines.py@@ -0,0 +1,1144 @@+"""Sines fitter: a recording of a tonal / pitched sound -> a small JSON model -> a close re-render, or Python code.++ from earshot.forge.fit import sines+ m = sines.fit('ding.wav') # or a 48 kHz array (mono or (n, 2))+ y = sines.render(m) # the re-render (mono, 48 kHz, same level and timing)+ y = sines.render(m, seed=3, knobs={'transpose': 2, 'decay': 1.4, 'vary': 0.3}) # a new variation+ src = sines.to_code(m, name='ding') # standalone numpy code that renders the same sound+ print(sines.describe(m)) # 'strike at 12 ms, 23 partials 523-9870 Hz, ...'++Analysis by synthesis in the McAulay-Quatieri / SMS tradition, with no harmonic series forced on the sound:+ 1. STFT peaks: zero-phase Blackman frames, x2 zero padding, local maxima that stand out from the local spectrum,+ frequency and amplitude by parabolic interpolation on the dB magnitude, phase at the peak.+ 2. Partial tracking: peaks joined frame to frame to the nearest predicted frequency (last frequency + slope, so+ chirps and glides track), births for unmatched peaks, deaths after a gap; short or quiet tracks are dropped and+ the strongest `max_partials` kept. Inharmonic partials (bells, bars, glass, kalimba tines) keep their own+ frequencies; doublet beating lives in the amplitude trajectory.+ 3. Onsets: a long window smears a strike backwards by half a window (a soft pre-echo attack). Strikes are found on+ a 1 ms band envelope; a partial born near one starts exactly at the strike with the measured rise, and its+ smeared first frames are replaced by the decay line extrapolated back from the first clean frames.+ A track is kept only if it stands well above the local median spectrum (a chain of noise peaks does not), and a+ second pass tracks the residual for partials hidden under stronger ones (doublet partners, weak highs).+ 4. Residual: the partials are re-synthesised phase-accurately (cubic phase interpolation between frames) and+ subtracted. At each strike the residual's first ms become damped sinusoids (matrix pencil: a 6-8 ms window above+ 400 Hz for the click, a 64 ms window below for the body thump), kept only if they explain the strike. What is+ left (breath, hiss, scrape, the recording's own noise floor, which CLAP and ears both notice when it is missing)+ is noise in 1/3-octave bands with dB envelopes on one shared adaptive time grid (dense around the attack, sparse+ in the tail); a band's level counts only its noise-like part (median of its STFT bins), so leftover partial+ energy never turns into hiss.+ 5. Compression: every partial's frequency (cents) and amplitude (dB) trajectories become breakpoints (Ramer-Douglas-+ Peucker with a vertical tolerance), the residual grid likewise.+ 6. Window choice by analysis-by-synthesis: the sound is fitted at several window sizes (short for chirps and pops,+ long for close bell partials) and the model whose re-render is spectrally closest to the recording is kept.++Model (plain JSON-serialisable dict):+ {'kind': 'sines', 'version': 1, 'sr': 48000, 'duration': s, 'onset': s (first strike), 'onsets': [s, ...],+ 'partials': [{'t0': birth s, 'rise': s, 't1': last breakpoint s, 'rel': release s, 'ph': phase at t0 (rad),+ 'freq': [[t, Hz], ...], 'amp': [[t, dBFS], ...]}, ...] (strongest first)+ 'transients': [{'t': start s, 'atoms': [[f Hz, tau s, amplitude, phase], ...]}, ...] (one per strike)+ 'residual': {'bands': [Hz centres, 1/3 octave], 'times': [s, ...], 'db': [[dBFS per time] per band]},+ 'width': side/mid energy of the source in dB (stereo renders), 'analysis': {...}, 'summary': {...}}+The residual bands are triangles on log frequency that sum to one; a band's dB is the RMS of the band-passed residual.++render(model, seed, knobs) knobs (all default to the identity, which re-renders the fit):+ transpose (semitones; every partial and the residual's spectrum move together, relative partials kept),+ stretch (time factor about the first strike; attacks keep their rise), decay (factor on every decay after its+ peak, frequency trajectories keep their timing), brightness (dB per octave about the partials' centroid),+ vibrato (cents) + vibrato_rate (Hz), drift (cents of slow random wander), residual (gain on the noise),+ transient (gain on the noise in the first 15 ms after each strike), vary (0-1: seeded per-partial detune,+ level and decay jitter, band jitter: new takes of the same object), partials (keep the N strongest),+ inharm (stretch of partial ratios about the lowest strong partial: f/f_low -> (f/f_low)^(1+inharm)),+ phases ('fit' or 'random'), gain_db, stereo (False: mono; True: (n, 2) with the residual decorrelated by width).++Deterministic: render(model, seed, knobs) is a pure function (the noise and every jitter come from `seed`).+Pure numpy / scipy; no recorded audio is stored in a model, only parameters.+"""+import inspect+import json++import numpy as np+from scipy import signal+from scipy.ndimage import median_filter, uniform_filter1d++SR = 48000+KIND = 'sines'+VERSION = 1+WINDOWS = (512, 1024, 2048, 4096)++DEFAULT_KNOBS = {'transpose': 0.0, 'stretch': 1.0, 'decay': 1.0, 'brightness': 0.0, 'vibrato': 0.0,+ 'vibrato_rate': 5.5, 'drift': 0.0, 'residual': 1.0, 'transient': 1.0, 'vary': 0.0, 'partials': None,+ 'inharm': 0.0, 'phases': 'fit', 'gain_db': 0.0, 'stereo': False}+++# ================================================================================================ small helpers+def _load(x, sr=SR):+ """(mono float64 signal, side/mid dB) from a path or an array (mono or (n, 2))"""+ if isinstance(x, str):+ from ... import audio+ x = audio.load(x, sr=SR)+ sr = SR+ x = np.asarray(x, np.float64)+ width = -120.0+ if x.ndim == 2:+ if x.shape[1] == 2:+ mid, side = x.mean(1), (x[:, 0] - x[:, 1]) / 2+ width = float(10 * np.log10((side ** 2).sum() / ((mid ** 2).sum() + 1e-20) + 1e-12))+ x = mid+ else:+ x = x.mean(1)+ if sr != SR:+ from math import gcd+ g = gcd(int(sr), SR)+ x = signal.resample_poly(x, SR // g, int(sr) // g)+ return x, max(width, -120.0)+++def _db(v, floor=-200.0):+ return np.maximum(20 * np.log10(np.abs(v) + 1e-20), floor)+++def _simplify(t, v, tol, max_pts=None):+ """indices of breakpoints whose linear interpolation stays within `tol` (vertical; a scalar or one per point) of v+ (Ramer-Douglas-Peucker); the tolerance grows until there are at most `max_pts` points"""+ t = np.asarray(t, float)+ v = np.asarray(v, float)+ n = len(t)+ if n <= 2:+ return np.arange(n)+ while True:+ keep = np.zeros(n, bool)+ keep[[0, n - 1]] = True+ stack = [(0, n - 1)]+ while stack:+ i, j = stack.pop()+ if j <= i + 1:+ continue+ seg = v[i] + (v[j] - v[i]) * (t[i + 1:j] - t[i]) / max(t[j] - t[i], 1e-12)+ err = np.abs(v[i + 1:j] - seg) / (tol[i + 1:j] if np.ndim(tol) else tol)+ k = int(np.argmax(err))+ if err[k] > 1.0:+ m = i + 1 + k+ keep[m] = True+ stack += [(i, m), (m, j)]+ idx = np.nonzero(keep)[0]+ if max_pts is None or len(idx) <= max_pts:+ return idx+ tol = tol * 1.4+++def _simplify_multi(t, V, tol, max_pts=None):+ """like _simplify for several rows sharing one time grid: a point is added where any row's error exceeds tol"""+ t = np.asarray(t, float)+ V = np.asarray(V, float)+ n = len(t)+ if n <= 2:+ return np.arange(n)+ while True:+ keep = np.zeros(n, bool)+ keep[[0, n - 1]] = True+ stack = [(0, n - 1)]+ while stack:+ i, j = stack.pop()+ if j <= i + 1:+ continue+ fr = (t[i + 1:j] - t[i]) / max(t[j] - t[i], 1e-12)+ seg = V[:, i:i + 1] + (V[:, j:j + 1] - V[:, i:i + 1]) * fr[None, :]+ err = np.abs(V[:, i + 1:j] - seg).max(axis=0)+ k = int(np.argmax(err))+ if err[k] > tol:+ m = i + 1 + k+ keep[m] = True+ stack += [(i, m), (m, j)]+ idx = np.nonzero(keep)[0]+ if max_pts is None or len(idx) <= max_pts:+ return idx+ tol *= 1.3+++def _band_centers(lo=50.0, hi=16000.0, per_oct=3):+ k = int(round(np.log2(hi / lo) * per_oct))+ return lo * 2.0 ** (np.arange(k + 1) / per_oct)+++# ================================================================================================ synthesis kernels+# These three functions are copied verbatim into to_code() output: keep them self-contained (numpy only, SR global).+def band_masks(centers, nfft, sr=48000):+ """triangles on log frequency, one per band centre, that sum to one at every frequency (flat beyond the ends)"""+ f = np.fft.rfftfreq(nfft, 1.0 / sr)+ lf = np.log2(np.maximum(f, 1.0))+ lc = np.log2(np.asarray(centers, float))+ eye = np.eye(len(lc))+ return np.array([np.interp(lf, lc, eye[b]) for b in range(len(lc))])+++def synth_partials(partials, n, sr=48000, cents=None):+ """sum of sinusoids: each partial follows its frequency breakpoints [[t, Hz]] (linear in log frequency) and+ amplitude breakpoints [[t, dB]] (linear in dB), starts at t0 with a linear rise and ends at t1 with a linear+ release; `cents` (optional array of n) bends every partial's pitch together (vibrato, drift)"""+ y = np.zeros(n)+ for p in partials:+ i0 = max(0, int(np.floor(p['t0'] * sr)))+ i1 = min(n, int(np.ceil((p['t1'] + p['rel']) * sr)) + 1)+ if i1 <= i0 + 1:+ continue+ t = np.arange(i0, i1) / sr+ fq = np.asarray(p['freq'], float)+ am = np.asarray(p['amp'], float)+ f = 2.0 ** np.interp(t, fq[:, 0], np.log2(fq[:, 1]))+ if cents is not None:+ f = f * 2.0 ** (cents[i0:i1] / 1200.0)+ a = 10.0 ** (np.interp(t, am[:, 0], am[:, 1]) / 20.0)+ a *= np.clip((t - p['t0']) / max(p['rise'], 1e-5), 0.0, 1.0)+ a *= np.clip((p['t1'] + p['rel'] - t) / max(p['rel'], 1e-5), 0.0, 1.0)+ a[f >= 0.5 * sr * 0.98] = 0.0+ ph = p['ph'] + 2 * np.pi * (np.cumsum(f) - f[0]) / sr + 2 * np.pi * f[0] * (i0 / sr - p['t0'])+ y[i0:i1] += a * np.cos(ph)+ return y+++def synth_noise(bands, times, levels, n, seed=0, sr=48000, pad=4096):+ """noise shaped by band envelopes: white noise split by band_masks(), each band at unit RMS times its dB envelope+ (levels[b] at `times`, linear in dB between them)"""+ r = np.random.default_rng(int(seed) & 0xFFFFFFFF)+ nfft = 1 << int(np.ceil(np.log2(n + 2 * pad)))+ spec = np.fft.rfft(r.standard_normal(nfft))+ masks = band_masks(bands, nfft, sr)+ t = np.arange(n) / sr+ y = np.zeros(n)+ for b in range(len(bands)):+ lv = np.asarray(levels[b], float)+ if lv.max() < -140:+ continue+ u = np.fft.irfft(spec * masks[b], nfft)[pad:pad + n]+ u /= np.sqrt(np.mean(u ** 2)) + 1e-20+ y += u * 10.0 ** (np.interp(t, times, lv) / 20.0)+ return y+++def synth_atoms(transients, n, sr=48000):+ """strike transients: each a start time and damped sinusoids [f Hz, tau s, amp, phase] that start at full+ amplitude (a click is a burst of very short modes)"""+ y = np.zeros(n)+ for tr in transients:+ i0 = int(round(tr['t'] * sr))+ for f, tau, a, ph in tr['atoms']:+ m = min(n - max(i0, 0), int(7 * tau * sr) + 1)+ if m <= 0:+ continue+ k = np.arange(m) + max(0, -i0)+ y[max(i0, 0):max(i0, 0) + m] += a * np.exp(-k / (tau * sr)) * np.cos(2 * np.pi * f * k / sr + ph)+ return y+++# ================================================================================================ analysis+def _pencil(y, sr=SR, max_atoms=24, energy=0.998, max_t60=0.02, clamp=True, ridge=1e-4):+ """damped sinusoids [f, tau, amp, phase] that rebuild the segment y (matrix pencil poles, real least squares)"""+ L = len(y)+ if L < 16 or not np.any(y):+ return []+ P = L // 3+ Y = np.lib.stride_tricks.sliding_window_view(y, P + 1)+ _, sv, Vh = np.linalg.svd(Y, full_matrices=False)+ cum = np.cumsum(sv ** 2) / (np.sum(sv ** 2) + 1e-30)+ M = int(min(2 * max_atoms, np.searchsorted(cum, energy) + 1, len(sv) - 1))+ V = Vh[:M].T+ z = np.linalg.eigvals(np.linalg.pinv(V[:-1]) @ V[1:])+ z = z[np.angle(z) >= -1e-9] # one of each conjugate pair+ zmax = 10 ** (-3.0 / (max_t60 * sr))+ if clamp: # long modes are shortened to max_t60+ z = np.where(np.abs(z) > zmax, z / np.abs(z) * zmax, z)+ else: # or dropped: only modes that die inside the window+ z = z[np.abs(z) <= zmax]+ z = z[np.abs(z) > 1e-3]+ mag = np.abs(z)+ w = np.abs(np.angle(z))+ # dedupe near-identical poles+ order = np.argsort(w)+ w, mag = w[order], mag[order]+ keep = np.ones(len(w), bool)+ for i in range(1, len(w)):+ if abs(w[i] - w[i - 1]) < 1e-4 and abs(mag[i] - mag[i - 1]) < 1e-3:+ keep[i] = False+ w, mag = w[keep], mag[keep]+ k = np.arange(L)+ cols, meta = [], []+ for wi, mi in zip(w, mag):+ d = mi ** k+ if wi < 1e-6 or wi > np.pi - 1e-6:+ cols.append(d * np.cos(wi * k))+ meta.append((wi, mi, 'r'))+ else:+ cols += [d * np.cos(wi * k), d * np.sin(wi * k)]+ meta += [(wi, mi, 'c'), None]+ if not cols:+ return []+ B = np.array(cols).T+ lam = ridge * np.trace(B.T @ B) / B.shape[1] # a little ridge: no huge cancelling pairs+ coef = np.linalg.solve(B.T @ B + lam * np.eye(B.shape[1]), B.T @ y)+ atoms, j = [], 0+ for m in meta:+ if m is None:+ j += 1+ continue+ wi, mi, kind = m+ if kind == 'r':+ a, ph = coef[j], 0.0+ if a < 0:+ a, ph = -a, np.pi+ j += 1+ else:+ c, s_ = coef[j], coef[j + 1]+ a, ph = np.hypot(c, s_), np.arctan2(-s_, c)+ j += 1+ tau = -1.0 / (sr * np.log(mi))+ atoms.append([wi * sr / (2 * np.pi), tau, a, ph])+ atoms.sort(key=lambda q: -q[2] ** 2 * q[1])+ return atoms[:max_atoms]+++def _transients(res, onsets, sr, peak, pre=0.0005, rel_db=-40.0, max_strikes=16, split=400.0):+ """matrix-pencil atoms for the residual at each strike whose residual is not negligible, in two bands: above+ `split` Hz a 6 ms window at the full rate (the click), below it a 60 ms window at 1/8 rate (the body thump)"""+ sos = signal.butter(4, split, 'low', fs=sr, output='sos')+ lo = signal.sosfiltfilt(sos, res)+ hi = res - lo+ D = 8+ out = []+ for o in sorted(onsets, key=lambda o: -o['strength'])[:max_strikes]:+ i0 = max(0, int(round((o['t'] - pre) * sr)))+ atoms = []+ for band, win, rate, na, kw, ok in (+ (hi, 0.008, 1, 24, {'max_t60': 0.02, 'clamp': True}, lambda f: f >= 0.6 * split),+ (lo, 0.064, D, 6, {'max_t60': 0.096, 'clamp': False, 'ridge': 1e-3}, lambda f: 40.0 <= f <= 1.5 * split)):+ seg = band[i0:i0 + int(win * sr)]+ if len(seg) < 32 or np.abs(seg).max() < peak * 10 ** (rel_db / 20):+ continue+ got = [q for q in _pencil(seg[::rate], sr / rate, max_atoms=na, **kw) if ok(q[0])]+ if not got:+ continue+ # keep them only if they explain the strike (analysis by synthesis): the residual energy must drop over+ # the window and the ring-out after it (atoms must not add energy where the recording has none)+ ext = band[i0:i0 + int((win * 2 + 0.02) * sr)]+ fit_ = synth_atoms([{'t': 0.0, 'atoms': got}], len(ext), sr)+ if ((ext - fit_) ** 2).sum() < 0.7 * (ext ** 2).sum():+ atoms += got+ if atoms:+ out.append({'t': round(i0 / sr, 6),+ 'atoms': [[round(f, 2), round(tau, 7), round(a, 7), round(ph, 4)] for f, tau, a, ph in atoms]})+ out.sort(key=lambda t: t['t'])+ return out+++def _frames(x, W, hop):+ """zero-phase windowed frames centred at k * hop (k = 0..K-1), x2 zero padded rfft: (spectrum, K, N)"""+ n = len(x)+ K = n // hop + 2+ xp = np.concatenate([np.zeros(W // 2), x, np.zeros(W // 2 + 2 * hop)])+ fr = np.lib.stride_tricks.sliding_window_view(xp, W)[::hop][:K]+ w = signal.get_window('blackman', W)+ N = 2 * W+ buf = np.zeros((len(fr), N))+ h = W // 2+ buf[:, :W - h] = fr[:, h:] * w[h:]+ buf[:, N - h:] = fr[:, :h] * w[:h]+ return np.fft.rfft(buf, axis=1), w.sum(), N+++def _peaks(X, wsum, N, sr, dyn_db=80.0, prom_db=6.0, max_peaks=60, fmin=30.0, ref_db=None):+ """per frame: arrays (freq Hz, amp linear, phase) of the spectral peaks that pass the thresholds (dyn_db under+ the loudest bin, or under `ref_db` when given: a residual pass keeps the original's reference)"""+ mag = np.abs(X)+ db = _db(mag)+ gmax = db.max() if ref_db is None else ref_db+ pw = mag ** 2+ local = 10 * np.log10(np.maximum(uniform_filter1d(pw, size=33, axis=1, mode="nearest"), 0) + 1e-40)+ is_pk = np.zeros_like(db, bool)+ is_pk[:, 1:-1] = (db[:, 1:-1] > db[:, :-2]) & (db[:, 1:-1] >= db[:, 2:])+ fmax_row = db.max(axis=1, keepdims=True)+ ok = is_pk & (db > gmax - dyn_db) & (db > fmax_row - dyn_db) & (db > local + prom_db)+ kmin = int(np.ceil(fmin * N / sr))+ ok[:, :kmin] = False+ ok[:, -2:] = False+ phase = np.angle(X)+ # the local noise floor: the median of blocks of 32 bins, interpolated (narrow peaks do not move a median)+ B = 32+ nb_ = db.shape[1] // B+ med = np.median(db[:, :nb_ * B].reshape(len(db), nb_, B), axis=2)+ cen_ = np.arange(nb_) * B + B / 2+ floor = np.array([np.interp(np.arange(db.shape[1]), cen_, row) for row in med])+ out = []+ for k in range(len(db)):+ b = np.nonzero(ok[k])[0]+ if len(b) > max_peaks:+ b = b[np.argsort(db[k, b])[::-1][:max_peaks]]+ b.sort()+ if not len(b):+ out.append((np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0)))+ continue+ a, c, e = db[k, b - 1], db[k, b], db[k, b + 1]+ den = a - 2 * c + e+ p = np.where(np.abs(den) > 1e-12, 0.5 * (a - e) / np.where(np.abs(den) > 1e-12, den, 1.0), 0.0)+ p = np.clip(p, -0.5, 0.5)+ f = (b + p) * sr / N+ amp = 10 ** ((c - 0.25 * (a - e) * p) / 20) * 2.0 / wsum+ nb = np.where(p >= 0, b + 1, b - 1)+ d = np.angle(np.exp(1j * (phase[k, nb] - phase[k, b])))+ ph = phase[k, b] + np.abs(p) * d+ out.append((f, amp, ph, c - floor[k, b]))+ return out+++def _sinusoidal(tr, W, sr, snr_db=10.0):+ """is this track a partial (not a chain of noise peaks)? A noise peak stands only ~5-9 dB above the median of+ its neighbourhood (an exponential power distribution almost never reaches 16x its median); a partial, even a+ short chirpy one in a pop, stands 15-50 dB above it. Energy-weighted over the track."""+ a2 = tr['a'] ** 2+ return float((a2 * tr['c']).sum() / (a2.sum() + 1e-30)) >= snr_db+++def _track(peaks, hop, sr, W, max_gap=2, rel_tol=0.025):+ """join peaks into partial tracks; returns a list of dicts with contiguous frame arrays k (frame index), f, a, ph"""+ df_min = 1.5 * sr / W+ active, done = [], []+ for k, (fs, amps, phs, cvs) in enumerate(peaks):+ used = np.zeros(len(fs), bool)+ if active and len(fs):+ pred = np.array([t['f'][-1] + t['slope'] * (k - t['k'][-1]) for t in active])+ tol = np.maximum(df_min, rel_tol * pred)+ D = np.abs(fs[None, :] - pred[:, None])+ lastdb = np.array([20 * np.log10(t['a'][-1] + 1e-20) for t in active])+ cost = D / tol[:, None] + 0.01 * np.abs(_db(amps)[None, :] - lastdb[:, None])+ cost[D > tol[:, None]] = np.inf+ ti, pi = np.nonzero(np.isfinite(cost))+ order = np.argsort(cost[ti, pi])+ took = np.zeros(len(active), bool)+ for o in order:+ a_, p_ = ti[o], pi[o]+ if took[a_] or used[p_]:+ continue+ took[a_] = used[p_] = True+ t = active[a_]+ gap = k - t['k'][-1]+ if len(t['f']) >= 2 or gap > 1:+ s = (fs[p_] - t['f'][-1]) / gap+ t['slope'] = 0.5 * t['slope'] + 0.5 * s if len(t['f']) >= 2 else s+ t['k'].append(k)+ t['f'].append(fs[p_])+ t['a'].append(amps[p_])+ t['ph'].append(phs[p_])+ t['c'].append(cvs[p_])+ keep = []+ for i, t in enumerate(active):+ if not took[i] and k - t['k'][-1] > max_gap:+ done.append(t)+ else:+ keep.append(t)+ active = keep+ elif active:+ keep = []+ for t in active:+ (done if k - t['k'][-1] > max_gap else keep).append(t)+ active = keep+ for p_ in np.nonzero(~used)[0]:+ active.append({'k': [k], 'f': [fs[p_]], 'a': [amps[p_]], 'ph': [phs[p_]], 'c': [cvs[p_]], 'slope': 0.0})+ done += active+ out = []+ for t in done:+ k = np.array(t['k'])+ kk = np.arange(k[0], k[-1] + 1)+ f = np.interp(kk, k, t['f'])+ a = np.interp(kk, k, t['a'])+ cv = np.interp(kk, k, t['c'])+ ph = np.zeros(len(kk))+ ph[k - k[0]] = t['ph']+ have = np.zeros(len(kk), bool)+ have[k - k[0]] = True+ for j in np.nonzero(~have)[0]: # across a gap: integrate the interpolated frequency (gaps are short)+ ph[j] = ph[j - 1] + 2 * np.pi * 0.5 * (f[j - 1] + f[j]) * hop / sr+ out.append({'k': kk, 'f': f, 'a': a, 'ph': ph, 'c': cv})+ return out+++def _band_env(x, sr, centers, hop_s=0.001, max_smooth=0.030):+ """per band: dB envelope (RMS of the band-passed signal, smoothed for its bandwidth) at `hop_s` steps"""+ n = len(x)+ pad = 4096+ nfft = 1 << int(np.ceil(np.log2(n + 2 * pad)))+ spec = np.fft.rfft(np.concatenate([np.zeros(pad), x, np.zeros(nfft - n - pad)]))+ masks = band_masks(centers, nfft, sr)+ step = max(1, int(round(hop_s * sr)))+ idx = np.arange(0, n, step)+ env = np.zeros((len(centers), len(idx)))+ bw = centers * (2 ** (1 / 3) - 2 ** (-1 / 3))+ for b in range(len(centers)):+ v = np.fft.irfft(spec * masks[b], nfft)[pad:pad + n]+ L = max(2, int(np.clip(4.0 / bw[b], 0.0005, max_smooth) * sr))+ c = np.concatenate([[0.0], np.cumsum(v ** 2)])+ j = np.arange(n)+ trail = (c[j + 1] - c[np.maximum(j + 1 - L, 0)]) / L # mean over (t - L, t]+ lead = (c[np.minimum(j + L, n)] - c[j]) / L # mean over [t, t + L)+ pw = np.minimum(trail, lead) # edges stay sharp: no smear before a strike+ env[b] = 10 * np.log10(pw[idx] + 1e-24)+ return idx / sr, env+++def _peak_env(x, sr, hold=0.0025):+ """causal peak envelope in dB: max |x| over the trailing `hold` seconds (rises exactly at a strike)"""+ from scipy.ndimage import maximum_filter1d+ L = max(1, int(hold * sr))+ e = maximum_filter1d(np.abs(x), size=L, origin=(L - 1) // 2, mode='constant')+ return _db(e, -240.0)+++def _onsets(x, sr, thresh_db=6.0, min_gap=0.025):+ """strikes as dicts {'t' (s), 'rise' (s), 'strength'}: detected where the mean positive rise of 1 ms octave-band+ envelopes (each against its own minimum of the previous 8 ms) peaks above `thresh_db`, then timed on the causal+ peak envelope (the strike starts where it leaves its pre-strike floor; the rise ends 1 dB under the peak)"""+ cen = _band_centers(150.0, 12000.0, per_oct=1)+ t, env = _band_env(x, sr, cen, 0.001, max_smooth=0.008)+ top = env.max()+ env = np.maximum(env, top - 70)+ tot = 10 * np.log10((10 ** (env / 10)).sum(0) + 1e-24)+ w = 5+ pad = np.concatenate([np.repeat(env[:, :1], w, axis=1), env], axis=1)+ mins = np.min(np.stack([pad[:, j:j + env.shape[1]] for j in range(w)]), axis=0)+ rise = np.clip(env - mins, 0, None)+ loud = env > top - 60+ O = (rise * loud).sum(0) / np.maximum(loud.sum(0), 1)+ O[tot < top - 45] = 0+ O[((rise > thresh_db) & loud).sum(0) < 3] = 0 # a strike is broadband; a beating partial is not+ peaks, _ = signal.find_peaks(O, height=thresh_db, distance=max(1, int(min_gap / 0.001)))+ on_first = int(np.argmax(tot > tot.max() - 25))+ cands = sorted(set(peaks.tolist()) | {on_first})+ pe = _peak_env(x, sr)+ ms = sr // 1000+ out = []+ for i in cands:+ c = int(t[i] * sr)+ lo = max(0, c - 25 * ms)+ hi = min(len(x), c + 30 * ms)+ if hi - lo < 2:+ continue+ seg = pe[lo:hi]+ ipk = int(np.argmax(seg[max(0, c - 8 * ms - lo):])) + max(0, c - 8 * ms - lo)+ pk = float(seg[ipk])+ base = max(float(seg[:ipk + 1].min()), pk - 70.0)+ if pk - base < 3.0 and i != on_first:+ continue+ ib = int(np.argmin(seg[:ipk + 1]))+ thr = max(base + 0.25 * (pk - base), pk - 30.0)+ st = ib + int(np.argmax(seg[ib:ipk + 1] >= thr))+ ir = st + int(np.argmax(seg[st:ipk + 1] >= pk - 1.0))+ out.append({'t': float((lo + st) / sr), 'rise': float(max(3e-4, (ir - st) / sr)),+ 'strength': float(O[i]) if i in set(peaks.tolist()) else float(pk - base)})+ merged = []+ for o in sorted(out, key=lambda o: o['t']):+ if merged and o['t'] - merged[-1]['t'] < min_gap:+ if o['strength'] > merged[-1]['strength']:+ merged[-1] = o+ continue+ merged.append(o)+ return merged+++def _split_at_strikes(tracks, onsets, W, hop, sr, jump_db=10.0, min_frames=3):+ """a track that jumps up by `jump_db` across a strike is two sounds (pre-strike junk or the previous strike's+ ring, then the new strike): cut it there, so the new part can start exactly at the strike"""+ half = W / 2 / sr+ out = []+ for tr in tracks:+ parts = [tr]+ for o in sorted(onsets, key=lambda o: o['t']):+ cur = parts[-1]+ times = cur['k'] * hop / sr+ if not (times[0] < o['t'] - 0.5 * half and times[-1] > o['t'] + 0.55 * half):+ continue+ adb = 20 * np.log10(cur['a'] + 1e-20)+ before = adb[(times >= o['t'] - 2 * half) & (times < o['t'] - 0.5 * half)]+ after = adb[(times >= o['t'] + 0.55 * half) & (times < o['t'] + 0.55 * half + 2 * half)]+ if len(before) and len(after) and after.max() - before.max() > jump_db:+ cut_a = times < o['t'] - 0.5 * half+ cut_b = times >= o['t'] - 0.5 * half+ a = {key: cur[key][cut_a] for key in ('k', 'f', 'a', 'ph', 'c')}+ b = {key: cur[key][cut_b] for key in ('k', 'f', 'a', 'ph', 'c')}+ parts = parts[:-1] + ([a] if len(a['k']) >= min_frames else []) + [b]+ out += parts+ # a track that lives only in the smear zone around a strike is the strike's pre-echo, not a partial+ zones = [(o['t'] - 1.1 * half, o['t'] + 0.55 * half) for o in onsets]++ def smear(t):+ tt, e = t['k'] * hop / sr, t['a'] ** 2+ return any(e[(tt >= a) & (tt <= b)].sum() >= 0.9 * e.sum() and tt[-1] <= b for a, b in zones)+ return [t for t in out if not smear(t)]+++def _fix_onsets(tracks, onsets, W, hop, sr):+ """start every track born in the smear zone of a strike exactly at the strike; replace its smeared first frames+ by the line through its first clean frames"""+ half = W / 2 / sr+ tracks = _split_at_strikes(tracks, onsets, W, hop, sr)+ for tr in tracks:+ times = tr['k'] * hop / sr+ tb = times[0]+ cands = [o for o in onsets if tb - 0.25 * half <= o['t'] <= tb + 1.05 * half]+ tr['t0'], tr['rise'] = None, None+ if not cands:+ continue+ o = max(cands, key=lambda o: o['strength'])+ to = o['t']+ adb = 20 * np.log10(tr['a'] + 1e-20)+ clean = times >= to + 0.55 * half+ sel = clean & (times <= to + 0.55 * half + max(4 * hop / sr, half))+ mx = adb.max()+ if sel.sum() >= 2:+ s, c = np.polyfit(times[sel] - to, adb[sel], 1)+ a0 = float(np.clip(c, mx - 40, mx + 6))+ line = a0 + s * (times - to)+ smear = (times < to + 0.55 * half)+ adb = np.where(smear, np.minimum(line, mx + 6), adb)+ elif clean.any():+ a0 = float(adb[clean][0])+ adb = np.where(times < to + 0.55 * half, a0, adb)+ else:+ a0 = float(mx)+ adb = np.full_like(adb, a0)+ keep = times > to+ if not keep.any():+ tr['k'] = tr['k'][-1:]+ keep = np.ones(1, bool)+ adb = adb[-1:]+ for key in ('f', 'a', 'ph', 'c'):+ tr[key] = tr[key][-1:]+ else:+ for key in ('k', 'f', 'ph', 'c'):+ tr[key] = tr[key][keep]+ adb = adb[keep]+ tr['a'] = 10 ** (adb / 20)+ tr['t0'], tr['rise'], tr['a0'] = to, o['rise'], 10 ** (a0 / 20)+ return tracks+++def _mq_synth(tracks, n, hop, sr):+ """phase-accurate re-synthesis of the tracks (cubic phase between frames, linear amplitude) for the residual"""+ y = np.zeros(n + 4 * hop)+ H = hop+ tt = np.arange(H, dtype=float)+ for tr in tracks:+ c = tr['k'] * hop+ w = 2 * np.pi * tr['f'] / sr+ th = tr['ph']+ a = tr['a']+ if len(c) >= 2:+ th0, th1, w0, w1 = th[:-1], th[1:], w[:-1], w[1:]+ M = np.round(((th0 + w0 * H - th1) + (w1 - w0) * H / 2) / (2 * np.pi))+ e = th1 - th0 - w0 * H + 2 * np.pi * M+ al = 3 / H ** 2 * e - (w1 - w0) / H+ be = -2 / H ** 3 * e + (w1 - w0) / H ** 2+ theta = th0[:, None] + w0[:, None] * tt + al[:, None] * tt ** 2 + be[:, None] * tt ** 3+ amp = a[:-1, None] + (a[1:] - a[:-1])[:, None] * tt / H+ seg = (amp * np.cos(theta)).ravel()+ s0 = c[0]+ lo = max(0, s0)+ y[lo:s0 + len(seg)] += seg[lo - s0:]+ # head: from the birth (strike) or one hop before the first frame+ if tr.get('t0') is not None:+ sb = int(round(tr['t0'] * sr))+ rise = max(1, int(round(tr['rise'] * sr)))+ pts_t = [sb, min(sb + rise, c[0]), c[0]]+ pts_a = [0.0, tr['a0'], a[0]]+ else:+ sb = c[0] - H+ pts_t, pts_a = [sb, c[0]], [0.0, a[0]]+ sb = max(0, sb)+ if c[0] > sb:+ s = np.arange(sb, c[0])+ amp = np.interp(s, pts_t, pts_a)+ y[s] += amp * np.cos(th[0] - w[0] * (c[0] - s))+ # tail: one hop of release+ s = np.arange(c[-1], c[-1] + H)+ s = s[(s >= 0) & (s < len(y))]+ y[s] += a[-1] * (1 - (s - c[-1]) / H) * np.cos(th[-1] + w[-1] * (s - c[-1]))+ return y[:n]+++def _noise_ratio(r, sr, centers, t, onsets, W=2048, hop=240, attack=0.03):+ """per band and time (dB <= 0): how much of the residual's band energy is noise-like. Leftover partial energy+ (narrow peaks) must not become band noise (a tonal leftover rendered as hiss is a loud tell): the noise power is+ estimated from the median of the band's STFT bins (/ ln 2), which narrow peaks do not move. Around strikes+ (-2 ms .. `attack`) the full band energy is kept (the attack burst is noise)."""+ f, tt, S = signal.stft(r, sr, nperseg=W, noverlap=W - hop, boundary='zeros')+ P = np.abs(S) ** 2+ # whiten by a running median across frequency (follows a sloping noise spectrum, ignores narrow peaks), so the+ # median / mean test inside a band measures peakiness, not the slope of the band's noise+ P = P / (median_filter(P, size=(31, 1), mode='nearest') + 1e-30)+ lc = np.log2(np.asarray(centers, float))+ lf = np.log2(np.maximum(f, 1.0))+ rho = np.zeros((len(centers), P.shape[1]))+ for b in range(len(centers)):+ lo = lc[b - 1] if b else lc[0] - (lc[1] - lc[0])+ hi = lc[b + 1] if b + 1 < len(lc) else lc[b] + (lc[b] - lc[b - 1])+ sel = (lf >= 0.5 * (lo + lc[b])) & (lf < 0.5 * (lc[b] + hi))+ if sel.sum() < 5:+ rho[b] = 0.0+ continue+ mean = P[sel].mean(0) + 1e-30+ med = np.median(P[sel], axis=0) / np.log(2)+ rho[b] = 10 * np.log10(np.clip(med / mean, 1e-4, 1.0))+ rho = median_filter(rho, size=(1, 5), mode='nearest')+ out = np.array([np.interp(t, tt, rho[b]) for b in range(len(centers))])+ for o in onsets:+ out[:, (t >= o['t'] - 0.002) & (t <= o['t'] + attack)] = 0.0+ return out+++_BIAS = {}+++def _env_bias(centers, sr=SR):+ """per band, how far the smoothed dB envelope of steady noise sits under its true level (the min of two short+ means and the dB-domain median are biased low, more so in wide high bands with short windows): calibrated once+ on seeded white noise and added back"""+ key = tuple(np.round(centers, 3))+ if key not in _BIAS:+ w = np.random.default_rng(12345).standard_normal(2 * sr)+ t, env = _band_env(w, sr, centers, 0.001)+ env = median_filter(env, size=(1, 5), mode='nearest')+ nfft = 1 << int(np.ceil(np.log2(len(w) + 2 * 4096)))+ spec = np.fft.rfft(np.concatenate([np.zeros(4096), w, np.zeros(nfft - len(w) - 4096)]))+ masks = band_masks(centers, nfft, sr)+ true = np.array([10 * np.log10(np.mean(np.fft.irfft(spec * masks[b], nfft)[4096:4096 + len(w)] ** 2))+ for b in range(len(centers))])+ mid = slice(int(0.1 * len(t)), int(0.9 * len(t)))+ _BIAS[key] = true - np.mean(env[:, mid], axis=1)+ return _BIAS[key]+++def _residual_model(r, sr, centers, floor_db, onsets=(), tol_db=2.0, max_times=96):+ """band dB envelopes of the residual's noise on one adaptive time grid"""+ t, env = _band_env(r, sr, centers, 0.001)+ env = env + _noise_ratio(r, sr, centers, t, onsets)+ env = median_filter(env, size=(1, 5), mode='nearest') + _env_bias(centers, sr)[:, None]+ env = np.maximum(env, floor_db)+ live = env.max(axis=1) > floor_db + 1+ g = _simplify_multi(t, env[live], tol_db, max_times) if live.any() else np.array([0, env.shape[1] - 1])+ return {'bands': [round(float(c), 2) for c in centers], 'times': [round(float(v), 5) for v in t[g]],+ 'db': [[round(float(v), 1) if v > floor_db + 0.05 else -150.0 for v in env[b, g]]+ for b in range(len(centers))]}+++def _partials_model(tracks, hop, sr, amp_tol_db, freq_tol_cents, max_amp_pts=64, max_freq_pts=48):+ """compress tracks to breakpoint partials (strongest first)"""+ out = []+ for tr in tracks:+ times = tr['k'] * hop / sr+ adb = 20 * np.log10(tr['a'] + 1e-20)+ f = tr['f']+ if len(f) >= 5:+ f = median_filter(f, size=5, mode='nearest')+ if tr.get('t0') is not None:+ t0, rise = tr['t0'], tr['rise']+ ta = np.concatenate([[t0], times])+ va = np.concatenate([[20 * np.log10(tr['a0'] + 1e-20)], adb])+ tf = np.concatenate([[t0], times])+ vf = np.concatenate([[f[0]], f])+ ph0 = tr['ph'][0] - 2 * np.pi * f[0] * (times[0] - t0)+ else:+ t0 = times[0] - hop / sr+ rise = hop / sr+ ta, va = np.concatenate([[t0], times]), np.concatenate([[adb[0]], adb])+ tf, vf = ta, np.concatenate([[f[0]], f])+ ph0 = tr['ph'][0] - 2 * np.pi * f[0] * hop / sr+ ia = _simplify(ta, va, amp_tol_db, max_amp_pts)+ cents = 1200 * np.log2(np.maximum(vf, 1.0))+ # frequency estimates get noisy as a partial sinks toward the floor: the tolerance widens 2x per 20 dB+ rel = np.clip((va.max() - np.interp(tf, ta, va)) / 20.0, 0.0, 4.0)+ jf = _simplify(tf, cents, freq_tol_cents * 2.0 ** rel, max_freq_pts)+ out.append({'t0': round(float(t0), 5), 'rise': round(float(max(rise, 2e-4)), 5),+ 't1': round(float(times[-1]), 5), 'rel': round(float(hop / sr), 5),+ 'ph': round(float(np.angle(np.exp(1j * ph0))), 3),+ 'freq': [[round(float(tf[j]), 5), round(float(vf[j]), 2)] for j in jf],+ 'amp': [[round(float(ta[i]), 5), round(float(va[i]), 1)] for i in ia]})+ out.sort(key=lambda p: -max(v for _, v in p['amp']))+ return out+++def _lsd(x, y, sizes=(256, 1024, 4096), range_db=60.0):+ """multi-resolution log-spectral distance (dB): mean |dB difference| of STFT magnitudes over the cells where+ either is within `range_db` of the louder signal's peak (differences capped at 40 dB), averaged over sizes"""+ n = max(len(x), len(y))+ x = np.pad(x, (0, n - len(x)))+ y = np.pad(y, (0, n - len(y)))+ ds = []+ for s in sizes:+ if n < s:+ continue+ _, _, A = signal.stft(x, nperseg=s, noverlap=s - s // 4, boundary='zeros')+ _, _, B = signal.stft(y, nperseg=s, noverlap=s - s // 4, boundary='zeros')+ a, b = _db(A), _db(B)+ fl = max(a.max(), b.max()) - range_db+ a, b = np.maximum(a, fl), np.maximum(b, fl)+ act = (a > fl) | (b > fl)+ if act.any():+ ds.append(float(np.minimum(np.abs(a - b)[act], 40).mean()))+ return float(np.mean(ds)) if ds else 0.0+++def _fit_window(x, sr, W, onsets, width, opts):+ return _analyze(x, sr, W, onsets, width, opts)['model']+++def _analyze(x, sr, W, onsets, width, opts):+ """the model at one window size plus the internals: {'model', 'det' (phase-exact partials), 'res' (x - det),+ 'atoms' (the strike transients' signal), 'tracks'}"""+ hop = max(32, W // 8)+ X, wsum, N = _frames(x, W, hop)+ pk = _peaks(X, wsum, N, sr, dyn_db=opts['dyn_db'], prom_db=opts['prom_db'], max_peaks=opts['max_peaks'])+ tracks = _track(pk, hop, sr, W)+ if not tracks:+ tracks = []+ # overlapping frames make a noise peak persist for about a window: a partial must outlive 1.25 windows+ min_frames = max(3, int(np.ceil(max(opts['min_ms'] / 1000, 1.25 * W / sr) * sr / hop)))+ gpk = max([t['a'].max() for t in tracks], default=1e-9)+ tracks = [t for t in tracks if len(t['k']) >= min_frames and t['a'].max() > gpk * 10 ** (-opts['keep_db'] / 20)+ and _sinusoidal(t, W, sr, opts['snr_db'])]+ tracks.sort(key=lambda t: -float((t['a'] ** 2).sum()))+ tracks = tracks[:opts['max_partials']]+ tracks = _fix_onsets(tracks, onsets, W, hop, sr)+ det = _mq_synth(tracks, len(x), hop, sr)+ res = x - det+ ref_db = float(_db(np.abs(X).max()))+ for _ in range(opts['passes'] - 1):+ # analysis by synthesis: partials hidden under stronger ones (doublet partners, beating sidebands, weak+ # high partials) show up in the residual; track them there and add them+ room = opts['max_partials'] - len(tracks)+ if room <= 0:+ break+ R, _, _ = _frames(res, W, hop)+ more = _track(_peaks(R, wsum, N, sr, dyn_db=opts['dyn_db'], prom_db=opts['prom_db'],+ max_peaks=opts['max_peaks'], ref_db=ref_db), hop, sr, W)+ more = [t for t in more if len(t['k']) >= min_frames and t['a'].max() > gpk * 10 ** (-opts['keep_db'] / 20)+ and _sinusoidal(t, W, sr, opts['snr_db'])]+ more.sort(key=lambda t: -float((t['a'] ** 2).sum()))+ more = _fix_onsets(more[:room], onsets, W, hop, sr)+ if not more:+ break+ d2 = _mq_synth(more, len(x), hop, sr)+ if ((res - d2) ** 2).sum() > 0.98 * (res ** 2).sum():+ break+ tracks += more+ det = det + d2+ res = x - det+ peak_db = float(_db(np.abs(x).max()))+ trans = _transients(res, onsets, sr, np.abs(x).max()) if opts['transients'] else []+ res2 = res - synth_atoms(trans, len(x), sr)+ centers = _band_centers()+ resid = _residual_model(res2, sr, centers, floor_db=peak_db - opts['res_range_db'], onsets=onsets)+ e_x = float((x ** 2).sum()) + 1e-20+ model = {'kind': KIND, 'version': VERSION, 'sr': SR, 'duration': round(len(x) / sr, 5),+ 'onset': round(onsets[0]['t'], 5) if onsets else 0.0,+ 'onsets': [round(o['t'], 5) for o in onsets], 'peak_db': round(peak_db, 2), 'width': round(width, 1),+ 'partials': _partials_model(tracks, hop, sr, opts['amp_tol_db'], opts['freq_tol_cents']),+ 'transients': trans, 'residual': resid,+ 'analysis': {'window': W, 'hop': hop, 'sines_share_db': round(float(10 * np.log10(+ max(1e-12, 1 - (res ** 2).sum() / e_x))), 2),+ 'residual_db': round(float(10 * np.log10((res ** 2).sum() / e_x + 1e-12)), 2)}}+ return {'model': model, 'det': det, 'res': res, 'atoms': res - res2, 'tracks': tracks}+++def fit(x, sr=SR, windows=WINDOWS, max_partials=160, dyn_db=80.0, keep_db=60.0, prom_db=4.0, max_peaks=100, min_ms=15.0,+ amp_tol_db=1.0, freq_tol_cents=1.0, res_range_db=140.0, transients=True, passes=2, snr_db=10.0, source=None):+ """a sines model of `x` (a path or an array at `sr`); every size in `windows` is tried and the model whose+ re-render (seed 0) is closest to `x` by multi-resolution log-spectral distance is kept"""+ if isinstance(x, str) and source is None:+ import os+ source = os.path.basename(x)+ x, width = _load(x, sr)+ opts = {'dyn_db': dyn_db, 'keep_db': keep_db, 'prom_db': prom_db, 'max_peaks': max_peaks, 'min_ms': min_ms,+ 'max_partials': max_partials, 'amp_tol_db': amp_tol_db, 'freq_tol_cents': freq_tol_cents,+ 'res_range_db': res_range_db, 'transients': transients, 'passes': passes, 'snr_db': snr_db}+ onsets = _onsets(x, SR)+ best, tried = None, {}+ for W in windows:+ if W > 2 * len(x) and best is not None:+ continue+ m = _fit_window(x, SR, W, onsets, width, opts)+ d = _lsd(x, render(m))+ tried[str(W)] = round(d, 2)+ if best is None or d < best[0]:+ best = (d, m)+ model = best[1]+ model['analysis']['lsd_db'] = round(best[0], 2)+ model['analysis']['tried'] = tried+ model['analysis']['onset_rise_ms'] = [round(o['rise'] * 1000, 2) for o in onsets]+ if source:+ model['source'] = source+ model['summary'] = summary(model)+ return model+++# ================================================================================================ reading a model+def _t60(p):+ """seconds for the partial to fall 60 dB, from the line through its amplitude breakpoints after the peak"""+ am = np.asarray(p['amp'], float)+ i = int(np.argmax(am[:, 1]))+ tail = am[i:]+ if len(tail) < 2 or tail[-1, 0] - tail[0, 0] < 0.01:+ return None+ s = np.polyfit(tail[:, 0] - tail[0, 0], tail[:, 1], 1)[0]+ return None if s >= -0.5 else float(-60.0 / s)+++def partial_freq(p):+ """a partial's energy-weighted mean frequency (Hz) from its breakpoints"""+ fq = np.asarray(p['freq'], float)+ am = np.asarray(p['amp'], float)+ t = np.linspace(am[0, 0], max(am[-1, 0], am[0, 0] + 1e-4), 200)+ w = 10 ** (np.interp(t, am[:, 0], am[:, 1]) / 10)+ f = 2 ** np.interp(t, fq[:, 0], np.log2(fq[:, 1]))+ return float((w * f).sum() / (w.sum() + 1e-30))+++def summary(model):+ """numbers a person (or a recipe) can read: partial frequencies, ratios, decays, inharmonicity, levels"""+ ps = model['partials']+ if not ps:+ return {'partials': 0}+ pk = np.array([max(v for _, v in p['amp']) for p in ps])+ fm = np.array([partial_freq(p) for p in ps])+ life = np.array([p['t1'] - p['t0'] for p in ps])+ strong = (pk > pk.max() - 30) & (life >= min(0.1, 0.5 * life.max())) # a short strike thump is not the pitch+ if not strong.any():+ strong = pk > pk.max() - 30+ f_low = float(fm[strong].min())+ w = 10 ** (pk / 10)+ centroid = float(np.exp((w * np.log(fm)).sum() / w.sum()))+ top = np.argsort(-pk)[:8]+ ratios = fm[strong] / f_low+ harm_dev = float(np.median(np.abs(ratios - np.round(ratios)) / np.maximum(np.round(ratios), 1))) if strong.sum() > 1 else 0.0+ glide = []+ for p in ps[:8]:+ fq = np.asarray(p['freq'], float)+ glide.append(round(float(1200 * np.log2(fq[-1, 1] / fq[0, 1])), 1))+ return {'partials': len(ps), 'f_low': round(f_low, 2), 'centroid': round(centroid, 2),+ 'f_range': [round(float(fm.min()), 1), round(float(fm.max()), 1)],+ 'top': [{'f': round(float(fm[i]), 2), 'db': round(float(pk[i]), 1),+ 't60': None if _t60(ps[i]) is None else round(_t60(ps[i]), 3)} for i in top],+ 'ratios': [round(float(r), 3) for r in sorted(ratios)[:12]],+ 'inharmonicity': round(harm_dev, 4), 'glide_cents': glide}+++def describe(model):+ """one line of words about a model"""+ s = model.get('summary') or summary(model)+ if not s.get('partials'):+ return 'no partials (noise only)'+ a = model['analysis']+ t60 = [t['t60'] for t in s['top'] if t['t60']]+ kind = 'harmonic' if s['inharmonicity'] < 0.01 else ('slightly inharmonic' if s['inharmonicity'] < 0.04 else 'inharmonic')+ gl = max(s['glide_cents'], key=abs) if s['glide_cents'] else 0+ words = (f"strike at {model['onset'] * 1000:.0f} ms ({len(model['onsets'])} strike(s)), {s['partials']} partials "+ f"{s['f_range'][0]:.0f}-{s['f_range'][1]:.0f} Hz, lowest strong {s['f_low']:.0f} Hz, {kind} "+ f"(ratios {', '.join(f'{r:.2f}' for r in s['ratios'][:5])}), centroid {s['centroid']:.0f} Hz")+ if t60:+ words += f", T60 {min(t60):.2f}-{max(t60):.2f} s"+ if abs(gl) > 50:+ words += f", glide {gl:+.0f} cents"+ words += (f"; residual {a['residual_db']:.1f} dB of the energy; window {a['window']}, "+ f"fit {a.get('lsd_db', float('nan')):.1f} dB LSD")+ return words+++# ================================================================================================ rendering+def _smooth_wander(n, r, rate=1.5, sr=SR):+ """unit-RMS slow random curve (sum of a few low sinusoids with seeded frequencies and phases)"""+ t = np.arange(n) / sr+ y = np.zeros(n)+ for _ in range(4):+ y += np.sin(2 * np.pi * rate * r.uniform(0.2, 1.0) * t + r.uniform(0, 2 * np.pi))+ return y / 2.0+++def render(model, seed=0, knobs=None, **kw):+ """the sound of a model (float64, 48 kHz, mono unless knobs['stereo']); knobs as in the module docstring"""+ if model.get('kind') != KIND:+ raise ValueError(f"not a sines model: kind={model.get('kind')!r}")+ k = dict(DEFAULT_KNOBS)+ k.update(knobs or {})+ k.update(kw)+ unknown = set(k) - set(DEFAULT_KNOBS)+ if unknown:+ raise ValueError(f'unknown knobs: {sorted(unknown)}')+ sr = model.get('sr', SR)+ r = np.random.default_rng((int(seed) * 7919 + 17) & 0xFFFFFFFF)+ on = float(model.get('onset', 0.0))+ s_, d_ = float(k['stretch']), float(k['decay'])+ ratio = 2.0 ** (float(k['transpose']) / 12.0)+ vary = float(k['vary'])+ summ = model.get('summary') or summary(model)+ f_ref = summ.get('centroid', 1000.0) or 1000.0+ f_low = summ.get('f_low', 100.0) or 100.0++ def T(t):+ t = np.asarray(t, float)+ return on + (t - on) * s_++ parts = list(model['partials'])+ if k['partials'] is not None:+ parts = parts[:int(k['partials'])]+ identity = (s_ == 1.0 and d_ == 1.0 and ratio == 1.0 and vary == 0.0 and k['brightness'] == 0.0+ and k['inharm'] == 0.0 and k['phases'] == 'fit')+ new = []+ for p in parts:+ if identity:+ new.append(p)+ continue+ fq = np.asarray(p['freq'], float).copy()+ am = np.asarray(p['amp'], float).copy()+ fmed = partial_freq(p)+ fac = ratio * (fmed / f_low) ** float(k['inharm']) if fmed > 0 else ratio+ detune = r.normal(0, 8.0 * vary)+ jit_db = r.normal(0, 2.0 * vary)+ jit_dec = float(np.exp(r.normal(0, 0.15 * vary)))+ ph = float(p['ph']) if k['phases'] == 'fit' else float(r.uniform(-np.pi, np.pi))+ fq[:, 1] = fq[:, 1] * fac * 2 ** (detune / 1200)+ am[:, 1] = am[:, 1] + jit_db + float(k['brightness']) * np.log2(max(fmed * ratio, 1.0) / f_ref)+ # decay: stretch the amplitude breakpoints after the peak about the peak+ ip = int(np.argmax(am[:, 1]))+ tp = am[ip, 0]+ dd = d_ * jit_dec+ am[ip + 1:, 0] = tp + (am[ip + 1:, 0] - tp) * dd+ t1 = tp + (float(p['t1']) - tp) * dd if p['t1'] > tp else float(p['t1'])+ new.append({'t0': float(T(p['t0'])), 'rise': float(p['rise']), 't1': float(T(t1)),+ 'rel': float(p['rel']) * max(1.0, s_),+ 'ph': ph, 'freq': np.column_stack([T(fq[:, 0]), fq[:, 1]]).tolist(),+ 'amp': np.column_stack([T(am[:, 0]), am[:, 1]]).tolist()})+ res = model['residual']+ bands = np.asarray(res['bands'], float)+ times = np.asarray(res['times'], float)+ lev = np.asarray(res['db'], float)+ if not identity or k['residual'] != 1.0:+ lev = lev.copy()+ if ratio != 1.0:+ lb = np.log2(bands)+ lev = np.array([np.interp(lb - np.log2(ratio), lb, lev[:, j]) for j in range(lev.shape[1])]).T+ lev += float(k['brightness']) * np.log2(bands * ratio / f_ref)[:, None]+ if vary:+ lev += r.normal(0, 1.5 * vary, size=(len(bands), 1))+ piv = on + 0.010+ times = np.where(times > piv, piv + (times - piv) * d_, times)+ times = T(times)+ if k['residual'] != 1.0:+ lev = lev + 20 * np.log10(max(float(k['residual']), 1e-6))+ lev = np.where(np.asarray(res['db'], float) <= -149, -150.0, lev)+ ends = [p['t1'] + p['rel'] for p in new] + [float(T(model['duration']))]+ n = int(np.ceil(max(ends) * sr)) + 1 if (d_ > 1.0 or s_ != 1.0) else int(round(model['duration'] * sr))+ cents = None+ if k['vibrato'] or k['drift']:+ tt = np.arange(n) / sr+ cents = float(k['vibrato']) * np.sin(2 * np.pi * float(k['vibrato_rate']) * tt + r.uniform(0, 2 * np.pi))+ cents = cents * np.clip((tt - on) / 0.15, 0, 1)+ cents = cents + float(k['drift']) * _smooth_wander(n, r)+ y = synth_partials(new, n, sr, cents)+ trans = model.get('transients', [])+ if trans and (not identity or k['transient'] != 1.0):+ tg = float(k['transient'])+ trans = [{'t': float(T(tr['t'])),+ 'atoms': [[f * ratio * 2 ** (r.normal(0, 30.0 * vary) / 1200), tau / ratio,+ a * tg * 10 ** ((r.normal(0, 2.0 * vary) + float(k['brightness'])+ * np.log2(max(f * ratio, 20.0) / f_ref)) / 20), ph]+ for f, tau, a, ph in tr['atoms']]} for tr in trans]+ y = y + synth_atoms(trans, n, sr)+ noise = synth_noise(bands, times, lev, n, seed, sr) if len(bands) else np.zeros(n)+ if k['transient'] != 1.0:+ tt = np.arange(n) / sr+ w = np.zeros(n)+ for o in model.get('onsets', [on]):+ to = float(T(o))+ w = np.maximum(w, np.clip(1 - np.abs(tt - to - 0.0075) / 0.0125, 0, 1) * (tt >= to - 0.002))+ noise = noise * (1 + (float(k['transient']) - 1) * w)+ y = y + noise+ if k['gain_db']:+ y = y * 10 ** (float(k['gain_db']) / 20)+ if k['stereo']:+ side = synth_noise(bands, times, lev, n, seed + 1000003, sr) * 10 ** (model.get('width', -120.0) / 20)+ side *= 10 ** (float(k['gain_db']) / 20)+ return np.column_stack([y + side, y - side])+ return y+++# ================================================================================================ model -> code+def _lit(v):+ return json.dumps(v, separators=(',', ':'))+++def to_code(model, name='sound'):+ """standalone Python (numpy only) that renders the model at its fit (render(model, seed) with default knobs)"""+ ps = model['partials']+ res = model['residual']+ s = model.get('summary') or summary(model)+ lines = [f'"""{name}: a sines model as code (earshot.forge.fit.sines v{model["version"]}).',+ '',+ f'{describe(model)}',+ '',+ 'render(seed) -> 48 kHz mono float array. Partials: (start s, rise s, end s, release s, phase rad,',+ 'frequency breakpoints [(t s, Hz)], amplitude breakpoints [(t s, dBFS)]). Residual: noise in 1/3-octave',+ 'bands (Hz centres) with dB envelopes at TIMES."""',+ 'import numpy as np',+ '',+ 'SR = 48000',+ f'DURATION = {model["duration"]}',+ f'# lowest strong partial {s.get("f_low")} Hz; ratios to it: {s.get("ratios", [])[:8]}',+ 'PARTIALS = [']+ for p in ps:+ lines.append(f" ({p['t0']}, {p['rise']}, {p['t1']}, {p['rel']}, {p['ph']},")+ lines.append(f" {_lit(p['freq'])},")+ lines.append(f" {_lit(p['amp'])}),")+ lines.append(']')+ lines.append('# strike transients: (start s, [(f Hz, decay tau s, amplitude, phase rad), ...])')+ lines.append('TRANSIENTS = [')+ for tr in model.get('transients', []):+ lines.append(f" ({tr['t']}, {_lit(tr['atoms'])}),")+ lines.append(']')+ lines.append(f"BANDS = {_lit(res['bands'])}")+ lines.append(f"TIMES = {_lit(res['times'])}")+ lines.append('LEVELS = [')+ for row in res['db']:+ lines.append(f' {_lit(row)},')+ lines.append(']')+ lines.append('')+ for fn in (band_masks, synth_partials, synth_atoms, synth_noise):+ lines.append('')+ lines.append(inspect.getsource(fn).rstrip())+ lines.append('')+ lines += ['',+ 'def render(seed=0):',+ ' n = int(round(DURATION * SR))',+ " parts = [{'t0': p[0], 'rise': p[1], 't1': p[2], 'rel': p[3], 'ph': p[4], 'freq': p[5], 'amp': p[6]}",+ ' for p in PARTIALS]',+ " trans = [{'t': t, 'atoms': a} for t, a in TRANSIENTS]",+ ' return (synth_partials(parts, n, SR) + synth_atoms(trans, n, SR)',+ ' + synth_noise(BANDS, TIMES, LEVELS, n, seed, SR))',+ '',+ '',+ "if __name__ == '__main__':",+ ' import sys, wave',+ ' y = render(int(sys.argv[2]) if len(sys.argv) > 2 else 0)',+ ' pcm = (np.clip(y, -1, 1) * 32767).astype(np.int16)',+ f" with wave.open(sys.argv[1] if len(sys.argv) > 1 else '{name}.wav', 'wb') as w:",+ ' w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR); w.writeframes(pcm.tobytes())',+ '']+ return '\n'.join(lines)+++def save(model, path):+ with open(path, 'w', encoding='utf-8') as fh:+ json.dump(model, fh, separators=(',', ':'))+ return path+++def load(path):+ with open(path, encoding='utf-8') as fh:+ m = json.load(fh)+ if m.get('kind') != KIND:+ raise ValueError(f'{path} is not a sines model')+ return mdiff --git a/earshot/forge/fit/spectral.py b/earshot/forge/fit/spectral.pynew file mode 100644index 0000000..a533613--- /dev/null+++ b/earshot/forge/fit/spectral.py@@ -0,0 +1,1295 @@+"""Spectral fitter: a real noisy / airy / textured recording -> a small JSON model -> fresh re-renders of it.++ from earshot.forge.fit import spectral+ m = spectral.fit('swish.wav') # analysis-by-synthesis; m is a plain JSON-serialisable dict+ y = spectral.render(m, seed=3) # (n, 2) float32 at 48 kHz: same sound, fresh noise+ y = spectral.render(m, seed=4, length=1.4, speed=0.8, sweep=1.3, tilt=-1.5, roughness=0.5, width=1.2)+ print(spectral.to_code(m)) # the model as readable Python that re-renders it+ print(spectral.summary(m)) # 'swish.wav: 0.42 s noise gesture, peak at 0.11 s, ...'+ q = spectral.compare(x, y) # mel dB (256/1024/4096), envelope corr, attack, tone, (CLAP)+ r = spectral.fit_report('swish.wav', clap=True) # fit + two renders + compare(orig, r1) and the+ # render-vs-render floor compare(r1, r2)++For whooshes, swishes, cloth / paper swipes, risers, downlifters, wind, shimmer beds and glitch textures: sounds that+are noise (or dense grains) shaped by a time-varying spectral envelope. The model (kind 'spectral_noise'):++ env the GESTURE: keyframes in time (non-uniform, chosen greedily where linear interpolation in dB misses the+ gesture by more than the tolerance, as a weighted mean over the cells that are loud in each frame), each+ a 48-band spectrum (20 Hz - 20 kHz, spaced on ln(1 + f / 80 Hz): ~1/3 octave in the lows, ~1/6 octave+ in the highs) of power density in dB re a full-scale white noise. Analysis: multi-resolution STFT (512 -+ 4096 per band, ~2 / bandwidth of window) on a 5 ms grid; 25 ms smoothing that never crosses the onset+ frame (the attack stays sharp), widened while the level still wanders > 2 dB around a running quadratic+ (crackle, flutter: those are texture, the tolerance rises to that wander too); a weighted low-rank+ (SVD) denoise whose rank stops where the residual reaches what a noise band's estimate wanders by+ (measured on white noise through the same analysis; quiet cells keep their measured level); then the+ gains are corrected by analysing renders of the model with the same analysis (analysis-by-synthesis, 3+ iterations x 2 seeds: band overlap, window smear and the low bands' slow filters are paid back).+ stereo per band group (0-300-1000-2500-5000-10000-24000 Hz) and keyframe: inter-channel level difference (dB)+ and inter-channel correlation; rendered from two independent noise sources mixed per band (L = cA + sB,+ R = cA - sB, c^2 - s^2 = correlation) with ILD gains, so width and pan trajectories come back. None for a+ mono source (both channels then carry the same render).+ texture what the smooth gesture does not hold, as statistics fitted by renders (mono, 3 seeds):+ grains crackle (cloth, paper, glitch dust): the excitation becomes a Poisson click train (log-normal+ amplitudes, spread 1 neper) of `density` clicks per second instead of Gaussian noise. Detected by+ excess fast (>= 128 Hz) log-amplitude variance (clicks put variance at every rate, flutter does+ not); density fitted to the std of the log analytic envelope around the gesture (Gaussian noise+ 0.64 nepers; it is monotone in density and stable across seeds, where kurtosis is ruled by the+ largest click)+ am flutter: the 6-64 Hz log-amplitude variance beyond what Gaussian noise (and the grains) already+ make, kept only where both halves of the active span have it; a half-octave rate spectrum, a depth+ per band group (std of log amplitude, nepers, capped at 0.6) and the coherence across groups+ stats the measured statistics behind those decisions (for reports)+ ridges tonal ridges (whistle / aeolian tones inside a whoosh): spectral peaks > 8 dB over the local floor on+ both sides, tracked for >= 50 ms, as keyframes of frequency (Hz) and amplitude (dB re full scale) with a+ small frequency jitter; their energy is taken out of the noise envelope before it is fitted.+ fine (opt-in, fit(fine=True)) a static fine spectral curve every 1/24 octave above ~300 Hz: resonances the+ bands cannot hold. Helps long steady sounds (the riser: CLAP 0.82 -> 0.88), costs a little on short+ ones (estimation noise), hence off by default.+ fit what the fit chose: gesture_ms (smoothing), rank, tol_db, fluct_db.++Rendering (`render`): each call draws NEW noise (seeded, deterministic per seed), so every render is a fresh but+statistically identical sound; knobs: length (time-stretch of the gesture, texture rates kept), speed (movement+speed: shorter, higher by SPEED_OCT octaves per doubling, faster flutter), sweep (scales the spectral centroid's+excursion around its mean), shift (octaves), tilt (dB / octave about 1 kHz), roughness (texture depth; 0 = smooth+Gaussian), width (side / pan amount), ridges (tonal ridge gain), gain_db. Output is levelled to the original's+loudest 50 ms RMS (+ gain_db), sample peak capped at -0.5 dBFS.++Judging a fit: a fresh-noise render can never match the samples, and even two renders of one model differ by a few+dB cell by cell (a noise band's level estimate fluctuates). So `fit_report` also gives the floor: compare(render,+render') with another seed. A fit is as good as this representation allows when compare(orig, render) is near that+floor; the gap is what the model misses.+Pure numpy / scipy. Deterministic: everything is a function of (model, seed, knobs).+"""+import json+import os++import numpy as np+import scipy.fft as sfft+from scipy.ndimage import convolve1d, median_filter, uniform_filter++KIND = 'spectral_noise'+VERSION = 1+SR = 48000+HOP = 240 # 5 ms analysis / control grid+N_BANDS = 48+F_LO, F_HI = 20.0, 20000.0+WARP_HZ = 80.0+GROUPS = (0.0, 300.0, 1000.0, 2500.0, 5000.0, 10000.0, 24000.0)+RATES = 2.0 ** np.arange(0.0, 9.5, 0.5) # modulation rate band centres, 1 .. 512 Hz (half-octave)+AM_MAX_RATE = 64.0 # AM statistics up to here; faster structure is the grains' business+AM_MIN_RATE = 6.0 # slower than this belongs to the gesture (key frames)+AM_MAX_DEPTH = 0.6 # nepers (~5 dB std of log amplitude): a safety cap+SPEED_OCT = 0.5 # octaves up per doubling of `speed`+NFFTS = (512, 1024, 2048, 4096)+NFFT_CYCLES = 2.0 # analysis window ~ this many / bandwidth per band+FLOOR_DB = 90.0 # envelope floor below its loudest cell+SPREAD = 1.0 # grain amplitude spread (log-normal sigma, nepers)+++def _workers():+ try:+ return max(1, int(os.environ.get('EARSHOT_THREADS', '2')))+ except ValueError:+ return 2+++# ----------------------------------------------------------------------------------------------- bands+++def warp(f):+ """the band axis: ln(1 + f / 80 Hz). About 1/3 octave per band below 300 Hz (where the ERB scale is coarser+ than the 1/3-octave balance the forge measures), ~1/6 octave per band above 2 kHz (finer than 1/3 octave, near+ the ERB)."""+ return np.log1p(np.asarray(f, np.float64) / WARP_HZ)+++def unwarp(e):+ return np.expm1(np.asarray(e, np.float64)) * WARP_HZ+++def centers(n=N_BANDS, f_lo=F_LO, f_hi=F_HI):+ """band centre frequencies (Hz), uniformly spaced on the band axis (warp)"""+ return unwarp(np.linspace(warp(f_lo), warp(f_hi), int(n)))+++def _wband(e, ec, b):+ """raised-cosine weight of band b on the band axis; the bands sum to exactly 1 above the first centre"""+ w = np.zeros(len(e))+ B = len(ec)+ if b == 0:+ lo = ec[0] - (ec[1] - ec[0]) # roll off below the first centre (no flat shelf to DC)+ m = (e >= lo) & (e < ec[0])+ w[m] = np.sin(0.5 * np.pi * (e[m] - lo) / (ec[0] - lo)) ** 2+ else:+ lo = ec[b - 1]+ m = (e >= lo) & (e < ec[b])+ w[m] = np.sin(0.5 * np.pi * (e[m] - lo) / (ec[b] - lo)) ** 2+ if b == B - 1:+ w[e >= ec[-1]] = 1.0+ else:+ hi = ec[b + 1]+ m = (e >= ec[b]) & (e < hi)+ w[m] = np.cos(0.5 * np.pi * (e[m] - ec[b]) / (hi - ec[b])) ** 2+ return w+++def weights(freqs, cents):+ """(B, F) partition-of-unity band weights at the given frequencies"""+ e = warp(freqs)+ ec = warp(cents)+ return np.stack([_wband(e, ec, b) for b in range(len(ec))])+++_BW = {}+++def bandwidths(cents):+ """effective bandwidth (Hz) of each band: the integral of its weight"""+ key = tuple(np.round(cents, 6))+ if key not in _BW:+ f = np.linspace(0, SR / 2, 96001)+ _BW[key] = weights(f, cents).sum(1) * (f[1] - f[0])+ return _BW[key].copy()+++def _band_nfft(cents):+ bw = bandwidths(cents)+ n = 2.0 ** np.round(np.log2(NFFT_CYCLES * SR / bw))+ return np.clip(n, NFFTS[0], NFFTS[-1]).astype(int)+++def _group_of(cents):+ return np.clip(np.searchsorted(GROUPS, cents, side='right') - 1, 0, len(GROUPS) - 2)+++def _group_centres():+ g = np.array(GROUPS, np.float64)+ c = np.sqrt(np.maximum(g[:-1], 50.0) * g[1:])+ c[0] = 150.0+ return c+++def _group_blend(cents):+ """per band: (g0, g1, a) so a band's group parameter = (1-a) p[g0] + a p[g1] (log-frequency interpolation)"""+ gc = np.log2(_group_centres())+ lf = np.log2(np.maximum(cents, 1.0))+ out = []+ for v in lf:+ if v <= gc[0]:+ out.append((0, 0, 0.0))+ elif v >= gc[-1]:+ out.append((len(gc) - 1, len(gc) - 1, 0.0))+ else:+ i = int(np.searchsorted(gc, v) - 1)+ out.append((i, i + 1, float((v - gc[i]) / (gc[i + 1] - gc[i]))))+ return out+++# ------------------------------------------------------------------------------------------- analysis+++def _load(x):+ if isinstance(x, str):+ from ... import audio+ x = audio.load(x)+ x = np.asarray(x, np.float64)+ if x.ndim == 1:+ x = np.stack([x, x], 1)+ if x.shape[1] == 1:+ x = np.repeat(x, 2, 1)+ return x[:, :2]+++def _hann(n):+ return 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / n)+++def _stft(x, n_fft, T):+ """(T, n_fft/2+1) complex, centred frames every HOP, scaled so |X|^2 is power density (white var s2 -> s2)"""+ win = _hann(n_fft)+ pad = n_fft // 2+ need = (T - 1) * HOP + n_fft+ xp = np.zeros(need)+ seg = x[:max(0, min(len(x), need - pad))]+ xp[pad:pad + len(seg)] = seg+ fr = np.lib.stride_tricks.sliding_window_view(xp, n_fft)[::HOP][:T]+ X = sfft.rfft(fr * win, axis=1, workers=_workers())+ return X / np.sqrt((win ** 2).sum())+++def n_frames(n):+ return int(n) // HOP + 1+++def analyse(x, cents=None, stereo=True):+ """band power densities on the 5 ms grid: {'D': (B, T) mid density, 'P_lr': ..., 'stereo': group L/R/cross}"""+ cents = centers() if cents is None else cents+ x = np.asarray(x, np.float64)+ mono = x.ndim == 1+ T = n_frames(len(x))+ sizes = _band_nfft(cents)+ D = np.zeros((len(cents), T))+ st = None+ todo = sorted(set(sizes.tolist()) | ({1024} if (stereo and not mono) else set()))+ for N in todo:+ if mono:+ XL = _stft(x, N, T)+ P = np.abs(XL) ** 2+ else:+ XL = _stft(x[:, 0], N, T)+ XR = _stft(x[:, 1], N, T)+ PL, PR = np.abs(XL) ** 2, np.abs(XR) ** 2+ P = 0.5 * (PL + PR)+ f = np.fft.rfftfreq(N, 1 / SR)+ sel = np.nonzero(sizes == N)[0]+ if len(sel):+ Wf = weights(f, cents)[sel]+ Wn = Wf / np.maximum(Wf.sum(1, keepdims=True), 1e-12)+ D[sel] = (P @ Wn.T).T+ if N == 1024 and stereo and not mono:+ gi = np.clip(np.searchsorted(GROUPS, f, side='right') - 1, 0, len(GROUPS) - 2)+ G = len(GROUPS) - 1+ M = np.zeros((len(f), G))+ M[np.arange(len(f)), gi] = 1.0+ C = np.real(XL * np.conj(XR))+ st = {'PL': (PL @ M).T, 'PR': (PR @ M).T, 'C': (C @ M).T}+ return {'D': D, 'stereo': st, 'T': T}+++def _smooth_t(D, k):+ k = int(k)+ if k <= 1:+ return D+ w = _hann(k + 1)[1:]+ w = w / w.sum()+ return convolve1d(D, w, axis=-1, mode='nearest')+++def _db(p, floor=1e-20):+ return 10.0 * np.log10(np.maximum(p, floor))+++# -------------------------------------------------------------------------------------------- keyframes+++def _interp_rows(Y, keys):+ T = len(Y)+ k = np.asarray(keys)+ t = np.arange(T)+ i = np.clip(np.searchsorted(k, t, side='right') - 1, 0, len(k) - 2)+ a = (t - k[i]) / np.maximum(k[i + 1] - k[i], 1)+ return Y[k[i]] * (1 - a)[:, None] + Y[k[i + 1]] * a[:, None]+++def _keyframes(Y, Wc, tol, must=(), max_keys=200):+ """greedy keyframe insertion: frames where linear interpolation between keys misses Y by > tol (weighted RMS)"""+ T = len(Y)+ if T <= 2:+ return list(range(T))+ keys = sorted(set([0, T - 1] + [int(m) for m in must if 0 <= m < T]))+ ws = Wc.sum(1)+ den = np.maximum(ws, 0.25 * ws.max()) + 1e-12 # weighted mean over the cells that matter in each frame+ while len(keys) < max_keys:+ Yh = _interp_rows(Y, keys)+ err = np.sqrt((Wc * (Yh - Y) ** 2).sum(1) / den)+ err[keys] = 0.0+ j = int(np.argmax(err))+ if err[j] <= tol:+ break+ keys = sorted(keys + [j])+ return keys+++# ------------------------------------------------------------------------------------------ synthesis+++def _gauss_process(m, fs, rates, spec, rng):+ """unit-variance Gaussian process of m samples at fs with the given (rate band -> variance) spectrum"""+ if m < 4 or spec is None or np.sum(spec) <= 0:+ return np.zeros(m)+ N = sfft.next_fast_len(max(m, 16))+ f = np.fft.rfftfreq(N, 1 / fs)+ lr = np.log2(np.maximum(f, 1e-3))+ s = np.asarray(spec, np.float64) / (np.asarray(rates) * (2 ** 0.25 - 2 ** -0.25)) # variance -> density+ dens = np.interp(lr, np.log2(rates), s, left=0.0, right=0.0)+ dens[f < rates[0] / 2 ** 0.25] = 0.0+ if dens.sum() <= 0:+ return np.zeros(m)+ Z = sfft.rfft(rng.standard_normal(N)) * np.sqrt(dens)+ z = sfft.irfft(Z, N)[:m]+ sd = z.std()+ return z / sd if sd > 0 else z+++def _clicks(N, rate, rng, spread=SPREAD):+ """unit-variance Poisson click train: `rate` clicks / s, log-normal amplitudes with random signs"""+ k = int(rng.poisson(max(rate, 1e-3) * N / SR))+ c = np.zeros(N)+ if k == 0:+ return c+ pos = rng.integers(0, N, k)+ amp = np.exp(spread * rng.standard_normal(k)) * rng.choice((-1.0, 1.0), k)+ np.add.at(c, pos, amp)+ p = np.sqrt((c ** 2).mean())+ return c / p if p > 0 else c+++def _synth(n, tk, env, cents, seed, stereo=None, texture=None, ridges=(), mono=False, rate_scale=1.0,+ rough=1.0, fine=None, fine_shift=0.0):+ """the renderer core. tk (K,) key times in s, env (K, B) density dB. Returns (n,) if mono else (n, 2)."""+ n = int(n)+ ss = np.random.SeedSequence(abs(int(seed)) % (2 ** 32))+ rA, rB, rC, rM, rR = [np.random.default_rng(s) for s in ss.spawn(5)]+ N = sfft.next_fast_len(max(n, 64))+ ts = np.arange(n) / SR+ tk = np.asarray(tk, np.float64)+ env = np.asarray(env, np.float64)+ G = len(GROUPS) - 1+ wk = _workers()++ grains = (texture or {}).get('grains')+ eA = rA.standard_normal(N)+ if grains and rough > 0:+ dens = float(grains['density']) / max(rough, 1e-3) ** 2 # rougher = sparser clicks+ eA = _clicks(N, dens * rate_scale, rC)+ FA = sfft.rfft(eA, workers=wk)+ FB = None if (mono or stereo is None) else sfft.rfft(rB.standard_normal(N), workers=wk)+ f = np.fft.rfftfreq(N, 1 / SR)+ if fine:+ gf = _fine_gain(fine, f / 2 ** fine_shift)+ FA = FA * gf+ if FB is not None:+ FB = FB * gf+ ef = warp(f)+ ec = warp(cents)+ blend = _group_blend(cents)++ # per group control signals at the sample rate+ am = (texture or {}).get('am')+ if am and rough > 0 and max(am['depth']) > 0:+ n1 = int(np.ceil(n / SR * 1000)) + 2+ t1 = np.arange(n1) / 1000.0+ rates = np.asarray(am['rates'], np.float64) * rate_scale+ zc = _gauss_process(n1, 1000.0, rates, am['spec'], rM)+ coh = float(np.clip(am.get('coh', 1.0), 0, 1))+ mods = []+ for g in range(G):+ zi = _gauss_process(n1, 1000.0, rates, am['spec'], rM)+ z = np.sqrt(coh) * zc + np.sqrt(1 - coh) * zi+ sg = float(am['depth'][g]) * rough+ mods.append(np.interp(ts, t1, np.exp(sg * z - sg * sg)))+ mods = np.stack(mods)+ else:+ mods = None+ if stereo is not None and not mono:+ ild = np.asarray(stereo['ild'], np.float64) # (K, G)+ icc = np.asarray(stereo['icc'], np.float64)+ th = 0.5 * np.arccos(np.clip(icc, -1, 1))+ r = 10 ** (ild / 10)+ par = np.stack([np.cos(th), np.sin(th), np.sqrt(2 * r / (1 + r)), np.sqrt(2 / (1 + r))]) # (4, K, G)+ ctl = np.stack([[np.interp(ts, tk, par[p, :, g]) for g in range(G)] for p in range(4)]) # (4, G, n)+ else:+ ctl = None++ L = np.zeros(n)+ R = None if mono else np.zeros(n)+ for b in range(len(cents)):+ w = _wband(ef, ec, b)+ nz = np.nonzero(w)[0]+ if not len(nz):+ continue+ lo, hi = nz[0], nz[-1] + 1+ Xb = np.zeros(len(f), complex)+ Xb[lo:hi] = FA[lo:hi] * w[lo:hi]+ nA = sfft.irfft(Xb, N, workers=wk)[:n]+ amp = 10 ** (np.interp(ts, tk, env[:, b]) / 20)+ g0, g1, a = blend[b]+ if mods is not None:+ amp = amp * ((1 - a) * mods[g0] + a * mods[g1])+ if mono:+ L += amp * nA+ continue+ if ctl is None: # a mono model renders the same signal on both channels+ L += amp * nA+ continue+ Xb[lo:hi] = FB[lo:hi] * w[lo:hi]+ nB = sfft.irfft(Xb, N, workers=wk)[:n]+ c, s, gl, gr = [(1 - a) * ctl[p, g0] + a * ctl[p, g1] for p in range(4)]+ L += amp * gl * (c * nA + s * nB)+ R += amp * gr * (c * nA - s * nB)++ for rd in ridges or ():+ rt = np.asarray(rd['t'], np.float64)+ fr = np.interp(ts, rt, np.asarray(rd['f'], np.float64))+ A = 10 ** (np.interp(ts, rt, np.asarray(rd['db'], np.float64)) / 20)+ A[(ts < rt[0]) | (ts > rt[-1])] = 0.0+ n1 = int(np.ceil(n / SR * 1000)) + 2+ z = _gauss_process(n1, 1000.0, RATES, np.where(RATES <= 16, 1.0, 0.0), rR)+ jit = float(rd.get('jitter', 0.002))+ fr = fr * (1 + jit * np.interp(ts, np.arange(n1) / 1000.0, z))+ ph = 2 * np.pi * np.cumsum(fr) / SR + rR.uniform(0, 2 * np.pi)+ y = A * np.sin(ph)+ # fade the ridge in / out over 5 ms at its ends+ e = np.clip(np.minimum(ts - rt[0], rt[-1] - ts) / 0.005, 0, 1)+ y = y * e+ if mono or ctl is None:+ L += y+ else:+ g = int(_group_of(np.array([np.median(rd['f'])]))[0])+ L += y * ctl[2, g]+ R += y * ctl[3, g]+ if mono:+ return L+ if ctl is None:+ R = L.copy()+ return np.stack([L, R], 1)+++def _peak_rms_db(x, win_s=0.05):+ x = np.asarray(x, np.float64)+ p = (x ** 2).mean(1) if x.ndim == 2 else x ** 2+ k = max(1, int(win_s * SR))+ if len(p) < k:+ return float(_db(p.mean()))+ c = np.concatenate([[0.0], np.cumsum(p)])+ return float(_db(((c[k:] - c[:-k]) / k).max()))+++# ------------------------------------------------------------------------------------------------- fit+++def _stereo_traj(st, T, mono):+ G = len(GROUPS) - 1+ if mono or st is None:+ return np.zeros((T, G)), np.ones((T, G)), np.ones((T, G))+ PL, PR, C = [_smooth_t(st[k], 7) for k in ('PL', 'PR', 'C')]+ ild = np.clip(_db(PL + 1e-30) - _db(PR + 1e-30), -20, 20)+ icc = np.clip(C / np.sqrt(PL * PR + 1e-30), -1, 1)+ pw = PL + PR+ act = _db(pw) > _db(pw.max()) - 45+ # quiet cells take the group's power-weighted mean, so noise does not wander the image+ for g in range(G):+ wgt = pw[g] * act[g]+ if wgt.sum() <= 0:+ ild[g], icc[g] = 0.0, 1.0+ continue+ mi = (ild[g] * wgt).sum() / wgt.sum()+ mc = (icc[g] * wgt).sum() / wgt.sum()+ ild[g] = np.where(act[g], ild[g], mi)+ icc[g] = np.where(act[g], icc[g], mc)+ gw = pw.sum(1)+ gw = gw / max(gw.sum(), 1e-30)+ return ild.T, icc.T, np.broadcast_to(gw, (T, G))+++def _find_ridges(xm, D, cents, max_ridges=4, min_prom=8.0, min_frames=10, f_lo=400.0, f_hi=16000.0):+ """tonal ridge tracks: list of {'k': frame idx, 'f': Hz, 'p': peak density, 'fl': floor density}"""+ N = 2048+ T = D.shape[1]+ X = _stft(xm, N, T)+ P = np.abs(X) ** 2+ f = np.fft.rfftfreq(N, 1 / SR)+ Pd = _db(P + 1e-30)+ # local floor on BOTH sides (median of 8 bins starting 2 bins away; the higher side wins), so the edge of a+ # band-limited noise is not a peak; +1.6 dB: the median of an exponential is ln 2 under its mean+ med = median_filter(Pd, size=(1, 8), mode='nearest')+ fl = np.maximum(np.roll(med, 6, axis=1), np.roll(med, -6, axis=1)) + 1.6+ prom = Pd - fl+ lvl = _db(P.sum(1))+ act = lvl > lvl.max() - 50+ band = (f >= f_lo) & (f <= f_hi)+ tracks, live = [], []+ for k in range(T):+ if not act[k]:+ live = [tr for tr in live if k - tr['k'][-1] <= 2]+ continue+ row = prom[k]+ cand = np.nonzero(band[2:-2] & (row[2:-2] > min_prom) & (Pd[k, 2:-2] >= Pd[k, 1:-3])+ & (Pd[k, 2:-2] >= Pd[k, 3:-1]) & (Pd[k, 2:-2] >= Pd[k, :-4]) & (Pd[k, 2:-2] >= Pd[k, 4:]))[0] + 2+ cand = sorted(cand, key=lambda i: -row[i])[:12]+ used = set()+ for i in cand:+ a, b0, c = Pd[k, i - 1], Pd[k, i], Pd[k, i + 1]+ den = a - 2 * b0 + c+ d = 0.5 * (a - c) / den if den < 0 else 0.0+ fi = (i + d) * SR / N+ pk = b0 - 0.25 * (a - c) * d+ best, bd = None, 0.04+ for j, tr in enumerate(live):+ if j in used:+ continue+ dd = abs(np.log2(fi / tr['f'][-1]))+ if dd < bd:+ best, bd = j, dd+ if best is None:+ tr = {'k': [], 'f': [], 'p': [], 'fl': []}+ live.append(tr)+ tracks.append(tr)+ best = len(live) - 1+ used.add(best)+ tr = live[best]+ tr['k'].append(k)+ tr['f'].append(fi)+ tr['p'].append(10 ** (pk / 10))+ tr['fl'].append(10 ** (fl[k, i] / 10))+ live = [tr for tr in live if k - tr['k'][-1] <= 2]+ good = []+ for tr in tracks:+ if len(tr['k']) < min_frames:+ continue+ pr = _db(np.array(tr['p'])) - _db(np.array(tr['fl']))+ if np.median(pr) < min_prom + 2:+ continue+ good.append(tr)+ good.sort(key=lambda tr: -float(np.sum(np.array(tr['p']) - np.array(tr['fl']))))+ return good[:max_ridges]+++def _ridge_model(tr, n_fft=2048):+ k = np.array(tr['k'])+ fz = np.array(tr['f'])+ p = np.maximum(np.array(tr['p']) - np.array(tr['fl']), 1e-30)+ A = np.sqrt(6 * p / n_fft) # Hann peak bin of a sinusoid of amplitude A: density A^2 N / 6+ adb = 20 * np.log10(A)+ t = k * HOP / SR+ Y = np.stack([np.log2(fz) / 0.006, adb / 1.5], 1)+ keys = _keyframes(Y, np.ones_like(Y), 1.0, max_keys=60)+ fs = _smooth_t(np.log2(fz)[None], 5)[0]+ jit = float(np.clip(np.std(np.log2(fz) - fs) * np.log(2), 0.0005, 0.02))+ return {'t': [round(float(t[i]), 4) for i in keys], 'f': [round(float(fz[i]), 1) for i in keys],+ 'db': [round(float(adb[i]), 1) for i in keys], 'jitter': round(jit, 4)}, (k, fz, A)+++def _ridge_remove(D, cents, k, fz, A):+ """subtract a sinusoid's contribution from the band densities (A^2 SR / (4 bw) spread by the band weights)"""+ bw = bandwidths(cents)+ W = weights(fz, cents) # (B, len)+ inc = W * (A ** 2)[None] * SR / (4 * bw[:, None])+ D = D.copy()+ D[:, k] = np.maximum(D[:, k] - inc, 0.05 * D[:, k])+ return D+++def _seg_smooth(D, k, on):+ """time smoothing that does not cross the onset frame (the attack stays sharp)"""+ if on <= 1 or on >= D.shape[1] - 1:+ return _smooth_t(D, k)+ return np.concatenate([_smooth_t(D[:, :on], k), _smooth_t(D[:, on:], k)], 1)+++def _lowrank(Y, W, K, iters=10):+ """weighted rank-K approximation of Y (T, B): per-band weighted mean + K components (EM over the weights)"""+ Z = Y.copy()+ Yh = Y.copy()+ for _ in range(iters):+ Z = W * Y + (1 - W) * Yh+ mu = Z.mean(0)+ U, S, Vt = np.linalg.svd(Z - mu, full_matrices=False)+ Yh = mu + (U[:, :K] * S[:K]) @ Vt[:K]+ return Yh+++def _noise_sigma(n, cents, k, on, seed=12345):+ """per band std (dB) of the analysis of white noise of this length: what a noise band's estimate wanders"""+ wn = np.random.default_rng(seed).standard_normal(n)+ Dn = _db(_seg_smooth(analyse(wn, cents, stereo=False)['D'], k, on))+ T = Dn.shape[1]+ sig = np.zeros(len(cents))+ sizes = _band_nfft(cents)+ for b in range(len(cents)):+ e = int(sizes[b] // 2 // HOP)+ row = Dn[b, e:T - e] if T - 2 * e > 8 else Dn[b]+ sig[b] = row.std()+ return sig+++def _wander(L, k, on):+ """RMS (dB) of a level curve around a running quadratic over ~4k frames, on its loud frames, onset excluded"""+ from scipy.signal import savgol_filter+ T = len(L)+ w = min(T - (1 - T % 2), 4 * k + 1)+ if w < 5:+ return 0.0+ Q = savgol_filter(L, w, 2, mode='interp')+ fa = (L > L.max() - 30) & (np.abs(np.arange(T) - on) > k)+ return float(np.sqrt(np.mean((L - Q)[fa] ** 2))) if fa.sum() > 4 else 0.0+++FINE_F0 = 40.0+FINE_STEP = 1.0 / 24 # octaves per point of the fine spectral curve+++def _fine_gain(fine, f):+ """amplitude gain of the static fine spectral curve at frequencies f"""+ db = np.asarray(fine['db'], np.float64)+ lg = np.log2(np.maximum(f, 1.0) / fine['f0'])+ return 10 ** (np.interp(lg, np.arange(len(db)) * fine['step'], db, left=0.0, right=0.0) / 20)+++def _fine_psd(x, n_pts):+ """long-term PSD on the 1/24-octave grid (Welch 4096, each point the mean over +-1/48 octave, nearest bin+ when that holds none)"""+ from scipy.signal import welch+ nper = int(min(4096, 2 ** int(np.log2(max(len(x), 256)))))+ f, P = welch(x, SR, nperseg=nper, noverlap=nper * 3 // 4, window='hann')+ g = FINE_F0 * 2 ** (np.arange(n_pts) * FINE_STEP)+ c = np.concatenate([[0.0], np.cumsum(P)])+ lo = np.searchsorted(f, g * 2 ** (-FINE_STEP / 2))+ hi = np.searchsorted(f, g * 2 ** (FINE_STEP / 2))+ near = np.clip(np.searchsorted(f, g), 0, len(f) - 1)+ out = np.where(hi > lo, (c[np.maximum(hi, lo + 1)] - c[lo]) / np.maximum(hi - lo, 1), P[near])+ return out+++def _fit_fine(xm, model, seeds=(41, 42), verbose=False):+ """static fine spectral structure the bands cannot hold (resonances, comb, a whistle that does not move): the+ long-term 1/24-octave PSD of the original over that of renders, minus its own band-scale trend (so the band+ levels stay calibrated), clipped to +-12 dB; None when it is under 0.4 dB RMS"""+ n_pts = int(np.floor(np.log2(F_HI / FINE_F0) / FINE_STEP)) + 1+ Po = _fine_psd(xm, n_pts)+ Pr = np.mean([_fine_psd(_mono_render(model, s, None), n_pts) for s in seeds], 0)+ r = _db(Po + 1e-30) - _db(Pr + 1e-30)+ trend = convolve1d(r, np.ones(9) / 9, mode='nearest') # +-1/6 octave+ fd = np.clip(r - trend, -12, 12)+ lv = _db(Po + 1e-30)+ fd[lv < lv.max() - 60] = 0.0+ g = FINE_F0 * 2 ** (np.arange(n_pts) * FINE_STEP)+ # below ~300 Hz the 4096-point PSD has too few bins per point for a fine curve to mean anything+ fd *= np.clip((g - 150.0) / 150.0, 0, 1)+ rms = float(np.sqrt(np.mean(fd ** 2)))+ if verbose:+ print(f' fine spectral curve: {rms:.2f} dB RMS')+ if rms < 0.4:+ return None+ return {'f0': FINE_F0, 'step': FINE_STEP, 'db': [round(float(v), 1) for v in fd]}+++def fit(x, name=None, n_bands=N_BANDS, tol_db=1.0, max_keys=160, gesture_ms=25.0, max_rank=16, iters=3, diff_frames=3,+ ridges=True, fine=False, texture=True, stereo=True, seeds=(1, 2), verbose=False):+ """fit a spectral-noise model to a recording (path or (n,)/(n, 2) 48 kHz array); returns the model dict"""+ if name is None and isinstance(x, str):+ name = os.path.basename(x)+ x2 = _load(x)+ n = len(x2)+ mono = bool(np.allclose(x2[:, 0], x2[:, 1]))+ cents = centers(n_bands)+ bw = bandwidths(cents)+ A = analyse(x2, cents, stereo=stereo and not mono)+ T = A['T']+ D = A['D']+ xm = x2.mean(1)++ rmods = []+ if ridges:+ for tr in _find_ridges(xm, D, cents):+ rm, (k, fz, amp) = _ridge_model(tr)+ rmods.append(rm)+ D = _ridge_remove(D, cents, k, fz, amp)++ k = max(1, int(round(gesture_ms / (1000.0 * HOP / SR))))+ lv0 = _db((D * bw[:, None]).sum(0))+ on = int(np.argmax(lv0 > lv0.max() - 30))+ k_max = int(max(k, min(32, T // 6)))+ while True:+ # texture-aware gesture scale: how much the smoothed level wanders around a local quadratic (crackle,+ # flutter; a quadratic follows the gesture's own curvature); widen the smoothing while that wander is well+ # above tolerance, the rest is left to the texture statistics+ L1 = _db((_seg_smooth(D, k, on) * bw[:, None]).sum(0))+ fluct = _wander(L1, k, on)+ if fluct <= 2.0 * tol_db or k >= k_max:+ break+ k = min(k_max, int(np.ceil(k * 1.5)))+ tgt = _db(_seg_smooth(D, k, on))+ top = tgt.max()+ tgt = np.maximum(tgt, top - FLOOR_DB)+ act = tgt > top - 70+ Gp0 = tgt + 10 * np.log10(bw)[:, None]+ W = np.clip((Gp0 - (Gp0.max() - 50)) / 25, 0, 1).T # (T, B) cell weights+ # low-rank denoising: keep only the structure that stands above what a noise band's estimate wanders+ sig = _noise_sigma(n, cents, k, on)+ sw = float(np.sqrt((W * sig[None] ** 2).sum() / max(W.sum(), 1e-9)))+ rank = max_rank+ Y = tgt.T+ for K in range(1, max_rank + 1):+ Yh = _lowrank(Y, W, K)+ r = float(np.sqrt((W * (Y - Yh) ** 2).sum() / max(W.sum(), 1e-9)))+ if r <= sw:+ rank = K+ break+ # quiet cells (weight < 1) keep their measured level: the low-rank fill there is a guess (a dark corner where+ # the highs have died must stay dark)+ tgtK = np.maximum((W * Yh + (1 - W) * Y).T, top - FLOOR_DB)+ if verbose:+ print(f' rank {rank}: residual {r:.2f} dB, noise {sw:.2f} dB, onset frame {on}')+ Gm = tgtK.copy()+ tk = np.arange(T) * HOP / SR+ for it in range(iters):+ acc = np.zeros_like(Gm)+ for s in seeds:+ y = _synth(n, tk, Gm.T, cents, 7919 * (it + 1) + s, mono=True)+ acc += _db(_seg_smooth(analyse(y, cents, stereo=False)['D'], k, on))+ diff = tgtK - acc / len(seeds)+ diff = uniform_filter(np.where(act, diff, 0.0), size=(3, diff_frames), mode="nearest")+ Gm = np.maximum(Gm + 0.85 * np.clip(diff, -12, 12), top - FLOOR_DB)+ if verbose:+ print(f' iter {it}: mean |diff| on active cells {np.abs(diff[act]).mean():.2f} dB')++ ild, icc, gw = _stereo_traj(A['stereo'], T, mono or not stereo)+ Gp = Gm + 10 * np.log10(bw)[:, None]+ wc = np.clip((Gp - (Gp.max() - 50)) / 25, 0, 1).T # (T, B)+ lvl = _db((10 ** (Gp / 10)).sum(0))+ peak = int(np.argmax(lvl))+ onset = int(np.argmax(lvl > lvl.max() - 30))+ gact = np.clip((lvl - (lvl.max() - 40)) / 20, 0, 1)[:, None] * gw * len(GROUPS) # (T, G)+ Y = np.concatenate([Gm.T, ild / 2.0, icc * 10.0], 1)+ Wc = np.concatenate([wc, 0.5 * gact, 0.5 * gact], 1)+ tol = max(tol_db, fluct)+ keys = _keyframes(Y, Wc, tol, must=(peak, onset), max_keys=max_keys)++ model = {+ 'kind': KIND, 'version': VERSION, 'source': name, 'sr': SR, 'dur': round(n / SR, 4),+ 'level_db': round(_peak_rms_db(x2), 2),+ 'bands': {'n': int(n_bands), 'f_lo': F_LO, 'f_hi': F_HI, 'scale': 'ln(1+f/80)'},+ 'fit': {'gesture_ms': round(k * 1000.0 * HOP / SR, 1), 'rank': rank, 'tol_db': round(tol, 2), 'fluct_db': round(fluct, 2)},+ 'env': {'t': [round(float(tk[k]), 4) for k in keys],+ 'db': [[round(float(v), 1) for v in Gm[:, k]] for k in keys]},+ 'stereo': None if (mono or not stereo) else {+ 'groups': list(GROUPS),+ 'ild': [[round(float(v), 2) for v in ild[k]] for k in keys],+ 'icc': [[round(float(v), 3) for v in icc[k]] for k in keys]},+ 'fine': None,+ 'texture': None,+ 'ridges': rmods,+ }+ if fine:+ model['fine'] = _fit_fine(xm, model, verbose=verbose)+ if texture:+ model['texture'] = _fit_texture(xm, model, verbose=verbose)+ return model+++# --------------------------------------------------------------------------------------------- texture+++def _env_dense(model, times):+ """interpolated band density dB (B, len(times)) of a model's env keyframes"""+ tk = np.asarray(model['env']['t'], np.float64)+ E = np.asarray(model['env']['db'], np.float64)+ return np.stack([np.interp(times, tk, E[:, b]) for b in range(E.shape[1])])+++def _group_env(model, n):+ """per group gesture amplitude at 1 kHz frames: sqrt(sum of band density x bandwidth / (SR/2))"""+ cents = centers(model['bands']['n'])+ bw = bandwidths(cents)+ m1 = n // 48+ t1 = (np.arange(m1) + 0.5) * 48 / SR+ Dl = 10 ** (_env_dense(model, t1) / 10) * (bw / (SR / 2))[:, None]+ gi = _group_of(cents)+ G = len(GROUPS) - 1+ Eg = np.stack([np.sqrt(Dl[gi == g].sum(0) + 1e-30) for g in range(G)])+ return Eg+++def _texture_stats(xm, Eg, onset_s=None):+ """per group: modulation spectrum (G, len(RATES)) of log amplitude around the gesture, the std of the log+ analytic envelope ('kurt' key: the impulsiveness statistic) and the low-rate log-amplitude series"""+ n = len(xm)+ m1 = Eg.shape[1]+ N = n+ X = sfft.rfft(xm, workers=_workers())+ f = np.fft.rfftfreq(N, 1 / SR)+ G = Eg.shape[0]+ spec = np.full((G, len(RATES)), np.nan)+ kurt = np.full(G, np.nan)+ halves = np.full((2, G, len(RATES)), np.nan)+ lows = [None] * G+ Edb = 20 * np.log10(Eg + 1e-30)+ gpow = (Eg ** 2).sum(1)+ share = gpow / max(gpow.sum(), 1e-30)+ t1 = np.arange(m1) / 1000.0+ fm = np.fft.rfftfreq(m1, 1e-3)+ ed = RATES * 2 ** -0.25, RATES * 2 ** 0.25+ for g in range(G):+ if share[g] < 0.004:+ continue+ mask = (f >= GROUPS[g]) & (f < GROUPS[g + 1])+ xg = sfft.irfft(X * mask, N, workers=_workers())+ a = np.sqrt((xg[:m1 * 48].reshape(m1, 48) ** 2).mean(1))+ act = Edb[g] > Edb[g].max() - 30+ if onset_s is not None:+ act &= np.abs(t1 - onset_s) > 0.015+ if act.sum() < 24:+ continue+ r = np.log(a + 1e-12) - np.log(Eg[g] + 1e-12)++ def modspec(sel):+ w = convolve1d(sel.astype(np.float64), np.ones(5) / 5, mode='constant') # soft edges+ mu = (r * w).sum() / w.sum()+ rc = (r - mu) * w+ S = np.abs(np.fft.rfft(rc)) ** 2+ var = (rc ** 2).sum() / w.sum()+ Sb = np.array([S[(fm >= lo) & (fm < hi)].sum() for lo, hi in zip(*ed)])+ return Sb / max(S[1:].sum(), 1e-30) * var, rc+ spec[g], rc = modspec(act)+ # the two halves of the active span apart: flutter that is there throughout, not a gesture misfit in one spot+ idx = np.nonzero(act)[0]+ mid = idx[len(idx) // 2]+ for h, sel in enumerate((act & (np.arange(m1) < mid), act & (np.arange(m1) >= mid))):+ halves[h, g] = modspec(sel)[0] if sel.sum() >= 12 else np.nan+ # impulsiveness: std of the log analytic envelope around the gesture (Gaussian noise: Rayleigh, 0.64 nepers;+ # sparse crackle: deep gaps between clicks, up to ~1.5). Robust where kurtosis is ruled by the largest click.+ Xa = np.zeros(N, complex)+ Xa[:len(f)] = X * mask+ Xa[1:len(f)] *= 2.0+ ae = np.abs(sfft.ifft(Xa, workers=_workers()))[:m1 * 48]+ sel = np.repeat(act, 48)+ lr_ = np.log(ae[sel] + 1e-12) - np.log(np.repeat(Eg[g], 48)[sel] + 1e-12)+ kurt[g] = float(lr_.std())+ lp = np.fft.irfft(np.fft.rfft(rc) * (fm <= AM_MAX_RATE), m1)+ lows[g] = (lp, act)+ return {'spec': spec, 'kurt': kurt, 'share': share, 'lows': lows, 'halves': halves}+++def _coherence(st):+ """mean correlation of the low-rate log amplitude between the two loudest active groups"""+ ok = [g for g in range(len(st['share'])) if st['lows'][g] is not None]+ if len(ok) < 2:+ return 0.0+ ok.sort(key=lambda g: -st['share'][g])+ (a, ma), (b, mb) = st['lows'][ok[0]], st['lows'][ok[1]]+ m = ma & mb+ if m.sum() < 24:+ return 0.0+ a, b = a[m], b[m]+ den = np.sqrt((a * a).sum() * (b * b).sum())+ return float((a * b).sum() / den) if den > 0 else 0.0+++def _mono_render(model, seed, texture):+ cents = centers(model['bands']['n'])+ n = int(round(model['dur'] * SR))+ return _synth(n, model['env']['t'], model['env']['db'], cents, seed, texture=texture,+ ridges=model.get('ridges') or (), mono=True, fine=model.get('fine'))+++def _avg_stats(model, n, Eg, texture, seeds, onset_s):+ sts = [_texture_stats(_mono_render(model, s, texture)[:n], Eg, onset_s) for s in seeds]+ spec = np.nanmean(np.stack([s['spec'] for s in sts]), 0)+ kurt = np.nanmean(np.stack([s['kurt'] for s in sts]), 0)+ halves = np.nanmean(np.stack([s['halves'] for s in sts]), 0)+ return {'spec': spec, 'kurt': kurt, 'share': sts[0]['share'], 'lows': sts[0]['lows'], 'all': sts, 'halves': halves}+++def _fit_am(Sr, base, wg, ok, low):+ """AM from the low-rate log-amplitude variance the real has beyond `base` (a render's stats)"""+ spr, sp0 = np.nan_to_num(Sr['spec']), np.nan_to_num(base['spec'])+ sd0 = np.nan_to_num(np.std(np.stack([s['spec'] for s in base['all']]), 0))+ sig = (spr > 1.25 * sp0 + 2.0 * sd0) & low[None]+ ex = np.where(sig, spr - sp0, 0.0)+ # only what both halves of the active span have in excess (stationary flutter, not one gesture misfit)+ hx = np.nan_to_num(Sr['halves'] - 1.25 * base['halves'], nan=0.0)+ ex = np.minimum(ex, np.maximum(np.minimum(hx[0], hx[1]), 0.0))+ ex[~ok] = 0.0+ depth = np.minimum(np.sqrt(ex.sum(1)), AM_MAX_DEPTH)+ shape = (wg[:, None] * ex).sum(0)+ if (depth * (wg > 0.03)).max() <= 0.08 or shape.sum() <= 0:+ return None+ coh = float(np.clip(_coherence(Sr) - _coherence(base['all'][0]), 0.0, 1.0))+ return {'rates': [float(r) for r in RATES], 'spec': [round(float(v), 5) for v in shape / shape.sum()],+ 'depth': [round(float(v), 4) for v in depth], 'coh': round(coh, 3)}+++def _fit_texture(xm, model, seeds=(31, 32, 33), verbose=False):+ """texture statistics by analysis-by-synthesis on mono renders of the gesture:+ grains are detected by excess fast (>= 128 Hz) log-amplitude variance (Poisson clicks put variance at every rate,+ flutter does not) and their density is fitted to the std of the log analytic envelope (monotone, stable across+ seeds; kurtosis is not: it is ruled by the largest click); AM is the low-rate (<= 64 Hz) log-amplitude variance+ beyond what Gaussian noise / the grains already make. Grains and AM are refitted once against each other."""+ import warnings+ n = len(xm)+ Eg = _group_env(model, n)+ tk = np.asarray(model['env']['t'])+ lv = np.asarray(model['env']['db']).max(1)+ onset_s = float(tk[int(np.argmax(lv > lv.max() - 30))])+ low = (RATES <= AM_MAX_RATE) & (RATES >= AM_MIN_RATE)+ high = RATES >= 128+ with warnings.catch_warnings():+ warnings.simplefilter('ignore', RuntimeWarning)+ Sr = _texture_stats(xm, Eg, onset_s)+ S0 = _avg_stats(model, n, Eg, None, seeds, onset_s)+ ok = ~np.isnan(Sr['kurt']) & ~np.isnan(S0['kurt'])+ if not ok.any():+ return None+ share = np.where(ok, Sr['share'], 0.0)+ wg = share / share.sum()+ rnd = lambda v, k=3: [None if not np.isfinite(e) else round(float(e), k) for e in v]+ hr = np.nansum(np.nan_to_num(Sr['spec'])[:, high], 1)+ h0 = np.nansum(np.nan_to_num(S0['spec'])[:, high], 1)+ hsd = np.std([np.nansum(np.nan_to_num(a['spec'])[:, high], 1) for a in S0['all']], 0)+ hx = float(np.sum(wg * (hr - h0)))+ hratio = float(np.sum(wg * hr) / max(np.sum(wg * h0), 1e-9))+ tex = {'am': None, 'grains': None, 'stats': {+ 'lenv_real': rnd(Sr['kurt']), 'lenv_gauss': rnd(S0['kurt']),+ 'fast_var_real': rnd(hr), 'fast_var_gauss': rnd(h0), 'fast_ratio': round(hratio, 2)}}+ grainy = hx > max(0.03, 3 * float(np.sum(wg * hsd))) and hratio > 1.5+ if verbose:+ print(' texture: lenv real', np.round(Sr['kurt'], 2), 'gauss', np.round(S0['kurt'], 2),+ f'fast var ratio {hratio:.2f}', 'grainy' if grainy else '')++ def fit_density(am):+ cache = {}++ def loss(d):+ st = _avg_stats(model, n, Eg, {'am': am, 'grains': {'density': d}}, seeds, onset_s)+ cache[d] = st+ return float(np.nansum(wg * (st['kurt'] - Sr['kurt']) ** 2))+ grid = [25, 60, 150, 400, 1000, 2500, 6000, 15000]+ ls = [loss(d) for d in grid]+ i = int(np.argmin(ls))+ best, bl = grid[i], ls[i]+ for j in (i - 1, i + 1):+ if 0 <= j < len(grid):+ d = float(np.sqrt(grid[i] * grid[j]))+ v = loss(d)+ if v < bl:+ best, bl = d, v+ return best, bl, cache[best]++ base = S0+ if grainy:+ dens, bl, base = fit_density(None)+ tex['grains'] = {'density': round(float(dens), 1), 'spread': SPREAD}+ if verbose:+ print(f' grains: density {dens:.0f}/s (lenv loss {bl:.4f})')+ am = _fit_am(Sr, base, wg, ok, low)+ if am is not None and grainy:+ # flutter raises the log-envelope spread too: refit the density with the AM in, then the AM again+ dens, bl, _ = fit_density(am)+ tex['grains'] = {'density': round(float(dens), 1), 'spread': SPREAD}+ base = _avg_stats(model, n, Eg, {'grains': tex['grains']}, seeds, onset_s)+ am = _fit_am(Sr, base, wg, ok, low)+ if verbose:+ print(f' grains refit with AM: density {dens:.0f}/s')+ if am is not None:+ S1 = _avg_stats(model, n, Eg, {'am': am, 'grains': tex['grains']}, seeds, onset_s)+ spr, sp0, sp1 = [np.nan_to_num(S['spec']) for S in (Sr, base, S1)]+ want = np.maximum(spr[:, low].sum(1) - sp0[:, low].sum(1), 0)+ got = np.maximum(sp1[:, low].sum(1) - sp0[:, low].sum(1), 1e-6)+ depth = np.asarray(am['depth'])+ depth = np.where(depth > 0, np.minimum(depth * np.sqrt(np.clip(want / got, 0.25, 4.0)), AM_MAX_DEPTH), 0.0)+ am['depth'] = [round(float(v), 4) for v in depth]+ if verbose:+ print(' am depth', np.round(depth, 3), 'peak rate', am['rates'][int(np.argmax(am['spec']))])+ tex['am'] = am+ tex['stats']['am_var_real'] = rnd(np.nan_to_num(Sr['spec'])[:, low].sum(1), 4)+ tex['stats']['am_var_base'] = rnd(np.nan_to_num(base['spec'])[:, low].sum(1), 4)+ return tex+++# ---------------------------------------------------------------------------------------------- render+++def check(model):+ if not isinstance(model, dict) or model.get('kind') != KIND:+ raise ValueError(f"not a {KIND} model (kind={model.get('kind') if isinstance(model, dict) else None!r})")+ if int(model.get('version', 0)) > VERSION:+ raise ValueError(f"model version {model.get('version')} is newer than this renderer ({VERSION})")+++def _centroid_oct(E, cents, bw):+ """per keyframe: centroid in log2(Hz) weighted by band loudness (power ** 0.3, so a sub rumble does not rule+ it), and the keyframe's total power"""+ p = 10 ** (E / 10) * bw[None]+ lw = (p / max(p.max(), 1e-30)) ** 0.3+ return (lw * np.log2(cents)[None]).sum(1) / np.maximum(lw.sum(1), 1e-30), p.sum(1)+++def render(model, seed=0, length=1.0, speed=1.0, sweep=1.0, shift=0.0, tilt=0.0, roughness=1.0, width=1.0,+ ridges=1.0, gain_db=0.0, level=True):+ """render a model: (n, 2) float32 at 48 kHz. New `seed` = new noise, same statistics. See the module doc."""+ check(model)+ cents = centers(model['bands']['n'])+ bw = bandwidths(cents)+ speed = max(float(speed), 1e-3)+ s = max(float(length), 1e-3) / speed+ n = max(64, int(round(model['dur'] * s * SR)))+ tk = np.asarray(model['env']['t'], np.float64) * s+ E = np.asarray(model['env']['db'], np.float64)+ oct_ = float(shift) + SPEED_OCT * np.log2(speed)+ co, cp = _centroid_oct(E, cents, bw)+ cm = (co * cp).sum() / max(cp.sum(), 1e-30)+ octs = oct_ + (float(sweep) - 1.0) * (co - cm)+ if np.any(np.abs(octs) > 1e-9):+ ec = warp(cents)+ E = np.stack([np.interp(warp(cents / 2 ** o), ec, row) for o, row in zip(octs, E)])+ if tilt:+ E = E + float(tilt) * np.log2(cents / 1000.0)[None]+ st = model.get('stereo')+ if st is not None:+ icc = 1 - float(width) * (1 - np.asarray(st['icc'], np.float64))+ st = {'ild': np.asarray(st['ild'], np.float64) * float(width), 'icc': np.clip(icc, -1, 1)}+ rds = []+ if ridges:+ for rd in model.get('ridges') or ():+ rt = np.asarray(rd['t'], np.float64)+ o = oct_ + (float(sweep) - 1.0) * (np.interp(rt, np.asarray(model['env']['t']), co) - cm)+ rds.append({'t': rt * s, 'f': np.minimum(np.asarray(rd['f']) * 2 ** o, SR * 0.45),+ 'db': np.asarray(rd['db']) + 20 * np.log10(float(ridges)), 'jitter': rd.get('jitter', 0.002)})+ y = _synth(n, tk, E, cents, seed, stereo=st, texture=model.get('texture'), ridges=rds, rate_scale=speed,+ fine=model.get('fine'), fine_shift=oct_,+ rough=float(roughness))+ if level:+ y *= 10 ** ((model['level_db'] + float(gain_db) - _peak_rms_db(y)) / 20)+ pk = np.abs(y).max()+ if pk > 10 ** (-0.5 / 20):+ y *= 10 ** (-0.5 / 20) / pk+ return y.astype(np.float32)+++# ------------------------------------------------------------------------------------- serialisation+++def save(model, path):+ with open(path, 'w', encoding='utf-8') as fh:+ json.dump(model, fh, separators=(',', ':'))+++def load(path):+ with open(path, encoding='utf-8') as fh:+ m = json.load(fh)+ check(m)+ return m+++def summary(model):+ """one paragraph in words: length, peak, centroid path, width, texture, ridges, model size"""+ check(model)+ cents = centers(model['bands']['n'])+ bw = bandwidths(cents)+ tk = np.asarray(model['env']['t'])+ E = np.asarray(model['env']['db'])+ co, cp = _centroid_oct(E, cents, bw)+ lv = _db(cp)+ pk = int(np.argmax(lv))+ on = int(np.argmax(lv > lv.max() - 20))+ act = lv > lv.max() - 20+ last = len(lv) - 1 - int(np.argmax(act[::-1]))+ hz = lambda o: f'{2 ** o / 1000:.2g} kHz' if 2 ** o >= 1000 else f'{2 ** o:.0f} Hz'+ w = [f"{model.get('source') or 'model'}: {model['dur']:.2f} s noise gesture, {len(tk)} keyframes",+ f'up 20 dB in {1000 * (tk[pk] - tk[on]):.0f} ms to the peak at {tk[pk]:.2f} s, '+ f'within 20 dB until {tk[last]:.2f} s',+ f'centroid {hz(co[on])} -> {hz(co[pk])} (peak) -> {hz(co[last])}']+ st = model.get('stereo')+ if st:+ icc = np.asarray(st['icc'])+ ild = np.asarray(st['ild'])+ w.append(f'inter-channel corr {np.median(icc):.2f} (min {icc.min():.2f}), pan {ild.min():+.1f}..{ild.max():+.1f} dB '+ '(per band group)')+ else:+ w.append('mono')+ tx = model.get('texture') or {}+ if tx.get('am'):+ am = tx['am']+ sp = np.asarray(am['spec'])+ w.append(f"flutter around {am['rates'][int(np.argmax(sp))]:.0f} Hz, depth up to "+ f"{8.686 * max(am['depth']):.1f} dB, coherence {am['coh']:.2f}")+ if tx.get('grains'):+ w.append(f"crackle: {tx['grains']['density']:.0f} grains / s")+ for rd in model.get('ridges') or ():+ w.append(f"tonal ridge {rd['f'][0]:.0f} -> {rd['f'][-1]:.0f} Hz over {rd['t'][-1] - rd['t'][0]:.2f} s")+ w.append(f"{len(json.dumps(model)) / 1024:.1f} kB JSON")+ return '; '.join(w)+++def to_code(model, var='MODEL'):+ """the model as readable Python source that re-renders it (fresh noise per seed)"""+ check(model)+ m = {k: v for k, v in model.items() if k not in ('env', 'stereo', 'texture', 'ridges', 'fine')}+ lines = [f'"""{summary(model)}"""',+ 'from earshot.forge.fit.spectral import render', '',+ f'{var} = {{']+ for k, v in m.items():+ lines.append(f' {k!r}: {v!r},')+ cents = centers(model['bands']['n'])+ lines.append(' # band centres (Hz): ' + ' '.join(f'{c:.0f}' for c in cents))+ lines.append(" # the gesture: keyframe time (s) -> band power density (dB re full-scale white noise),")+ lines.append(" # linear in dB between keyframes")+ lines.append(" 'env': {'t': " + repr(model['env']['t']) + ",")+ lines.append(" 'db': [")+ for t, row in zip(model['env']['t'], model['env']['db']):+ lines.append(f" {row!r}, # {t:.3f} s")+ lines.append(' ]},')+ st = model.get('stereo')+ if st:+ lines.append(" # per band group " + repr(st['groups']) + ' Hz at each keyframe: L/R level difference (dB) and correlation')+ lines.append(" 'stereo': {'groups': " + repr(st['groups']) + ",")+ lines.append(" 'ild': " + repr(st['ild']) + ",")+ lines.append(" 'icc': " + repr(st['icc']) + '},')+ else:+ lines.append(" 'stereo': None,")+ lines.append(" # optional static fine spectral curve (dB every 1/24 octave from f0), multiplied into the noise")+ lines.append(f" 'fine': {model.get('fine')!r},")+ lines.append(" # statistics of what the gesture does not hold: flutter (am) and crackle (grains)")+ lines.append(f" 'texture': {model.get('texture')!r},")+ lines.append(" # tonal ridges: keyframes of frequency (Hz) and amplitude (dB re full scale)")+ lines.append(f" 'ridges': {model.get('ridges')!r},")+ lines.append('}')+ lines += ['', '', 'def make(seed=0, **knobs):',+ ' """knobs: length, speed, sweep, shift, tilt, roughness, width, ridges, gain_db"""',+ f' return render({var}, seed=seed, **knobs)', '']+ return '\n'.join(lines)+++# ---------------------------------------------------------------------------------------------- quality+++def _mono(x):+ x = np.asarray(x, np.float64)+ return x.mean(1) if x.ndim == 2 else x+++def _onset_trim(m, db=-30.0, pre_ms=5.0):+ k = 48+ nb = len(m) // k+ if nb < 2:+ return m+ e = _db((m[:nb * k].reshape(nb, k) ** 2).mean(1))+ on = int(np.argmax(e > e.max() + db)) * k+ return m[max(0, on - int(SR * pre_ms / 1000)):]+++def _mel_fb(n_fft, n_mel=64, f_lo=30.0, f_hi=20000.0):+ mel = lambda f: 2595 * np.log10(1 + f / 700)+ imel = lambda m: 700 * (10 ** (m / 2595) - 1)+ pts = imel(np.linspace(mel(f_lo), mel(f_hi), n_mel + 2))+ f = np.fft.rfftfreq(n_fft, 1 / SR)+ fb = np.zeros((n_mel, len(f)))+ for i in range(n_mel):+ a, c, b = pts[i], pts[i + 1], pts[i + 2]+ fb[i] = np.clip(np.minimum((f - a) / (c - a), (b - f) / (b - c)), 0, None)+ if fb[i].sum() == 0:+ fb[i, int(np.argmin(np.abs(f - c)))] = 1.0+ return fb+++def _melspec(m, n_fft):+ hop = n_fft // 4+ T = max(1, (len(m) + hop - 1) // hop)+ win = _hann(n_fft)+ xp = np.zeros(T * hop + n_fft)+ xp[n_fft // 2:n_fft // 2 + len(m)] = m+ fr = np.lib.stride_tricks.sliding_window_view(xp, n_fft)[::hop][:T]+ P = np.abs(np.fft.rfft(fr * win, axis=1)) ** 2+ return _db(P @ _mel_fb(n_fft).T + 1e-20)+++def _env_db(m, ms=5.0):+ k = int(SR * ms / 1000)+ nb = max(1, len(m) // k)+ return _db((m[:nb * k].reshape(nb, k) ** 2).mean(1) + 1e-20)+++def _attack_ms(m):+ e = _env_db(m, 2.0)+ e = np.convolve(e, np.ones(3) / 3, mode='same')+ pk = int(np.argmax(e))+ on = int(np.argmax(e > e[pk] - 20))+ return 2.0 * (pk - on)+++def compare(a, b, clap=False):+ """distances between two sounds (each levelled to its loudest 50 ms RMS, onset-aligned):+ mel_db (mean |dB| over active log-mel cells, mean of FFT 256 / 1024 / 4096), mel_256/1024/4096, env_corr+ (5 ms dB envelopes), attack_ms (a, b), tone_db (1/3-octave balance RMS), len_s (a, b), optional clap cosine"""+ from ..tone import profile+ A = _onset_trim(_mono(a))+ B = _onset_trim(_mono(b))+ A = A * 10 ** (-_peak_rms_db(A) / 20)+ B = B * 10 ** (-_peak_rms_db(B) / 20)+ n = max(len(A), len(B))+ Ap, Bp = np.zeros(n), np.zeros(n)+ Ap[:len(A)] = A+ Bp[:len(B)] = B+ out = {}+ ds = []+ for nf in (256, 1024, 4096):+ MA, MB = _melspec(Ap, nf), _melspec(Bp, nf)+ top = max(MA.max(), MB.max())+ MA, MB = np.maximum(MA, top - 80), np.maximum(MB, top - 80)+ actv = np.maximum(MA, MB) > top - 60+ d = float(np.abs(MA - MB)[actv].mean()) if actv.any() else 0.0+ out[f'mel_{nf}'] = round(d, 2)+ ds.append(d)+ out['mel_db'] = round(float(np.mean(ds)), 2)+ ea, eb = _env_db(Ap), _env_db(Bp)+ top = max(ea.max(), eb.max())+ ea, eb = np.maximum(ea, top - 60), np.maximum(eb, top - 60)+ actv = np.maximum(ea, eb) > top - 60+ out['env_corr'] = round(float(np.corrcoef(ea[actv], eb[actv])[0, 1]), 3) if actv.sum() > 3 else 0.0+ out['attack_ms'] = (_attack_ms(A), _attack_ms(B))+ out['tone_db'] = round(float(np.sqrt(np.mean((profile(A) - profile(B)) ** 2))), 2)+ out['len_s'] = (round(len(_mono(a)) / SR, 3), round(len(_mono(b)) / SR, 3))+ if clap:+ from ...models import clap as _clap+ E = _clap.get().embed_audio([_mono(a).astype(np.float32), _mono(b).astype(np.float32)])+ out['clap_cos'] = round(float(E[0] @ E[1]), 4)+ return out+++def fit_report(x, clap=False, seeds=(11, 12), **fit_kw):+ """fit + two renders; {'model', 'renders', 'fit': compare(orig, r1), 'floor': compare(r1, r2), 'seconds'}"""+ import time+ t0 = time.time()+ x2 = _load(x)+ m = fit(x if isinstance(x, str) else x2, **fit_kw)+ t1 = time.time()+ r1 = render(m, seed=seeds[0])+ r2 = render(m, seed=seeds[1])+ q = compare(x2, r1, clap=clap)+ fl = compare(r1, r2, clap=clap)+ return {'model': m, 'renders': (r1, r2), 'orig': x2, 'fit': q, 'floor': fl,+ 'seconds': {'fit': round(t1 - t0, 2), 'render': round((time.time() - t1) / 2, 2)}}+++def pair_png(path, rows, span_s=None, title=None):+ """spectrogram pairs: rows of (label, original, resynthesis[, resynthesis 2]); log-frequency, same dB range"""+ import matplotlib+ matplotlib.use('Agg')+ import matplotlib.pyplot as plt+ ncol = max(len(r) - 1 for r in rows) + 1+ fig, axs = plt.subplots(len(rows), ncol, figsize=(4.2 * ncol, 2.6 * len(rows)), squeeze=False)+ for i, row in enumerate(rows):+ label, sigs = row[0], [_onset_trim(_mono(s)) for s in row[1:]]+ sp = span_s or max(len(s) for s in sigs) / SR+ nsp = int(sp * SR)+ Ss = []+ for s in sigs:+ s = s * 10 ** (-_peak_rms_db(s) / 20)+ z = np.zeros(nsp)+ z[:min(nsp, len(s))] = s[:nsp]+ Ss.append(_melspec(z, 1024))+ top = max(S.max() for S in Ss)+ for j, S in enumerate(Ss):+ ax = axs[i, j]+ ax.imshow(np.maximum(S, top - 80).T, origin='lower', aspect='auto', cmap='magma', vmin=top - 80, vmax=top,+ extent=(0, sp, 0, 64))+ ax.set_yticks([0, 16, 32, 48, 64])+ ax.set_yticklabels(['30', '600', '2k', '6k', '20k'], fontsize=6)+ ax.tick_params(labelsize=6)+ ax.set_title(f"{label} | {'orig' if j == 0 else f'render {j}'}", fontsize=7)+ ax = axs[i, -1]+ for j, s in enumerate(sigs):+ s = s * 10 ** (-_peak_rms_db(s) / 20)+ e = _env_db(s[:nsp])+ ax.plot(np.arange(len(e)) * 0.005, np.maximum(e, -70), lw=0.8, label='orig' if j == 0 else f'r{j}')+ ax.set_ylim(-70, 5)+ ax.legend(fontsize=6)+ ax.tick_params(labelsize=6)+ ax.set_title('5 ms envelope dB', fontsize=7)+ if title:+ fig.suptitle(title, fontsize=9)+ fig.tight_layout()+ fig.savefig(path, dpi=110)+ plt.close(fig)+ return pathdiff --git a/tests/test_fit_engine.py b/tests/test_fit_engine.pynew file mode 100644index 0000000..e979d25--- /dev/null+++ b/tests/test_fit_engine.py@@ -0,0 +1,234 @@+"""The fit engine (earshot/forge/fit: auto, quality, codegen, CLI): synthetic signals of known structure only."""+import json++import numpy as np+import pytest++from earshot.forge import dsp+from earshot.forge.fit import auto, codegen+from earshot.forge.fit import quality as Q++SR = 48000+++def struck(f=(1200.0, 2900.0), tau=(0.03, 0.012), amp=(0.6, 0.3), n_s=0.15, t0=0.01, seed=0, noise=0.02):+ """a click: damped modes from t0 plus a short decaying noise burst and a faint floor"""+ r = np.random.default_rng(seed)+ n = int(n_s * SR)+ t = np.arange(n) / SR - t0+ on = t >= 0+ y = np.zeros(n)+ for fi, ti, ai in zip(f, tau, amp):+ y += on * ai * np.exp(-np.clip(t, 0, None) / ti) * np.sin(2 * np.pi * fi * np.clip(t, 0, None))+ y += on * noise * 10 * r.standard_normal(n) * np.exp(-np.clip(t, 0, None) / 0.004)+ y += 1e-4 * r.standard_normal(n)+ return y+++def swell(n_s=0.5, seed=1):+ """a noise gesture: band-limited noise swelling over 300 ms, then fading"""+ r = np.random.default_rng(seed)+ n = int(n_s * SR)+ t = np.arange(n) / SR+ env = np.minimum(t / 0.3, 1.0) ** 2 * np.exp(-np.clip(t - 0.3, 0, None) / 0.05)+ return 0.3 * dsp.butter(r.standard_normal(n), 'band', (800.0, 5000.0)) * env+++def tone(f=(660.0, 1320.0), n_s=1.2, decay=0.4):+ t = np.arange(int(n_s * SR)) / SR+ y = sum(a * np.sin(2 * np.pi * fi * t) for fi, a in zip(f, (0.5, 0.2)))+ return y * np.exp(-t / decay) * np.minimum(t / 0.003, 1.0)+++def chirp(n_s=0.2, f0=400.0, f1=1400.0):+ t = np.arange(int(n_s * SR)) / SR+ f = f0 * (f1 / f0) ** (t / n_s)+ ph = 2 * np.pi * np.cumsum(f) / SR+ return 0.5 * np.sin(ph) * np.minimum(t / 0.002, 1.0) * np.exp(-t / 0.08)+++# --------------------------------------------------------------------------------------------------- quality+def test_quality_identity_gain_and_shift():+ x = struck()+ q = Q.quality(x, x)+ assert q['mel_db'] == 0 and q['tone_db'] == 0 and q['onset_err'] == 0 and q['env_corr'] > 0.999+ q2 = Q.quality(x, 0.5 * x) # each sound is levelled: only level_db sees a gain+ assert abs(q2['level_db'] + 6.02) < 0.05 and q2['mel_db'] < 1e-6+ q3 = Q.quality(x, np.roll(x, int(0.03 * SR))) # a timing error counts (no re-alignment on the resynthesis)+ assert q3['mel_db'] > 5 and q3['env_corr'] < q['env_corr']+ assert Q.score(q) < Q.score(q3)+++def test_quality_onset_sharpness_and_tone():+ x = struck()+ t = np.arange(len(x)) / SR - 0.01+ soft = Q.quality(x, x * np.clip(t / 0.004, 0, 1))['onset_err'] # a 4 ms fade-in over the strike+ softer = Q.quality(x, x * np.clip(t / 0.012, 0, 1))['onset_err'] # a 12 ms one+ assert Q.quality(x, x.copy())['onset_err'] < 0.05 and 0.4 < soft < softer and softer > 1.0+ dark = dsp.butter(x, 'low', 1500.0)+ assert Q.quality(x, dark)['tone_db'] > 3+++# --------------------------------------------------------------------------------------------------- character[email protected]('sig,cls,first', [+ (struck(), 'struck', 'modal'),+ (swell(), 'gesture', 'spectral'),+ (tone(), 'ringing', 'sines'),+ (chirp(), 'glide', 'sines'),+])+def test_character_classes(sig, cls, first):+ c = auto.character(sig)+ assert c['class'] == cls, c+ p = auto.plan(c)+ assert p[0] == first+ assert len(p) == len(set(p))+ if c['dur_s'] < 1.0:+ assert set(p) == set(auto.ALL) # short sounds: every candidate is cheap enough to try+++# --------------------------------------------------------------------------------------------------- fitting+def test_auto_picks_by_quality_and_post_stage():+ x = struck()+ got = {}+ m = auto.fit(x, candidates=['modal', 'spectral'], fast=True, collect=got)+ fe = m['fit_engine']+ assert fe['kind'] == 'auto' and set(got) == {'modal', 'spectral'}+ sc = {r['candidate']: r['score'] for r in fe['candidates']}+ assert fe['chosen'] == min(sc, key=sc.get) == 'modal'+ assert set(m['post']) >= {'eq_db', 'gain_db', 'pre'} and len(m['post']['eq_db']) == 28+ y = auto.render(m, seed=0)+ assert len(y) == len(x)+ q = Q.quality(x, y)+ assert q['mel_db'] < 6 and q['env_corr'] > 0.85 and abs(q['level_db']) < 1.5+ assert np.array_equal(auto.render(m, seed=3), auto.render(m, seed=3)) # deterministic per seed+++def test_post_stage_cleans_the_pre_onset_and_matches_balance():+ x = struck(t0=0.02)+ r = np.random.default_rng(5)+ leak = x + 0.05 * r.standard_normal(len(x)) * (np.arange(len(x)) < int(0.02 * SR)) # noise before the strike+ leak = dsp.butter(leak, 'low', 6000.0) # and a darker balance+ post = auto.fit_post(x, [leak])+ y = auto.apply_post(leak, post)+ n_on = int(0.019 * SR)+ p = lambda v: 10 * np.log10(np.mean(v[:n_on] ** 2) + 1e-20)+ assert p(y) < p(leak) - 15 # pre-onset leak removed+ assert Q.quality(x, y)['tone_db'] < Q.quality(x, leak)['tone_db']+++def test_hybrid_layers_and_deterministic_part():+ x = struck(noise=0.05)+ m = auto.fit_hybrid(x, ('modal', 'spectral'), fast=True)+ assert m['kind'] == 'hybrid' and [L['role'] for L in m['layers']] == ['body', 'air']+ det = m['layers'][0]['model']+ assert det['layer'] == 'deterministic' and 'post' not in det+ assert all(max(v for _, v in env) <= -200 for env in det['noise']['env']) # no noise in the deterministic layer+ y = auto.render(m, seed=1)+ assert y.shape[0] == len(x) and Q.quality(x, y)['mel_db'] < 7+ y2 = auto.render(m, seed=1, body_db=-60.0) # the air layer alone is quieter+ assert np.sqrt(np.mean(y2 ** 2)) < np.sqrt(np.mean(y ** 2))+ with pytest.raises(ValueError):+ auto.fit_hybrid(x, ('spectral', 'sines'))+++def test_render_rejects_unknown_knobs():+ m = auto.fit(struck(), kind='modal', fast=True)+ with pytest.raises(ValueError):+ auto.render(m, seed=0, transpose=2)+ assert len(auto.render(m, seed=0, size=1.2, vary=0.3)) > 0+++# --------------------------------------------------------------------------------------------------- codegen+def test_codegen_recipe_round_trip(tmp_path):+ x = struck()+ m = auto.fit(x, kind='modal', fast=True)+ src = codegen.to_recipe(m, name='synth_click', target='a short test click')+ assert 'fit_engine' not in src.split('MODEL = ', 1)[1]+ ns = {}+ exec(codegen.literal(m), ns)+ assert ns['MODEL'] == {k: v for k, v in m.items() if k != 'fit_engine'} # the literal is exact+ p = codegen.write_recipe(str(tmp_path / 'synth_click.py'), m, target='a short test click')+ rec = codegen.load_recipe(p)+ assert rec.TARGET == 'a short test click' and rec.KIND == 'modal'+ assert set(rec.SPACE) == set(rec.DEFAULTS) == set(auto.KNOBS['modal'])+ for spec in rec.SPACE.values(): # valid forge SPACE specs+ assert len(spec) in (2, 3) and spec[0] < spec[1]+ assert np.array_equal(rec.render_seed(0), auto.render(m, seed=0)) # the code renders the fit, bitwise+ seed = int(dsp.rng(7).integers(0, 2 ** 31 - 1))+ assert np.array_equal(rec.render(rec.DEFAULTS, dsp.rng(7)), auto.render(m, seed=seed))+ var = rec.render(dict(rec.DEFAULTS, size=1.2, vary=0.4), dsp.rng(7))+ assert len(var) > 0 and not np.allclose(var[:len(x)], rec.render_seed(0)[:len(var)])+++def test_codegen_sines_and_spectral_recipes(tmp_path):+ for sig, kind in ((tone(n_s=0.5, decay=0.15), 'sines'), (swell(), 'spectral')):+ m = auto.fit(sig, kind=kind, fast=True)+ rec = codegen.load_recipe(codegen.write_recipe(str(tmp_path / f'r_{kind}.py'), m))+ assert np.array_equal(rec.render_seed(2), auto.render(m, seed=2))+ assert set(rec.SPACE) == set(auto.KNOBS[kind])+++# --------------------------------------------------------------------------------------------------- morph+def _strongest_mode(m):+ md = np.array(m['strikes'][0]['modes'])+ return md[np.argmax(md[:, 2] ** 2 * md[:, 1]), 0]+++def test_morph_modal_interpolates_frequency_and_keeps_endpoints():+ a = auto.fit(struck(f=(1000.0,), tau=(0.04,), amp=(0.6,), noise=0.002), kind='modal', fast=True)+ b = auto.fit(struck(f=(1600.0,), tau=(0.04,), amp=(0.6,), noise=0.002, seed=3), kind='modal', fast=True)+ mid = auto.morph(a, b, 0.5)+ assert abs(_strongest_mode(mid) / np.sqrt(1000.0 * 1600.0) - 1) < 0.03+ assert np.allclose(auto.render(auto.morph(a, b, 0.0), 1), auto.render(a, 1), atol=1e-9)+ assert np.allclose(auto.render(auto.morph(a, b, 1.0), 1), auto.render(b, 1), atol=1e-9)+ mm = auto.morph_model(a, b, 0.3)+ assert 'morph' in auto.knobs_of(mm)+ assert np.array_equal(auto.render(mm, 2), auto.render(auto.morph(a, b, 0.3), 2))+ assert np.array_equal(auto.render(mm, 2, morph=0.5), auto.render(mid, 2))+ s = auto.fit(swell(), kind='spectral', fast=True)+ with pytest.raises(ValueError):+ auto.morph(a, s, 0.5)+++def test_morph_sines_and_spectral():+ from earshot.forge.fit.sines import partial_freq+ a = auto.fit(tone(f=(440.0, 880.0), n_s=0.4, decay=0.15), kind='sines', fast=True)+ b = auto.fit(tone(f=(660.0, 1320.0), n_s=0.4, decay=0.15), kind='sines', fast=True)+ mid = auto.morph(a, b, 0.5)+ f0 = partial_freq(mid['partials'][0])+ assert abs(f0 / np.sqrt(440.0 * 660.0) - 1) < 0.03+ assert len(auto.render(mid, 0)) > 0+ r = np.random.default_rng(2)+ lo = auto.fit(0.2 * dsp.butter(r.standard_normal(SR // 3), 'low', 1000.0), kind='spectral', fast=True)+ hi = auto.fit(0.2 * dsp.butter(r.standard_normal(SR // 3), 'high', 4000.0), kind='spectral', fast=True)+ cen = lambda y: float(np.sum(np.abs(np.fft.rfft(Q.mono(y))) ** 2 * np.fft.rfftfreq(len(Q.mono(y)), 1 / SR))+ / np.sum(np.abs(np.fft.rfft(Q.mono(y))) ** 2))+ c_lo, c_mid, c_hi = (cen(auto.render(m, 0)) for m in (lo, auto.morph(lo, hi, 0.5), hi))+ assert c_lo < c_mid < c_hi+++# --------------------------------------------------------------------------------------------------- CLI+def test_cli_fit_and_morph(tmp_path, wav):+ from earshot.cli import main+ a = wav(struck(), 'a.wav')+ b = wav(struck(f=(1500.0, 3600.0), seed=4), 'b.wav')+ out = tmp_path / 'made' / 'a_fit.py'+ assert main(['fit', a, '-o', str(out), '--kind', 'modal', '--fast', '--quiet', '--json',+ '--out', str(tmp_path / 'r.json')]) == 0+ r = json.load(open(tmp_path / 'r.json'))+ for k in ('recipe', 'wav', 'png', 'model'):+ assert (tmp_path / 'made').joinpath(r['files'][k].rsplit('/', 1)[-1]).exists()+ assert r['code_renders_fit'] is True and r['quality']['mel_db'] < 6+ assert main(['fit', '--morph', a, b, '--amount', '0.4', '-o', str(tmp_path / 'ab.py'), '--fast', '--quiet']) == 0+ rec = codegen.load_recipe(str(tmp_path / 'ab.py'))+ assert 'morph' in rec.SPACE and rec.DEFAULTS['morph'] == 0.4+ assert len(rec.render(rec.DEFAULTS, dsp.rng(0))) > 0+++def test_fitted_recipe_runs_in_the_forge(tmp_path):+ from earshot.forge import forge+ m = auto.fit(struck(), kind='modal', fast=True)+ rec = codegen.load_recipe(codegen.write_recipe(str(tmp_path / 'f.py'), m, target='a short plastic click'))+ r = forge(rec, refs=None, budget=8, pop=4, keep=1, seed=0, out=None, log=lambda *a: None)+ assert r['picks'] and set(r['picks'][0]['params']) >= set(rec.SPACE)diff --git a/tests/test_fit_modal.py b/tests/test_fit_modal.pynew file mode 100644index 0000000..a8da7d2--- /dev/null+++ b/tests/test_fit_modal.py@@ -0,0 +1,208 @@+"""Tests for the modal fitter (earshot/forge/fit/modal.py): synthetic struck sounds of KNOWN parameters (modes, onsets,+fades) must be recovered; the model must be JSON-plain, render deterministically, follow its knobs, and turn into a+standalone script that renders the same samples. The slow test fits real forge-split refs (needs the registry)."""+import json++import numpy as np+import pytest++from earshot.forge.fit import modal++SR = 48000+++def struck(modes, t0=0.010, length=0.3, noise=1e-4, seed=0):+ """damped sinusoids [(f, tau, amp, phase)] starting at t0, plus white noise"""+ n = int(length * SR)+ t = np.arange(n) / SR+ x = np.zeros(n)+ o = int(round(t0 * SR))+ for f, tau, a, ph in modes:+ tt = t[o:] - t[o]+ x[o:] += a * np.exp(-tt / tau) * np.cos(2 * np.pi * f * tt + ph)+ return x + noise * np.random.default_rng(seed).standard_normal(n)+++TRUE = [(440.0, 0.08, 0.5, 0.3), (1234.5, 0.03, 0.3, -1.0), (3150.0, 0.012, 0.2, 2.0), (95.0, 0.15, 0.25, 0.0)]++[email protected](scope='module')+def fitted():+ x = struck(TRUE)+ return x, modal.fit(x)+++def test_recovers_known_modes(fitted):+ x, md = fitted+ assert md['kind'] == 'modal' and md['version'] == modal.VERSION+ assert len(md['strikes']) == 1+ assert abs(md['strikes'][0]['t'] - 0.010) < 0.0003+ rows = md['strikes'][0]['modes']+ for f, tau, a, ph in TRUE:+ best = min(rows, key=lambda q: abs(q[0] - f))+ assert abs(best[0] - f) / f < 0.002, (f, best)+ assert abs(best[1] - tau) / tau < 0.05, (tau, best)+ assert abs(best[2] - a) / a < 0.05, (a, best)+ # the four true modes carry nearly all the energy: nothing big was invented+ E = sorted((q[2] ** 2 * q[1] for q in rows), reverse=True)+ assert sum(E[4:]) < 0.01 * sum(E[:4])+++def test_resynthesis_is_close(fitted):+ x, md = fitted+ y = modal.render(md, seed=0)+ assert y.shape == x.shape+ mel, per = modal.mel_distance(x, y)+ assert mel < 3.0, per+ assert modal.env_corr(x, y) > 0.98+ assert np.sqrt(np.mean((x - y) ** 2)) < 0.05 * np.sqrt(np.mean(x ** 2)) # waveform-level match for pure modes+++def test_model_is_plain_json_and_deterministic(fitted, tmp_path):+ x, md = fitted+ back = json.loads(json.dumps(md))+ assert back == md+ a, b = modal.render(back, seed=3), modal.render(md, seed=3)+ assert np.array_equal(a, b)+ c = modal.render(md, seed=4)+ assert not np.array_equal(a, c)+ assert np.sqrt(np.mean((a - c) ** 2)) < 0.05 * np.sqrt(np.mean(a ** 2)) # seeds change the noise only+ p = modal.save(md, str(tmp_path / 'm.json'))+ assert modal.load(p) == md+ with pytest.raises(ValueError):+ modal.render({'kind': 'other', 'version': 1})+++def test_two_strikes_and_a_damping_contact():+ a = struck([(700.0, 0.2, 0.4, 0.0), (1900.0, 0.05, 0.2, 1.0)], t0=0.01, length=0.35, noise=0)+ n = len(a)+ o2 = int(0.12 * SR)+ a[o2:] *= np.exp(-np.arange(n - o2) / (0.004 * SR)) # a finger stops the ring at 120 ms+ b = struck([(2600.0, 0.03, 0.3, 0.5)], t0=0.12, length=0.35, noise=0)+ x = a + b + 1e-4 * np.random.default_rng(1).standard_normal(n)+ md = modal.fit(x)+ ts = [s['t'] for s in md['strikes']]+ assert len(ts) == 2 and abs(ts[0] - 0.01) < 0.0003 and abs(ts[1] - 0.12) < 0.0005, ts+ assert any(abs(q[0] - 2600) < 5 for q in md['strikes'][1]['modes'])+ y = modal.render(md, 0)+ late = slice(int(0.16 * SR), int(0.3 * SR)) # the stopped ring must stay stopped+ assert np.sqrt(np.mean(y[late] ** 2)) < 2.0 * np.sqrt(np.mean(x[late] ** 2)) + 1e-4+ assert modal.mel_distance(x, y)[0] < 4.0+++def test_onsets_and_fade():+ n = int(0.4 * SR)+ x = 1e-4 * np.random.default_rng(2).standard_normal(n)+ for t0 in (0.02, 0.15, 0.27):+ o = int(t0 * SR)+ k = np.arange(n - o)+ x[o:] += 0.5 * np.exp(-k / (0.01 * SR)) * np.random.default_rng(int(t0 * 1000)).standard_normal(n - o)+ ons = modal.onsets(x)+ assert len(ons) == 3+ assert all(abs(o / SR - t) < 0.0015 for o, t in zip(ons, (0.02, 0.15, 0.27))), ons+ y = struck([(300.0, 0.4, 0.5, 0.0)], t0=0.01, length=0.5, noise=1e-5)+ nf = int(0.03 * SR)+ y[-nf:] *= np.linspace(1, 0, nf)+ assert modal.fade_out(y) in (0.02, 0.03, 0.05)+ assert modal.fade_out(struck([(300.0, 0.4, 0.5, 0.0)], length=0.5)) == 0.0+++def test_knobs(fitted):+ x, md = fitted++ def peak_hz(y):+ F = np.abs(np.fft.rfft(y * np.hanning(len(y)), 1 << 16))+ return np.fft.rfftfreq(1 << 16, 1 / SR)[np.argmax(F)]++ def centroid(y):+ F = np.abs(np.fft.rfft(y)) ** 2+ f = np.fft.rfftfreq(len(y), 1 / SR)+ return float((F * f).sum() / F.sum())++ y0 = modal.render(md, 0)+ assert abs(peak_hz(modal.render(md, 0, size=2.0)) - peak_hz(y0) / 2) < 2.0+ assert len(modal.render(md, 0, size=2.0)) > len(y0) # bigger rings longer: the tail grows+ late = slice(int(0.1 * SR), int(0.2 * SR))+ e0 = np.mean(y0[late] ** 2)+ assert np.mean(modal.render(md, 0, damping=2.0)[late] ** 2) < 0.2 * e0+ assert centroid(modal.render(md, 0, brightness=6.0)) > 1.3 * centroid(y0)+ assert centroid(modal.render(md, 0, brightness=-6.0)) < centroid(y0)+ yv = modal.render(md, 5, vary=0.6)+ assert len(yv) == len(y0) and not np.allclose(yv, y0)+ assert np.allclose(modal.render(md, 0, gain=-6.0), y0 * 10 ** (-6 / 20))+ s = modal.render(md, 0, stereo=True, room=0.3)+ assert s.shape == (len(y0), 2) and np.isfinite(s).all()+++def test_stereo_side_follows_the_original():+ m = struck(TRUE, noise=3e-3)+ side = 0.3 * struck([(440.0, 0.08, 0.5, 1.3), (1234.5, 0.03, 0.3, 0.2)], noise=3e-3, seed=5)+ x = np.stack([m + side, m - side], axis=1)+ md = modal.fit(x)+ assert md['channels'] == 2 and md['side'] and len(md['side']) == len(md['noise']['env'])+ y = modal.render(md, 0)+ assert y.shape == x.shape+ cx = np.corrcoef(x[:, 0], x[:, 1])[0, 1]+ cy = np.corrcoef(y[:, 0], y[:, 1])[0, 1]+ assert abs(cx - cy) < 0.15, (cx, cy)+++def test_to_code_renders_the_same_samples(fitted, tmp_path):+ x, md = fitted+ src = modal.to_code(md, name='synthetic_strike')+ assert 'def render(' in src and 'MODEL = {' in src and 'earshot' not in src.split('"""', 2)[2]+ ns = {'__name__': 'emitted'}+ exec(compile(src, 'emitted.py', 'exec'), ns)+ for knobs in ({}, {'size': 1.3, 'damping': 0.8, 'brightness': -2.0, 'vary': 0.4}):+ assert np.array_equal(ns['render'](7, **knobs), modal.render(md, 7, **knobs))+ # a stereo, faded take with a sub-bass bump: every model field must reach the script+ y = struck([(300.0, 0.4, 0.5, 0.0), (2100.0, 0.02, 0.2, 1.0)], t0=0.01, length=0.4, noise=1e-3)+ y[int(0.01 * SR):int(0.08 * SR)] += 0.3 * np.hanning(int(0.07 * SR)) # a slow pressure pulse+ nf = int(0.03 * SR)+ y[-nf:] *= np.linspace(1, 0, nf)+ st = np.stack([y, 0.8 * y + 0.01 * np.random.default_rng(3).standard_normal(len(y))], axis=1)+ m2 = modal.fit(st)+ assert m2['fade_out_s'] > 0 and m2['sub'] is not None and m2['channels'] == 2+ ns2 = {'__name__': 'emitted'}+ exec(compile(modal.to_code(m2), 'emitted2.py', 'exec'), ns2)+ assert np.array_equal(ns2['render'](3, size=1.2, room=0.2), modal.render(m2, 3, size=1.2, room=0.2))+++def test_band_masks_are_power_complementary():+ W = modal.band_masks(1 << 14)+ assert W.shape[0] == len(modal.NOISE_EDGES) + 1+ assert np.allclose((W ** 2).sum(0), 1.0, atol=1e-9)+++def test_esprit_recovers_poles():+ n = np.arange(200)+ z_true = np.array([0.98 * np.exp(0.3j), 0.95 * np.exp(-1.1j), 0.99 * np.exp(2.0j)])+ s = sum(np.exp(n * np.log(z)) * c for z, c in zip(z_true, (1.0, 0.5, 0.25)))+ z, k = modal.esprit(s, kmax=8)+ assert k == 3+ for zt in z_true:+ assert np.min(np.abs(z - zt)) < 1e-6+++def test_mel_distance_basics():+ x = struck(TRUE)+ assert modal.mel_distance(x, x)[0] == 0.0+ assert 4.5 < modal.mel_distance(x, 0.5 * x)[0] <= 6.03 # -6 dB, less where cells sit on the floor+++def test_real_refs_resynthesise_closely():+ from earshot import audio+ from earshot.forge import refsets+ try:+ refs = refsets.refset('click', 'forge')[:2] + refsets.refset('typing_key', 'forge')[:1]+ except refsets.RefsetsMissing:+ pytest.skip('no reference-set registry on this machine')+ for p in refs:+ x = audio.load(p)+ md = modal.fit(x)+ y = modal.render(md, 0)+ floor = modal.mel_distance(y, modal.render(md, 1))[0] # two noise draws of the same model+ mel = modal.mel_distance(x, y)[0]+ assert mel < floor + 1.5, (p, mel, floor)+ assert modal.env_corr(x, y) > 0.8, pdiff --git a/tests/test_fit_sines.py b/tests/test_fit_sines.pynew file mode 100644index 0000000..0871ae0--- /dev/null+++ b/tests/test_fit_sines.py@@ -0,0 +1,209 @@+"""earshot.forge.fit.sines: recover known parameters from synthetic tonal sounds, and the render / code contract."""+import json+import os++import numpy as np+import pytest++from earshot.forge.fit import sines++SR = 48000+++def _bell(dur=1.0, on=0.05, parts=((440.0, -12.0, 1.0, 0.3), (1213.0, -18.0, 0.6, 1.1), (2390.5, -24.0, 0.3, 2.0)),+ floor_db=-70.0, seed=1):+ """struck inharmonic partials (f, dBFS at the strike, T60 s, phase) with a white noise floor"""+ n = int(dur * SR)+ t = np.arange(n) / SR+ tt = np.clip(t - on, 0, None)+ x = np.zeros(n)+ for f, a, t60, ph in parts:+ x += (t >= on) * 10 ** (a / 20) * 10 ** (-3 * tt / t60) * np.cos(2 * np.pi * f * tt + ph)+ return x + 10 ** (floor_db / 20) * np.random.default_rng(seed).standard_normal(n)+++def _near(model, f, tol_hz):+ """the strongest partial whose median frequency is within tol_hz of f"""+ best = None+ for p in model['partials']:+ fm = sines.partial_freq(p)+ if abs(fm - f) <= tol_hz:+ pk = max(v for _, v in p['amp'])+ if best is None or pk > best[0]:+ best = (pk, fm, p)+ assert best is not None, f'no partial near {f} Hz'+ return best++[email protected](scope='module')+def bell_model():+ x = _bell()+ return x, sines.fit(x, windows=(1024, 2048))+++def test_recovers_partials_strike_and_decays(bell_model):+ x, m = bell_model+ assert m['kind'] == 'sines' and m['version'] == sines.VERSION+ assert abs(m['onset'] - 0.05) < 0.0015 # the strike, to the sample region+ for f, a, t60, _ in ((440.0, -12.0, 1.0, 0), (1213.0, -18.0, 0.6, 0), (2390.5, -24.0, 0.3, 0)):+ pk, fm, p = _near(m, f, 5.0)+ assert abs(fm - f) < 0.5 # frequency within half a hertz+ assert abs(pk - a) < 1.0 # strike level within 1 dB (no pre-echo smear)+ assert abs(p['t0'] - 0.05) < 0.0015 # each partial starts at the strike+ assert abs(sines._t60(p) - t60) / t60 < 0.1 # decay within 10 %+ s = m['summary']+ assert abs(s['f_low'] - 440) < 1 and s['inharmonicity'] > 0.04 # no harmonic series forced on it+ strong = [p for p in m['partials'] if max(v for _, v in p['amp']) > -40]+ assert len(strong) == 3 # no spurious strong partials+++def test_resynthesis_is_close(bell_model):+ x, m = bell_model+ y = sines.render(m)+ assert len(y) == len(x)+ assert sines._lsd(x, y) < 3.0+ e = lambda z: 10 * np.log10((z[int(0.06 * SR):int(0.5 * SR)] ** 2).sum())+ assert abs(e(x) - e(y)) < 0.5 # level of the body+++def test_chirp_trajectory_tracks():+ n = int(0.3 * SR)+ t = np.arange(n) / SR+ on = 0.02+ tt = np.clip(t - on, 0, None)+ f0, f1, T = 600.0, 1500.0, 0.15+ k = np.log(f1 / f0) / T+ ph = 2 * np.pi * f0 * np.where(tt < T, (np.exp(k * tt) - 1) / k, (np.exp(k * T) - 1) / k + np.exp(k * T) * (tt - T))+ x = (t >= on) * 0.3 * np.exp(-tt / 0.08) * np.sin(ph) + 1e-4 * np.random.default_rng(0).standard_normal(n)+ m = sines.fit(x, windows=(512, 1024))+ p = m['partials'][0]+ fq = np.asarray(p['freq'])+ for tq in (0.06, 0.10, 0.14):+ true = f0 * np.exp(k * (tq - on))+ got = 2 ** np.interp(tq, fq[:, 0], np.log2(fq[:, 1]))+ assert abs(1200 * np.log2(got / true)) < 40 # within 40 cents mid-glide+ assert m['summary']['glide_cents'][0] > 1200 # reads as an upward glide+++def test_transient_click_is_modelled():+ """a struck partial plus a short click: the click must come back as a click (atoms), not as smeared noise"""+ n = int(0.25 * SR)+ t = np.arange(n) / SR+ on = 0.03+ tt = np.clip(t - on, 0, None)+ click = (t >= on) * 0.5 * np.exp(-tt / 0.0008) * np.cos(2 * np.pi * 3100 * tt)+ x = (t >= on) * 0.2 * np.exp(-tt / 0.1) * np.cos(2 * np.pi * 700 * tt) + click+ x += 1e-4 * np.random.default_rng(2).standard_normal(n)+ m = sines.fit(x, windows=(512, 1024))+ assert m['transients'], 'no transient atoms at the strike'+ y = sines.render(m)+ a, b = int((on - 0.001) * SR), int((on + 0.004) * SR)+ assert abs(np.abs(y[a:b]).max() - np.abs(x[a:b]).max()) < 0.15 # the click's peak survives+ pre = slice(0, int((on - 0.002) * SR))+ assert np.abs(y[pre]).max() < 0.01 # nothing before the strike+++def test_residual_noise_band_levels():+ """a decaying tone over a steady band of noise: the noise comes back in the right band at the right level"""+ from scipy import signal+ n = int(0.8 * SR)+ t = np.arange(n) / SR+ r = np.random.default_rng(3)+ nz = signal.sosfiltfilt(signal.butter(4, [2000, 4000], 'band', fs=SR, output='sos'), r.standard_normal(n)) * 0.02+ x = 0.3 * np.exp(-t / 0.3) * np.cos(2 * np.pi * 500 * t) + nz+ m = sines.fit(x, windows=(2048,))+ y = sines.render(m, knobs={'residual': 1.0}) - sines.synth_partials(m['partials'], n) \+ - sines.synth_atoms(m['transients'], n)+ band = lambda z: signal.sosfiltfilt(signal.butter(4, [2300, 3600], 'band', fs=SR, output='sos'), z)+ e = lambda z: 10 * np.log10((z[int(0.1 * SR):int(0.7 * SR)] ** 2).mean())+ assert abs(e(band(y)) - e(band(nz))) < 2.0+ lo = lambda z: signal.sosfiltfilt(signal.butter(4, 300, 'low', fs=SR, output='sos'), z)+ assert e(lo(y)) < e(band(y)) - 20 # no noise where there was none+++def test_json_round_trip_and_determinism(bell_model, tmp_path):+ _, m = bell_model+ s = json.dumps(m)+ m2 = json.loads(s)+ assert np.array_equal(sines.render(m), sines.render(m2))+ path = sines.save(m, str(tmp_path / 'm.json'))+ assert np.array_equal(sines.render(sines.load(path), seed=4), sines.render(m, seed=4))+ a, b = sines.render(m, seed=1), sines.render(m, seed=2)+ assert not np.array_equal(a, b) # the seed changes the noise+ assert np.array_equal(sines.render(m, seed=1, knobs={'vary': 0.4}), sines.render(m, seed=1, knobs={'vary': 0.4}))+++def _peak_hz(y, lo, hi):+ F = np.abs(np.fft.rfft(y * np.hanning(len(y))))+ f = np.fft.rfftfreq(len(y), 1 / SR)+ s = (f >= lo) & (f <= hi)+ return f[s][np.argmax(F[s])]+++def test_knobs(bell_model):+ x, m = bell_model+ up = sines.render(m, knobs={'transpose': 12})+ assert abs(_peak_hz(up, 700, 1000) - 880) < 3 # an octave up, partials keep their ratios+ assert abs(_peak_hz(up, 2200, 2700) - 2426) < 6+ st = sines.render(m, knobs={'stretch': 2.0})+ assert abs(len(st) / len(x) - 2.0) < 0.05+ from earshot.forge.tone import t40_ms+ assert t40_ms(sines.render(m, knobs={'decay': 2.0})) > 1.6 * t40_ms(sines.render(m))+ hi_ = sines.render(m, knobs={'brightness': 6.0})+ lo_ = sines.render(m, knobs={'brightness': -6.0})+ assert _peak_hz(hi_, 2000, 3000) == pytest.approx(_peak_hz(lo_, 2000, 3000), abs=3)+ e = lambda z: (np.abs(np.fft.rfft(z))[int(2300 * len(z) / SR):int(2500 * len(z) / SR)] ** 2).sum()+ assert e(hi_) > 10 * e(lo_)+ few = sines.render(m, knobs={'partials': 1})+ assert e(few) < 1e-3 * e(sines.render(m))+ vib = sines.render(m, knobs={'vibrato': 50, 'drift': 10})+ assert np.isfinite(vib).all() and len(vib) == len(x)+ st2 = sines.render(m, knobs={'stereo': True})+ assert st2.shape == (len(x), 2)+ with pytest.raises(ValueError):+ sines.render(m, knobs={'nope': 1})+++def test_to_code_reproduces_render(bell_model, tmp_path):+ _, m = bell_model+ src = sines.to_code(m, name='bell')+ assert 'def render(seed=0)' in src and 'import numpy as np' in src+ ns = {}+ exec(compile(src, 'bell.py', 'exec'), ns)+ for seed in (0, 3):+ assert np.allclose(ns['render'](seed), sines.render(m, seed=seed), atol=1e-9)+ p = tmp_path / 'bell.py'+ p.write_text(src, encoding='utf-8')+ assert os.path.getsize(p) > 1000+++def test_describe_and_stereo_input():+ x = _bell(dur=0.6)+ st = np.column_stack([x, 0.9 * x])+ m = sines.fit(st, windows=(1024,))+ assert m['width'] > -40 # side energy measured+ words = sines.describe(m)+ assert 'partials' in words and 'Hz' in words+++def test_noise_only_input_does_not_crash():+ x = 0.05 * np.random.default_rng(0).standard_normal(int(0.2 * SR)) * np.exp(-np.arange(int(0.2 * SR)) / 2000)+ m = sines.fit(x, windows=(512,))+ y = sines.render(m)+ assert np.isfinite(y).all() and len(y) == len(x)+++def test_real_tonal_refs_fit_closely():+ """manual / slow check on the real forge-split refs (needs the licensed reference registry)"""+ from earshot.forge.refsets import refset, RefsetsMissing+ from earshot import audio+ try:+ refs = refset('notify')[:2] + refset('pop')[:2]+ except (RefsetsMissing, KeyError):+ pytest.skip('no reference registry on this machine')+ for p in refs:+ x = audio.load(p).mean(1)+ m = sines.fit(p)+ y = sines.render(m)+ assert sines._lsd(x, y) < 6.0, os.path.basename(p)diff --git a/tests/test_fit_spectral.py b/tests/test_fit_spectral.pynew file mode 100644index 0000000..e63fb55--- /dev/null+++ b/tests/test_fit_spectral.py@@ -0,0 +1,222 @@+"""earshot.forge.fit.spectral: recover KNOWN parameters from synthetic signals, render knobs, serialisation.+Real-recording checks are marked slow (they need the local refsets registry)."""+import json++import numpy as np+import pytest++from earshot.forge.fit import spectral as sp++SR = 48000+++def _band(x, lo, hi):+ X = np.fft.rfft(x)+ f = np.fft.rfftfreq(len(x), 1 / SR)+ X[(f < lo) | (f > hi)] = 0+ return np.fft.irfft(X, len(x))+++def _tilted(n, slope_db_oct, rng, lo=200.0, hi=12000.0):+ """white noise with a power-density slope of `slope_db_oct` dB per octave about 1 kHz, band-limited"""+ X = np.fft.rfft(rng.standard_normal(n))+ f = np.fft.rfftfreq(n, 1 / SR)+ X *= 10 ** (slope_db_oct * np.log2(np.maximum(f, 1.0) / 1000.0) / 20)+ X[(f < lo) | (f > hi)] = 0+ return np.fft.irfft(X, n)+++def _env(n, rise=0.08, tau=0.12, start=0.02):+ t = np.arange(n) / SR+ e = np.clip((t - start) / rise, 0, 1) ** 2+ return e * np.exp(-np.maximum(t - start - rise, 0) / tau)+++def test_bands_partition_and_widths():+ c = sp.centers()+ assert len(c) == sp.N_BANDS and np.all(np.diff(c) > 0)+ f = np.linspace(c[0], sp.SR / 2, 5000)+ assert np.allclose(sp.weights(f, c).sum(0), 1.0, atol=1e-9)+ bw = sp.bandwidths(c)+ assert np.all(bw > 0) and bw[-1] > bw[5]+ assert np.all((sp._band_nfft(c) >= 512) & (sp._band_nfft(c) <= 4096))+++def test_recovers_spectral_tilt():+ rng = np.random.default_rng(1)+ x = 0.05 * _tilted(int(0.8 * SR), -6.0, rng)+ m = sp.fit(x, texture=False, ridges=False)+ c = sp.centers()+ E = np.asarray(m['env']['db'])+ tk = np.asarray(m['env']['t'])+ mid = E[(tk > 0.15) & (tk < 0.65)].mean(0)+ sel = (c > 500) & (c < 8000)+ slope = np.polyfit(np.log2(c[sel]), mid[sel], 1)[0]+ assert slope == pytest.approx(-6.0, abs=1.0)+++def test_recovers_envelope_and_attack():+ rng = np.random.default_rng(2)+ n = int(0.6 * SR)+ e = _env(n)+ x = 0.2 * _band(rng.standard_normal(n), 100, 15000) * e+ m = sp.fit(x, texture=False, ridges=False)+ c = sp.centers()+ bw = sp.bandwidths(c)+ tk = np.asarray(m['env']['t'])+ lv = sp._db((10 ** (np.asarray(m['env']['db']) / 10) * bw).sum(1))+ truth = 20 * np.log10(np.interp(tk, np.arange(n) / SR, e) + 1e-9)+ act = truth > truth.max() - 25+ err = (lv - lv.max()) - (truth - truth.max())+ assert np.median(np.abs(err[act])) < 2.0+ # peak time within 20 ms of the true peak (start + rise)+ assert abs(tk[int(np.argmax(lv))] - 0.10) < 0.02+ y = sp.render(m, seed=4)+ q = sp.compare(x, y)+ assert q['env_corr'] > 0.95 and q['tone_db'] < 3.0+++def test_stereo_correlation_and_level_difference():+ rng = np.random.default_rng(3)+ n = int(0.8 * SR)+ a, b = [_band(rng.standard_normal(n), 300, 12000) for _ in range(2)]+ rho = 0.3+ th = 0.5 * np.arccos(rho)+ L = np.cos(th) * a + np.sin(th) * b+ R = np.cos(th) * a - np.sin(th) * b+ g = 10 ** (6.0 / 20) # L 6 dB louder+ x = 0.1 * np.stack([L * np.sqrt(2 * g * g / (1 + g * g)), R * np.sqrt(2 / (1 + g * g))], 1)+ m = sp.fit(x, texture=False, ridges=False)+ icc = np.asarray(m['stereo']['icc'])[:, 1:5]+ ild = np.asarray(m['stereo']['ild'])[:, 1:5]+ assert np.median(icc) == pytest.approx(rho, abs=0.12)+ assert np.median(ild) == pytest.approx(6.0, abs=1.0)+ y = sp.render(m, seed=1).astype(np.float64)+ assert np.corrcoef(y[:, 0], y[:, 1])[0, 1] == pytest.approx(rho, abs=0.15)+ assert 10 * np.log10((y[:, 0] ** 2).sum() / (y[:, 1] ** 2).sum()) == pytest.approx(6.0, abs=1.5)+++def test_tonal_ridge_tracked():+ rng = np.random.default_rng(4)+ n = int(0.8 * SR)+ t = np.arange(n) / SR+ noise = 0.05 * _band(rng.standard_normal(n), 200, 15000)+ f = 2000 * (3000 / 2000) ** (t / t[-1])+ tone = 0.05 * np.sin(2 * np.pi * np.cumsum(f) / SR)+ m = sp.fit(noise + tone, texture=False)+ assert len(m['ridges']) >= 1+ rd = m['ridges'][0]+ assert rd['f'][0] == pytest.approx(2000, rel=0.04)+ assert rd['f'][-1] == pytest.approx(3000, rel=0.04)+ assert rd['t'][-1] - rd['t'][0] > 0.6+ # pure noise: no ridge+ assert sp.fit(noise, texture=False)['ridges'] == []+++def test_flutter_found_and_gaussian_noise_left_plain():+ rng = np.random.default_rng(5)+ n = SR+ t = np.arange(n) / SR+ env = np.minimum(1, t / 0.1) * np.minimum(1, (1 - t) / 0.2)+ plain = 0.1 * _band(rng.standard_normal(n), 200, 12000) * env+ m0 = sp.fit(plain, ridges=False)+ assert m0['texture'] is None or (m0['texture']['am'] is None and m0['texture']['grains'] is None)+ am = plain * (1 + 0.8 * np.sin(2 * np.pi * 40 * t))+ m = sp.fit(am, ridges=False)+ tx = m['texture']+ assert tx['am'] is not None and tx['grains'] is None+ peak = tx['am']['rates'][int(np.argmax(tx['am']['spec']))]+ assert 28 <= peak <= 64+ assert 0.3 < max(tx['am']['depth']) <= sp.AM_MAX_DEPTH # truth: std of ln(1 + 0.8 sin) = 0.6+ # roughness 0 renders without the flutter: less low-rate envelope variance+ var = lambda y: np.var(sp._env_db(sp._mono(y))[20:-40])+ assert var(sp.render(m, seed=2, roughness=0.0)) < var(sp.render(m, seed=2))+++def test_crackle_density_order_of_magnitude():+ rng = np.random.default_rng(6)+ n = int(0.8 * SR)+ t = np.arange(n) / SR+ env = np.minimum(1, t / 0.1) * np.minimum(1, (t[-1] - t) / 0.2)+ k = rng.poisson(300 * n / SR)+ c = np.zeros(n)+ np.add.at(c, rng.integers(0, n, k), np.exp(rng.standard_normal(k)) * rng.choice([-1, 1], k))+ x = _band(c, 200, 12000) * env+ m = sp.fit(0.2 * x / np.abs(x).max(), ridges=False)+ gr = m['texture']['grains']+ assert gr is not None and 100 <= gr['density'] <= 1500+++def test_json_roundtrip_determinism_and_fresh_noise(tmp_path):+ rng = np.random.default_rng(7)+ n = int(0.5 * SR)+ x = 0.2 * _band(rng.standard_normal(n), 150, 14000) * _env(n)+ m = sp.fit(x, name='synthetic')+ assert m['kind'] == sp.KIND and m['version'] == sp.VERSION+ p = tmp_path / 'm.json'+ sp.save(m, str(p))+ m2 = sp.load(str(p))+ assert json.loads(json.dumps(m)) == m2+ a, b = sp.render(m, seed=3), sp.render(m2, seed=3)+ assert a.shape == (n, 2) and a.dtype == np.float32+ assert np.array_equal(a, b)+ c = sp.render(m, seed=4)+ assert abs(np.corrcoef(a[:, 0], c[:, 0])[0, 1]) < 0.2 # fresh noise, not the same samples+ q, fl = sp.compare(x, a), sp.compare(a, c)+ assert q['mel_1024'] < fl['mel_1024'] + 1.5 # as close to the original as to itself+++def test_render_knobs():+ rng = np.random.default_rng(8)+ n = int(0.5 * SR)+ x = 0.2 * _band(rng.standard_normal(n), 150, 14000) * _env(n)+ m = sp.fit(x, texture=False)+ base = sp.render(m, seed=1)+ assert len(sp.render(m, seed=1, length=2.0)) == pytest.approx(2 * len(base), abs=2)+ assert len(sp.render(m, seed=1, speed=2.0)) == pytest.approx(len(base) / 2, abs=2)++ def centroid(y):+ P = np.abs(np.fft.rfft(sp._mono(y))) ** 2+ f = np.fft.rfftfreq(len(y), 1 / SR)+ return (P * f).sum() / P.sum()+ assert centroid(sp.render(m, seed=1, tilt=4.0)) > 1.3 * centroid(base)+ assert centroid(sp.render(m, seed=1, shift=1.0)) > 1.3 * centroid(base)+ assert centroid(sp.render(m, seed=1, speed=2.0)) > centroid(base)+ w0 = sp.render(m, seed=1, width=0.0).astype(np.float64)+ assert np.corrcoef(w0[:, 0], w0[:, 1])[0, 1] > 0.99+ assert np.abs(sp.render(m, seed=1, gain_db=-6.0)).max() < np.abs(base).max()+++def test_to_code_executes_and_matches_render():+ rng = np.random.default_rng(9)+ n = int(0.3 * SR)+ x = 0.2 * _band(rng.standard_normal(n), 150, 14000) * _env(n, rise=0.03, tau=0.06)+ m = sp.fit(x, name='tiny', texture=False)+ src = sp.to_code(m)+ ns = {}+ exec(compile(src, 'fitted_tiny.py', 'exec'), ns)+ assert np.array_equal(ns['make'](seed=5), sp.render(m, seed=5))+ assert 'keyframe' in src and sp.summary(m).startswith('tiny:')+++def test_compare_identity_and_check():+ rng = np.random.default_rng(10)+ x = 0.1 * rng.standard_normal(SR // 4)+ q = sp.compare(x, x)+ assert q['mel_db'] == 0.0 and q['env_corr'] == pytest.approx(1.0) and q['tone_db'] == 0.0+ with pytest.raises(ValueError):+ sp.render({'kind': 'modal', 'version': 1})+++def test_real_refs_resynthesis_near_floor():+ """on real forge refs the resynthesis sits near the render-vs-render floor (spectro-temporal statistics)"""+ from earshot.forge import refsets+ try:+ files = refsets.refset('whoosh_fast', 'forge')[:2] + refsets.refset('whoosh_big', 'forge')[:1]+ except refsets.RefsetsMissing:+ pytest.skip('no refsets registry on this machine')+ for f in files:+ r = sp.fit_report(f)+ assert r['fit']['mel_db'] < r['floor']['mel_db'] + 2.5, (f, r['fit'], r['floor'])+ assert r['fit']['env_corr'] > 0.9