diff --git a/Makefile b/Makefile index 144a88d5a..f4e2da24f 100644 --- a/Makefile +++ b/Makefile @@ -28,7 +28,7 @@ help: @echo $(Q) make test-docs - Run the doctests$(Q) @echo $(Q) make benchmarks - Run the measured-duration suite$(Q) @echo $(Q) make screens - Run the screen scenarios: the application driven on a virtual display (needs Xvfb)$(Q) - @echo $(Q) make check - Run pre-commit on every file, the doctests, the suite and the screen scenarios, and mark the commit they passed on for a push (needs Xvfb)$(Q) + @echo $(Q) make check - Run pre-commit on every file, the doctests, the suite and the screen scenarios, and mark the commit they passed on for a push (needs Xvfb; ARGS="--workers 2 --screen-workers 1" lowers the load)$(Q) @echo $(Q) make calibration - Measure reconstruction on the reference sounds; writes the renders and a report$(Q) @echo $(Q) make tracker-playback BITPHASE=folder FAMITRACKER=FamiTracker.exe [PROJECT=song.stp] - Play exported projects (the corpus by default) in Bitphase, FamiTracker or both; reports every tick that differs from the app$(Q) @echo $(Q) make icons - Write the application icon suite from the mark into the package$(Q) @@ -102,7 +102,7 @@ screens: $(PYTHON) scripts/run_tests.py screens check: - $(PYTHON) scripts/check.py + $(PYTHON) scripts/check.py $(ARGS) lint: $(PYTHON) scripts/lint.py $(ARGS) diff --git a/docs/concepts/reconstruction.md b/docs/concepts/reconstruction.md index e2d285109..8c84aff95 100644 --- a/docs/concepts/reconstruction.md +++ b/docs/concepts/reconstruction.md @@ -118,6 +118,14 @@ sharper frequency resolution requires a longer time window, and vice versa): with the FFT path's frame centers. Each column centers on the middle of its frame, and the first columns read the audio from its first sample, with silence before it. +A conversion may read every frame with more than one method (`generation.layers`): the +library's own method and each method a layer adds, such as `cqt` for the low notes and `logfft` +for when they change. The frame's feature then holds every method's bins one after another, and a +candidate's feature holds the same bins, each method's read from that method's library. Every step +of the search reads a frame bin by bin, so it reads the stacked feature as it reads one method's. +Each method's bins hold its layer's share of the criterion's weight, spread over them as the method +weighs them alone, and the window model reads each bin through its own method's window. + The target and the library candidates are always described by the *same* method, so their features are directly comparable bin by bin. All three methods share one scale convention: a bin-centered tone of amplitude `A` contributes `A²/2` — its mean-square @@ -326,9 +334,9 @@ on a channel: the channel's [drive](../glossary.md#drive) scales what the row ad neighbors hears the row through its analysis window ([section 5.6](#56-hearing-a-frame-among-its-neighbors)). The library holds each row's power, and the frame's hearing is the one reader that turns a row into what the frame hears. So the first fit hears each note on the channel its proposal would sound on, and lets it -reach what every channel of its kind plays at full volume. A note's strength is the power its level sounds -heard alone. The full criterion phases the channels by how loud each plays its row heard alone at its -drive. +reach what every channel of its kind plays at full volume. A note's strength is the power its level adds +to the frame's reading. The full criterion phases the channels by how loud each plays its row heard alone +at its drive. Where the source drives its two pulses alike, they go to the channels that keep each nearest the note it played a frame before, so a held line stays on its channel. Every source is solved on its own channels, @@ -420,11 +428,13 @@ it. What the neighbors play is a fixed part of every mix the frame's assignment row the frame plays adds its own share of its power. A row sounding the note held up to the frame, or the note held from it, extends that note, and the two add in amplitude. A note held through the frame then reaches it as a note heard alone does, and a note that stopped two frames before is heard as its -frames' tail. The joint assignment's second and third steps read the frame this way: the fit of every -combination reads a fitted level at the level of the note it extends, and the full criterion scores each -combination with the leak in its mix. Its first step, the fit of every note, stands over the leak and hears -each note alone, as a note held through the whole window. That fit weighs every note of the frame at once, -and the window model reads a note cut at a frame boundary only approximately. +frames' tail. Every step of the joint assignment reads the frame this way. The fit of every note and the +fit of every combination stand over the leak and read a fitted level at the level of the note it extends, +and the full criterion scores each combination with the leak in its mix. A note's strength is what its +fitted level adds to the reading: a note of the frame's own adds its own share of the window, and a note +extending a held one adds what joining it adds. The leak's part of a held note stays in the reading +whatever the frame plays, so the strength leaves it out, and the frame's own evidence ranks the notes it +proposes. A low bin's window averages a channel over many frames, so a channel switched on and off from frame to frame reads there as a level between the two: a triangle quieter than its one volume, or a noise quieter diff --git a/docs/concepts/stems.md b/docs/concepts/stems.md index 3ba46042e..041fab6ef 100644 --- a/docs/concepts/stems.md +++ b/docs/concepts/stems.md @@ -47,10 +47,10 @@ approximates the summed recordings because each part approximates its part. ### 3. A drive reaches for a louder instruction A stem's settings name a drive per channel it holds. `1.00` is the level the library is calibrated to. The -drive belongs to the conversion alone. Every candidate is read at unit drive, so the instruction winning a -frame is the one that sounds it at the drive. A channel pushed harder is answered by louder instructions, -up to the loudest that channel holds. Past that the channel saturates, which is the effect a drive is used -for. +drive belongs to the conversion alone. Every candidate is read at the channel's drive, a drive `d` reading +it at `1/d` of its amplitude, so the instruction winning a frame is the one that sounds it `d` times +louder. A channel pushed harder is answered by louder instructions, up to the loudest that channel holds. +Past that the channel saturates, which is the effect a drive is used for. A drive applies to one channel of one stem. Raising it lifts that part of the mix, and the other stems and the stem's other channels stay where they are. Afterwards a frame sounds the instruction it carries, so @@ -128,7 +128,7 @@ A stem's channels fall into groups, each of one kind at one drive: the groups sounds distinct and is weighed on its own. A pick scores each group as one column, which resolves to the group's lowest free channel, so successive -picks over one kind land on the lowest free channel. The +picks over one group land on its lowest free channel. The [joint assignment](reconstruction.md#52-assigning-channels-jointly) searches every placement of a frame's proposals over the groups. Equal candidates go to the stem earlier in level order, so a rerun assigns the same way every time. diff --git a/docs/development/bugs-and-todos.md b/docs/development/bugs-and-todos.md index 68f5f6b78..eab0380e9 100644 --- a/docs/development/bugs-and-todos.md +++ b/docs/development/bugs-and-todos.md @@ -108,6 +108,10 @@ dimension the import starts carrying. * The `fft` and `logfft` analysis floors. Their window spans two cycles of the pulse's lowest note, so the triangle's lowest octave reaches them by its harmonics alone. Covering it doubles their window and coarsens their timing. +* Spectrum layers in the application. Its library step builds the library of `library.spectrum_method` + alone, so a configuration adding `generation.layers` converts there only once each added method's + library exists; the command line prepares every one (`ensure_library`). The application's library step + building each analysis layer's library closes it. * The joint assignment for stems that share channels. It solves each stem on its own channels, so a setup where two stems may take one channel is refused under `generation.assignment.method: joint`. A joint choice across stems, ordered by the hierarchy, closes it. diff --git a/docs/development/tooling.md b/docs/development/tooling.md index 11882eef0..36407d9c9 100644 --- a/docs/development/tooling.md +++ b/docs/development/tooling.md @@ -161,6 +161,9 @@ push looks the mark up. `make check` runs pre-commit over every file, then the doctests, the suite and the screen scenarios. Every check runs whatever the earlier ones reported, so one run shows everything that is wrong. The +suite and the screen scenarios run on as many workers as `make test` and `make screens` do, and +`make check ARGS="--workers 2 --screen-workers 1"` runs them on fewer, for a machine busy with other +work. The run marks the commit when every check passed and the work tree held exactly that commit's files from the start of the run to its end. A run over uncommitted files marks nothing, and it says so as it starts. diff --git a/docs/formats/configuration.md b/docs/formats/configuration.md index b8f95271c..e1d5fd0ed 100644 --- a/docs/formats/configuration.md +++ b/docs/formats/configuration.md @@ -55,6 +55,7 @@ records them. | Key | Meaning | Values | | --- | --- | --- | | `reset_phase` | reset oscillator phase within each instruction | `true` / `false` | +| `layers` | spectrum methods every frame is also read with, beside `library.spectrum_method`, each with the weight its reading holds against a weight of `1` for the library's method; each method reads its own library, built as that method's library is | list of `{method, weight}`, `method` one of `fft` / `logfft` / `cqt` other than the library's and each other's, `weight` > 0; empty by default | ### `generation.calculation` diff --git a/docs/tools/calibration.md b/docs/tools/calibration.md index 27ab5cbc4..367c40ad2 100644 --- a/docs/tools/calibration.md +++ b/docs/tools/calibration.md @@ -56,6 +56,7 @@ listening page. | `run.json` | what the run measures, which `--resume` checks before it goes on, and the order of its variants, which the page's columns follow | | `renders//` | a JSON file per reconstruction with its scores and the frames each channel plays, and a FLAC file of each listed one | | `renders///` | each listed reconstruction cut by channel, one file per combination | +| `renders/oracle/` | the [oracle](#the-oracle) of each sound written as NES frames, as the variants' renders are | | `recordings/` | each reference sound, as the run prepared it for reconstruction: at the library's sample rate and the level the conversion matched | | `recordings/true/` | each reference sound as a run with `--levels true` prepared it, at the level its file holds | | `corpus/` | the reference sounds as generated | @@ -98,8 +99,8 @@ Each cell has: reconstruction plays that channel, and empty where that channel is unused. Each channel keeps the same place in every cell of a family, so you can compare a row across its columns. -The last column shows the change from the first column to the last. A rise means the last variant is -closer to the recording. +The last column shows the change from the first variant's column to the last. A rise means the last +variant is closer to the recording. Every column starts closed. Click a column's heading to open it in every card of the tab. Click it again to close it. An open column adds a bar beside each square, showing the frames where that channel plays. @@ -128,6 +129,26 @@ Beside each render, a JSON file of the same name has: A render that scores worse than silence is a sign to listen before trusting the number. +### The oracle + +A sound written as NES frames shows the **oracle** first, in its own column. The oracle plays the +sound's frames exactly, every note, volume and duty cycle right. It can still score above zero, +because of the noise. The noise channel plays a random sequence, and every frame's period and mode +move it along, so a conversion that misses one noise frame plays another stretch of the sequence from +then on: the same hiss in kind, but not the recording's. The pulses and the triangle start where the +recording's channels start, so the oracle plays them exactly. + +The run renders each such sound's frames with the noise's sequence starting at eight places, drawn +at random once per sound, and scores every render. The cell shows the mean, which is what a perfect +transcription scores on average. Point at the score to see the closest and the farthest of the +eight. A sound without noise reads **exact**. The **▶** button plays +the render whose score lies nearest the mean, and the oracle plays beside the recording as the +sound's file holds it, so its row has a `true` recording button. A sound written another way, such as +a synthesized tone or a recording, shows a dash there. The change column leaves the oracle out. + +A variant scoring near the oracle has its notes right, and what remains is the noise's sequence. The report holds the oracle as a row of its own, named `oracle`, with `lowest` and +`highest` beside each audio referee's score. + ## Read the report A *referee* is a method that scores a reconstruction against its original: zero for identical signals, @@ -237,6 +258,12 @@ refused before the run starts. The packaged sets: - `joint-fitted-combinations-neighbors1-tonal-inertia05`, `-tonal-inertia1`: the pass with the pulses and the triangle kept to their neighbors at an inertia of 0.5 and 1, the noise free; `joint-fitted-combinations-neighbors1-inertia05` keeps every channel at 0.5. +- `joint-logfft`, `joint-fitted-combinations-logfft`, `joint-fitted-combinations-neighbors1-logfft`: the + joint assignment, the fitted level with whole combinations, and the pass, each reading every frame + with `logfft` beside the library's own method, at equal weight + ([several methods at once](../concepts/reconstruction.md#32-spectrum-methods-fft-log-fft-and-cqt)); + `joint-fitted-combinations-logfft05` and `joint-fitted-combinations-neighbors1-logfft05` read `logfft` at + half the library method's weight. `--levels true` matches every sound at the level its file holds, whatever working level its settings name, the fitted one included. For a sound written as NES frames that is the level the channels play diff --git a/scripts/check.py b/scripts/check.py index 08f450891..1b0e1fbfa 100644 --- a/scripts/check.py +++ b/scripts/check.py @@ -29,29 +29,57 @@ "Commit the changes and run `make check` again before pushing." ) MARKED: Final[str] = "Commit {commit} passed every check and can be pushed." +WORKERS_OPTION: Final[str] = "--workers" +SCREEN_WORKERS_OPTION: Final[str] = "--screen-workers" -def planned_checks(python: str) -> Tuple[Pass, ...]: +def planned_checks(python: str, runner_options: Sequence[str]) -> Tuple[Pass, ...]: """Every check a push waits for, in order: pre-commit over every file, then the doctests, the covered suite and the screen scenarios. These are the passes CI runs on a pull request. The hooks come first, since they answer in - minutes and the tests take far longer. Each test pass is the command its make target runs, so - a pass the check runs behaves as it does on its own. + minutes and the tests take far longer. Each test pass is the command its make target runs, with + the options the check was given for the test runner, so a pass the check runs behaves as it + does on its own. Args: python: The interpreter the test runner runs on. + runner_options: The test runner's options every test pass takes (``worker_options``). Returns: Tuple[Pass, ...]: The checks, in the order they run. """ hooks = Pass(HOOKS, "Checking every file with pre-commit...", RUN_HOOKS) tests = ( - Pass(name, f"Checking {description}...", (python, RUN_TESTS_SCRIPT, name)) for name, description in TEST_PASSES + Pass(name, f"Checking {description}...", (python, RUN_TESTS_SCRIPT, name, *runner_options)) + for name, description in TEST_PASSES ) return (hooks, *tests) +def worker_options(workers: Optional[str], screen_workers: Optional[str]) -> Tuple[str, ...]: + """The test runner's options for the worker counts the check was given. + + A count left out keeps the test runner's own default, so a check run on a busy machine may lower + the load its passes take and an idle one runs as ``make test`` and ``make screens`` do. + + Args: + workers: The pytest workers for the covered suite, or ``None`` for the runner's default. + screen_workers: The pytest workers for the screen scenarios, or ``None`` for the runner's default. + + Returns: + Tuple[str, ...]: The options, each count after its flag. + """ + options: Tuple[str, ...] = () + if workers is not None: + options = (*options, WORKERS_OPTION, workers) + + if screen_workers is not None: + options = (*options, SCREEN_WORKERS_OPTION, screen_workers) + + return options + + def check_commit( root: Path, checks: Sequence[Pass], @@ -106,11 +134,21 @@ def mark_unchanged_commit(root: Path, started_on: Optional[str]) -> None: def main(argv: Sequence[str]) -> int: """Runs every check a push waits for and marks the commit they passed on.""" parser = argparse.ArgumentParser(description="Run every check a push waits for and mark the commit they passed on.") - parser.parse_args(list(argv)) + parser.add_argument( + WORKERS_OPTION, + default=None, + help="pytest workers for the covered suite, the test runner's default where left out", + ) + parser.add_argument( + SCREEN_WORKERS_OPTION, + default=None, + help="pytest workers for the screen scenarios, the test runner's default where left out", + ) + arguments = parser.parse_args(list(argv)) return check_commit( repository_root(), - planned_checks(sys.executable), + planned_checks(sys.executable, worker_options(arguments.workers, arguments.screen_workers)), runner=run, environment=os.environ, ) diff --git a/scripts/run_tests.py b/scripts/run_tests.py index 7bedd0f29..19eeee221 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -91,8 +91,8 @@ def run_environment(base: Dict[str, str], *, shard: Optional[str]) -> Dict[str, return environment -def main(argv: Sequence[str]) -> int: - """Runs one pass of the tests and exits with the status pytest gave it.""" +def argument_parser() -> argparse.ArgumentParser: + """The test runner's command line: the pass to run, its worker counts and its shard.""" parser = argparse.ArgumentParser(description="Run one pass of the SampleToNES tests.") parser.add_argument( "name", @@ -114,7 +114,12 @@ def main(argv: Sequence[str]) -> int: default=None, help="the part of the screen scenarios this run takes, as INDEX/COUNT, when a run spreads them over machines", ) - arguments = parser.parse_args(list(argv)) + return parser + + +def main(argv: Sequence[str]) -> int: + """Runs one pass of the tests and exits with the status pytest gave it.""" + arguments = argument_parser().parse_args(list(argv)) return run_pass( planned_passes(arguments.workers, arguments.screen_workers)[arguments.name], diff --git a/src/sampletones_core/configs/config.py b/src/sampletones_core/configs/config.py index 9bde82e48..53019a599 100644 --- a/src/sampletones_core/configs/config.py +++ b/src/sampletones_core/configs/config.py @@ -3,7 +3,7 @@ from pathlib import Path from typing import Dict, Optional, Self, Union -from pydantic import ConfigDict, Field +from pydantic import ConfigDict, Field, model_validator from sampletones_core.configs.general import GeneralConfig from sampletones_core.configs.generation import GenerationConfig @@ -38,6 +38,19 @@ class Config(DataModel): description="Application metadata", ) + @model_validator(mode="after") + def _check_layers_read_other_methods(self) -> Self: + """Refuse a spectrum layer reading the library's own method, or a method another layer reads. + + Raises: + ValueError: If two of the frame's readings share a spectrum method. + """ + methods = [self.library.spectrum_method, *(layer.method for layer in self.generation.layers)] + if len(set(methods)) < len(methods): + raise ValueError(f"Each spectrum method reads the frames once; the readings are {', '.join(methods)}") + + return self + @classmethod def default(cls) -> Self: if not CONFIG_PATH.exists(): diff --git a/src/sampletones_core/configs/generation.py b/src/sampletones_core/configs/generation.py index 1370e2e3f..c593b7e89 100644 --- a/src/sampletones_core/configs/generation.py +++ b/src/sampletones_core/configs/generation.py @@ -1,4 +1,4 @@ -from typing import Final, Self, assert_never +from typing import Final, Self, Tuple, assert_never from pydantic import ConfigDict, Field, model_validator @@ -9,6 +9,7 @@ PhaseAlignerName, SelectorName, SpectralDistance, + SpectrumMethod, ) from sampletones_core.data import DataModel @@ -164,6 +165,29 @@ class RefinementConfig(DataModel): window: int = Field(default=generation_default("refinement", "window"), ge=0) +class SpectrumLayer(DataModel): + """A spectrum method the frames are read with beside the library's own, and the weight its reading holds. + + A frame read by several methods is one feature of their bins stacked, the library's method first, + each read from the library its own method builds. Every layer holds its weight's share of the + criterion's weight, against a weight of one for the library's method. + """ + + model_config = ConfigDict(extra="forbid", frozen=True) + + method: SpectrumMethod + weight: float = Field(gt=0.0) + + +def shipped_layers() -> Tuple[SpectrumLayer, ...]: + """The spectrum layers a conversion reads by default, as the field holds them. + + A document written before the layers existed takes this default as it loads, so it is the + tuple of layers itself and every render key over its configuration hashes. + """ + return tuple(SpectrumLayer.model_validate(layer) for layer in generation_default("layers")) + + class GenerationConfig(DataModel): """How a conversion chooses what every channel plays. @@ -182,6 +206,7 @@ class GenerationConfig(DataModel): assignment: AssignmentConfig = Field(default_factory=AssignmentConfig) decoder: DecoderConfig = Field(default_factory=DecoderConfig) refinement: RefinementConfig = Field(default_factory=RefinementConfig) + layers: Tuple[SpectrumLayer, ...] = Field(default_factory=shipped_layers) @model_validator(mode="after") def _check_decoder_reads_the_assignment(self) -> Self: diff --git a/src/sampletones_core/configs/generation.yaml b/src/sampletones_core/configs/generation.yaml index 49ae09669..db9215d96 100644 --- a/src/sampletones_core/configs/generation.yaml +++ b/src/sampletones_core/configs/generation.yaml @@ -38,3 +38,5 @@ refinement: confidence: 0.10 change_weight: 2.0 window: 4 + +layers: [] diff --git a/src/sampletones_core/fft/fragment/audio.py b/src/sampletones_core/fft/fragment/audio.py index 4324e1524..435c6dc8c 100644 --- a/src/sampletones_core/fft/fragment/audio.py +++ b/src/sampletones_core/fft/fragment/audio.py @@ -7,7 +7,7 @@ from sampletones_core.configs import Config -from ..features import get_feature_extractor +from ..layers import read_frames from ..window.window import Window from .fragment import Fragment @@ -23,7 +23,7 @@ class FragmentedAudio(BaseModel): def create(cls, audio: np.ndarray, config: Config, window: Window) -> FragmentedAudio: length = (audio.shape[0] // window.frame_length) * window.frame_length audio = audio[:length].copy() - fragments = get_feature_extractor(config, window).extract(audio) + fragments = read_frames(audio, config, window) return cls(audio=audio, fragments=fragments, config=config) def __getitem__(self, index: int) -> Fragment: diff --git a/src/sampletones_core/fft/fragment/fragment.py b/src/sampletones_core/fft/fragment/fragment.py index efccdabf4..329e62ed5 100644 --- a/src/sampletones_core/fft/fragment/fragment.py +++ b/src/sampletones_core/fft/fragment/fragment.py @@ -1,12 +1,26 @@ from __future__ import annotations from dataclasses import dataclass +from typing import Protocol, runtime_checkable from sampletones_core.configs import Config -from sampletones_core.structures.histogram import Histogram from sampletones_shared.types.array import Array +@runtime_checkable +class FrameFeature(Protocol): + """A frame's spectral reading as the search reads it: one value per bin. + + A frame read by one spectrum method holds that method's histogram, and a frame read by several + holds their bins stacked (``StackedFeature``). The protocol is checked at runtime, since the + models holding fragments validate what they hold. + """ + + @property + def values(self) -> Array: + """The reading's value in every bin.""" + + @dataclass(frozen=True) class Fragment: """ @@ -15,5 +29,5 @@ class Fragment: """ audio: Array - feature: Histogram + feature: FrameFeature config: Config diff --git a/src/sampletones_core/fft/fragment/stacked.py b/src/sampletones_core/fft/fragment/stacked.py new file mode 100644 index 000000000..80cadf45c --- /dev/null +++ b/src/sampletones_core/fft/fragment/stacked.py @@ -0,0 +1,26 @@ +from dataclasses import dataclass +from functools import cached_property +from typing import Tuple + +import numpy as np + +from sampletones_core.structures.histogram import Histogram + + +@dataclass(frozen=True) +class StackedFeature: + """A frame's reading by several spectrum methods, their bins stacked in order. + + Every step of the search reads a frame bin by bin, so the bins of several methods stand in one + feature, each method's bins after the one before it. + + Attributes: + layers: Each method's histogram of the frame, the library's method first. + """ + + layers: Tuple[Histogram, ...] + + @cached_property + def values(self) -> np.ndarray: + """Every method's values, one method after another.""" + return np.concatenate([np.asarray(layer.values) for layer in self.layers]) diff --git a/src/sampletones_core/fft/layers.py b/src/sampletones_core/fft/layers.py new file mode 100644 index 000000000..47d615646 --- /dev/null +++ b/src/sampletones_core/fft/layers.py @@ -0,0 +1,83 @@ +from dataclasses import dataclass +from functools import cached_property +from typing import Final, List, Tuple + +import numpy as np + +from sampletones_core.configs import Config +from sampletones_core.constants.enums import SpectrumMethod + +from .features import FeatureExtractor, get_feature_extractor +from .fragment.fragment import Fragment +from .fragment.stacked import StackedFeature +from .window.window import Window + +LIBRARY_WEIGHT: Final[float] = 1.0 + + +@dataclass(frozen=True) +class AnalysisLayer: + """One spectrum method a conversion reads its frames with. + + A conversion reads every frame with its library's spectrum method, and with each method its + ``generation.layers`` add. A layer stands for one of them: the conversion's configuration with + the library's method set to the layer's, which selects the layer's window, extractor and library, + the criterion's weights on its bins and the window model's profiles of them. + + Attributes: + config: The conversion's configuration reading with the layer's method alone. + weight: The weight the layer's reading holds in the criterion, ``LIBRARY_WEIGHT`` for the + library's own method. + """ + + config: Config + weight: float + + @cached_property + def window(self) -> Window: + """The analysis window the layer's method reads a frame through.""" + return Window.from_config(self.config) + + @cached_property + def extractor(self) -> FeatureExtractor: + """The extractor reading a frame with the layer's method.""" + return get_feature_extractor(self.config, self.window) + + +def analysis_layers(config: Config) -> Tuple[AnalysisLayer, ...]: + """Every spectrum method a conversion under ``config`` reads its frames with, the library's own first.""" + library = AnalysisLayer(config=layer_config(config, config.library.spectrum_method), weight=LIBRARY_WEIGHT) + added = ( + AnalysisLayer(config=layer_config(config, layer.method), weight=layer.weight) + for layer in config.generation.layers + ) + return (library, *added) + + +def layer_config(config: Config, method: SpectrumMethod) -> Config: + """``config`` reading the frames with ``method`` alone: the library's method set to it, and no layer added.""" + library = config.library.model_copy(update={"spectrum_method": method}) + generation = config.generation.model_copy(update={"layers": ()}) + return config.model_copy(update={"library": library, "generation": generation}) + + +def read_frames(audio: np.ndarray, config: Config, window: Window) -> List[Fragment]: + """Every whole frame of ``audio``, read with each spectrum method a conversion under ``config`` reads. + + A frame read by the library's method alone holds that method's histogram, read through + ``window``. A frame read by several methods holds their bins stacked (``StackedFeature``), each + read through its own layer's window, and keeps its own stretch of the audio. + """ + layers = analysis_layers(config) + if len(layers) == 1: + return get_feature_extractor(config, window).extract(audio) + + readings = [layer.extractor.extract(audio) for layer in layers] + return [ + Fragment( + audio=frames[0].audio, + feature=StackedFeature(layers=tuple(frame.feature for frame in frames)), + config=config, + ) + for frames in zip(*readings) + ] diff --git a/src/sampletones_core/generators/__init__.py b/src/sampletones_core/generators/__init__.py index 715cef847..d135157af 100644 --- a/src/sampletones_core/generators/__init__.py +++ b/src/sampletones_core/generators/__init__.py @@ -12,7 +12,7 @@ INSTRUCTION_TO_GENERATOR_MAP, MIXER_LEVELS, ) -from .render import render_channels, render_instructions +from .render import render_channels, render_instructions, render_on from .tonal import TonalGenerator from .types import ( GeneratorClass, @@ -51,4 +51,5 @@ "get_generators_map", "render_channels", "render_instructions", + "render_on", ] diff --git a/src/sampletones_core/generators/render.py b/src/sampletones_core/generators/render.py index 076bef12a..c03f573f8 100644 --- a/src/sampletones_core/generators/render.py +++ b/src/sampletones_core/generators/render.py @@ -7,6 +7,7 @@ from sampletones_core.instructions import InstructionUnion from .maps import CHANNEL_CLASSES +from .types import GeneratorUnion def render_instructions( @@ -31,7 +32,26 @@ def render_instructions( Raises: ValueError: If the channel describes no frame. """ - generator = CHANNEL_CLASSES[channel_name](config, channel_name.value) + return render_on(CHANNEL_CLASSES[channel_name](config, channel_name.value), instructions) + + +def render_on(generator: GeneratorUnion, instructions: Sequence[InstructionUnion]) -> np.ndarray: + """One channel's audio rendered frame by frame on ``generator``, from where its oscillator stands. + + Each frame continues the oscillator the one before it left running, so a note held across + frames sounds as a single tone. A fresh generator starts from its oscillator's reset state, and + one whose timer was set elsewhere starts there. + + Args: + generator: The generator of the channel the instructions drive. + instructions: The channel's instructions, one per frame. + + Returns: + np.ndarray: The channel's waveform, one frame per instruction. + + Raises: + ValueError: If the channel describes no frame. + """ frames = [generator(instruction, save=True) for instruction in instructions] # type: ignore[arg-type] return np.concatenate(frames) diff --git a/src/sampletones_core/headless/library.py b/src/sampletones_core/headless/library.py index e19bdf19f..f201c036e 100644 --- a/src/sampletones_core/headless/library.py +++ b/src/sampletones_core/headless/library.py @@ -4,6 +4,7 @@ from sampletones_core.configs import Config from sampletones_core.fft import Window +from sampletones_core.fft.layers import analysis_layers from sampletones_core.library import ( InstructionLibrary, InstructionLibraryData, @@ -16,17 +17,29 @@ def ensure_library(config: Config) -> None: - """Prepares the instruction library a conversion under ``config`` searches. + """Prepares every instruction library a conversion under ``config`` searches. - A library this build reads is used as it stands. A library built by another version is rebuilt - in its place, and a missing one is generated. + A conversion searches the library of its library's spectrum method, and the library of each + method ``generation.layers`` adds (``analysis_layers``). A library this build reads is used as it + stands. A library built by another version is rebuilt in its place, and a missing one is + generated. Args: - config: The configuration selecting the library. + config: The configuration selecting the libraries. Raises: KeyboardInterrupt: If the generation is interrupted, so the conversion stops with it. """ + for layer in analysis_layers(config): + _ensure_one_library(layer.config) + + +def _ensure_one_library(config: Config) -> None: + """Prepares the library of ``config``'s spectrum method, as ``ensure_library`` does for each. + + Raises: + KeyboardInterrupt: If the generation is interrupted. + """ window = Window.from_config(config) library = InstructionLibrary.from_config(config) key = library.create_key(config, window) diff --git a/src/sampletones_core/reconstructions/criterion/weights.py b/src/sampletones_core/reconstructions/criterion/weights.py index 6b10e20d8..73910bf6a 100644 --- a/src/sampletones_core/reconstructions/criterion/weights.py +++ b/src/sampletones_core/reconstructions/criterion/weights.py @@ -6,6 +6,7 @@ from sampletones_core.fft import FFTTransformer, Window, calculate_weights_from_edges from sampletones_core.fft.cqt.frequencies import calculate_cqt_frequencies from sampletones_core.fft.cqt.geometry import resolvable_bins +from sampletones_core.fft.layers import analysis_layers from sampletones_shared.array import xp @@ -23,19 +24,42 @@ def calculate_spectral_weights( target signal is too short to resolve. The weighting policy of the criterion lives entirely in this module, so a change of perceptual model touches one place. + A frame read with several spectrum methods (``analysis_layers``) stacks their bins, and each + method's bins hold its layer's weight's share of the whole weight, spread over them as that + method weighs them alone. So the spectral loss reads every method in proportion to its layer's + weight, however many bins each holds. + Args: - config: Configuration selecting the spectrum method and the perceptual exponent. - window: Analysis window of the configuration. + config: Configuration selecting the spectrum methods and the perceptual exponent. + window: Analysis window of the library's own method. signal_length: Number of samples of the matching target signal. Returns: - A weight per spectral bin, on the active array backend. + A weight per spectral bin, every layer's bins in order, on the active array backend. """ + layers = analysis_layers(config) + windows = (window, *(layer.window for layer in layers[1:])) + perceptual = [_method_weights(layer.config, layer_window) for layer, layer_window in zip(layers, windows)] + bins = sum(int(weights.shape[-1]) for weights in perceptual) + total = sum(layer.weight for layer in layers) + return xp.concatenate( + [ + _summing_to(weights, bins * layer.weight / total) + * _reliability_mask(layer.config, signal_length, int(weights.shape[-1])) + for layer, weights in zip(layers, perceptual) + ] + ) + + +def _method_weights(config: Config, window: Window) -> xp.ndarray: + """The perceptual weights of the bins one spectrum method reads, before any normalization.""" metric = config.generation.metric - edges = _reference_edges(config, window) - weights = xp.asarray(calculate_weights_from_edges(edges, metric.perceptual_exponent)) - weights = len(weights) * weights / xp.sum(weights) - return weights * _reliability_mask(config, signal_length, int(weights.shape[-1])) + return xp.asarray(calculate_weights_from_edges(_reference_edges(config, window), metric.perceptual_exponent)) + + +def _summing_to(weights: xp.ndarray, held: float) -> xp.ndarray: + """``weights`` scaled to sum to ``held``, each bin keeping its share of them.""" + return held * weights / xp.sum(weights) def _reference_edges(config: Config, window: Window) -> np.ndarray: diff --git a/src/sampletones_core/reconstructions/reconstructor/candidates.py b/src/sampletones_core/reconstructions/reconstructor/candidates.py index 4379b00f8..58f8aa00c 100644 --- a/src/sampletones_core/reconstructions/reconstructor/candidates.py +++ b/src/sampletones_core/reconstructions/reconstructor/candidates.py @@ -56,12 +56,25 @@ class CandidateProvider: candidate's power is read off its phase-averaged library feature once per library and kept per generator class, so every frame mixes the same rows. Its waveform and its moments are read where a shortlist asks for them. + + A conversion reading its frames with several spectrum methods (``analysis_layers``) reads each + candidate in each method's library, so a candidate's power holds every method's bins stacked in + the order the frame's feature stacks them, the library's own method first. Its waveform and + moments are the library's own. + + Attributes: + config: The conversion's configuration. + window: The analysis window of the library's own method. + library_data: The library of the library's own method. + extractor: The extractor of the library's own method, whose transform reads every bin. + layer_data: The library of each spectrum method the conversion adds, in the order it adds them. """ config: Config window: Window library_data: InstructionLibraryData extractor: FeatureExtractor + layer_data: Tuple[InstructionLibraryData, ...] _cached_powers: CachedPowers = field(init=False) _moments: Dict[InstructionUnion, Tuple[float, float]] = field(init=False, default_factory=dict) @@ -70,11 +83,20 @@ class CandidateProvider: def __post_init__(self) -> None: object.__setattr__(self, "_cached_powers", self._build_cached_powers()) + @property + def libraries(self) -> Tuple[InstructionLibraryData, ...]: + """Every library a candidate is read in, the library's own method first.""" + return (self.library_data, *self.layer_data) + + @cached_property + def sizes(self) -> Tuple[int, ...]: + """How many bins each library's feature axis holds, in the order the frame's feature stacks them.""" + return tuple(_axis(data).shape[0] - 1 for data in self.libraries) + @cached_property def widths(self) -> np.ndarray: - """The width of every bin of the feature axis the library is described on.""" - feature = next(iter(self.library_data.values())).feature - return np.asarray(np.diff(feature.edges), dtype=np.float64) + """The width of every bin of the feature axes the libraries are described on, stacked in order.""" + return np.concatenate([np.diff(_axis(data)) for data in self.libraries]) def candidates(self, generator_classes: Dict[GeneratorClassName, GeneratorUnion]) -> ClassCandidates: """Every candidate of ``generator_classes`` with the power its library sample plays at, gathered once.""" @@ -95,7 +117,9 @@ def features_of(self, powers: xp.ndarray) -> xp.ndarray: def power_of(self, instruction: InstructionUnion) -> np.ndarray: """The candidate's power density per bin averaged over phase, as its library sample plays.""" - values = np.asarray(self.library_data[instruction].feature.values, dtype=np.float64) + values = np.concatenate( + [np.asarray(data[instruction].feature.values, dtype=np.float64) for data in self.libraries] + ) return np.asarray(self.extractor.transformer.backward(values / self.widths)) def library_waveform(self, instruction: InstructionUnion) -> np.ndarray: @@ -123,3 +147,8 @@ def cached(serialized_instructions: SerializedInstructions) -> xp.ndarray: return xp.asarray(np.stack(rows)) return cached + + +def _axis(library_data: InstructionLibraryData) -> np.ndarray: + """The bin edges of the feature axis a library describes its candidates on.""" + return np.asarray(next(iter(library_data.values())).feature.edges, dtype=np.float64) diff --git a/src/sampletones_core/reconstructions/reconstructor/contribution.py b/src/sampletones_core/reconstructions/reconstructor/contribution.py index 475cdd61c..1562d6f8d 100644 --- a/src/sampletones_core/reconstructions/reconstructor/contribution.py +++ b/src/sampletones_core/reconstructions/reconstructor/contribution.py @@ -18,7 +18,7 @@ class Contribution: sequence adds its mean level, with its spread about that mean as the variance. Attributes: - power: The candidate's power density per bin, read at unit drive. + power: The candidate's power density per bin, read at the channel's drive. expectation: The waveform the candidate is expected to render over the frame. variance: The per-sample variance about that waveform. sounding: Whether the candidate sounds a note, which a frame's cost charges the channel for. diff --git a/src/sampletones_core/reconstructions/reconstructor/drive.py b/src/sampletones_core/reconstructions/reconstructor/drive.py index ddcd9bbb5..61f064b67 100644 --- a/src/sampletones_core/reconstructions/reconstructor/drive.py +++ b/src/sampletones_core/reconstructions/reconstructor/drive.py @@ -1,3 +1,5 @@ +import numpy as np + from sampletones_core.constants.algorithm import UNIT_DRIVE from sampletones_shared.array import xp @@ -7,8 +9,9 @@ def driven_powers(powers: xp.ndarray, drive: float) -> xp.ndarray: A drive ``d`` asks a channel to play its part of the stem's audio ``d`` times louder. The stem's audio is one target for all its channels, each at its own drive, so the rows are scaled instead: - each is read at ``1 / d`` of its library amplitude, its power divided by ``d²``, and the row - matching the audio is the one ``d`` times louder. At unit drive the powers stand as they are. + each is read at ``1 / d`` of its library amplitude (``driven_amplitudes``), its power divided by + ``d²``, and the row matching the audio is the one ``d`` times louder. At unit drive the powers + stand as they are. Args: powers: Power densities per bin as the library sample plays them, on either array backend. @@ -21,3 +24,23 @@ def driven_powers(powers: xp.ndarray, drive: float) -> xp.ndarray: return powers return powers / drive**2 + + +def driven_amplitudes(amplitudes: np.ndarray, drive: float) -> np.ndarray: + """Library amplitudes, a waveform or its mean level, as a channel played at ``drive`` reads them. + + A row is read at ``1 / d`` of its library amplitude, the half of the drive's rule that waveforms + follow, as its power follows ``driven_powers``. At unit drive the amplitudes stand as they are. + """ + if drive == UNIT_DRIVE: + return amplitudes + + return amplitudes / drive + + +def driven_variance(variance: float, drive: float) -> float: + """A library waveform's variance as a channel played at ``drive`` reads it, divided by ``d²`` as its power is.""" + if drive == UNIT_DRIVE: + return variance + + return variance / drive**2 diff --git a/src/sampletones_core/reconstructions/reconstructor/matching.py b/src/sampletones_core/reconstructions/reconstructor/matching.py index 450e971fc..56c5fce0f 100644 --- a/src/sampletones_core/reconstructions/reconstructor/matching.py +++ b/src/sampletones_core/reconstructions/reconstructor/matching.py @@ -11,7 +11,7 @@ from .candidates import CandidateProvider, ClassCandidates from .contribution import Contribution -from .drive import driven_powers +from .drive import driven_amplitudes, driven_powers, driven_variance from .mix import FrameMix from .phase import PhaseAligner from .scorer import Scorer @@ -71,8 +71,9 @@ class FrameMatcher: scoring and the per-candidate contribution build. What the scoring produces is a column of alternatives on one scale, the channel's silence among them, which the assignment turns into ownership and the decoder into a stream. A drive lifts what a channel reaches for: every - candidate is read at unit drive, so the row fitting the target is the one sounding it at the - drive, and a channel is answered at the level its own recording is given. + candidate is read at the channel's drive (``driven_powers``, ``driven_amplitudes``), so the row + fitting the target is the one sounding it louder by the drive, and a channel is answered at the + level its own recording is given. A search settling its own shortlist hands the rows it kept (``score_rows``), and the rows of several channels are scored in one pass of the criterion (``score_requests``), each request @@ -100,8 +101,8 @@ def score_column( """ Score one generator class's candidates in two stages, each added to ``mix``. - Every candidate is read at unit drive: its waveform divides by the drive and its power - by the drive's square, so a rising drive reaches for a louder row and settles on the + Every candidate is read at the channel's drive: its waveform divides by the drive and its + power by the drive's square, so a rising drive reaches for a louder row and settles on the loudest the class holds. Each candidate's power is added to the mix and the result ranked by the spectral term, which compares phase-averaged powers and is therefore immune to how the waveforms happen to be phased. The ``top_k`` best and the class's silent instruction @@ -225,9 +226,9 @@ def contribution( Args: instruction: The candidate. residual: What the frame's waveform holds beyond the stem's other picks. - power: The candidate's power density per bin, read at unit drive. + power: The candidate's power density per bin, read at the channel's drive. drive: The level the channel reaches for, which the candidate's waveform and mean - level divide by, and its variance the drive's square. + level are read at (``driven_amplitudes``), and its variance (``driven_variance``). Returns: Contribution: The candidate's power, expected waveform and variance. @@ -240,15 +241,15 @@ def contribution( mean, variance = self.candidate_provider.expected_moments(instruction) return Contribution( power=power, - expectation=np.full(residual.shape[0], mean / drive), - variance=variance / drive**2, + expectation=driven_amplitudes(np.full(residual.shape[0], mean), drive), + variance=driven_variance(variance, drive), sounding=instruction.on, ) if self.config.generation.calculation.find_best_phase: waveform = self.phase_aligner.align(residual, instruction, drive) else: - waveform = self.candidate_provider.library_waveform(instruction) / drive + waveform = driven_amplitudes(self.candidate_provider.library_waveform(instruction), drive) return Contribution(power=power, expectation=waveform, variance=0.0, sounding=instruction.on) diff --git a/src/sampletones_core/reconstructions/reconstructor/phase.py b/src/sampletones_core/reconstructions/reconstructor/phase.py index f6d94bbda..5ea5ef28b 100644 --- a/src/sampletones_core/reconstructions/reconstructor/phase.py +++ b/src/sampletones_core/reconstructions/reconstructor/phase.py @@ -11,6 +11,8 @@ from sampletones_core.instructions import InstructionUnion from sampletones_core.library import InstructionLibraryData +from .drive import driven_amplitudes + class PhaseAligner(ABC): def __init__( @@ -25,12 +27,12 @@ def __init__( @abstractmethod def align(self, waveform: np.ndarray, instruction: InstructionUnion, drive: float) -> np.ndarray: - """The frame the candidate renders at its best phase against ``waveform``, read at unit drive.""" + """The frame the candidate renders at its best phase against ``waveform``, read at the channel's ``drive``.""" def _rendering(self, instruction: InstructionUnion, shift: int, drive: float) -> np.ndarray: - """The candidate's frame starting ``shift`` samples into its library sample, read at unit drive.""" + """The candidate's frame starting ``shift`` samples into its library sample, read at the channel's ``drive``.""" fragment = self.library_data[instruction].get_fragment(shift, self.config, self.window) - return np.asarray(fragment.audio, dtype=np.float64) / drive + return driven_amplitudes(np.asarray(fragment.audio, dtype=np.float64), drive) def _cycle(self, instruction: InstructionUnion) -> np.ndarray: """Two cycles of the candidate's library sample, which every shift of one frame reads from.""" @@ -41,12 +43,12 @@ def _cycle(self, instruction: InstructionUnion) -> np.ndarray: class SlidingRmsePhaseAligner(PhaseAligner): """ Finds the cyclic shift minimizing the RMSE between the waveform and the candidate read at - unit drive, and returns the candidate's frame at that shift. + the channel's drive, and returns the candidate's frame at that shift. """ def align(self, waveform: np.ndarray, instruction: InstructionUnion, drive: float) -> np.ndarray: windows = sliding_window_view(self._cycle(instruction), self.config.library.frame_length) - remainder = np.asarray(waveform, dtype=np.float64) - windows / drive + remainder = np.asarray(waveform, dtype=np.float64) - driven_amplitudes(windows, drive) rmse = np.sqrt((remainder**2).mean(axis=1)) return self._rendering(instruction, int(np.argmin(rmse)), drive) @@ -55,7 +57,7 @@ def align(self, waveform: np.ndarray, instruction: InstructionUnion, drive: floa class CrossCorrelationPhaseAligner(PhaseAligner): """ Finds the cyclic shift minimizing the squared error between the waveform and the candidate - read at unit drive via FFT cross-correlation, expanding + read at the channel's drive via FFT cross-correlation, expanding `||waveform - candidate / drive||^2` into a per-shift cost of `energy / drive - 2 * correlation` (the constant waveform energy and the positive drive factor drop out of the argmin), and returns the candidate's frame at that shift. diff --git a/src/sampletones_core/reconstructions/reconstructor/reconstructor.py b/src/sampletones_core/reconstructions/reconstructor/reconstructor.py index 6558da808..6ed25969f 100644 --- a/src/sampletones_core/reconstructions/reconstructor/reconstructor.py +++ b/src/sampletones_core/reconstructions/reconstructor/reconstructor.py @@ -15,6 +15,7 @@ from sampletones_core.configs.generation import PASSES_HEARD_ALONE from sampletones_core.constants.enums import ChannelName, ordered_channels from sampletones_core.fft import Fragment, FragmentedAudio, Window +from sampletones_core.fft.layers import analysis_layers from sampletones_core.generators import get_generators_by_channels from sampletones_core.library import InstructionLibrary, InstructionLibraryData from sampletones_core.reconstructions.progress import ( @@ -159,6 +160,7 @@ def __init__( self.window: Window = Window.from_config(self.config) self.level: WorkingLevel = level_factory(self.config, self.channels, self.window) self.library_data: InstructionLibraryData = self.load_library(library) + self.layer_data: Tuple[InstructionLibraryData, ...] = self.load_layer_libraries(library) def __call__( self, @@ -379,6 +381,7 @@ def _build_worker(self, signal_length: int) -> ReconstructorWorker: window=self.window, channels=self.channels, library_data=self.library_data, + layer_data=self.layer_data, signal_length=signal_length, ) @@ -430,7 +433,7 @@ def _assign_beside_neighbors( neighbor_pass = NeighborPass.over( JointAssigner(stems_config, self.channels, worker.matcher, worker.decoder.lattice_width), streams, - frame_profiles(self.config, self.window, self._bins(stem_frames)), + frame_profiles(self.config, self.window, worker.candidate_provider.sizes), TransitionWeights.of(self.config), self.config.generation.assignment.inertia, ) @@ -456,11 +459,6 @@ def _frames_announced( announce(report, ReconstructionStage.MATCHING, matched + frames, total) - @staticmethod - def _bins(stem_frames: Dict[int, FragmentedAudio]) -> int: - """The bins every frame's feature holds, which the first stem's first frame shows.""" - return len(next(iter(stem_frames.values()))[0].feature.values) - @staticmethod def _frames_at(stem_frames: Dict[int, FragmentedAudio], frame: int) -> Dict[int, Fragment]: """Frame ``frame`` of every stem's recording, keyed by stem id.""" @@ -550,16 +548,39 @@ def load_library(self, library: Optional[InstructionLibrary] = None) -> Instruct Raises: NoLibraryDataError: If no library exists for the configuration and window. """ - library = library or InstructionLibrary.from_config(self.config) - library_data = library.get(self.config, self.window) - key = library.create_key(self.config, self.window) + return self._library_of(library or InstructionLibrary.from_config(self.config), self.config, self.window) + + def load_layer_libraries(self, library: Optional[InstructionLibrary] = None) -> Tuple[InstructionLibraryData, ...]: + """Loads the library of every spectrum method ``generation.layers`` adds, each for the enabled channels. + + Args: + library: The instruction library to draw from; a default library rooted at the + configured directory is used when omitted. + + Returns: + One library per added method, in the order the configuration adds them. + + Raises: + NoLibraryDataError: If an added method's library is missing. + """ + source = library or InstructionLibrary.from_config(self.config) + return tuple(self._library_of(source, layer.config, layer.window) for layer in analysis_layers(self.config)[1:]) + + def _library_of(self, library: InstructionLibrary, config: Config, window: Window) -> InstructionLibraryData: + """The library ``config`` and ``window`` select from ``library``, restricted to the enabled channels. + + Raises: + NoLibraryDataError: If no library exists for the configuration and window. + """ + library_data = library.get(config, window) + key = library.create_key(config, window) if not library_data: raise NoLibraryDataError( f"No library data found for the given configuration and window: {library.get_path(key)}" ) return InstructionLibraryData.create( - config=self.config, + config=config, data=library_data.filter( tuple(generator.class_name() for generator in self.channels.values()), ), diff --git a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/assigner.py b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/assigner.py index 1723d10e2..c4281581a 100644 --- a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/assigner.py +++ b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/assigner.py @@ -131,8 +131,9 @@ class JointAssigner: A frame is first heard alone, each note as if held through the whole analysis window. Once the recording is decoded, a frame may be assigned again among the notes its neighbors play (``assign_beside``): what they leave in its window is a fixed part of every mix, and a note - extending a neighbor's note adds to it as one note held across the frames. Its choice, columns - and pool may then also pay for breaking with what the frames beside it play. + extending a neighbor's note adds to it as one note held across the frames. Every step reads the + frame through its hearing, the fit of every note included. Its choice, columns and pool may then + also pay for breaking with what the frames beside it play. """ def __init__( @@ -146,8 +147,8 @@ def __init__( Each kind's rows are read once for the recording: as the joint assignment names them, and in feature values at every drive the stems give the kind's channels. Each stem holding a channel - has its note dictionary. The fit of every note hears a stem's atoms alone in every frame, alike - in each, so the first frame hears them for the recording (``steady_atoms``). + has its note dictionary. A frame heard alone hears a stem's atoms alike in every frame, so the + first frame heard alone hears them for the recording (``steady_atoms``). Raises: ValueError: If a stem allows a channel the run has no generator for, or two stems may @@ -177,9 +178,11 @@ def assign(self, fragments: Dict[int, Fragment]) -> StemFrameAssignment: The channels each stem holds, the channels left resting and every stem's pool. """ bins = self._bins(fragments) + hearings = {layout.stem_id: self._alone(layout, bins) for layout in self.layouts} return self._assigned( fragments, - {layout.stem_id: self._alone(layout, bins) for layout in self.layouts}, + hearings, + self._heard_alone(hearings), {layout.stem_id: StemContinuity.free(layout, self.catalogs) for layout in self.layouts}, ) @@ -208,8 +211,13 @@ def assign_beside( for layout in self.layouts if layout.slots } + atoms = { + stem_id: self.dictionaries[stem_id].heard(hearings[stem_id]) + for stem_id in sounding_stems(fragments) + if stem_id in self.dictionaries + } continuities = {layout.stem_id: StemContinuity.of(layout, self.catalogs, continuity) for layout in self.layouts} - return self._assigned(fragments, hearings, continuities) + return self._assigned(fragments, hearings, atoms, continuities) def lines(self, streams: Streams) -> Dict[ChannelName, ChannelLine]: """Every stem channel's decoded frames as the analysis hears them, at the drive the stem gives it. @@ -255,11 +263,11 @@ def settle(self, lines: Mapping[ChannelName, ChannelLine], frame: int, assignmen catalog.instructions[row], ) - def _heard_alone(self, bins: int) -> Dict[int, HeardAtoms]: - """Every stem's atoms as a frame heard alone hears them, heard by the first frame for the recording.""" - for layout in self.layouts: - if layout.stem_id in self.dictionaries and layout.stem_id not in self.steady_atoms: - self.steady_atoms[layout.stem_id] = self.dictionaries[layout.stem_id].heard(self._alone(layout, bins)) + def _heard_alone(self, hearings: Mapping[int, SteadyHearing]) -> Dict[int, HeardAtoms]: + """Every stem's atoms as a frame heard alone hears them, heard by the first such frame for the recording.""" + for stem_id, dictionary in self.dictionaries.items(): + if stem_id not in self.steady_atoms: + self.steady_atoms[stem_id] = dictionary.heard(hearings[stem_id]) return self.steady_atoms @@ -276,15 +284,15 @@ def _assigned( self, fragments: Dict[int, Fragment], hearings: Mapping[int, FrameHearing], + atoms: Mapping[int, HeardAtoms], continuities: Mapping[int, StemContinuity], ) -> StemFrameAssignment: """Assigns one frame, each sounding stem's frame heard as ``hearings`` hears it and kept to ``continuities``. - The fit of every note hears each stem's atoms alone (``steady_atoms``). The channels left + ``atoms`` holds each sounding stem's atoms as its hearing hears them. The channels left resting stand in channel order. """ sounding = sounding_stems(fragments) - atoms = self._heard_alone(self._bins(fragments)) answers: List[StemAnswer] = [] for layout in self.layouts: if not layout.slots: diff --git a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/catalog.py b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/catalog.py index 565240ba6..210597d05 100644 --- a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/catalog.py +++ b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/catalog.py @@ -96,16 +96,17 @@ def volume_at(self, level: float) -> float: class KindCatalog: """One kind of channel's library rows, each read as the note, the timbre and the volume it sounds. - The catalog holds each row's library power, read at unit drive. A row's feature values belong to - the row played on a channel, at the drive the stem gives the channel, so they are read where a - frame hears the row (``FrameHearing``, ``DrivenFeatures``). The rows of one note in one timbre - differ in volume alone, so the search moves along a note's rows to change its level or its timbre. + The catalog holds each row's library power, as the library sample plays it. A row's feature + values belong to the row played on a channel, at the drive the stem gives the channel, so they + are read where a frame hears the row (``FrameHearing``, ``DrivenFeatures``). The rows of one note + in one timbre differ in volume alone, so the search moves along a note's rows to change its level + or its timbre. Attributes: kind: The generator class the rows belong to. generator: A generator of the class, which answers its silent instruction. instructions: The rows, in the order the candidate provider holds them. - powers: Each row's power density per bin, at unit drive. + powers: Each row's power density per bin, as the library sample plays it. notes: Each row's note, ``SILENT_NOTE`` for the silent row. timbres: Each row's timbre within its note. volumes: Each row's volume; the triangle's one level reads as full volume. diff --git a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/columns.py b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/columns.py index faec99ada..e425ff82d 100644 --- a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/columns.py +++ b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/columns.py @@ -12,7 +12,7 @@ from .catalog import KindCatalog from .choice import ScoredCombination from .hearing import FrameHearing -from .layout import StemLayout +from .layout import ChannelGroup, StemLayout VOLUME_NEIGHBORS: Final[int] = 4 SILENCE_ROOM: Final[int] = 1 @@ -29,7 +29,7 @@ class ChannelDraft: place: The channel's place in the layout. options: What the choice plays on the channel, then the nearest volumes of its note. mix: What the stem's other channels sound in the frame, playing the choice. - notes: The proposed notes of the channel's kind that no channel of that kind plays in the + notes: The proposed notes of the channel's kind that no channel of its group plays in the choice, in proposal order. """ @@ -47,8 +47,10 @@ class ChannelColumns: - what the choice plays on the channel, and for a sounding pulse or noise its ``VOLUME_NEIGHBORS`` nearest volumes of the same note and timbre; - - the best row of every proposed note of the channel's kind that no channel of that kind plays in - the choice, by the spectral cost of the frame with the others sounding, cheapest first; + - the best row of every proposed note of the channel's kind that no channel of its group plays in + the choice, by the spectral cost of the frame with the others sounding, cheapest first. A channel + of the group stands in for the one playing the note, so the move would play the choice again in + another order; a channel of another group sounds the note at its own level, a sound of its own; - cut to leave ``SILENCE_ROOM`` of the ``width`` the decoder reads, keeping at least ``LEAST_KEPT``, then the channel's silence where the cut left it out. @@ -138,20 +140,18 @@ def _others_mix(self, index: int, winner: ScoredCombination) -> FrameMix: def _untaken_notes( self, index: int, winner: ScoredCombination, proposals: Mapping[GeneratorClassName, Sequence[int]] ) -> List[int]: - """The notes proposed for the channel's kind that no channel of the kind plays in ``winner``, each once.""" - kind = self.layout.slots[index].kind - catalog = self.catalogs[kind] - taken = self._taken_notes(kind, winner) - proposed = (int(catalog.notes[row]) for row in proposals.get(kind, ())) + """The notes proposed for the channel's kind that no channel of its group plays in ``winner``, each once.""" + group = self.layout.group_of(index) + catalog = self.catalogs[group.kind] + taken = self._taken_notes(group, winner) + proposed = (int(catalog.notes[row]) for row in proposals.get(group.kind, ())) return list(dict.fromkeys(note for note in proposed if note not in taken)) - def _taken_notes(self, kind: GeneratorClassName, winner: ScoredCombination) -> Set[int]: - """The notes ``winner`` sounds on the stem's channels of ``kind``.""" - catalog = self.catalogs[kind] + def _taken_notes(self, group: ChannelGroup, winner: ScoredCombination) -> Set[int]: + """The notes ``winner`` sounds on the channels of ``group``.""" + catalog = self.catalogs[group.kind] return { - int(catalog.notes[row]) - for slot, row in zip(self.layout.slots, winner.rows) - if slot.kind == kind and catalog.sounding(row) + int(catalog.notes[winner.rows[place]]) for place in group.places if catalog.sounding(winner.rows[place]) } def _alternates(self, drafts: Sequence[ChannelDraft]) -> List[List[int]]: diff --git a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/hearing.py b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/hearing.py index 46bbc3d51..fe21a8bd2 100644 --- a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/hearing.py +++ b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/hearing.py @@ -21,14 +21,13 @@ class FrameHearing(Protocol): """How one frame of a stem hears the rows its channels may play: the one reader of a row in a frame. - A row's sound belongs to the row played on a channel. The channel's drive scales the power the - row adds, and the frame's analysis window hears the row among what the channel's other frames - play, so a row's power and feature values are read for the row on a channel, in a frame. The - catalog holds each row's library power, ``DrivenFeatures`` the feature values of each row heard - alone on a channel, and every step of the joint assignment reads a row through a hearing. The fit - of every combination, the search's mixes and the judge's read it through the frame's hearing. The - fit of every note reads each note through a frame heard alone, over the frame's leak - (``note_strengths``). + What a row adds to a frame depends on the channel that plays it and on the frame's neighbors. The + channel's drive scales the row's power, and the frame's analysis window hears the row among what + the channel's other frames play, so a row's power and feature values are read for the row on a + channel, in a frame. The catalog holds each row's library power, ``DrivenFeatures`` the feature + values of each row heard alone on a channel, and every step of the joint assignment reads a row + through the frame's hearing: the fit of every note, the fit of every combination, the search's + mixes and the judge's. A hearing answers what the frame holds before any of its rows sound, its leak, and what each row adds when a channel plays it, at the drive the stem gives the channel. A reading adds the @@ -49,13 +48,6 @@ def leak_features(self) -> np.ndarray: def powers(self, place: int, rows: RowSet) -> np.ndarray: """The power each of ``rows`` adds when the channel at ``place`` in the layout plays it, one row per row.""" - def steady_powers(self, place: int, rows: RowSet) -> np.ndarray: - """The power each of ``rows`` adds heard alone on the channel at ``place``, as a note held through the window. - - It is the row's library power at the channel's drive (``library_powers``), whatever the - frame's neighbors play. - """ - def unit_powers(self, place: int, rows: RowSet) -> np.ndarray: """What each of ``rows`` adds as a fit of its level reads it: a scale of the row's power.""" @@ -141,13 +133,10 @@ def leak_features(self) -> np.ndarray: return np.zeros(self.bins) def powers(self, place: int, rows: RowSet) -> np.ndarray: - return self.steady_powers(place, rows) - - def steady_powers(self, place: int, rows: RowSet) -> np.ndarray: return library_powers(self.layout, self.catalogs, place, rows) def unit_powers(self, place: int, rows: RowSet) -> np.ndarray: - return self.steady_powers(place, rows) + return self.powers(place, rows) def unit_features(self, place: int, rows: RowSet) -> np.ndarray: return self.driven.at(self.layout.slots[place], rows) @@ -217,14 +206,11 @@ def of( ) def powers(self, place: int, rows: RowSet) -> np.ndarray: - return self.surroundings[place].heard(self._keys(place, rows), self.steady_powers(place, rows)) - - def steady_powers(self, place: int, rows: RowSet) -> np.ndarray: - return library_powers(self.layout, self.catalogs, place, rows) + return self.surroundings[place].heard(self._keys(place, rows), self._library_powers(place, rows)) def unit_powers(self, place: int, rows: RowSet) -> np.ndarray: gains = self.surroundings[place].gains(self._keys(place, rows)) - return np.asarray(gains * self.steady_powers(place, rows)) + return np.asarray(gains * self._library_powers(place, rows)) def unit_features(self, place: int, rows: RowSet) -> np.ndarray: return heard_features(self.provider, self.unit_powers(place, rows)) @@ -248,6 +234,10 @@ def empty_mix(self, fragment: Fragment) -> FrameMix: """ return replace(FrameMix.empty(fragment), power=self.leak) + def _library_powers(self, place: int, rows: RowSet) -> np.ndarray: + """Each row's library power at the drive of the channel at ``place``, before the window hears it.""" + return library_powers(self.layout, self.catalogs, place, rows) + def _keys(self, place: int, rows: RowSet) -> List[Optional[NoteKey]]: """The note and timbre each of ``rows`` sounds on the channel at ``place``, ``None`` for silence.""" catalog = self.catalogs[self.layout.slots[place].kind] diff --git a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/layout.py b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/layout.py index f79c9bcdf..fb52e986e 100644 --- a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/layout.py +++ b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/layout.py @@ -126,6 +126,10 @@ def groups_of(self, kind: GeneratorClassName) -> Tuple[ChannelGroup, ...]: """The groups of the stem's channels of ``kind``, in the order of their lowest channels.""" return tuple(group for group in self.groups if group.kind == kind) + def group_of(self, place: int) -> ChannelGroup: + """The group holding the channel at ``place``.""" + return next(group for group in self.groups if place in group.places) + def first_place(self, kind: GeneratorClassName) -> int: """The place a row of ``kind`` sounding alone fills first: the lowest channel of the kind's first group. diff --git a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/proposals.py b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/proposals.py index ba332407e..348ba9676 100644 --- a/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/proposals.py +++ b/src/sampletones_core/reconstructions/reconstructor/stems/assignment/joint/proposals.py @@ -11,7 +11,7 @@ from .batches import cheapest_row, split_by_group from .catalog import KindCatalog, alike_timbres from .fit import FitTarget, fitted_levels -from .hearing import FrameHearing, SteadyHearing, rows_by_place +from .hearing import FrameHearing, rows_by_place from .layout import StemLayout FREE_FIT_START: Final[float] = 0.05 @@ -31,9 +31,9 @@ class NoteStrengths: """How strongly a frame sounds each note of each kind, as the fit of every note at once reads it. - A note's strength is the power its atoms' fitted levels sound it at heard alone (``HeardAtoms``), - summed over its timbres and unweighted, so a bass counts for what it plays where the criterion's - weights are light. + A note's strength is the power its atoms' fitted levels add to the frame's reading + (``HeardAtoms``), summed over its timbres and unweighted, so a bass counts for what it plays where + the criterion's weights are light. Attributes: strengths: Each note's strength, keyed by its kind and note, in the dictionary's order. @@ -53,31 +53,37 @@ def strongest(self, kind: GeneratorClassName, count: int) -> List[int]: @dataclass(frozen=True) class HeardAtoms: - """A note dictionary's atoms as a frame heard alone hears them, each on the channel its note is heard on. + """A note dictionary's atoms as one frame hears them, each on the channel its note is heard on. A level of one sounds an atom's unit row on its channel, at the drive the stem gives the - channel, and a frame heard alone reads it there as the row's power at the drive - (``FrameHearing.unit_features``). An atom's cap is what every channel of its kind playing it at + channel, and the frame's hearing reads what it adds there (``FrameHearing.unit_features``): heard + alone, the row's power at the drive; among the frame's neighbors, its own share of the window, + joined with the note it extends. An atom's cap is what every channel of its kind playing it at full volume sounds, as a level of the atom on its channel: its full level times the channel's ``StemLayout.gain``. The caps and the powers move with the atoms, so the most a note sounds is what the stem's channels play at every drive. - An atom's power is its unit row's power heard alone on its channel - (``FrameHearing.steady_powers``), so a note's strength is the power its fitted level sounds the - note at, heard alone. The power sums the row's power densities over the bins, the form the - catalog holds a row's power in. The proposal counts (``PROPOSED_NOTES``) and the triangle run's - shares (``level.reading``) were tuned on strengths read in densities. A density weighs a partial - by its bin's width, so where the bins widen with frequency, as under ``cqt`` and above about - 500 Hz under ``logfft``, a note's low partials weigh more than its high ones. Under ``fft`` every - bin is as wide, and the densities rank the notes as their bin powers do. + An atom's power is what its unit row adds to the frame's reading (``FrameHearing.unit_powers``), + so a note's strength is the power its fitted level adds: the part of the reading the frame's + choice decides, which the frame loses where it leaves the note out. A note held beside the frame + counts what joining it adds, the leak's part of it staying whatever the frame plays, so a held + note and a note of the frame's own rank by the same measure. Heard alone, a row adds its whole + power. + + The power sums the row's power densities over the bins, the form the catalog holds a row's power + in. The proposal counts (``PROPOSED_NOTES``) and the triangle run's shares (``level.reading``) + were tuned on strengths read in densities. A density weighs a partial by its bin's width, so + where the bins widen with frequency, as under ``cqt`` and above about 500 Hz under ``logfft``, a + note's low partials weigh more than its high ones. Under ``fft`` every bin is as wide, and the + densities rank the notes as their bin powers do. Attributes: kinds: Each atom's kind. notes: Each atom's note. - features: Each atom's feature values heard alone at a level of one, one per row. + features: The feature values of what each atom adds to the frame at a level of one, one per row. caps: The highest level each atom may reach. - powers: Each atom's whole power heard alone on its channel, which a fitted note's strength is - read in. + powers: The whole power each atom adds to the frame at a level of one, which a fitted note's + strength is read in. """ kinds: Tuple[GeneratorClassName, ...] @@ -101,9 +107,9 @@ class NoteDictionary: """One atom per note and timbre a stem's channels may sound, which a frame's levels are fitted over. An atom is the unit row of its note in its timbre, so a level of one sounds that row. The - dictionary holds the atoms' rows, and a frame heard alone hears them (``heard``): a row's sound - belongs to the row on a channel. The atoms stand kind by kind in name order, each kind's notes - ascending and each note's timbres ascending. + dictionary holds the atoms' rows, and each frame hears them through its hearing (``heard``), as + every step of the joint assignment hears a row. The atoms stand kind by kind in name order, each + kind's notes ascending and each note's timbres ascending. Attributes: layout: The stem's channels. @@ -146,8 +152,8 @@ def of(cls, layout: StemLayout, catalogs: Mapping[GeneratorClassName, KindCatalo full_levels=np.array(full_levels, dtype=np.float64), ) - def heard(self, hearing: SteadyHearing) -> HeardAtoms: - """The atoms as a frame heard alone hears them, each on the channel it hears its note's proposal on. + def heard(self, hearing: FrameHearing) -> HeardAtoms: + """The atoms as ``hearing`` hears its frame, each on the channel it hears its note's proposal on. The atoms span the frame's bins at every count of atoms, so a dictionary of no atom is heard as no atom over the bins. @@ -162,7 +168,7 @@ def heard(self, hearing: SteadyHearing) -> HeardAtoms: rows = [int(row) for row in self.rows[placed]] features[placed] = hearing.unit_features(place, rows) caps[placed] = self.full_levels[placed] * self.layout.gain(place) - powers[placed] = [float(power.sum()) for power in hearing.steady_powers(place, rows)] + powers[placed] = [float(power.sum()) for power in hearing.unit_powers(place, rows)] return HeardAtoms(kinds=self.kinds, notes=self.notes, features=features, caps=caps, powers=powers) @@ -208,12 +214,9 @@ def _costs(self, kind: GeneratorClassName, rows: np.ndarray) -> np.ndarray: def note_strengths(target: FitTarget, atoms: HeardAtoms, hearing: FrameHearing) -> NoteStrengths: """How strongly the frame sounds each note, every note fitted to it at once. - The atoms are heard as a frame heard alone hears them (``NoteDictionary.heard``): each row at its - channel's drive, as a note held through the whole window. They are fitted over what the frame - holds before its rows sound, the leak of ``hearing``, from ``FREE_FIT_START`` for - ``FREE_FIT_UPDATES`` updates. Among the frame's neighbors the fit hears each row alone as well, - since the window model reads a note cut at a frame boundary approximately, and the fit weighs - every note of the frame through what it reads. + The atoms, heard as ``hearing`` hears the frame (``NoteDictionary.heard``), are fitted over what + the frame holds before its rows sound, its leak, from ``FREE_FIT_START`` for ``FREE_FIT_UPDATES`` + updates. A note's strength is the power its fitted level adds to the frame's reading. """ levels = fitted_levels( target, @@ -237,12 +240,12 @@ def proposed_rows( ) -> Dict[GeneratorClassName, List[int]]: """The rows a frame's search starts from: each kind's strongest notes, each on its best row alone. - Every note is fitted to the frame at once, its ``atoms`` heard alone over what ``hearing`` holds - before its rows sound (``note_strengths``), and each kind proposes its ``PROPOSED_NOTES`` - strongest notes. A note is proposed on the row of its own, of any timbre and volume, that fits - the frame best alone, which settles its duty cycle and a first volume. A row alone leaves the - frame's other notes uncovered, so the bins it falls short in count at ``SHORTFALL_WEIGHT`` of - their cost, and what it adds beyond the frame counts in full. + Every note is fitted to the frame at once, its ``atoms`` heard as ``hearing`` hears the frame + (``note_strengths``), and each kind proposes its ``PROPOSED_NOTES`` strongest notes. A note is + proposed on the row of its own, of any timbre and volume, that fits the frame best alone, which + settles its duty cycle and a first volume. A row alone leaves the frame's other notes uncovered, + so the bins it falls short in count at ``SHORTFALL_WEIGHT`` of their cost, and what it adds + beyond the frame counts in full. Where the stem holds two pulses, its ``DOUBLED_NOTES`` strongest pulse notes are proposed again, each on the best row of a duty cycle sounding unlike its first, so two pulses may sound one note. diff --git a/src/sampletones_core/reconstructions/reconstructor/window/profiles.py b/src/sampletones_core/reconstructions/reconstructor/window/profiles.py index 55ecedc62..eec019724 100644 --- a/src/sampletones_core/reconstructions/reconstructor/window/profiles.py +++ b/src/sampletones_core/reconstructions/reconstructor/window/profiles.py @@ -12,6 +12,7 @@ from sampletones_core.fft.cqt.geometry import calculate_wavelet_lengths from sampletones_core.fft.cqt.kernel import window_envelope from sampletones_core.fft.cqt.transform import FRAMES_WINDOW, wavelet_positions +from sampletones_core.fft.layers import analysis_layers CACHED_PROFILES: Final[int] = 4 @@ -114,40 +115,55 @@ def energy_at(self, offset: int) -> np.ndarray: return np.asarray(self.energy[self.reach + offset]) -def frame_profiles(config: Config, window: Window, bins: int) -> FrameProfiles: - """The frame profiles of the feature ``config`` analyzes with. +def frame_profiles(config: Config, window: Window, sizes: Sequence[int]) -> FrameProfiles: + """The frame profiles of the feature ``config`` analyzes with, every analysis layer's bins in order. The constant-Q feature reads each bin through a wavelet of its own length, standing where the transform places it around the middle of the frame. The windowed features read every bin through - one tapered window starting where ``window`` places it. + one tapered window starting where the layer's window places it. A frame read by several spectrum + methods stacks their bins (``analysis_layers``), so its profiles stack each method's. Args: - config: The configuration whose spectrum method the frames are read with. - window: The analysis window, which sets the frame length and the windowed features' envelope. - bins: How many bins a frame's feature holds. + config: The configuration whose spectrum methods the frames are read with. + window: The analysis window of the library's own method, which sets the frame length. + sizes: How many bins each analysis layer's reading holds, in the order the frame's feature + stacks them. Returns: The profiles of every bin. """ + layers = analysis_layers(config) + windows = (window, *(layer.window for layer in layers[1:])) + return FrameProfiles.of( + [ + bin_window + for layer, layer_window, bins in zip(layers, windows, sizes, strict=True) + for bin_window in _layer_windows(layer.config, layer_window, bins) + ] + ) + + +def _layer_windows(config: Config, window: Window, bins: int) -> Tuple[BinWindow, ...]: + """Each bin's window over the frames, for the bins one spectrum method reads.""" method = config.library.spectrum_method match method: case SpectrumMethod.CQT: - return _constant_q_profiles(config.library.sample_rate, window.frame_length, bins) + return _constant_q_windows(config.library.sample_rate, window.frame_length, bins) case SpectrumMethod.FFT | SpectrumMethod.LOG_SPACED_FFT: envelope = tuple(float(weight) for weight in window.envelope) - return _windowed_profiles(envelope, window.left_offset, window.frame_length, bins) + return (_tapered_window(envelope, window.left_offset, window.frame_length),) * bins case _: assert_never(method) @lru_cache(maxsize=CACHED_PROFILES) -def _constant_q_profiles(sample_rate: int, frame_length: int, bins: int) -> FrameProfiles: - """Each bin's wavelet weighed over the frames, on the bins the constant-Q feature reads. +def _constant_q_windows(sample_rate: int, frame_length: int, bins: int) -> Tuple[BinWindow, ...]: + """Each bin's wavelet over the frames, on the bins the constant-Q feature reads. - The profiles depend on the configuration alone, so a process builds them once for each + The wavelets depend on the configuration alone, so a process lays them once for each configuration it converts with. """ - return FrameProfiles.of(constant_q_windows(sample_rate, frame_length, bins)) + return tuple(constant_q_windows(sample_rate, frame_length, bins)) def constant_q_windows(sample_rate: int, frame_length: int, bins: int) -> List[BinWindow]: @@ -174,12 +190,11 @@ def _wavelet(length: int, kernel_length: int, frame_length: int) -> BinWindow: @lru_cache(maxsize=CACHED_PROFILES) -def _windowed_profiles(envelope: Tuple[float, ...], left_offset: int, frame_length: int, bins: int) -> FrameProfiles: - """One tapered window weighed over the frames, shared by every bin. +def _tapered_window(envelope: Tuple[float, ...], left_offset: int, frame_length: int) -> BinWindow: + """The one tapered window every bin of a windowed feature reads through. The window's ``envelope`` arrives as a tuple so the cache can key on it. Its first sample lies ``left_offset`` samples from the frame's start. """ weights = np.asarray(envelope, dtype=np.float64) - tapered = BinWindow.placed(left_offset + np.arange(weights.shape[0]), weights, frame_length) - return FrameProfiles.of([tapered] * bins) + return BinWindow.placed(left_offset + np.arange(weights.shape[0]), weights, frame_length) diff --git a/src/sampletones_core/reconstructions/reconstructor/worker.py b/src/sampletones_core/reconstructions/reconstructor/worker.py index d33a3d30a..f2ca43102 100644 --- a/src/sampletones_core/reconstructions/reconstructor/worker.py +++ b/src/sampletones_core/reconstructions/reconstructor/worker.py @@ -1,5 +1,5 @@ from dataclasses import dataclass, field -from typing import Dict +from typing import Dict, Tuple from sampletones_core.configs import Config from sampletones_core.constants.enums import ChannelName @@ -23,13 +23,16 @@ class ReconstructorWorker: Everything a reconstruction run needs beyond its target sits here, built once for the signal it will work on: the scorer and candidate provider the matching draws from, the phase aligner and feature extractor it measures with, the `FrameMatcher` the stems - assignment scores through, and the `Decoder` the configuration names. + assignment scores through, and the `Decoder` the configuration names. A conversion reading its + frames with several spectrum methods hands the library of each method it adds + (``layer_data``), which the candidate provider stacks beside the library's own. """ config: Config window: Window channels: Dict[ChannelName, GeneratorUnion] library_data: InstructionLibraryData + layer_data: Tuple[InstructionLibraryData, ...] signal_length: int scorer: Scorer = field(init=False) @@ -42,7 +45,13 @@ class ReconstructorWorker: def __post_init__(self) -> None: scorer = Scorer(self.config, self.window, self.signal_length) feature_extractor = get_feature_extractor(self.config, self.window) - candidate_provider = CandidateProvider(self.config, self.window, self.library_data, feature_extractor) + candidate_provider = CandidateProvider( + config=self.config, + window=self.window, + library_data=self.library_data, + extractor=feature_extractor, + layer_data=self.layer_data, + ) phase_aligner_class = PHASE_ALIGNERS[self.config.generation.calculation.phase_aligner] phase_aligner = phase_aligner_class(self.config, self.window, self.library_data) matcher = FrameMatcher( diff --git a/src/sampletones_tools/calibration/board/composition.py b/src/sampletones_tools/calibration/board/composition.py index c203a074c..9cdaf99b6 100644 --- a/src/sampletones_tools/calibration/board/composition.py +++ b/src/sampletones_tools/calibration/board/composition.py @@ -5,13 +5,14 @@ from sampletones_shared.paths.extensions import EXT_FILE_FLAC from sampletones_shared.utils.system.paths import get_filename from sampletones_tools.calibration.config.level import VariantLevel -from sampletones_tools.calibration.layout import combination_name +from sampletones_tools.calibration.layout import ORACLE_LABEL, combination_name +from sampletones_tools.calibration.oracle.reading import HIGHEST_READING, LOWEST_READING from sampletones_tools.calibration.renders import RenderRecord, item_directory, recording_path, variant_directory from sampletones_tools.calibration.variants import LABEL_SEPARATOR from sampletones_tools.web.roles.table import channel_role from .clips import ClipStore -from .headings import heading_column, shared_words +from .headings import heading_column, oracle_column, shared_words from .model import ( BoardCell, BoardChannel, @@ -36,9 +37,10 @@ def compose_page( """ Assemble everything a page draws from the runs it reports. - One run is read across its variants, which become the columns of a single table. Several runs - are read against each other, so each variant becomes a table of its own and the runs stand as - its columns — the comparison a person makes when they run the same settings on two versions. + One run is read across its variants, which become the columns of a single table, the oracle's + first where the run read it. Several runs are read against each other, so each variant becomes a + table of its own and the runs stand as its columns — the comparison a person makes when they run + the same settings on two versions. Args: runs: The runs the page reports, in the order the page holds them. @@ -66,10 +68,15 @@ def compose_page( def _column_group(run: RunReading, store: ClipStore) -> Tuple[BoardGroup, ...]: - """One table whose columns are the configurations the run measured.""" + """One table whose columns are the configurations the run measured, after the oracle where the run read it. + + The oracle reads only the sounds written as NES frames, so a row of another sound leaves its + oracle cell empty. + """ variants = run.variants - rows = _rows(store, _items(run), [(run, variant) for variant in variants]) - return (_group(run.label, variants, rows),) + oracle = run if run.holds_oracle else None + rows = _rows(store, _items(run), [(run, variant) for variant in variants], oracle) + return (_group(run.label, variants, rows, oracle=oracle is not None),) def _variant_groups(runs: Sequence[RunReading], store: ClipStore) -> Tuple[BoardGroup, ...]: @@ -77,19 +84,23 @@ def _variant_groups(runs: Sequence[RunReading], store: ClipStore) -> Tuple[Board groups: List[BoardGroup] = [] for variant in _shared_variants(runs): holders = [run for run in runs if variant in run.variants] - rows = _rows(store, _shared_items(holders), [(run, variant) for run in holders]) - groups.append(_group(variant, [run.label for run in holders], rows)) + rows = _rows(store, _shared_items(holders), [(run, variant) for run in holders], None) + groups.append(_group(variant, [run.label for run in holders], rows, oracle=False)) return tuple(groups) -def _group(name: str, columns: Sequence[str], rows: Tuple[BoardRow, ...]) -> BoardGroup: - """A tab of these columns and rows, each heading naming what its column adds to the words they share.""" +def _group(name: str, columns: Sequence[str], rows: Tuple[BoardRow, ...], *, oracle: bool) -> BoardGroup: + """A tab of these columns and rows, each heading naming what its column adds to the words they share. + + The oracle's column, where the group holds it, stands first and outside the shared words. + """ prefix = shared_words(columns) + headed = tuple(heading_column(column, prefix) for column in columns) return BoardGroup( name=name, prefix=LABEL_SEPARATOR.join(prefix), - columns=tuple(heading_column(column, prefix) for column in columns), + columns=(oracle_column(), *headed) if oracle else headed, families=_families(rows), rows=rows, ) @@ -100,7 +111,9 @@ def _families(rows: Sequence[BoardRow]) -> Tuple[BoardFamily, ...]: sounding: Dict[str, Set[ChannelName]] = {} for row in rows: channels = sounding.setdefault(row.family, set()) - channels.update(ChannelName(channel.name) for cell in row.cells for channel in cell.channels) + channels.update( + ChannelName(channel.name) for cell in row.cells if cell is not None for channel in cell.channels + ) return tuple( BoardFamily(name=family, channels=tuple(channel.value for channel in ordered_channels(channels))) @@ -112,9 +125,14 @@ def _rows( store: ClipStore, items: Sequence[str], places: Sequence[Tuple[RunReading, str]], + oracle: Optional[RunReading], ) -> Tuple[BoardRow, ...]: - """A row per item every column holds a render of, so each row reads across the whole table.""" - rows = [_row(store, item, places) for item in items] + """A row per item every column holds a render of, so each row reads across the whole table. + + Where ``oracle`` names a run, each row leads with that run's oracle cell of the item, empty where + the run read no oracle of it. + """ + rows = [_row(store, item, places, oracle) for item in items] return tuple(row for row in rows if row is not None) @@ -122,18 +140,25 @@ def _row( store: ClipStore, item: str, places: Sequence[Tuple[RunReading, str]], + oracle: Optional[RunReading], ) -> Optional[BoardRow]: records = [(run, _record(run, item, variant)) for run, variant in places] held = [(run, record) for run, record in records if record is not None] if len(held) != len(records): return None + cells: Tuple[Optional[BoardCell], ...] = tuple(_cell(run, store, record) for run, record in held) + if oracle is not None: + read = _record(oracle, item, ORACLE_LABEL) + cells = (None if read is None else _cell(oracle, store, read), *cells) + held = [(oracle, read), *held] if read is not None else held + return BoardRow( item=item, family=held[0][1].family, category=held[0][1].category, recordings=_recordings(store, item, held), - cells=tuple(_cell(run, store, record) for run, record in held), + cells=cells, ) @@ -160,9 +185,19 @@ def _cell(run: RunReading, store: ClipStore, record: RenderRecord) -> BoardCell: score=run.score(record), silence=run.silence(record), channels=tuple(_channel(run, store, record, channel, channels) for channel in channels), + spread=_spread(run, record), ) +def _spread(run: RunReading, record: RenderRecord) -> Optional[Tuple[float, float]]: + """The lowest and highest headline score of the renders a record's score is the mean of, where it keeps them.""" + readings = record.judgments[run.referee] + if LOWEST_READING not in readings or HIGHEST_READING not in readings: + return None + + return readings[LOWEST_READING], readings[HIGHEST_READING] + + def _channel( run: RunReading, store: ClipStore, diff --git a/src/sampletones_tools/calibration/board/headings.py b/src/sampletones_tools/calibration/board/headings.py index 1ef95bc0f..84d6a7367 100644 --- a/src/sampletones_tools/calibration/board/headings.py +++ b/src/sampletones_tools/calibration/board/headings.py @@ -1,6 +1,7 @@ from itertools import takewhile from typing import Final, Sequence, Tuple +from sampletones_tools.calibration.layout import ORACLE_LABEL from sampletones_tools.calibration.variants import LABEL_SEPARATOR from .model import BoardColumn @@ -31,7 +32,12 @@ def shared_words(names: Sequence[str]) -> Tuple[str, ...]: def heading_column(name: str, prefix: Sequence[str]) -> BoardColumn: """The column called ``name``, its heading holding the words of the name past ``prefix``.""" - return BoardColumn(name=name, words=tuple(name.split(LABEL_SEPARATOR)[len(prefix) :])) + return BoardColumn(name=name, words=tuple(name.split(LABEL_SEPARATOR)[len(prefix) :]), oracle=False) + + +def oracle_column() -> BoardColumn: + """The oracle's column, its heading naming it whole.""" + return BoardColumn(name=ORACLE_LABEL, words=(ORACLE_LABEL,), oracle=True) def _alike(words: Tuple[str, ...]) -> bool: diff --git a/src/sampletones_tools/calibration/board/model.py b/src/sampletones_tools/calibration/board/model.py index a9ff88c6f..520e4d03a 100644 --- a/src/sampletones_tools/calibration/board/model.py +++ b/src/sampletones_tools/calibration/board/model.py @@ -1,4 +1,4 @@ -from typing import Dict, Tuple +from typing import Dict, Optional, Tuple from pydantic import BaseModel, ConfigDict @@ -29,6 +29,8 @@ class BoardCell(BaseModel): score: The headline referee's distance between the render and its recording. silence: What the same referee scores complete silence at, the distance a render closes. channels: The channels the render sounds, in the order the hardware holds them. + spread: The lowest and the highest score among the renders the score is the mean of, for + the oracle's cell; ``None`` for a cell of one render. """ model_config = ConfigDict(frozen=True, extra="forbid") @@ -37,6 +39,7 @@ class BoardCell(BaseModel): score: float silence: float channels: Tuple[BoardChannel, ...] + spread: Optional[Tuple[float, float]] class BoardRecording(BaseModel): @@ -62,7 +65,8 @@ class BoardRow(BaseModel): category: The corpus category the item belongs to. recordings: One recording per level the cells were matched at, in the order the columns first reach each level, so every cell plays beside the recording at its own level. - cells: One cell per column, in the columns' order. + cells: One cell per column, in the columns' order; ``None`` under the oracle's column for a + sound written otherwise than as NES frames. """ model_config = ConfigDict(frozen=True, extra="forbid") @@ -71,7 +75,7 @@ class BoardRow(BaseModel): family: str category: str recordings: Tuple[BoardRecording, ...] - cells: Tuple[BoardCell, ...] + cells: Tuple[Optional[BoardCell], ...] class BoardColumn(BaseModel): @@ -82,12 +86,15 @@ class BoardColumn(BaseModel): words: The words of the name past the prefix every column of the group shares, one per line of the heading. A column named by the prefix alone holds none, as the base configuration the other columns add to. + oracle: Whether the column holds the oracle, what playing each sound's frames exactly + scores, which stands beside the conversions and outside the change across them. """ model_config = ConfigDict(frozen=True, extra="forbid") name: str words: Tuple[str, ...] + oracle: bool class BoardFamily(BaseModel): diff --git a/src/sampletones_tools/calibration/board/reading.py b/src/sampletones_tools/calibration/board/reading.py index f7d138e9f..2511d4f17 100644 --- a/src/sampletones_tools/calibration/board/reading.py +++ b/src/sampletones_tools/calibration/board/reading.py @@ -5,7 +5,7 @@ from sampletones_shared.paths.extensions import EXT_FILE_JSON from sampletones_tools.calibration.fingerprint import measured_variants -from sampletones_tools.calibration.layout import RENDERS_DIRECTORY +from sampletones_tools.calibration.layout import ORACLE_LABEL, RENDERS_DIRECTORY from sampletones_tools.calibration.referee.protocol import SCORE_READING from sampletones_tools.calibration.renders import RenderRecord @@ -17,8 +17,8 @@ class RunReading(BaseModel): label: The name the page calls the run by, which is unique among the runs it holds. directory: The run directory every reference the page makes resolves against. measured: The labels of the variants the run measured, in the order it measured them. - records: Every render the run wrote under the variants it measured, in the order the corpus - generates its items. + records: Every render the run wrote under the variants it measured and the oracle's, in the + order the corpus generates its items. """ model_config = ConfigDict(frozen=True, extra="forbid") @@ -38,6 +38,11 @@ def variants(self) -> Tuple[str, ...]: recorded = {record.variant for record in self.records} return tuple(variant for variant in self.measured if variant in recorded) + @property + def holds_oracle(self) -> bool: + """Whether the run read the oracle of any sound, which the page then shows beside the variants.""" + return any(record.variant == ORACLE_LABEL for record in self.records) + @property def referee(self) -> str: """The referee whose score the page reports, which is the one the run's report leads with. @@ -67,7 +72,7 @@ def read_run(directory: Path, label: str) -> RunReading: The records carry the scores, the categories and the frames each channel sounded, so a page is assembled from a finished run without repeating any measurement. The fingerprint lists the variants in the order the run measured them, which the page's columns follow, and the records of - those variants alone are read. + those variants and of the oracle alone are read. Args: directory: The run directory, the one holding ``renders`` and the fingerprint. @@ -86,7 +91,7 @@ def read_run(directory: Path, label: str) -> RunReading: measured = measured_variants(directory) records = [RenderRecord.model_validate_json(path.read_text(encoding="utf-8")) for path in paths] - held = [record for record in records if record.variant in measured] + held = [record for record in records if record.variant in measured or record.variant == ORACLE_LABEL] held.sort(key=lambda record: (record.position, record.variant)) return RunReading(label=label, directory=directory, measured=measured, records=tuple(held)) diff --git a/src/sampletones_tools/calibration/board/static/page.js b/src/sampletones_tools/calibration/board/static/page.js index a08536e3e..9c882238c 100644 --- a/src/sampletones_tools/calibration/board/static/page.js +++ b/src/sampletones_tools/calibration/board/static/page.js @@ -13,6 +13,8 @@ const MESSAGES = { silent: "—", exact: "exact", closed: (nats) => `${nats} nats`, + spread: (lowest, highest) => `From ${lowest} to ${highest} over the starts the run drew`, + unread: "—", openAll: "Open all", closeAll: "Close all", }; @@ -196,11 +198,18 @@ function playNode(cell, glyph) { return render; } -/** A render's score over how far it stands from silence. */ +/** + * A render's score over how far it stands from silence. A score that is the mean of several + * renders, as the oracle's is, names their closest and farthest in its tooltip. + */ function readingNode(cell) { const reading = element("div", "reading"); reading.append(element("b", null, rounded(closeness(cell)))); reading.append(element("span", null, fromSilence(cell))); + if (cell.spread) { + const [lowest, highest] = cell.spread; + reading.title = MESSAGES.spread(rounded(-highest), rounded(-lowest)); + } return reading; } @@ -215,14 +224,16 @@ function cellNode(cell, channels, board) { } /** - * The change of the turned score from the first column to the last, so a rise means the last - * column is closer to the recording. A change rounding to zero is marked neither better nor worse, - * and a row of one column leaves the cell empty. + * The change of the turned score from the first conversion's column to the last, so a rise means + * the last column is closer to the recording. The oracle's column stands outside it. A change + * rounding to zero is marked neither better nor worse, and a row of one conversion leaves the cell + * empty. */ -function changeNode(row) { +function changeNode(row, columns) { const node = element("td", "change"); - if (row.cells.length < CHANGE_COLUMNS) { return node; } - const change = closeness(row.cells[row.cells.length - 1]) - closeness(row.cells[0]); + const cells = row.cells.filter((cell, place) => !columns[place].oracle); + if (cells.length < CHANGE_COLUMNS) { return node; } + const change = closeness(cells[cells.length - 1]) - closeness(cells[0]); const shown = rounded(change); if (Number(shown) !== 0) { node.classList.add(change > 0 ? "better" : "worse"); } node.textContent = `${Number(shown) >= 0 ? "+" : ""}${shown}`; @@ -242,19 +253,27 @@ function recordingsNode(row) { return node; } -/** One sound across the table: its name, its recordings, a cell per version and the change. */ -function rowNode(row, channels, board) { +/** The class a version's heading and cells carry, the oracle's column marked apart. */ +function versionClass(column) { + return column.oracle ? "version oracle" : "version"; +} + +/** + * One sound across the table: its name, its recordings, a cell per version and the change. A + * sound the oracle reads no frames of leaves the oracle's cell holding a dash. + */ +function rowNode(row, columns, channels, board) { const node = element("tr", "sound-row"); const sound = element("td", "sound"); sound.append(breakable(row.item)); node.append(sound); node.append(recordingsNode(row)); row.cells.forEach((cell, place) => { - const holder = inColumn(element("td", "version"), place); - holder.append(cellNode(cell, channels, board)); + const holder = inColumn(element("td", versionClass(columns[place])), place); + holder.append(cell ? cellNode(cell, channels, board) : element("span", "unread", MESSAGES.unread)); node.append(holder); }); - node.append(changeNode(row)); + node.append(changeNode(row, columns)); return node; } @@ -325,7 +344,7 @@ function headingWords(column) { * name stays in the tooltip. */ function versionHeading(column, place, glyphs) { - const heading = inColumn(element("th", "version"), place); + const heading = inColumn(element("th", versionClass(column)), place); heading.title = column.name; const toggle = element("button", "column-toggle"); toggle.setAttribute("aria-expanded", "false"); @@ -353,13 +372,13 @@ function headNode(layout, glyphs) { } /** The sound rows, a category heading opening each stretch of rows of one category. */ -function bodyNode(rows, channels, span, board) { +function bodyNode(rows, columns, channels, span, board) { const body = element("tbody"); let category = null; for (const row of rows) { if (row.category !== category) { body.append(categoryNode(row.category, span)); } category = row.category; - body.append(rowNode(row, channels, board)); + body.append(rowNode(row, columns, channels, board)); } return body; } @@ -375,7 +394,7 @@ function tableNode(columns, family, rows, board) { table.append( widthsNode(layout), headNode(layout, board.glyphs), - bodyNode(rows, family.channels, layout.length, board), + bodyNode(rows, columns, family.channels, layout.length, board), ); return table; } diff --git a/src/sampletones_tools/calibration/board/static/style.css b/src/sampletones_tools/calibration/board/static/style.css index 8b6034e74..b9036a473 100644 --- a/src/sampletones_tools/calibration/board/static/style.css +++ b/src/sampletones_tools/calibration/board/static/style.css @@ -193,6 +193,17 @@ col.change { background: var(--card-header-hover); } +/* The oracle's heading reads apart from the conversions', since it plays every sound's frames exactly. */ +.table.sounds th.version.oracle .column-toggle { + font-style: italic; + color: var(--text-muted); +} + +/* A sound the oracle reads no frames of holds a dash in its column. */ +td.version .unread { + color: var(--text-muted); +} + .column-toggle { appearance: none; margin: 0; diff --git a/src/sampletones_tools/calibration/config/settings.yaml b/src/sampletones_tools/calibration/config/settings.yaml index 9ec8d9f5e..959e7e0c0 100644 --- a/src/sampletones_tools/calibration/config/settings.yaml +++ b/src/sampletones_tools/calibration/config/settings.yaml @@ -110,3 +110,51 @@ settings: inertia: {pulse1: 0.5, pulse2: 0.5, triangle: 0.5, noise: 0.5} decoder: selector: combinations + joint-logfft: + generation: + assignment: + method: joint + layers: + - {method: logfft, weight: 1.0} + joint-fitted-combinations-logfft: + general: + level: fitted + generation: + assignment: + method: joint + decoder: + selector: combinations + layers: + - {method: logfft, weight: 1.0} + joint-fitted-combinations-neighbors1-logfft: + general: + level: fitted + generation: + assignment: + method: joint + neighbors: 1 + decoder: + selector: combinations + layers: + - {method: logfft, weight: 1.0} + joint-fitted-combinations-logfft05: + general: + level: fitted + generation: + assignment: + method: joint + decoder: + selector: combinations + layers: + - {method: logfft, weight: 0.5} + joint-fitted-combinations-neighbors1-logfft05: + general: + level: fitted + generation: + assignment: + method: joint + neighbors: 1 + decoder: + selector: combinations + layers: + - {method: logfft, weight: 0.5} diff --git a/src/sampletones_tools/calibration/layout.py b/src/sampletones_tools/calibration/layout.py index 05bb58af0..bd285a6e3 100644 --- a/src/sampletones_tools/calibration/layout.py +++ b/src/sampletones_tools/calibration/layout.py @@ -7,6 +7,7 @@ RENDERS_DIRECTORY: Final[str] = "renders" CSV_REPORT: Final[str] = "report.csv" MARKDOWN_REPORT: Final[str] = "report.md" +ORACLE_LABEL: Final[str] = "oracle" CHANNEL_SEPARATOR: Final[str] = "+" MIX_NAME: Final[str] = "mix" diff --git a/src/sampletones_tools/calibration/oracle/__init__.py b/src/sampletones_tools/calibration/oracle/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/src/sampletones_tools/calibration/oracle/judging.py b/src/sampletones_tools/calibration/oracle/judging.py new file mode 100644 index 000000000..edd679748 --- /dev/null +++ b/src/sampletones_tools/calibration/oracle/judging.py @@ -0,0 +1,177 @@ +import zlib +from pathlib import Path +from typing import Dict, Final, List, Mapping, Optional, Sequence, Tuple + +import numpy as np +from tqdm import tqdm + +from sampletones_core.audio.mixing import mix +from sampletones_core.configs import Config +from sampletones_core.constants.enums import ChannelName +from sampletones_core.instructions import InstructionUnion +from sampletones_tools.calibration.config.level import VariantLevel +from sampletones_tools.calibration.corpus.item import CorpusItem +from sampletones_tools.calibration.layout import ORACLE_LABEL +from sampletones_tools.calibration.referee.panel import RefereePanel +from sampletones_tools.calibration.referee.protocol import Judgment +from sampletones_tools.calibration.renders import ( + RenderRecord, + read_record, + sounding_timelines, + write_channel_renders, + write_record, + write_recording, + write_render, +) +from sampletones_tools.calibration.rows import CalibrationRow, recorded_rows + +from .reading import OracleReading +from .starts import started_channels + +ORACLE_STARTS: Final[int] = 8 +ORACLE_SEED: Final[int] = 0 +PROGRESS_LABEL: Final[str] = "Oracle" +PROGRESS_UNIT: Final[str] = "sound" + +StartedRender = Tuple[Dict[ChannelName, np.ndarray], np.ndarray] + + +def oracle_rows( + items: Sequence[CorpusItem], + panel: RefereePanel, + run_directory: Path, + config: Config, + *, + resume: bool, +) -> List[CalibrationRow]: + """The oracle's rows of every sound written as NES frames: what playing its frames exactly scores. + + A sound written as frames carries them as its truth, and its recording is what they render to + from the channels' reset states. A conversion naming every frame right still plays the noise's + sequence from wherever its own earlier frames left it, so the oracle renders the frames from + ``ORACLE_STARTS`` starting states of the noise (``started_channels``) and reads every audio + referee over them (``OracleReading``). It stands beside the variants as the best a transcription + can score. A resumed run takes the record a sound's oracle left. + + Args: + items: The run's reference sounds, in corpus order. + panel: The referees, whose audio referees judge each render. + run_directory: The directory the run writes its renders and records into. + config: The configuration the corpus renders its frames at. + resume: Whether a sound's oracle that left a record is taken from it. + + Returns: + One row per (sound, referee, reading), in corpus order. + """ + written = [(position, item) for position, item in enumerate(items) if _written_frames(item) is not None] + rows: List[CalibrationRow] = [] + for position, item in tqdm(written, desc=PROGRESS_LABEL, unit=PROGRESS_UNIT): + record = read_record(run_directory, ORACLE_LABEL, item.name) if resume else None + if record is None: + record = judge_oracle(item, position, panel, run_directory, config) + + rows.extend(recorded_rows(record)) + + return rows + + +def judge_oracle( + item: CorpusItem, + position: int, + panel: RefereePanel, + run_directory: Path, + config: Config, +) -> RenderRecord: + """Render a written sound's frames from every start, judge each against the sound, and write the record. + + Each sound draws its starts from a seed of its own name, so a sound's oracle reads alike in + every run that holds it. The render is judged against the sound as its file holds it, the true + level, so the oracle reads the frames alone. A listed sound's recording and the typical start's + render are written for the page (``OracleReading.typical``). + + Args: + item: A sound written as NES frames. + position: The sound's place in the corpus. + panel: The referees, whose audio referees judge each render. + run_directory: The directory the run writes its renders and records into. + config: The configuration the corpus renders its frames at. + + Returns: + The oracle's record of the sound. + + Raises: + ValueError: If the sound is not written as NES frames. + """ + instructions = _written_frames(item) + if instructions is None: + raise ValueError(f"Sound '{item.name}' is not written as NES frames") + + audio = np.asarray(item.audio, dtype=np.float64) + random = np.random.default_rng([ORACLE_SEED, zlib.crc32(item.name.encode())]) + renders = [_render(instructions, config, random, audio.shape[0]) for _ in range(ORACLE_STARTS)] + reading = OracleReading(starts=tuple(_judged(panel, audio, mixed) for _, mixed in renders)) + record = RenderRecord( + variant=ORACLE_LABEL, + item=item.name, + position=position, + family=item.family.value, + category=item.category, + listed=item.listed, + level=VariantLevel.TRUE, + timelines=sounding_timelines({channel: instructions[channel] for channel in renders[0][0]}), + judgments=reading.readings(), + silence={referee.name: referee.judge(audio, np.zeros_like(audio)).score for referee in panel.audio}, + ) + if item.listed: + headline = panel.audio[0].name + channels, mixed = renders[reading.typical(headline)] + _write_listened(run_directory, record, audio, channels, mixed, config.library.sample_rate) + else: + write_record(run_directory, record) + + return record + + +def _written_frames(item: CorpusItem) -> Optional[Mapping[ChannelName, Sequence[InstructionUnion]]]: + """The frames a sound written as NES frames plays, which its truth holds; ``None`` for a sound written otherwise.""" + if item.truth is None or not item.truth.instructions: + return None + + return item.truth.instructions + + +def _render( + instructions: Mapping[ChannelName, Sequence[InstructionUnion]], + config: Config, + random: np.random.Generator, + length: int, +) -> StartedRender: + """Each sounding channel's frames from one drawn start, and their mix, cut to the sound's ``length``. + + A sound none of whose channels sounds mixes to its length of silence. + """ + channels = {channel: audio[:length] for channel, audio in started_channels(instructions, config, random).items()} + if not channels: + return channels, np.zeros(length) + + return channels, np.asarray(mix(list(channels.values())), dtype=np.float64) + + +def _judged(panel: RefereePanel, audio: np.ndarray, mixed: np.ndarray) -> Dict[str, Judgment]: + """Every audio referee's judgment of one render against the sound, over the length they share.""" + length = min(audio.shape[0], mixed.shape[0]) + return {referee.name: referee.judge(audio[:length], mixed[:length]) for referee in panel.audio} + + +def _write_listened( + run_directory: Path, + record: RenderRecord, + audio: np.ndarray, + channels: Mapping[ChannelName, np.ndarray], + mixed: np.ndarray, + sample_rate: int, +) -> None: + """Write what the page plays of the oracle: the sound at the true level, the start's channel parts, its render.""" + write_recording(run_directory, record.level, record.item, audio, sample_rate) + write_channel_renders(run_directory, record.variant, record.item, channels, sample_rate) + write_render(run_directory, record, mixed, sample_rate) diff --git a/src/sampletones_tools/calibration/oracle/reading.py b/src/sampletones_tools/calibration/oracle/reading.py new file mode 100644 index 000000000..bc1ebcfc5 --- /dev/null +++ b/src/sampletones_tools/calibration/oracle/reading.py @@ -0,0 +1,48 @@ +from dataclasses import dataclass +from statistics import fmean +from typing import Dict, Final, Mapping, Tuple + +from sampletones_tools.calibration.referee.protocol import SCORE_READING, Judgment + +LOWEST_READING: Final[str] = "lowest" +HIGHEST_READING: Final[str] = "highest" + + +@dataclass(frozen=True) +class OracleReading: + """The audio referees' judgments of one written sound's frames, rendered from several starting states. + + No transcription settles where the noise's sequence stands, so a sound's frames played exactly + score as its state falls. The oracle reads each referee as the mean over the starts, + which is what a conversion naming every frame right scores in expectation, and keeps the + score's lowest and highest beside it, the range such a conversion lands in. + + Attributes: + starts: Every referee's judgment of each start's render, by referee name, one mapping per start. + """ + + starts: Tuple[Mapping[str, Judgment], ...] + + def readings(self) -> Dict[str, Dict[str, float]]: + """Each referee's readings: every reading's mean over the starts, then its score's lowest and highest. + + The referees and the readings keep the order the first start's judgments hold them in. + """ + readings: Dict[str, Dict[str, float]] = {} + for referee in self.starts[0]: + judged = [start[referee].readings() for start in self.starts] + means = {name: fmean(reading[name] for reading in judged) for name in judged[0]} + scores = [reading[SCORE_READING] for reading in judged] + readings[referee] = {**means, LOWEST_READING: min(scores), HIGHEST_READING: max(scores)} + + return readings + + def typical(self, referee: str) -> int: + """The start whose score under ``referee`` lies nearest its mean, the earliest of equally near ones. + + It is the start a listener hears for the oracle, the render that scores as the oracle reads. + """ + scores = [start[referee].score for start in self.starts] + mean = fmean(scores) + distances = [abs(score - mean) for score in scores] + return distances.index(min(distances)) diff --git a/src/sampletones_tools/calibration/oracle/starts.py b/src/sampletones_tools/calibration/oracle/starts.py new file mode 100644 index 000000000..9898ee370 --- /dev/null +++ b/src/sampletones_tools/calibration/oracle/starts.py @@ -0,0 +1,58 @@ +from typing import Dict, Mapping, Sequence + +import numpy as np + +from sampletones_core.configs import Config +from sampletones_core.constants.enums import ChannelName +from sampletones_core.generators import CHANNEL_CLASSES, NoiseGenerator, render_on +from sampletones_core.instructions import InstructionUnion, NoiseInstruction + + +def started_channels( + instructions: Mapping[ChannelName, Sequence[InstructionUnion]], + config: Config, + random: np.random.Generator, +) -> Dict[ChannelName, np.ndarray]: + """Every sounding channel's frames rendered as a conversion naming each frame right plays them. + + A transcription names each frame's note, volume and timbre, and each channel's oscillator runs on + through the frames. A pulse and the triangle start from their reset phase, as the recording's + channels do, so a conversion naming their frames right plays the waveform the recording plays, + the phase between two channels included. The noise's shift register steps through a sequence + that every earlier frame's period and mode move along, so a conversion missing any of them plays + another stretch of it from then on. The noise therefore starts from a register value and a clock + position drawn from ``random``, uniform over the states its first sounding frame may take. + + Args: + instructions: What each channel plays, one instruction per frame. + config: The configuration the frames are rendered at. + random: Where the noise's starting state is drawn from. + + Returns: + The waveform of each channel sounding a frame, in channel order. + """ + rendered: Dict[ChannelName, np.ndarray] = {} + for channel_name in ChannelName.items(): + stream = instructions.get(channel_name, ()) + first = next((instruction for instruction in stream if instruction.on), None) + if first is None: + continue + + generator = CHANNEL_CLASSES[channel_name](config, channel_name.value) + if isinstance(generator, NoiseGenerator) and isinstance(first, NoiseInstruction): + _start_elsewhere(generator, first, random) + + rendered[channel_name] = render_on(generator, stream) + + return rendered + + +def _start_elsewhere(generator: NoiseGenerator, first: NoiseInstruction, random: np.random.Generator) -> None: + """Stand the noise's register at a value drawn from ``random`` on the cycle its first frame ``first`` runs through. + + A value off the cycle of the frame's mode opens the sequence at its start, so the value is drawn + from that cycle, and the clock from between two of its steps. + """ + cycle = generator.timer.lfsr_tables[first.short].lfsrs + generator.timer.lfsr = int(cycle[random.integers(len(cycle))]) + generator.timer.clock = float(random.random()) diff --git a/src/sampletones_tools/calibration/session.py b/src/sampletones_tools/calibration/session.py index dedaf2015..accdc3b74 100644 --- a/src/sampletones_tools/calibration/session.py +++ b/src/sampletones_tools/calibration/session.py @@ -24,6 +24,7 @@ write_fingerprint, ) from sampletones_tools.calibration.layout import CORPUS_DIRECTORY, CSV_REPORT, MARKDOWN_REPORT +from sampletones_tools.calibration.oracle.judging import oracle_rows from sampletones_tools.calibration.paths import SOURCE_DIRECTORIES from sampletones_tools.calibration.referee.panel import RefereePanel, build_panel from sampletones_tools.calibration.renders import clear_renders, holds_renders @@ -147,8 +148,9 @@ def calibrate(request: CalibrationRequest) -> CalibrationOutcome: recordings an earlier run left and writes the fingerprint of what it measures, and a resumed run confirms the directory's fingerprint matches before it takes up the records already written. The referees are built before the claim, since the fingerprint holds them. The corpus is written - next, since every conversion reads its sound from a file. The reports and the page come last, - from every row and record. + next, since every conversion reads its sound from a file. Every sound written as NES frames is + then read by the oracle, what playing its frames exactly scores (``oracle_rows``). The reports + and the page come last, from every row and record. Returns: CalibrationOutcome: The report and the listening page the run wrote. @@ -176,6 +178,7 @@ def calibrate(request: CalibrationRequest) -> CalibrationOutcome: workers=request.workers, resume=request.resume, ) + rows.extend(oracle_rows(items, panel, request.output, request.base, resume=request.resume)) report = _write_reports(rows, request.output) page = build_board( diff --git a/tests/integration/sampletones_application/utils/midi/test_alsa_sequencer.py b/tests/integration/sampletones_application/utils/midi/test_alsa_sequencer.py index bc88d66e2..4697ff4b3 100644 --- a/tests/integration/sampletones_application/utils/midi/test_alsa_sequencer.py +++ b/tests/integration/sampletones_application/utils/midi/test_alsa_sequencer.py @@ -18,6 +18,9 @@ STALE_NOTE: Final[int] = 59 PLAYED_NOTE: Final[int] = 60 VELOCITY: Final[int] = 100 +SEQUENCER_GROUP: Final[str] = "alsa-sequencer" + +pytestmark = pytest.mark.xdist_group(SEQUENCER_GROUP) class Keyboard: diff --git a/tests/unit/sampletones_core/configs/test_config.py b/tests/unit/sampletones_core/configs/test_config.py index dc0de4cf9..52d8f1d9b 100644 --- a/tests/unit/sampletones_core/configs/test_config.py +++ b/tests/unit/sampletones_core/configs/test_config.py @@ -1,10 +1,11 @@ from pathlib import Path -from typing import Final +from typing import Dict, Final, List import pytest from pydantic import ValidationError from sampletones_core.configs import Config +from sampletones_core.constants.enums import SpectrumMethod from sampletones_shared.paths.user import LIBRARY_DIRECTORY, RECONSTRUCTIONS_DIRECTORY WORKERS: Final[int] = 3 @@ -56,3 +57,25 @@ def test_the_workers_are_set_and_nothing_else_moves(self) -> None: def test_fewer_than_one_worker_is_refused(self, count: int) -> None: with pytest.raises(ValidationError): Config().with_workers(count) + + +class TestTheSpectrumLayers: + """Each spectrum method reads a frame once: the library's own, then each the generation adds.""" + + def test_a_layer_adds_a_method_the_library_reads_beside_its_own(self) -> None: + config = Config.model_validate({"generation": {"layers": [{"method": "logfft", "weight": 0.5}]}}) + + assert [layer.method for layer in config.generation.layers] == [SpectrumMethod.LOG_SPACED_FFT] + + @pytest.mark.parametrize( + "layers", + [[{"method": "cqt", "weight": 1.0}], [{"method": "fft", "weight": 1.0}, {"method": "fft", "weight": 2.0}]], + ids=["the_library_s_own", "one_method_twice"], + ) + def test_a_method_read_twice_is_refused(self, layers: List[Dict[str, object]]) -> None: + with pytest.raises(ValidationError, match="reads the frames once"): + Config.model_validate({"generation": {"layers": layers}}) + + def test_a_layer_of_no_weight_is_refused(self) -> None: + with pytest.raises(ValidationError): + Config.model_validate({"generation": {"layers": [{"method": "logfft", "weight": 0.0}]}}) diff --git a/tests/unit/sampletones_core/configs/test_defaults.py b/tests/unit/sampletones_core/configs/test_defaults.py index c1004a564..0d190dac8 100644 --- a/tests/unit/sampletones_core/configs/test_defaults.py +++ b/tests/unit/sampletones_core/configs/test_defaults.py @@ -1,7 +1,6 @@ from typing import Any, Dict, Mapping, Tuple import pytest -from pydantic import BaseModel from sampletones_core.configs.defaults import GENERATION_DEFAULTS_PATH, generation_default from sampletones_core.configs.generation import GenerationConfig @@ -14,16 +13,13 @@ def _shipped() -> Mapping[str, Any]: return values -def _settings(model: BaseModel, *path: str) -> Dict[Tuple[str, ...], Any]: - """Every value the model holds, keyed by the path of names reaching it.""" - held: Dict[Tuple[str, ...], Any] = {} - for name, value in model: - if isinstance(value, BaseModel): - held.update(_settings(value, *path, name)) - else: - held[(*path, name)] = value +def _settings() -> Dict[Tuple[str, ...], Any]: + """Every value the default settings hold, written as the file writes it, keyed by the path of names reaching it. - return held + The file is YAML, which writes a tuple as a list and an enumeration by its value, so the + settings are read in the form they serialize to. + """ + return _stated(GenerationConfig().model_dump(mode="json")) def _stated(values: Mapping[str, Any], *path: str) -> Dict[Tuple[str, ...], Any]: @@ -42,11 +38,11 @@ class TestTheFileStatesTheMatchingDefaults: """The packaged `generation.yaml` is where a matching default is written, and the only place.""" def test_every_setting_starts_at_the_value_the_file_states(self) -> None: - for path, value in _settings(GenerationConfig()).items(): + for path, value in _settings().items(): assert value == generation_default(*path) def test_every_value_the_file_states_names_a_setting(self) -> None: - assert set(_stated(_shipped())) == set(_settings(GenerationConfig())) + assert set(_stated(_shipped())) == set(_settings()) class TestReadingOneDefault: diff --git a/tests/unit/sampletones_core/configs/test_generation.py b/tests/unit/sampletones_core/configs/test_generation.py index 16b68fe76..5bcc13b27 100644 --- a/tests/unit/sampletones_core/configs/test_generation.py +++ b/tests/unit/sampletones_core/configs/test_generation.py @@ -111,3 +111,17 @@ def test_a_negative_count_of_neighbor_passes_is_refused(self) -> None: def test_a_negative_channel_price_is_refused(self) -> None: with pytest.raises(ValidationError): WeightsConfig(channel_price=-0.01) + + +class TestADocumentWrittenBeforeTheLayers: + """A reconstruction written before the spectrum layers existed reads the shipped layers as it loads.""" + + def test_its_generation_holds_the_shipped_layers_and_hashes(self) -> None: + shipped = GenerationConfig() + data = GenerationConfig.unpack(shipped.serialize()) + data.pop("layers") + + older = GenerationConfig.deserialize_inner(data) + + assert older == shipped + assert hash(older) == hash(shipped) diff --git a/tests/unit/sampletones_core/fft/test_layers.py b/tests/unit/sampletones_core/fft/test_layers.py new file mode 100644 index 000000000..fdf105b1b --- /dev/null +++ b/tests/unit/sampletones_core/fft/test_layers.py @@ -0,0 +1,85 @@ +from typing import Final, List + +import numpy as np +import pytest + +from sampletones_core.configs import Config +from sampletones_core.constants.enums import SpectrumMethod +from sampletones_core.fft import Window +from sampletones_core.fft.features import get_feature_extractor +from sampletones_core.fft.fragment.stacked import StackedFeature +from sampletones_core.fft.layers import LIBRARY_WEIGHT, analysis_layers, read_frames +from sampletones_core.structures.histogram import Histogram +from tests.suite.base import BaseTestSuite + +ADDED_WEIGHT: Final[float] = 0.5 +FRAMES: Final[int] = 12 +SEED: Final[int] = 0 + + +def _layered() -> Config: + return Config.model_validate( + {"generation": {"layers": [{"method": SpectrumMethod.LOG_SPACED_FFT.value, "weight": ADDED_WEIGHT}]}} + ) + + +@pytest.fixture(name="audio", scope="module") +def audio_fixture() -> np.ndarray: + frame_length = Config().library.frame_length + return (0.1 * np.random.default_rng(SEED).standard_normal(FRAMES * frame_length)).astype(np.float32) + + +class TestTheAnalysisLayers(BaseTestSuite): + """The library's own spectrum method first, at weight one, then each method the configuration adds.""" + + def test_a_configuration_adding_no_layer_reads_its_library_s_method_alone(self) -> None: + (layer,) = analysis_layers(Config()) + + assert (layer.config.library, layer.weight) == (Config().library, LIBRARY_WEIGHT) + + def test_each_added_method_follows_the_library_s_own_at_its_weight(self) -> None: + config = _layered() + + layers = analysis_layers(config) + + assert [(layer.config.library.spectrum_method, layer.weight) for layer in layers] == [ + (config.library.spectrum_method, LIBRARY_WEIGHT), + (SpectrumMethod.LOG_SPACED_FFT, ADDED_WEIGHT), + ] + + def test_a_layer_reads_one_method_and_keeps_every_other_library_setting(self) -> None: + config = _layered() + + for layer in analysis_layers(config): + assert not layer.config.generation.layers + assert layer.config.library.model_copy(update={"spectrum_method": config.library.spectrum_method}) == ( + config.library + ) + + +class TestReadingFrames(BaseTestSuite): + """A frame holds one method's histogram, or every layer's bins stacked in order.""" + + def test_a_frame_read_by_one_method_holds_its_histogram(self, audio: np.ndarray) -> None: + config = Config() + window = Window.from_config(config) + + frames = read_frames(audio, config, window) + + alone = get_feature_extractor(config, window).extract(audio) + assert all(isinstance(frame.feature, Histogram) for frame in frames) + assert all(np.array_equal(frame.feature.values, other.feature.values) for frame, other in zip(frames, alone)) + + def test_a_frame_read_by_several_methods_stacks_each_method_s_reading(self, audio: np.ndarray) -> None: + config = _layered() + + frames = read_frames(audio, config, Window.from_config(config)) + + readings: List[List[np.ndarray]] = [ + [np.asarray(frame.feature.values) for frame in layer.extractor.extract(audio)] + for layer in analysis_layers(config) + ] + assert len(frames) == FRAMES + for index, frame in enumerate(frames): + assert isinstance(frame.feature, StackedFeature) + assert np.array_equal(frame.feature.values, np.concatenate([reading[index] for reading in readings])) diff --git a/tests/unit/sampletones_core/generators/test_render.py b/tests/unit/sampletones_core/generators/test_render.py index f4c33a273..e5b70ea91 100644 --- a/tests/unit/sampletones_core/generators/test_render.py +++ b/tests/unit/sampletones_core/generators/test_render.py @@ -5,7 +5,8 @@ from sampletones_core.configs import Config from sampletones_core.constants.enums import ChannelName -from sampletones_core.generators.render import render_channels, render_instructions +from sampletones_core.generators import PulseGenerator +from sampletones_core.generators.render import render_channels, render_instructions, render_on from sampletones_core.instructions import ( InstructionUnion, NoiseInstruction, @@ -60,6 +61,29 @@ def test_a_channel_describing_no_frame_raises(self, config: Config) -> None: render_instructions([], ChannelName.PULSE1, config) +class TestRenderOn: + """One channel's audio rendered on a given generator, from where its oscillator stands.""" + + def test_a_fresh_generator_renders_as_the_channel_does( + self, pulse_stream: List[InstructionUnion], config: Config + ) -> None: + generator = PulseGenerator(config, ChannelName.PULSE1.value) + + assert np.array_equal( + render_on(generator, pulse_stream), render_instructions(pulse_stream, ChannelName.PULSE1, config) + ) + + def test_an_oscillator_standing_elsewhere_starts_the_frames_there( + self, pulse_stream: List[InstructionUnion], config: Config + ) -> None: + generator = PulseGenerator(config, ChannelName.PULSE1.value) + generator.timer.phase = 0.5 + + rendered = render_on(generator, pulse_stream) + + assert not np.array_equal(rendered, render_instructions(pulse_stream, ChannelName.PULSE1, config)) + + class TestRenderGenerators: """The audio of every channel that describes a frame, in channel order.""" diff --git a/tests/unit/sampletones_core/headless/test_library.py b/tests/unit/sampletones_core/headless/test_library.py index 0cef62526..20917ae39 100644 --- a/tests/unit/sampletones_core/headless/test_library.py +++ b/tests/unit/sampletones_core/headless/test_library.py @@ -5,7 +5,10 @@ import pytest from sampletones_core.configs import Config +from sampletones_core.configs.generation import SpectrumLayer +from sampletones_core.constants.enums import SpectrumMethod from sampletones_core.fft import Window +from sampletones_core.fft.layers import analysis_layers from sampletones_core.headless import library as headless_library from sampletones_core.headless.library import ensure_library from sampletones_core.library import InstructionLibrary, InstructionLibraryData @@ -69,3 +72,28 @@ def test_whether_it_is_generated( ensure_library(config) assert generated == ([config] if test_case.expected else []) + + +class TestEveryLayersLibrary(BaseTestSuite): + """A conversion reading several spectrum methods prepares each method's library.""" + + def test_each_missing_library_of_a_layered_conversion_is_generated( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + generated: List[Config] = [] + monkeypatch.setattr(headless_library, "generate_library", generated.append) + rooted = _config_in(tmp_path) + config = rooted.model_copy( + update={ + "generation": rooted.generation.model_copy( + update={"layers": (SpectrumLayer(method=SpectrumMethod.LOG_SPACED_FFT, weight=1.0),)} + ) + } + ) + _write_current(analysis_layers(config)[0].config) + + ensure_library(config) + + assert [generated_config.library.spectrum_method for generated_config in generated] == [ + SpectrumMethod.LOG_SPACED_FFT + ] diff --git a/tests/unit/sampletones_core/reconstructions/criterion/test_weights.py b/tests/unit/sampletones_core/reconstructions/criterion/test_weights.py new file mode 100644 index 000000000..9004139cf --- /dev/null +++ b/tests/unit/sampletones_core/reconstructions/criterion/test_weights.py @@ -0,0 +1,48 @@ +from typing import Final + +import numpy as np +import pytest + +from sampletones_core.configs import Config +from sampletones_core.constants.enums import SpectrumMethod +from sampletones_core.fft import Window +from sampletones_core.fft.layers import analysis_layers +from sampletones_core.reconstructions.criterion.weights import calculate_spectral_weights +from sampletones_shared.array import to_numpy +from tests.suite.base import BaseTestSuite + +ADDED_WEIGHT: Final[float] = 0.5 +SIGNAL_LENGTH: Final[int] = 735 * 120 + + +def _weights(config: Config) -> np.ndarray: + return np.asarray(to_numpy(calculate_spectral_weights(config, Window.from_config(config), SIGNAL_LENGTH))) + + +@pytest.fixture(name="layered", scope="module") +def layered_fixture() -> Config: + return Config.model_validate( + {"generation": {"layers": [{"method": SpectrumMethod.LOG_SPACED_FFT.value, "weight": ADDED_WEIGHT}]}} + ) + + +class TestTheWeightsOfStackedMethods(BaseTestSuite): + """Each method's bins hold its layer's share of the weight, spread over them as the method weighs them alone.""" + + def test_the_weights_average_one_over_every_bin(self, layered: Config) -> None: + assert _weights(layered).mean() == pytest.approx(1.0) + + def test_each_method_holds_its_layer_s_share_of_the_weight(self, layered: Config) -> None: + weights = _weights(layered) + own = _weights(Config()).shape[0] + + assert weights[:own].sum() / weights.sum() == pytest.approx(1.0 / (1.0 + ADDED_WEIGHT)) + assert weights[own:].sum() / weights.sum() == pytest.approx(ADDED_WEIGHT / (1.0 + ADDED_WEIGHT)) + + def test_each_method_weighs_its_bins_as_it_does_alone(self, layered: Config) -> None: + weights = _weights(layered) + alone = [_weights(layer.config) for layer in analysis_layers(layered)] + own = alone[0].shape[0] + + for part, single in ((weights[:own], alone[0]), (weights[own:], alone[1])): + assert part / part.sum() == pytest.approx(single / single.sum()) diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/conftest.py b/tests/unit/sampletones_core/reconstructions/reconstructor/conftest.py index f2661d397..6de7f6416 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/conftest.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/conftest.py @@ -78,6 +78,7 @@ def worker( window=window, channels=channels, library_data=library_data, + layer_data=(), signal_length=WORKER_SIGNAL_LENGTH, ) @@ -216,5 +217,6 @@ def joint_matcher( window=window, channels=all_channels, library_data=joint_library, + layer_data=(), signal_length=JOINT_SIGNAL_LENGTH, ).matcher diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/conftest.py b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/conftest.py index 7720afd58..d0c9ca6b2 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/conftest.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/conftest.py @@ -211,5 +211,6 @@ def library_matcher( window=window, channels=channels, library_data=InstructionLibraryData.create(config, data), + layer_data=(), signal_length=JOINT_SIGNAL_LENGTH, ).matcher diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_assigner.py b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_assigner.py index aaa920e4d..430647b3b 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_assigner.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_assigner.py @@ -21,6 +21,7 @@ from sampletones_core.reconstructions.reconstructor.decoder.base import PooledCombination from sampletones_core.reconstructions.reconstructor.decoder.transition import TransitionWeights from sampletones_core.reconstructions.reconstructor.matching import FrameMatcher +from sampletones_core.reconstructions.reconstructor.stems.assignment.joint import assigner as assigner_module from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.assigner import ( UNVOICED_DISTANCE, JointAssigner, @@ -30,8 +31,14 @@ from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.choice import ScoredCombination from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.combinations import Rows from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.continuity import ChannelContinuity -from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.hearing import SteadyHearing -from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.layout import separate_layouts +from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.fit import FitTarget +from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.hearing import ( + FrameHearing, + SequenceHearing, + SteadyHearing, +) +from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.layout import StemLayout, separate_layouts +from sampletones_core.reconstructions.reconstructor.stems.assignment.joint.proposals import HeardAtoms, proposed_rows from sampletones_core.reconstructions.reconstructor.stems.configs.config import StemsConfig from sampletones_core.reconstructions.reconstructor.stems.configs.entry import StemEntry from sampletones_core.reconstructions.reconstructor.stems.configs.hierarchy import StemsHierarchy @@ -388,7 +395,7 @@ def _beside( """Assigns ``frame`` of ``played`` (``lines`` where unnamed) among neighbors decoded to play ``lines``.""" fragments = extractor.extract(played_lines(config, lines if played is None else played, SEQUENCE_FRAMES)) bins = len(fragments[frame].feature.values) - profiles = frame_profiles(config, window, bins) + profiles = frame_profiles(config, window, (bins,)) silence = Contribution.silence(bins, config.library.frame_length) decoded = assigner.lines(decoded_lines(lines, assigner.channels, silence, SEQUENCE_FRAMES)) heard = {channel_name: surroundings(line, frame, profiles) for channel_name, line in decoded.items()} @@ -406,25 +413,43 @@ def test_the_frame_after_a_bass_stops_hears_the_bass_s_tail_as_its_neighbors( assert _notes(_heads(assignment)) == {("pulse", LEAD.pitch)} - def test_a_frame_among_its_neighbors_fits_its_notes_heard_alone( + def test_a_frame_among_its_neighbors_fits_its_notes_through_its_own_hearing( self, config: Config, window: Window, extractor: FeatureExtractor, every_channel_assigner: JointAssigner, staccato: Dict[ChannelName, List[InstructionUnion]], + monkeypatch: pytest.MonkeyPatch, ) -> None: - """The fit of every note hears each note alone among the frame's neighbors too, as a frame heard alone does.""" + """The fit of every note reads the atoms as the frame's hearing hears them, its own share of the window.""" assigner = every_channel_assigner (layout,) = assigner.layouts + fitted: List[Tuple[HeardAtoms, FrameHearing]] = [] + + def proposing( + fragment: Fragment, + target: FitTarget, + stem: StemLayout, + atoms: HeardAtoms, + catalogs: Mapping[GeneratorClassName, KindCatalog], + matcher: FrameMatcher, + hearing: FrameHearing, + ) -> Dict[GeneratorClassName, List[int]]: + fitted.append((atoms, hearing)) + return proposed_rows(fragment, target, stem, atoms, catalogs, matcher, hearing) + + monkeypatch.setattr(assigner_module, "proposed_rows", proposing) self._beside(config, window, extractor, assigner, staccato, BASS_FRAMES) - bins = int(next(iter(assigner.catalogs.values())).powers.shape[1]) - alone = SteadyHearing(layout=layout, catalogs=assigner.catalogs, driven=assigner.driven, bins=bins) - heard = assigner.dictionaries[layout.stem_id].heard(alone) - assert np.array_equal(assigner.steady_atoms[layout.stem_id].features, heard.features) - assert np.array_equal(assigner.steady_atoms[layout.stem_id].powers, heard.powers) + ((atoms, hearing),) = fitted + assert isinstance(hearing, SequenceHearing) + heard = assigner.dictionaries[layout.stem_id].heard(hearing) + assert np.array_equal(atoms.features, heard.features) + assert np.array_equal(atoms.powers, heard.powers) + alone = SteadyHearing(layout=layout, catalogs=assigner.catalogs, driven=assigner.driven, bins=len(hearing.leak)) + assert np.all(atoms.powers < assigner.dictionaries[layout.stem_id].heard(alone).powers) def test_a_frame_inside_a_held_chord_keeps_the_chord( self, @@ -454,7 +479,7 @@ def test_settling_a_frame_hands_the_frames_after_it_the_frame_s_choice( decoded_lines(silent_lead, every_channel_assigner.channels, silence, SEQUENCE_FRAMES) ) frame = BASS_FRAMES - profiles = frame_profiles(config, window, len(fragments[frame].feature.values)) + profiles = frame_profiles(config, window, (len(fragments[frame].feature.values),)) heard = {channel_name: surroundings(line, frame, profiles) for channel_name, line in lines.items()} assignment = every_channel_assigner.assign_beside( diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_catalog.py b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_catalog.py index 2bf813c33..fea0d7055 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_catalog.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_catalog.py @@ -239,6 +239,7 @@ def silenceless_matcher_fixture(config: Config, window: Window, extractor: Featu window=window, channels=channels, library_data=InstructionLibraryData.create(config, data), + layer_data=(), signal_length=JOINT_SIGNAL_LENGTH, ).matcher diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_choice.py b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_choice.py index 9321527b1..78968f9e7 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_choice.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_choice.py @@ -108,6 +108,7 @@ def duty_matcher_fixture( window=window, channels=pulse_channels, library_data=InstructionLibraryData.create(config, data), + layer_data=(), signal_length=JOINT_SIGNAL_LENGTH, ).matcher diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_columns.py b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_columns.py index 8eb7a8355..29cf6c2c6 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_columns.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_columns.py @@ -43,6 +43,7 @@ SECOND_OTHER: Final[PulseInstruction] = PulseInstruction(on=True, pitch=57, volume=8, duty_cycle=1) BASS: Final[TriangleInstruction] = TriangleInstruction(on=True, pitch=48) OTHER_BASS: Final[TriangleInstruction] = TriangleInstruction(on=True, pitch=45) +LOUDER_DRIVE: Final[float] = 2.0 HIT: Final[NoiseInstruction] = NoiseInstruction(on=True, period=4, volume=15, short=False) SILENT_NOISE: Final[NoiseInstruction] = NoiseInstruction.null_instruction() CHORD: Final[Dict[ChannelName, InstructionUnion]] = { @@ -80,10 +81,13 @@ def row(self, kind: GeneratorClassName, instruction: InstructionUnion) -> int: def _columns_of( - fragment: Fragment, all_channels: Dict[ChannelName, GeneratorUnion], joint_matcher: FrameMatcher + fragment: Fragment, + all_channels: Dict[ChannelName, GeneratorUnion], + joint_matcher: FrameMatcher, + settings: StemSettings, ) -> _Columns: """The columns of ``fragment`` around a winner playing the chord, with the proposals they draw on.""" - layout = separate_layouts(StemsConfig.single_entry(StemSettings.covering(EVERY_CHANNEL)), all_channels)[0] + layout = separate_layouts(StemsConfig.single_entry(settings), all_channels)[0] catalogs = { slot.kind: KindCatalog.build(joint_matcher.candidate_provider, all_channels[slot.channel_name]) for slot in layout.slots @@ -120,7 +124,21 @@ def columns_fixture( all_channels: Dict[ChannelName, GeneratorUnion], joint_matcher: FrameMatcher, ) -> _Columns: - return _columns_of(rendered_fragment(config, extractor, CHORD), all_channels, joint_matcher) + return _columns_of( + rendered_fragment(config, extractor, CHORD), all_channels, joint_matcher, StemSettings.covering(EVERY_CHANNEL) + ) + + +@pytest.fixture(name="driven_apart_columns", scope="module") +def driven_apart_columns_fixture( + config: Config, + extractor: FeatureExtractor, + all_channels: Dict[ChannelName, GeneratorUnion], + joint_matcher: FrameMatcher, +) -> _Columns: + """The chord's columns with the first pulse driven louder, so the pulses stand in two groups.""" + settings = StemSettings.covering(EVERY_CHANNEL).with_drive(ChannelName.PULSE1, LOUDER_DRIVE) + return _columns_of(rendered_fragment(config, extractor, CHORD), all_channels, joint_matcher, settings) @pytest.fixture(name="louder_columns", scope="module") @@ -132,7 +150,9 @@ def louder_columns_fixture( ) -> _Columns: """The columns of a frame whose lead plays at full volume, around a winner playing it quieter.""" louder = {**CHORD, ChannelName.PULSE1: FULL_LEAD} - return _columns_of(rendered_fragment(config, extractor, louder), all_channels, joint_matcher) + return _columns_of( + rendered_fragment(config, extractor, louder), all_channels, joint_matcher, StemSettings.covering(EVERY_CHANNEL) + ) def _instructions(column: Column) -> List[InstructionUnion]: @@ -172,6 +192,13 @@ def test_a_note_the_choice_plays_on_the_other_pulse_is_left_out(self, columns: _ assert HARMONY.pitch not in _pitches(first) assert LEAD.pitch not in _pitches(second) + def test_a_note_the_choice_plays_on_a_pulse_driven_apart_is_offered(self, driven_apart_columns: _Columns) -> None: + """A pulse of another group sounds the note at its own level, so the move sounds a combination of its own.""" + first, second, _, _ = driven_apart_columns.built(WIDE) + + assert HARMONY.pitch in _pitches(first) + assert LEAD.pitch in _pitches(second) + def test_the_triangle_offers_its_one_level_and_each_untaken_note(self, columns: _Columns) -> None: _, _, triangle, _ = columns.built(WIDE) diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_hearing.py b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_hearing.py index 3118f01c9..6b1076738 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_hearing.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_hearing.py @@ -156,7 +156,6 @@ def test_a_row_adds_its_library_power_at_its_channel_s_drive( assert np.array_equal( hearing.powers(place, rows), catalogs[PULSE].powers[rows] / pulses.slots[place].drive ** 2 ) - assert np.array_equal(hearing.steady_powers(place, rows), hearing.powers(place, rows)) @pytest.mark.parametrize("place", [0, 1], ids=["first", "second"]) def test_a_fit_reads_a_row_in_the_feature_values_of_its_power( @@ -296,7 +295,6 @@ def test_a_row_is_heard_through_its_own_channel_s_surroundings_at_its_drive( hearing = SequenceHearing.of(pulses, catalogs, around, provider) library = catalog.powers[rows] / pulses.slots[place].drive ** 2 - assert np.array_equal(hearing.steady_powers(place, rows), library) assert hearing.powers(place, rows) == pytest.approx(around[place].heard(keys, library)) assert hearing.unit_powers(place, rows) == pytest.approx(around[place].gains(keys) * library) assert hearing.unit_features(place, rows) == pytest.approx( @@ -388,7 +386,7 @@ class TestHearingAFrameOfALine(BaseTestSuite): @staticmethod def _profiles(method: SpectrumMethod, bins: int) -> FrameProfiles: config = Config(library=InstructionsLibraryConfig(spectrum_method=method)) - return frame_profiles(config, Window.from_config(config), bins) + return frame_profiles(config, Window.from_config(config), (bins,)) @staticmethod def _hearing( diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_layout.py b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_layout.py index 52fc02bff..1c3a72984 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_layout.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_layout.py @@ -154,6 +154,19 @@ def test_channels_driven_alike_away_from_unit_drive_form_one_group(self) -> None assert _described(layout.groups_of(PULSE)) == [(PULSE, LOUDER_DRIVE, (0, 1))] + @pytest.mark.parametrize( + "first, second, expected", + [(LOUDER_DRIVE, LOUDER_DRIVE, (0, 1)), (LOUDER_DRIVE, SOFTER_DRIVE, (1,))], + ids=["alike", "apart"], + ) + def test_a_channel_s_group_holds_the_channels_driven_alike( + self, first: float, second: float, expected: Tuple[int, ...] + ) -> None: + layout = _pulses_at(first, second) + + assert layout.group_of(1).places == expected + assert layout.group_of(2).places == (2,) + def test_a_stem_of_no_channel_holds_no_group(self) -> None: assert StemLayout(stem_id=0, slots=(), cap=0).groups == () diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_neighbors.py b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_neighbors.py index f10fd43fb..d9c757904 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_neighbors.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_neighbors.py @@ -79,7 +79,7 @@ def __init__(self, recording: _Recording, played: Lines, decoded: Lines, inertia self.neighbor_pass = NeighborPass.over( assigner, decoded_lines(decoded, assigner.channels, silence, frames), - frame_profiles(config, window, bins), + frame_profiles(config, window, (bins,)), TransitionWeights.of(config), _inertia(inertia), ) diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_proposals.py b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_proposals.py index 8eccad3b4..d815d0eb6 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_proposals.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/stems/test_joint_proposals.py @@ -138,6 +138,7 @@ def alike_matcher_fixture(config: Config, window: Window, extractor: FeatureExtr window=window, channels=channels, library_data=InstructionLibraryData.create(config, data), + layer_data=(), signal_length=JOINT_SIGNAL_LENGTH, ).matcher @@ -202,6 +203,28 @@ def _first_notes(catalog: KindCatalog, rows: List[int]) -> List[int]: return list(_first_rows(catalog, rows)) +def _held_lead( + layout: StemLayout, pulses: Dict[GeneratorClassName, KindCatalog], provider: CandidateProvider +) -> SequenceHearing: + """A frame whose second pulse holds the lead up to it, the frame's own share of every bin's window a half. + + The held note reaches every bin at half the lead's amplitude, and the first pulse holds nothing. + """ + lead_row = pulses[PULSE].rows_by_instruction[LEAD] + amplitude = np.sqrt(pulses[PULSE].powers[lead_row]) + bins = amplitude.shape[0] + held = HeldNote( + key=pulses[PULSE].key(lead_row), frames=range(0, 1), amplitude=HALF * amplitude, share=np.full(bins, HALF) + ) + surroundings = [ + TonalSurroundings( + leak=np.zeros(bins), before=HeldNote.silence(bins), after=HeldNote.silence(bins), own=np.full(bins, HALF) + ), + TonalSurroundings(leak=held.power, before=held, after=HeldNote.silence(bins), own=np.full(bins, HALF)), + ] + return SequenceHearing.of(layout, pulses, surroundings, provider) + + class TestTheNoteDictionary(BaseTestSuite): """One atom per note and timbre: the note's unit row, heard on its channel as the frame hears it. @@ -271,6 +294,43 @@ def test_a_cap_at_drive_two_reaches_the_loudest_row_at_that_drive( _features(provider, loudest / LOUDER_DRIVE**2) ) + def test_an_atom_among_the_frame_s_neighbors_adds_what_the_window_hears_of_its_unit_row( + self, every_pulse: StemLayout, catalogs: Dict[GeneratorClassName, KindCatalog], joint_matcher: FrameMatcher + ) -> None: + """Each atom is read where the frame hears its note, its features and power those of what it adds there.""" + pulses = {PULSE: catalogs[PULSE]} + hearing = _held_lead(every_pulse, pulses, joint_matcher.candidate_provider) + dictionary = NoteDictionary.of(every_pulse, pulses) + + atoms = dictionary.heard(hearing) + + for atom, row in enumerate(int(row) for row in dictionary.rows): + place = hearing.place_of(PULSE, row) + assert atoms.features[atom] == pytest.approx(hearing.unit_features(place, [row])[0]) + assert atoms.powers[atom] == pytest.approx(hearing.unit_powers(place, [row])[0].sum()) + + def test_a_held_note_s_atom_adds_its_whole_less_the_part_its_neighbor_leaves( + self, every_pulse: StemLayout, catalogs: Dict[GeneratorClassName, KindCatalog], joint_matcher: FrameMatcher + ) -> None: + """Joined to the lead held at half amplitude, the lead's own timbre restores its whole power, of which the + leak holds a quarter whatever the frame plays, so the atom adds three quarters. The lead's other timbres + join nothing and add the frame's own quarter. + """ + pulses = {PULSE: catalogs[PULSE]} + hearing = _held_lead(every_pulse, pulses, joint_matcher.candidate_provider) + dictionary = NoteDictionary.of(every_pulse, pulses) + + atoms = dictionary.heard(hearing) + + for atom, row in enumerate(int(row) for row in dictionary.rows): + if pulses[PULSE].notes[row] != LEAD.pitch: + continue + + whole = pulses[PULSE].powers[row].sum() + joined = pulses[PULSE].timbres[row] == LEAD.duty_cycle + expected = (1.0 - HALF**2) * whole if joined else HALF**2 * whole + assert atoms.powers[atom] == pytest.approx(expected) + def test_a_note_s_strength_is_its_atoms_fitted_power_over_every_timbre( self, every_channel: StemLayout, catalogs: Dict[GeneratorClassName, KindCatalog], joint_matcher: FrameMatcher ) -> None: @@ -471,19 +531,7 @@ def test_a_proposal_extending_a_note_a_pulse_holds_is_tried_joined_to_it_on_that note's leak, and a far quieter one would fit. """ pulses = {PULSE: catalogs[PULSE]} - lead_row = catalogs[PULSE].rows_by_instruction[LEAD] - amplitude = np.sqrt(catalogs[PULSE].powers[lead_row]) - bins = amplitude.shape[0] - held = HeldNote( - key=catalogs[PULSE].key(lead_row), frames=range(0, 1), amplitude=HALF * amplitude, share=np.full(bins, HALF) - ) - surroundings = [ - TonalSurroundings( - leak=np.zeros(bins), before=HeldNote.silence(bins), after=HeldNote.silence(bins), own=np.ones(bins) - ), - TonalSurroundings(leak=held.power, before=held, after=HeldNote.silence(bins), own=np.full(bins, HALF)), - ] - hearing = SequenceHearing.of(every_pulse, pulses, surroundings, joint_matcher.candidate_provider) + hearing = _held_lead(every_pulse, pulses, joint_matcher.candidate_provider) proposed = proposed_rows( lead, diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/test_candidates.py b/tests/unit/sampletones_core/reconstructions/reconstructor/test_candidates.py index 19fd062f7..9db613fad 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/test_candidates.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/test_candidates.py @@ -3,11 +3,16 @@ from typing import Dict import numpy as np +import pytest -from sampletones_core.constants.enums import ChannelName +from sampletones_core.configs import Config +from sampletones_core.configs.generation import SpectrumLayer +from sampletones_core.constants.enums import ChannelName, SpectrumMethod +from sampletones_core.fft import Window +from sampletones_core.fft.layers import analysis_layers from sampletones_core.generators import GeneratorUnion from sampletones_core.instructions import InstructionUnion -from sampletones_core.library import InstructionLibraryData +from sampletones_core.library import InstructionLibraryData, InstructionLibraryFragment from sampletones_core.reconstructions.reconstructor.worker import ReconstructorWorker from sampletones_shared.array import to_numpy @@ -38,3 +43,66 @@ def test_every_candidate_of_a_class_holds_a_row_of_power( assert powers.shape == (len(candidates.instructions), worker.candidate_provider.widths.shape[0]) for instruction, row in zip(candidates.instructions, powers): np.testing.assert_allclose(row, worker.candidate_provider.power_of(instruction)) + + +class TestALayeredProvider: + """A candidate read in every layer's library holds each method's bins, in the order a frame stacks them.""" + + @staticmethod + @pytest.fixture(name="layered", scope="class") + def layered_fixture( + config: Config, + window: Window, + channels: Dict[ChannelName, GeneratorUnion], + library_data: InstructionLibraryData, + ) -> ReconstructorWorker: + """A worker reading the frames with ``logfft`` beside the test library's own method.""" + layered = config.model_copy( + update={ + "generation": config.generation.model_copy( + update={"layers": (SpectrumLayer(method=SpectrumMethod.LOG_SPACED_FFT, weight=1.0),)} + ) + } + ) + _, added = analysis_layers(layered) + generators = {generator.class_name(): generator for generator in channels.values()} + logfft_data = InstructionLibraryData.create( + added.config, + { + instruction: InstructionLibraryFragment.create( + generators[library_data[instruction].generator_class], instruction, added.extractor + ) + for instruction in library_data.keys() + }, + ) + return ReconstructorWorker( + config=layered, + window=window, + channels=channels, + library_data=library_data, + layer_data=(logfft_data,), + signal_length=config.library.frame_length, + ) + + def test_each_library_s_bins_follow_the_one_before( + self, layered: ReconstructorWorker, library_data: InstructionLibraryData + ) -> None: + provider = layered.candidate_provider + (logfft_data,) = layered.layer_data + own, added = (len(next(iter(data.values())).feature.values) for data in (library_data, logfft_data)) + + assert provider.sizes == (own, added) + assert provider.widths.shape == (own + added,) + + def test_a_power_reads_back_as_every_library_s_feature_stacked( + self, layered: ReconstructorWorker, library_data: InstructionLibraryData, audible_instruction: InstructionUnion + ) -> None: + provider = layered.candidate_provider + (logfft_data,) = layered.layer_data + + feature = to_numpy(provider.features_of(provider.power_of(audible_instruction)[None, :]))[0] + + expected = np.concatenate( + [library_data[audible_instruction].feature.values, logfft_data[audible_instruction].feature.values] + ) + np.testing.assert_allclose(feature, expected, rtol=1e-4, atol=1e-9) diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/test_drive.py b/tests/unit/sampletones_core/reconstructions/reconstructor/test_drive.py index 0532a1f0d..be66ac9ec 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/test_drive.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/test_drive.py @@ -4,10 +4,12 @@ import pytest from sampletones_core.constants.algorithm import UNIT_DRIVE -from sampletones_core.reconstructions.reconstructor.drive import driven_powers +from sampletones_core.reconstructions.reconstructor.drive import driven_amplitudes, driven_powers, driven_variance from tests.suite.base import BaseTestSuite POWERS: Final[np.ndarray] = np.array([[1.0, 4.0, 0.0], [0.5, 2.0, 8.0]]) +WAVEFORM: Final[np.ndarray] = np.array([0.5, -0.25, 0.0, 1.0]) +VARIANCE: Final[float] = 0.36 LOUDER_DRIVE: Final[float] = 2.0 SOFTER_DRIVE: Final[float] = 0.5 @@ -23,3 +25,23 @@ def test_a_drive_reads_a_row_at_the_inverse_square_of_its_power(self, drive: flo def test_at_unit_drive_the_powers_stand_as_they_are(self) -> None: assert np.array_equal(driven_powers(POWERS, UNIT_DRIVE), POWERS) + + +class TestDrivenAmplitudes(BaseTestSuite): + """A waveform read at a drive keeps the power ``driven_powers`` reads, its variance divided alike.""" + + @pytest.mark.parametrize("drive", [LOUDER_DRIVE, SOFTER_DRIVE], ids=["louder", "softer"]) + def test_a_driven_waveform_holds_the_driven_power(self, drive: float) -> None: + driven = driven_amplitudes(WAVEFORM, drive) + + assert np.square(driven) == pytest.approx(driven_powers(np.square(WAVEFORM), drive)) + + @pytest.mark.parametrize("drive", [LOUDER_DRIVE, SOFTER_DRIVE], ids=["louder", "softer"]) + def test_a_driven_variance_is_the_variance_of_the_driven_waveform(self, drive: float) -> None: + assert driven_variance(float(np.var(WAVEFORM)), drive) == pytest.approx( + float(np.var(driven_amplitudes(WAVEFORM, drive))) + ) + + def test_at_unit_drive_the_amplitudes_and_the_variance_stand_as_they_are(self) -> None: + assert np.array_equal(driven_amplitudes(WAVEFORM, UNIT_DRIVE), WAVEFORM) + assert driven_variance(VARIANCE, UNIT_DRIVE) == VARIANCE diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/test_matching.py b/tests/unit/sampletones_core/reconstructions/reconstructor/test_matching.py index 007d9f85c..d51f1550d 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/test_matching.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/test_matching.py @@ -67,6 +67,7 @@ def _searching( window=window, channels=channels, library_data=library_data, + layer_data=(), signal_length=WORKER_SIGNAL_LENGTH, ) @@ -92,6 +93,7 @@ def _rebuilt(worker: ReconstructorWorker, generation: GenerationConfig) -> Recon window=worker.window, channels=worker.channels, library_data=worker.library_data, + layer_data=(), signal_length=WORKER_SIGNAL_LENGTH, ) @@ -247,6 +249,7 @@ def test_a_priced_column_charges_each_sounding_candidate_the_price_and_its_silen window=window, channels=channels, library_data=library_data, + layer_data=(), signal_length=WORKER_SIGNAL_LENGTH, ) for generator in _kinds(worker): @@ -317,6 +320,7 @@ def test_a_library_without_the_class_s_silence_is_refused( window=window, channels={ChannelName.PULSE1: pulse}, library_data=InstructionLibraryData.create(config, data), + layer_data=(), signal_length=WORKER_SIGNAL_LENGTH, ) @@ -479,6 +483,7 @@ def mute_worker_fixture( window=window, channels={ChannelName.PULSE1: generator}, library_data=InstructionLibraryData.create(config, data), + layer_data=(), signal_length=WORKER_SIGNAL_LENGTH, ) @@ -651,6 +656,7 @@ def ladder_worker( window=window, channels={ChannelName.PULSE1: generator}, library_data=InstructionLibraryData.create(config, data), + layer_data=(), signal_length=WORKER_SIGNAL_LENGTH, ) diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/test_worker.py b/tests/unit/sampletones_core/reconstructions/reconstructor/test_worker.py index 8e0779aef..d54f504a0 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/test_worker.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/test_worker.py @@ -25,6 +25,7 @@ def _worker_with_selector( window=window, channels=channels, library_data=library_data, + layer_data=(), signal_length=config.library.frame_length, ) diff --git a/tests/unit/sampletones_core/reconstructions/reconstructor/window/test_profiles.py b/tests/unit/sampletones_core/reconstructions/reconstructor/window/test_profiles.py index 7ffc55109..9e5552c35 100644 --- a/tests/unit/sampletones_core/reconstructions/reconstructor/window/test_profiles.py +++ b/tests/unit/sampletones_core/reconstructions/reconstructor/window/test_profiles.py @@ -44,7 +44,7 @@ def _profiles(method: SpectrumMethod) -> FrameProfiles: config = _config(method) window = Window.from_config(config) bins = calculate_n_bins(config.library.sample_rate) if method == SpectrumMethod.CQT else WINDOWED_BINS - return frame_profiles(config, window, bins) + return frame_profiles(config, window, (bins,)) def _window(positions: List[int], weights: List[float]) -> BinWindow: @@ -242,7 +242,7 @@ def _assert_read_as_the_model_hears(self, method: SpectrumMethod, frequency: flo readings = self._readings(extractor, centered, sounding, frames) - profiles = frame_profiles(config, window, steady.shape[0]) + profiles = frame_profiles(config, window, (steady.shape[0],)) for frame in range(frames): shares = self._held_shares(profiles, bin_index, sounding, frame) assert readings[frame, bin_index] == pytest.approx( @@ -328,3 +328,21 @@ def _impulse_reading(window: BinWindow, offset: int) -> float: share = float(window.weights[on_frame[0]] / window.weights.sum()) return ONE_SIDED_POWER * share**2 + + +class TestTheProfilesOfStackedMethods(BaseTestSuite): + """A frame read by several methods holds each method's bins, each read through its own method's window.""" + + def test_each_method_s_bins_keep_its_own_profiles(self) -> None: + layered = Config.model_validate( + {"generation": {"layers": [{"method": SpectrumMethod.LOG_SPACED_FFT.value, "weight": 1.0}]}} + ) + own = calculate_n_bins(layered.library.sample_rate) + + stacked = frame_profiles(layered, Window.from_config(layered), (own, WINDOWED_BINS)) + + constant_q, windowed = _profiles(SpectrumMethod.CQT), _profiles(SpectrumMethod.LOG_SPACED_FFT) + assert np.array_equal(stacked.own_amplitude[:own], constant_q.own_amplitude) + assert np.array_equal(stacked.own_amplitude[own:], windowed.own_amplitude) + assert np.array_equal(stacked.own_energy[own:], windowed.own_energy) + assert stacked.reach == max(constant_q.reach, windowed.reach) diff --git a/tests/unit/sampletones_tools/calibration/board/test_composition.py b/tests/unit/sampletones_tools/calibration/board/test_composition.py index f0fe171de..86b88b0bd 100644 --- a/tests/unit/sampletones_tools/calibration/board/test_composition.py +++ b/tests/unit/sampletones_tools/calibration/board/test_composition.py @@ -10,10 +10,18 @@ from sampletones_tools.calibration.board.reading import read_runs from sampletones_tools.calibration.config.level import VariantLevel from sampletones_tools.calibration.fingerprint import write_fingerprint -from sampletones_tools.calibration.layout import combination_name +from sampletones_tools.calibration.layout import ORACLE_LABEL, combination_name from sampletones_tools.calibration.renders import RenderRecord, recording_path, write_record from sampletones_tools.web.roles.table import channel_role -from tests.unit.sampletones_tools.calibration.runs import probe_fingerprint, write_renders, write_run +from tests.unit.sampletones_tools.calibration.runs import ( + ORACLE_HIGHEST, + ORACLE_LOWEST, + ORACLE_SCORE, + probe_fingerprint, + write_oracle, + write_renders, + write_run, +) TITLE: Final[str] = "Calibration" GLYPHS: Final[BoardGlyphs] = BoardGlyphs(header="≈", expanded="▾", collapsed="▸", play="▶") @@ -183,3 +191,59 @@ class TestNoRun: def test_a_page_without_a_run_is_refused(self) -> None: with pytest.raises(ValueError, match="at least one run"): compose_page([], InPlaceClips(), TITLE, GLYPHS) + + +class TestTheOracle: + """A run that read the oracle of its written sounds shows it first, beside the variants.""" + + @pytest.fixture(name="oracle_run") + def oracle_run_fixture(self, run: Path) -> Path: + write_oracle(run, ["tone-a", "chord-a"]) + return run + + def test_the_oracle_s_column_leads_the_table(self, oracle_run: Path) -> None: + columns = page_of([oracle_run], oracle_run).groups[0].columns + + assert [(column.name, column.oracle) for column in columns] == [ + (ORACLE_LABEL, True), + ("cqt-pe1", False), + ("fft-pe1", False), + ] + assert columns[0].words == (ORACLE_LABEL,) + + def test_a_sound_the_oracle_read_holds_its_mean_and_its_spread_first(self, oracle_run: Path) -> None: + tone = page_of([oracle_run], oracle_run).groups[0].rows[0] + + oracle = tone.cells[0] + assert oracle is not None + assert (oracle.score, oracle.spread) == (ORACLE_SCORE, (ORACLE_LOWEST, ORACLE_HIGHEST)) + assert all(cell is not None and cell.spread is None for cell in tone.cells[1:]) + + def test_a_sound_the_oracle_left_unread_keeps_its_row_with_an_empty_oracle_cell(self, oracle_run: Path) -> None: + rows = page_of([oracle_run], oracle_run).groups[0].rows + + mix = next(row for row in rows if row.item == "mix-a") + assert mix.cells[0] is None + assert all(cell is not None for cell in mix.cells[1:]) + + def test_the_oracle_plays_beside_the_recording_at_the_true_level(self, oracle_run: Path) -> None: + tone = page_of([oracle_run], oracle_run).groups[0].rows[0] + + assert [recording.level for recording in tone.recordings] == [ + VariantLevel.TRUE.value, + VariantLevel.DEFAULT.value, + ] + assert all((oracle_run / recording.clip).is_file() for recording in tone.recordings) + + def test_a_run_that_read_no_oracle_holds_no_oracle_column(self, run: Path) -> None: + columns = page_of([run], run).groups[0].columns + + assert not any(column.oracle for column in columns) + + def test_a_page_comparing_runs_holds_the_versions_alone(self, runs: List[Path], tmp_path: Path) -> None: + for directory in runs: + write_oracle(directory, ["tone-a"]) + + page = page_of(runs, tmp_path) + + assert all(not column.oracle for group in page.groups for column in group.columns) diff --git a/tests/unit/sampletones_tools/calibration/board/test_data.py b/tests/unit/sampletones_tools/calibration/board/test_data.py index ec915d0be..93b1386c0 100644 --- a/tests/unit/sampletones_tools/calibration/board/test_data.py +++ b/tests/unit/sampletones_tools/calibration/board/test_data.py @@ -19,13 +19,13 @@ def page() -> BoardPage: channel = BoardChannel(name="noise", timeline="1100", solo="a.flac", mute="b.flac") - cell = BoardCell(render="renders/cqt-pe1/tone-a.flac", score=9.5, silence=20.0, channels=(channel,)) + cell = BoardCell(render="renders/cqt-pe1/tone-a.flac", score=9.5, silence=20.0, channels=(channel,), spread=None) recording = BoardRecording(level="default", clip="recordings/tone-a.flac") row = BoardRow(item="tone-a", family="sines", category="tone", recordings=(recording,), cells=(cell,)) group = BoardGroup( name="run-a", prefix="", - columns=(BoardColumn(name="cqt-pe1", words=("cqt", "pe1")),), + columns=(BoardColumn(name="cqt-pe1", words=("cqt", "pe1"), oracle=False),), families=(BoardFamily(name="sines", channels=("noise",)),), rows=(row,), ) diff --git a/tests/unit/sampletones_tools/calibration/board/test_reading.py b/tests/unit/sampletones_tools/calibration/board/test_reading.py index ff21e5c2f..2cd1e739d 100644 --- a/tests/unit/sampletones_tools/calibration/board/test_reading.py +++ b/tests/unit/sampletones_tools/calibration/board/test_reading.py @@ -6,10 +6,12 @@ from sampletones_tools.calibration.board.reading import read_run, read_runs from sampletones_tools.calibration.config.level import VariantLevel from sampletones_tools.calibration.fingerprint import FINGERPRINT_FILE, write_fingerprint +from sampletones_tools.calibration.layout import ORACLE_LABEL from tests.unit.sampletones_tools.calibration.runs import ( REFEREE, SILENCE_SCORE, probe_fingerprint, + write_oracle, write_renders, write_run, ) @@ -36,6 +38,18 @@ def test_the_headline_referee_is_the_one_the_report_leads_with(self, run: Path) assert reading.silence(reading.records[0]) == SILENCE_SCORE assert reading.score(reading.records[0]) == 10.0 + def test_the_oracle_is_read_beside_the_variants_the_run_measured(self, run: Path) -> None: + write_oracle(run, ["tone-a"]) + + reading = read_run(run, "run-a") + + assert reading.holds_oracle + assert reading.variants == ("cqt-pe1", "fft-pe1") + assert [record.item for record in reading.records if record.variant == ORACLE_LABEL] == ["tone-a"] + + def test_a_run_holds_no_oracle_until_one_is_read(self, run: Path) -> None: + assert not read_run(run, "run-a").holds_oracle + def test_a_directory_without_renders_is_reported(self, tmp_path: Path) -> None: with pytest.raises(FileNotFoundError, match="holds no calibration renders"): read_run(tmp_path, "empty") diff --git a/tests/unit/sampletones_tools/calibration/oracle/__init__.py b/tests/unit/sampletones_tools/calibration/oracle/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/unit/sampletones_tools/calibration/oracle/test_judging.py b/tests/unit/sampletones_tools/calibration/oracle/test_judging.py new file mode 100644 index 000000000..343479603 --- /dev/null +++ b/tests/unit/sampletones_tools/calibration/oracle/test_judging.py @@ -0,0 +1,134 @@ +from dataclasses import replace +from pathlib import Path +from typing import Dict, Final, List, Tuple + +import pytest + +from sampletones_core.configs import Config +from sampletones_core.constants.enums import ChannelName +from sampletones_core.instructions import InstructionUnion, NoiseInstruction, PulseInstruction +from sampletones_tools.calibration.config.level import VariantLevel +from sampletones_tools.calibration.corpus.families import Family +from sampletones_tools.calibration.corpus.item import CorpusItem +from sampletones_tools.calibration.corpus.nes import held, written_item +from sampletones_tools.calibration.layout import ORACLE_LABEL +from sampletones_tools.calibration.oracle.judging import oracle_rows +from sampletones_tools.calibration.oracle.reading import HIGHEST_READING, LOWEST_READING +from sampletones_tools.calibration.referee.panel import RefereePanel, build_panel +from sampletones_tools.calibration.referee.protocol import SCORE_READING +from sampletones_tools.calibration.renders import read_record, recording_path, variant_directory, write_record +from sampletones_tools.calibration.rows import CalibrationRow +from tests.suite.base import BaseTestSuite + +SOUNDING: Final[int] = 20 +SILENT: Final[int] = 4 +TONE: Final[PulseInstruction] = PulseInstruction(on=True, pitch=60, volume=12, duty_cycle=2) +HISS: Final[NoiseInstruction] = NoiseInstruction(on=True, period=4, volume=10, short=False) +SENTINEL: Final[float] = 123.0 + + +@pytest.fixture(name="config", scope="module") +def config_fixture() -> Config: + return Config() + + +@pytest.fixture(name="panel", scope="module") +def panel_fixture(config: Config) -> RefereePanel: + return build_panel(config.library.sample_rate) + + +@pytest.fixture(name="written", scope="module") +def written_fixture(config: Config) -> CorpusItem: + """A tone over hiss written as NES frames, which the page lists.""" + instructions: Dict[ChannelName, List[InstructionUnion]] = { + ChannelName.PULSE1: held(ChannelName.PULSE1, TONE, sounding=SOUNDING, silent=SILENT), + ChannelName.NOISE: held(ChannelName.NOISE, HISS, sounding=SOUNDING, silent=SILENT), + } + return written_item( + "tone-over-hiss", Family.SEQUENCES, "sequences-mixed", listed=True, instructions=instructions, config=config + ) + + +@pytest.fixture(name="recorded") +def recorded_fixture(written: CorpusItem) -> CorpusItem: + """A sound the corpus knows no frames of, as a recording's truth is.""" + return replace(written, name="recorded", truth=None) + + +def _readings(rows: List[CalibrationRow]) -> Dict[Tuple[str, str], float]: + return {(row.referee, row.component): row.score for row in rows} + + +class TestOracleRows(BaseTestSuite): + """The oracle reads every sound written as NES frames, from several starts of its channels.""" + + def test_a_written_sound_is_read_by_every_audio_referee_within_its_spread( + self, tmp_path: Path, written: CorpusItem, panel: RefereePanel, config: Config + ) -> None: + readings = _readings(oracle_rows([written], panel, tmp_path, config, resume=False)) + + for referee in panel.audio: + low, mean, high = ( + readings[(referee.name, part)] for part in (LOWEST_READING, SCORE_READING, HIGHEST_READING) + ) + assert low <= mean <= high + + def test_the_noise_s_starts_spread_the_oracle_s_score( + self, tmp_path: Path, written: CorpusItem, panel: RefereePanel, config: Config + ) -> None: + readings = _readings(oracle_rows([written], panel, tmp_path, config, resume=False)) + + headline = panel.audio[0].name + assert readings[(headline, LOWEST_READING)] < readings[(headline, HIGHEST_READING)] + + def test_a_sound_written_otherwise_is_left_unread( + self, tmp_path: Path, recorded: CorpusItem, panel: RefereePanel, config: Config + ) -> None: + assert not oracle_rows([recorded], panel, tmp_path, config, resume=False) + assert read_record(tmp_path, ORACLE_LABEL, recorded.name) is None + + def test_a_sound_reads_alike_in_every_run( + self, tmp_path: Path, written: CorpusItem, panel: RefereePanel, config: Config + ) -> None: + first = oracle_rows([written], panel, tmp_path / "first", config, resume=False) + second = oracle_rows([written], panel, tmp_path / "second", config, resume=False) + + assert first == second + + def test_the_record_stands_at_the_true_level_with_the_channels_the_frames_sound( + self, tmp_path: Path, written: CorpusItem, panel: RefereePanel, config: Config + ) -> None: + oracle_rows([written], panel, tmp_path, config, resume=False) + + record = read_record(tmp_path, ORACLE_LABEL, written.name) + assert record is not None + assert record.level == VariantLevel.TRUE + assert record.timelines == { + ChannelName.PULSE1.value: "1" * SOUNDING + "0" * SILENT, + ChannelName.NOISE.value: "1" * SOUNDING + "0" * SILENT, + } + + def test_a_listed_sound_s_render_parts_and_recording_are_written_for_the_page( + self, tmp_path: Path, written: CorpusItem, panel: RefereePanel, config: Config + ) -> None: + oracle_rows([written], panel, tmp_path, config, resume=False) + + assert (variant_directory(tmp_path, ORACLE_LABEL) / f"{written.name}.flac").is_file() + assert (variant_directory(tmp_path, ORACLE_LABEL) / written.name / "pulse1.flac").is_file() + assert recording_path(tmp_path, VariantLevel.TRUE, written.name).is_file() + + def test_a_resumed_run_takes_the_record_an_oracle_left( + self, tmp_path: Path, written: CorpusItem, panel: RefereePanel, config: Config + ) -> None: + oracle_rows([written], panel, tmp_path, config, resume=False) + record = read_record(tmp_path, ORACLE_LABEL, written.name) + assert record is not None + headline = panel.audio[0].name + write_record( + tmp_path, + record.model_copy(update={"judgments": {**record.judgments, headline: {SCORE_READING: SENTINEL}}}), + ) + + readings = _readings(oracle_rows([written], panel, tmp_path, config, resume=True)) + + assert readings[(headline, SCORE_READING)] == SENTINEL diff --git a/tests/unit/sampletones_tools/calibration/oracle/test_reading.py b/tests/unit/sampletones_tools/calibration/oracle/test_reading.py new file mode 100644 index 000000000..e836edd80 --- /dev/null +++ b/tests/unit/sampletones_tools/calibration/oracle/test_reading.py @@ -0,0 +1,55 @@ +from typing import Dict, Final, Tuple + +import pytest + +from sampletones_tools.calibration.oracle.reading import HIGHEST_READING, LOWEST_READING, OracleReading +from sampletones_tools.calibration.referee.protocol import SCORE_READING, Judgment +from tests.suite.base import BaseTestSuite + +HEADLINE: Final[str] = "mr-auditory-dB" +SECOND: Final[str] = "mr-loudness-dB" +PART: Final[str] = "missing" +SCORES: Final[Tuple[float, ...]] = (1.0, 4.0, 2.0, 3.5) + + +def _start(score: float) -> Dict[str, Judgment]: + return { + HEADLINE: Judgment(score=score, components={PART: 2.0 * score}), + SECOND: Judgment(score=10.0 - score, components={}), + } + + +@pytest.fixture(name="reading") +def reading_fixture() -> OracleReading: + return OracleReading(starts=tuple(_start(score) for score in SCORES)) + + +class TestAnOracleReading(BaseTestSuite): + """Every referee read as its mean over the starts, its score's lowest and highest beside it.""" + + def test_each_reading_is_its_mean_over_the_starts(self, reading: OracleReading) -> None: + readings = reading.readings() + + mean = sum(SCORES) / len(SCORES) + assert readings[HEADLINE][SCORE_READING] == pytest.approx(mean) + assert readings[HEADLINE][PART] == pytest.approx(2.0 * mean) + assert readings[SECOND][SCORE_READING] == pytest.approx(10.0 - mean) + + def test_the_score_keeps_its_lowest_and_highest_beside_the_mean(self, reading: OracleReading) -> None: + readings = reading.readings() + + assert (readings[HEADLINE][LOWEST_READING], readings[HEADLINE][HIGHEST_READING]) == (min(SCORES), max(SCORES)) + assert (readings[SECOND][LOWEST_READING], readings[SECOND][HIGHEST_READING]) == ( + 10.0 - max(SCORES), + 10.0 - min(SCORES), + ) + + def test_the_referees_and_readings_keep_the_judgments_order(self, reading: OracleReading) -> None: + readings = reading.readings() + + assert list(readings) == [HEADLINE, SECOND] + assert list(readings[HEADLINE]) == [SCORE_READING, PART, LOWEST_READING, HIGHEST_READING] + + def test_the_typical_start_scores_nearest_the_mean(self, reading: OracleReading) -> None: + """The mean is 2.625, and 2.0 lies nearest it.""" + assert reading.typical(HEADLINE) == SCORES.index(2.0) diff --git a/tests/unit/sampletones_tools/calibration/oracle/test_starts.py b/tests/unit/sampletones_tools/calibration/oracle/test_starts.py new file mode 100644 index 000000000..417e58d90 --- /dev/null +++ b/tests/unit/sampletones_tools/calibration/oracle/test_starts.py @@ -0,0 +1,66 @@ +from typing import Dict, Final, List + +import numpy as np +import pytest + +from sampletones_core.configs import Config +from sampletones_core.constants.enums import ChannelName +from sampletones_core.generators import render_channels +from sampletones_core.instructions import InstructionUnion, NoiseInstruction, PulseInstruction, TriangleInstruction +from sampletones_tools.calibration.oracle.starts import started_channels +from tests.suite.base import BaseTestSuite + +FRAMES: Final[int] = 6 +SEED: Final[int] = 3 +OTHER_SEED: Final[int] = 4 +TONE: Final[PulseInstruction] = PulseInstruction(on=True, pitch=60, volume=12, duty_cycle=2) +BASS: Final[TriangleInstruction] = TriangleInstruction(on=True, pitch=45) +SHORT_HISS: Final[NoiseInstruction] = NoiseInstruction(on=True, period=4, volume=12, short=True) +LONG_HISS: Final[NoiseInstruction] = NoiseInstruction(on=True, period=4, volume=12, short=False) + + +def _held(instruction: InstructionUnion) -> List[InstructionUnion]: + return [instruction] * FRAMES + + +def _started(instructions: Dict[ChannelName, List[InstructionUnion]], seed: int) -> Dict[ChannelName, np.ndarray]: + return started_channels(instructions, Config(), np.random.default_rng(seed)) + + +class TestStartedChannels(BaseTestSuite): + """Each sounding channel plays its frames as a conversion naming them right does, the noise from a state drawn for it.""" + + def test_every_sounding_channel_plays_every_frame_and_a_silent_one_renders_nothing(self) -> None: + silent: List[InstructionUnion] = [PulseInstruction.null_instruction()] * FRAMES + + started = _started({ChannelName.PULSE1: _held(TONE), ChannelName.PULSE2: silent}, SEED) + + assert list(started) == [ChannelName.PULSE1] + assert started[ChannelName.PULSE1].shape == (FRAMES * Config().library.frame_length,) + + def test_one_draw_renders_alike_every_time(self) -> None: + instructions = {ChannelName.PULSE1: _held(TONE), ChannelName.NOISE: _held(LONG_HISS)} + + first, second = _started(instructions, SEED), _started(instructions, SEED) + + assert all(np.array_equal(first[channel], second[channel]) for channel in instructions) + + @pytest.mark.parametrize("instruction", [TONE, BASS], ids=["pulse", "triangle"]) + def test_a_tone_plays_from_its_reset_phase_as_the_recording_s_channel_does( + self, instruction: InstructionUnion + ) -> None: + channel = ChannelName.PULSE1 if isinstance(instruction, PulseInstruction) else ChannelName.TRIANGLE + + started = _started({channel: _held(instruction)}, SEED)[channel] + + assert np.array_equal(started, render_channels({channel: _held(instruction)}, Config())[channel]) + + @pytest.mark.parametrize("instruction", [LONG_HISS, SHORT_HISS], ids=["long", "short"]) + def test_a_noise_started_elsewhere_plays_another_stretch_of_its_sequence( + self, instruction: InstructionUnion + ) -> None: + """A short noise starts on its own mode's cycle, since a register value off it opens the sequence at its start.""" + first = _started({ChannelName.NOISE: _held(instruction)}, SEED)[ChannelName.NOISE] + second = _started({ChannelName.NOISE: _held(instruction)}, OTHER_SEED)[ChannelName.NOISE] + + assert not np.array_equal(first, second) diff --git a/tests/unit/sampletones_tools/calibration/runs.py b/tests/unit/sampletones_tools/calibration/runs.py index 1d2092aaa..1b3e71d7d 100644 --- a/tests/unit/sampletones_tools/calibration/runs.py +++ b/tests/unit/sampletones_tools/calibration/runs.py @@ -8,6 +8,8 @@ from sampletones_tools.calibration.config.level import VariantLevel from sampletones_tools.calibration.digest import sha256_digest from sampletones_tools.calibration.fingerprint import RunFingerprint, write_fingerprint +from sampletones_tools.calibration.layout import ORACLE_LABEL +from sampletones_tools.calibration.oracle.reading import HIGHEST_READING, LOWEST_READING from sampletones_tools.calibration.renders import ( RenderRecord, write_channel_renders, @@ -21,6 +23,9 @@ SECOND_REFEREE: Final[str] = "mr-loudness-dB" SOURCE: Final[str] = "probe-source" SILENCE_SCORE: Final[float] = 20.0 +ORACLE_SCORE: Final[float] = 2.0 +ORACLE_LOWEST: Final[float] = 1.5 +ORACLE_HIGHEST: Final[float] = 2.5 @dataclass(frozen=True) @@ -96,3 +101,37 @@ def write_renders(directory: Path, variants: Sequence[str], offset: float, *, le write_channel_renders(directory, variant, probe.item, approximations, SAMPLE_RATE) return directory + + +def write_oracle(directory: Path, items: Sequence[str]) -> None: + """The oracle's renders, records and recordings of the probes named ``items``, written as the oracle writes them.""" + for position, probe in enumerate(ITEMS): + if probe.item not in items: + continue + + write_recording(directory, VariantLevel.TRUE, probe.item, channel_audio(ChannelName.TRIANGLE), SAMPLE_RATE) + approximations = {channel: channel_audio(channel) for channel in probe.channels} + write_render( + directory, + RenderRecord( + variant=ORACLE_LABEL, + item=probe.item, + position=position, + family=probe.family, + category=probe.category, + level=VariantLevel.TRUE, + timelines={channel.value: "1111" for channel in probe.channels}, + judgments={ + REFEREE: {"score": ORACLE_SCORE, LOWEST_READING: ORACLE_LOWEST, HIGHEST_READING: ORACLE_HIGHEST}, + SECOND_REFEREE: { + "score": ORACLE_SCORE, + LOWEST_READING: ORACLE_LOWEST, + HIGHEST_READING: ORACLE_HIGHEST, + }, + }, + silence={REFEREE: SILENCE_SCORE, SECOND_REFEREE: SILENCE_SCORE}, + ), + sum(approximations.values()), + SAMPLE_RATE, + ) + write_channel_renders(directory, ORACLE_LABEL, probe.item, approximations, SAMPLE_RATE) diff --git a/tests/unit/scripts/test_check.py b/tests/unit/scripts/test_check.py index 4d7b0b885..1ebb7fc13 100644 --- a/tests/unit/scripts/test_check.py +++ b/tests/unit/scripts/test_check.py @@ -15,7 +15,9 @@ run_tests = load_script("run_tests.py") PYTHON: Final[str] = "/usr/bin/python3" -CHECKS = check.planned_checks(PYTHON) +CHECKS = check.planned_checks(PYTHON, ()) +FEWER_WORKERS: Final[str] = "2" +ONE_SCREEN_WORKER: Final[str] = "1" FAILING_SUITE: Final[str] = f"{RUN_TESTS_SCRIPT} {check.SUITE}" @@ -58,6 +60,25 @@ def test_every_test_pass_is_one_the_test_runner_plans(self) -> None: assert {current.name for current in CHECKS[1:]} <= set(planned) + def test_worker_counts_given_to_the_check_reach_every_test_pass(self) -> None: + options = check.worker_options(FEWER_WORKERS, ONE_SCREEN_WORKER) + + tests = check.planned_checks(PYTHON, options)[1:] + + assert options == (check.WORKERS_OPTION, FEWER_WORKERS, check.SCREEN_WORKERS_OPTION, ONE_SCREEN_WORKER) + assert all(current.command == (PYTHON, RUN_TESTS_SCRIPT, current.name, *options) for current in tests) + + def test_a_worker_count_left_out_keeps_the_test_runner_s_default(self) -> None: + assert check.worker_options(None, None) == () + assert check.worker_options(None, ONE_SCREEN_WORKER) == (check.SCREEN_WORKERS_OPTION, ONE_SCREEN_WORKER) + + def test_the_test_runner_reads_the_worker_counts_the_check_forwards(self) -> None: + options = check.worker_options(FEWER_WORKERS, ONE_SCREEN_WORKER) + + arguments = run_tests.argument_parser().parse_args([check.SUITE, *options]) + + assert (arguments.workers, arguments.screen_workers) == (FEWER_WORKERS, ONE_SCREEN_WORKER) + class TestCheckCommit: def test_every_check_passing_on_a_commit_marks_it(