Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
26 changes: 18 additions & 8 deletions docs/concepts/reconstruction.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions docs/concepts/stems.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions docs/development/bugs-and-todos.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions docs/development/tooling.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions docs/formats/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
31 changes: 29 additions & 2 deletions docs/tools/calibration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<variant>/` | a JSON file per reconstruction with its scores and the frames each channel plays, and a FLAC file of each listed one |
| `renders/<variant>/<sound>/` | 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 |
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
50 changes: 44 additions & 6 deletions scripts/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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,
)
Expand Down
11 changes: 8 additions & 3 deletions scripts/run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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],
Expand Down
15 changes: 14 additions & 1 deletion src/sampletones_core/configs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand Down
Loading
Loading