Skip to content

hertzforge.core.sine

sine

Sine sweep specifications: named tones, each with its own sweep and its own time.

A sine test's requirement is not a curve over one abscissa. It is a set of tones, each a breakpoint table with its own sweep law and its own start time, played at the same time and usually overlapping only in part (for example, four tones playing 0-15, 2-13, 3-14 and 1-8 s of one 15 s environment). That does not fit a DataArray, so it has its own class.

The sweep law is the one checked against the controller's own records:

  • segment_rate[i] governs the segment from frequency[i] to frequency[i+1] (the leading convention), which matched to 0.0009 Hz over a 14 s sweep.
  • A linear segment's rate is in Hz/s and a logarithmic segment's rate is in oct/min: one octave at rate 10 was measured at 5.87 s, against the 6 s that unit gives.
  • A descending segment takes a negative rate. A rate whose sign contradicts its breakpoints raises ValueError here, naming the segment; the controller also refuses it, as a negative sweep time.

Amplitude between breakpoints is interpolated linearly in time, which is linear in frequency on a linear segment and linear in log frequency on a logarithmic one. SineTone.target interpolates that way per segment, so the comparison curve is the curve the controller was following.

The controller ramps each tone up for the environment's ramp_time before sweeping, so the recorded sweep leaves its start frequency at start_time + ramp_time. Four tones rebuilt with exactly that lag matched the controller's own record to 0.0000 Hz.

A dwell, a tone held at one frequency for a time, is written the way a controller's file writes it: a linear segment across a hair of a hertz, since the controller refuses a segment with no span, and so does this class. SineTone.dwell builds one, sweeping DWELL_SWEEP of its frequency over the time it holds, and is_dwell reads any segment that spans no more than DWELL_SPAN of its frequency as a dwell, so a file written upstream today reads exactly as it did.

Everything is stored in SI, like every other object in core.

Classes:

Name Description
SineTone

One tone: breakpoints, a sweep law, and its own span of time.

SineSweepSpecification

What a sine test was controlled to: tones over control channels.

SineTarget

One tone's requirement over frequency, as a curve.

SineLevel

A sine sweep's measured level: amplitude against frequency.

SineLevelSet

One extraction as one object: the tones' levels, grouped the way

SineExtraction

How a sweep's levels are read out of a recording: settings kept

Functions:

Name Description
find_tone

Where a tone's sweep begins in a recording, in seconds, by

find_environment

Where the tones' shared clock starts in a recording, by joint

vold_kalman

Every tone's complex envelope at every sample of one channel,

sample_levels

The levels read at windows points along each tone, cheaply.

scatter_db

The predicted standard deviation of a reading, in dB, from the

suggest_cycles

The smoothing the data asks for, in cycles: the first step of

extract_sine

Read each tone's level out of a recording, against its own sweep.

Classes

SineTone

SineTone(name: str, start_time: float, frequency: Any, amplitude: Any, segment_type: Any, segment_rate: Any, phase: Any = None, warning_lower: Any = None, warning_upper: Any = None, abort_lower: Any = None, abort_upper: Any = None, *, from_file: bool = False)

One tone: breakpoints, a sweep law, and its own span of time.

Raises ValueError when the shapes disagree, when a segment holds one frequency (a dwell has no sweep time), when a rate's sign does not match its segment's direction, or when a breakpoint is not above 0 Hz. from_file leaves that last one out, so a file already holding such a tone still opens.

Attributes: name: What the controller called it ('Sine Tone 1'). start_time: Seconds after the environment started that this tone turns on. A tone is silent outside its own span, not held at an end frequency. frequency: Breakpoints, Hz, shape (n,). Ascending or descending per segment; each segment's rate sign must agree. amplitude: Target amplitude at each breakpoint per control channel, shape (n, m), SI. phase: Radians at each breakpoint per channel, shape (n, m). segment_type: (n-1,), LINEAR or LOG per segment. segment_rate: (n-1,), Hz/s for a linear segment, oct/min for a logarithmic one; negative for a descending segment. warning_lower, warning_upper, abort_lower, abort_upper: Band curves at the breakpoints, shape (n, m), or None where the specification carries no such limit.

Methods:

Name Description
dwell

A tone that holds one frequency for seconds.

is_dwell

Whether segment segment holds one frequency: a sweep across

dwell_segments

The segments that hold one frequency (is_dwell), in order;

segment_seconds

How long each segment takes, in seconds, from its span and

duration

The tone's sweep time in seconds: the sum of

span

(start, end), when this tone plays, in environment seconds.

trajectory

Frequency against time over the tone's own span, at steps of

argument

The cosine argument in radians over the tone's span,

frequency_at

The instantaneous frequency, Hz, at seconds t from the

time_at

When segment segment sweeps through frequency, in seconds

phase_at

The cosine argument, radians, at seconds t from the

grid

The sample times trajectory(dt) lays down, from sample

grid_at

The sample times trajectory(dt) lays down, at the given

target

The specified level at the given frequencies, shape

Methods:
dwell classmethod
dwell(name: str, frequency: float, amplitude: Any, seconds: float, *, start_time: float = 0.0, phase: Any = None, **limits: Any) -> SineTone

A tone that holds one frequency for seconds.

Written as a controller writes a dwell: two breakpoints, the second DWELL_SWEEP of the frequency above the first, joined by one linear segment whose rate crosses that span in seconds, so is_dwell reads it and every file format carries it unchanged. Raises ValueError when seconds is not more than zero.

Parameters:

Name Type Description Default
name str

The tone's name.

required
frequency float

Hz, more than zero.

required
amplitude array - like

The level held, per control channel, shape (m,), SI.

required
seconds float

How long the tone holds.

required
start_time float

Seconds after the environment started that the tone turns on.

0.0
phase array - like

Radians per channel, shape (m,).

None
**limits Any

warning_lower, warning_upper, abort_lower and abort_upper, each shape (m,), held like the amplitude.

{}

Returns:

Type Description
SineTone

The dwell, one segment long.

is_dwell
is_dwell(segment: int) -> bool

Whether segment segment holds one frequency: a sweep across no more than DWELL_SPAN of its frequency, the form a controller's file (and SineTone.dwell) gives a dwell.

dwell_segments
dwell_segments() -> list[int]

The segments that hold one frequency (is_dwell), in order; empty for a tone that only sweeps.

segment_seconds
segment_seconds() -> ndarray

How long each segment takes, in seconds, from its span and its rate.

duration
duration() -> float

The tone's sweep time in seconds: the sum of segment_seconds.

span
span() -> tuple[float, float]

(start, end), when this tone plays, in environment seconds.

trajectory
trajectory(dt: float) -> tuple[ndarray, ndarray]

Frequency against time over the tone's own span, at steps of about dt.

Returns (t, f): t in seconds from the tone's start (add start_time for environment time), f in Hz. Each segment gets a whole number of steps, at least one, so the step is dt only approximately. This rebuild matched the controller's own record to 0.0009 Hz.

argument
argument(dt: float) -> ndarray

The cosine argument in radians over the tone's span, 2piintegral(f), at the sample times trajectory returns.

It is phase_at on those times, so a slice of the sweep (phase_at on grid) gives the same numbers as the whole.

frequency_at
frequency_at(t: Any) -> ndarray

The instantaneous frequency, Hz, at seconds t from the tone's start.

The same law trajectory lays on its grid, evaluated at any time, so a slice of a long sweep costs only the slice. Before the start it is the first breakpoint's frequency and after the end the last one's.

Parameters:

Name Type Description Default
t array - like

Seconds from the tone's start.

required

Returns:

Type Description
ndarray

Hz, the shape of t.

time_at
time_at(frequency: Any, segment: int) -> ndarray

When segment segment sweeps through frequency, in seconds from the tone's start: frequency_at inverted on that segment.

A frequency outside the segment's span gives a time outside it, on the same law carried on.

Parameters:

Name Type Description Default
frequency array - like

Hz.

required
segment int

The segment's index.

required

Returns:

Type Description
ndarray

Seconds from the tone's start, the shape of frequency.

phase_at
phase_at(t: Any) -> ndarray

The cosine argument, radians, at seconds t from the tone's start.

2*pi times the integral of the frequency law, segment by segment in closed form: a linear sweep's chirp, a log sweep's exponential. It is zero at and before the start and holds its final value after the end.

Parameters:

Name Type Description Default
t array - like

Seconds from the tone's start.

required

Returns:

Type Description
ndarray

Radians, the shape of t.

grid
grid(dt: float, first: int, last: int) -> ndarray

The sample times trajectory(dt) lays down, from sample first to last (exclusive): the whole grid's numbers for a slice of it, without building the whole grid.

Parameters:

Name Type Description Default
dt float

The sample interval.

required
first int

The slice of the sweep's samples.

required
last int

The slice of the sweep's samples.

required

Returns:

Type Description
ndarray

Seconds from the tone's start.

grid_at
grid_at(dt: float, samples: Any) -> ndarray

The sample times trajectory(dt) lays down, at the given sample indices: grid for a few samples picked out of a long sweep, without building the whole sweep.

Parameters:

Name Type Description Default
dt float

The sample interval.

required
samples array-like of int

Sample indices into the sweep's grid.

required

Returns:

Type Description
ndarray

Seconds from the tone's start, the shape of samples.

target
target(frequencies: Any, curve: str = 'amplitude', seconds: Any = None) -> ndarray

The specified level at the given frequencies, shape (len(frequencies), m).

curve is 'amplitude' or one of the limit names (LIMITS); a limit the tone does not carry raises ValueError. Values are interpolated linearly in time between breakpoints, which is linear in frequency on a linear segment and linear in log frequency on a logarithmic one, because that is the target the controller follows. Frequencies the tone never sweeps come back NaN: nothing is specified there, and zero would read as a requirement of zero.

A sweep up and back passes a frequency twice, maybe at two levels. seconds, from the tone's start, says when each line was read, and a line takes the pass nearest that time; without it the later pass answers. A tone that passes each frequency once reads the same either way.

SineSweepSpecification

SineSweepSpecification(tones: Sequence[SineTone], response_dof: Sequence[str], ordinate_dim: str = 'acceleration', ordinate_unit: str | None = None, comment: str = '')

What a sine test was controlled to: tones over control channels.

One object per sine environment, matching the controller's file: the tones (each with its own breakpoints, sweep law, limits and start time) and the control DOFs their amplitude columns belong to. Simultaneous tones are the ordinary case, not a special one. Raises ValueError when a tone's amplitude columns do not match the control channels or when tone names repeat.

Attributes: tones: The SineTone list, in the file's order. response_dof: The control channel DOF strings, the columns of every tone's amplitude table, in order. ordinate_dim: What the amplitudes are ('acceleration' for a controller run on accelerometers). ordinate_unit: The SI unit the amplitudes are stored in, or None while undeclared, the same convention every DataArray follows. comment: One line about the set as a whole.

Methods:

Name Description
tone

The tone named name; KeyError when there is none.

span

(start, end), when any tone is playing, in environment

tone_curve

One tone's requirement as a SineTarget, a curve that can be

Methods:
tone
tone(name: str) -> SineTone

The tone named name; KeyError when there is none.

span
span() -> tuple[float, float]

(start, end), when any tone is playing, in environment seconds: the first start to the last end.

tone_curve
tone_curve(name: str, lines: int = 400) -> SineTarget

One tone's requirement as a SineTarget, a curve that can be plotted and compared.

The abscissa follows the tone's own sweep: about lines points evenly spaced in time along it, sorted ascending whichever way it swept. The tone's limits come with it as Bounded limit curves. A specification whose units are not declared (ordinate_unit None) gives a curve of undeclared units, its quantity kept as the dimension hint, since its amplitudes are as written.

SineTarget

SineTarget(*args: Any, tone: str = '', **kwargs: Any)

Bases: Bounded, Spectrum

One tone's requirement over frequency, as a curve.

What SineSweepSpecification.tone_curve gives the plot and the report: the tone's amplitude interpolated along its own sweep, with the warning and abort limits as the four limit curves every Bounded object carries. The comparison against an extracted level is then drawn with the same zones, shading and pairing a random specification gets, by the same code. It is derived when needed; the specification remains the only source.

SineLevel

SineLevel(*args: Any, tone: str = '', onset: float = 0.0, seconds: Any = None, floor: Any = None, below_floor: Any = None, drift_hz: float = 0.0, **kwargs: Any)

Bases: Spectrum

A sine sweep's measured level: amplitude against frequency.

What extract_sine reads out of a recording for one tone: the demodulated complex amplitude of that tone at each control channel, sampled along the sweep and placed over frequency. The magnitude is the tracked amplitude the controller was controlling; the angle is the phase relative to the reconstructed sweep argument, meaningful between channels rather than on its own. sine_tracking.track_sine returns its readings in this class too, as real levels.

The frequency coverage is what was run: a run stopped early, or a tone the instructions windowed, extracts fewer lines, and the comparison against the specification shows how much of the required range was run.

Attributes: tone: The specification tone this level was extracted for. onset: Seconds into the recording where the tone's sweep was found (by matched filter, or the caller's override), reported so the alignment can be checked. seconds: When each line was measured, in recording seconds, one entry per abscissa line. This is what places the level on the 3-D stage without the specification beside it. None on a level saved before the clock was kept. floor: The noise floor beside each reading, channels × lines, in the level's own units: the amplitude a tone would need to stand clear of the noise the smoothing let through. None on a level saved before it was kept. below_floor: Channels × lines, True where the tone was under its floor and the reading is reported at the floor rather than at zero. Such a line is marked on the plot and not judged in the comparison. None on an older level. drift_hz: The sweep-clock correction applied at the end of the tone's sweep, in Hz, when the recording's sweep had drifted from the specification's; 0 when none was needed.

Methods:

Name Description
target_on

tone's curve at each line, on the pass the line was read

Attributes:

Name Type Description
resolved ndarray

Channels × lines, True where the tone was above its floor;

Attributes
resolved property
resolved: ndarray

Channels × lines, True where the tone was above its floor; True on every line of a level that kept no floor.

Methods:
target_on
target_on(tone: SineTone, curve: str = 'amplitude') -> ndarray

tone's curve at each line, on the pass the line was read on (SineTone.target), shape (lines, m). A level that kept no clock has only its frequencies to go by.

SineLevelSet

SineLevelSet(levels: Sequence[SineLevel], cycles: float | None = None)

One extraction as one object: the tones' levels, grouped the way the specification groups its tones.

Each tone sweeps its own frequencies on its own clock, so the levels stay separate SineLevel objects inside, since different abscissas cannot share a DataArray. The project holds one object, which expands into one row per tone, and selecting rows plots a subset, as the specification does. Raises ValueError when tone names repeat.

Attributes: levels: The per-tone SineLevels, in the specification's order. cycles: The smoothing the levels were read with, in cycles of each tone's instantaneous frequency; None on a set saved before it was kept.

Methods:

Name Description
tone

The level for the tone named name; KeyError when there is

Attributes:

Name Type Description
tone_names list[str]

The tones' names, in order.

response_dof list[str]

The channels, from the first level; empty when there is

Attributes
tone_names property
tone_names: list[str]

The tones' names, in order.

response_dof property
response_dof: list[str]

The channels, from the first level; empty when there is none.

Methods:
tone
tone(name: str) -> SineLevel

The level for the tone named name; KeyError when there is none.

SineExtraction dataclass

SineExtraction(cycles: float | None = None, target_db: float = TARGET_SCATTER_DB, refine: bool = True, chosen: float | None = None)

How a sweep's levels are read out of a recording: settings kept with the time history, as Averaging and Filtering are. The sine view sets them, and Extract Sine Levels uses whatever is there.

cycles is the smoothing: how many cycles of the tone's own instantaneous frequency each reading averages over. Fewer cycles follow a resonance closely; more keep the random environment out of the reading. None means automatic: the extraction samples the recording at BASE_CYCLES, measures how much noise the smoothing lets through against the tone it finds, and steps up CYCLES_LADDER until the predicted scatter of the readings is under target_db (default TARGET_SCATTER_DB, one standard deviation in dB). chosen records what the automatic choice picked, so the setting read back says what was used.

refine (default True) corrects the specification's sweep clock against the recording: the envelope's residual phase is fitted, the sweep argument is moved by it, and the solve is repeated, so a controller whose sweep drifted from the specified rate over a long run does not read low once the drift leaves the filter's bandwidth.

Frozen like the other settings: whether a result is out of date is decided by comparing these fields, and a mutable setting could change without that comparison seeing it.

Methods:

Name Description
describe

One line for a status bar.

Attributes:

Name Type Description
automatic bool

Whether the smoothing is chosen from the data.

Attributes
automatic property
automatic: bool

Whether the smoothing is chosen from the data.

Methods:
describe
describe() -> str

One line for a status bar.

Functions:

find_tone

find_tone(records: ndarray, dt: float, tone: SineTone, search: tuple[float, float] | None = None) -> float

Where a tone's sweep begins in a recording, in seconds, by matched filter.

The reconstructed sweep is correlated against every record and the correlation power summed across them. The processing gain over a whole sweep is what finds a tone under a much louder random excitation (measured: a correct find under +15.6 dB of random). search, (low, high) in seconds, limits the onset when the caller knows roughly where to look. A recording shorter than the sweep is correlated on the half of the sweep that fits; one holding less than a second of it raises ValueError, as does a search window with no candidates.

find_environment

find_environment(records: ndarray, dt: float, tones: Sequence[SineTone], ticker: Ticker | None = None) -> float

Where the tones' shared clock starts in a recording, by joint matched filter.

Every tone in one environment begins at its own start_time on one clock, so there is one unknown, the clock's position in the recording, and each tone's correlation is added in at its own lag. The tones that correlate sharply then place the ones that are ambiguous alone: a near-dwell or a log sweep that locks in the wrong place on its own (measured: half a second off in a four-tone mix) is placed correctly by the linear sweeps beside it. Returns the clock origin in seconds; tone i's sweep begins at origin + start_time_i. ticker, when given, gets one tick per tone. Raises ValueError when no tone fits the recording at its own start time.

vold_kalman

vold_kalman(signal: ndarray, arguments: Sequence[ndarray], frequencies: Sequence[ndarray], starts: Sequence[int], dt: float, cycles: float = BASE_CYCLES, chunk: int | None = None) -> list[ndarray]

Every tone's complex envelope at every sample of one channel, solved jointly by the second-order Vold-Kalman filter.

The record is modeled as the sum of the tones, each a slowly varying complex amplitude on its own known sweep argument, and the amplitudes are found by least squares with a penalty on each envelope's second difference, weighted so the envelope is smoothed over cycles cycles of its tone's instantaneous frequency.

The record is solved in chunks of CHUNK samples (or chunk), each with a margin of MARGIN_WINDOWS smoothing windows of the slowest tone live at its edges, solved beyond it and discarded. The penalty's memory is a few windows, so the interior matches the whole-record solve and the memory used is the chunk's, not the record's.

signal is one evenly sampled channel. Per tone, arguments and frequencies are the cosine argument and the instantaneous frequency (Hz) over the tone's span, as SineTone.argument and SineTone.trajectory give them, and starts the sample at which its span begins in signal. dt is the sample interval in seconds. Returns, per tone, the complex envelope over its span clipped to the record: the magnitude is the peak amplitude and the angle the phase against the reconstructed sweep. Raises ValueError when no tone overlaps the recording.

sample_levels

sample_levels(history: Any, specification: SineSweepSpecification, cycles: float = BASE_CYCLES, windows: int = SAMPLE_WINDOWS, tones: Sequence[str] | None = None, onsets: dict[str, float] | None = None, ticker: Any = None) -> list[dict[str, Any]]

The levels read at windows points along each tone, cheaply.

Used for the sine view's preview and the automatic smoothing's measurement. Instead of solving the whole record, it solves one smoothing window at each of windows evenly spaced points along each tone (with the chunked solve's margin around it) and reads the amplitude and the noise floor at the center. That is a few short solves per channel whatever the record's length, so it can run on every edit of the setting.

Returns, per wanted tone, a dict: 'tone', 'frequency' (Hz at the sampled points), 'seconds' (recording seconds), 'amplitude' and 'floor' (channels × points, debiased as in the full extraction, except that the amplitude is zero where the tone is under the floor), 'scatter_db' (channels × points, the predicted standard deviation of a reading at this smoothing, scatter_db of the amplitude and the floor; infinite where the tone is under the floor), and 'cycles'.

scatter_db

scatter_db(amplitude: ndarray, floor: ndarray) -> ndarray

The predicted standard deviation of a reading, in dB, from the debiased amplitude and the noise floor beside it.

The envelope is the tone plus a complex noise of power floor²; half of that power lies along the tone, so the amplitude's standard deviation is floor/√2, and in dB of the amplitude 8.686 (20/ln 10) times their ratio. Infinite where the amplitude is zero (a tone under its floor, as sample_levels reports it), since there is no reading to scatter around.

suggest_cycles

suggest_cycles(history: Any, specification: SineSweepSpecification, target_db: float = TARGET_SCATTER_DB, tones: Sequence[str] | None = None, onsets: dict[str, float] | None = None, ticker: Any = None) -> float

The smoothing the data asks for, in cycles: the first step of CYCLES_LADDER at which the predicted scatter of the readings is under target_db (one standard deviation).

Measured once at BASE_CYCLES with sample_levels, where the noise the smoothing lets through is read beside the tone. The scatter falls as the square root of the smoothing, so the smoothing needed follows from that one measurement, with half again added, because in dB the scatter grows faster than the noise-to-tone ratio once the noise is a fair fraction of the tone. The median over the sampled points and channels sets each tone's need, so a resonance or a dropout does not set the smoothing for a whole sweep, and the tone that needs the most sets it for the recording, since one setting is used for all of it. A tone under the floor at more than half of its sampled points asks for the top of the ladder. The result is capped where a tone's smoothing window at its lowest frequency would reach a quarter of the tone's duration, since past that the reading is the sweep's mean, not a level along it, and it is never below BASE_CYCLES.

extract_sine

extract_sine(history: Any, specification: SineSweepSpecification, tones: Sequence[str] | None = None, onsets: dict[str, float] | None = None, cycles: float | None = None, points_per_window: float = 2.0, refine: bool = True, target_db: float = TARGET_SCATTER_DB, workers: int | None = None, progress: Callable[[int, int], None] | None = None) -> SineLevelSet

Read each tone's level out of a recording, against its own sweep.

Every wanted tone's sweep is rebuilt from the specification's breakpoints, and the start of the environment's clock is found in the recording by joint matched filter (find_environment; onsets overrides it per tone name, and each level carries its onset as SineLevel.onset). Every tone's complex envelope on every control channel is then solved jointly with the second-order Vold-Kalman filter (vold_kalman): the record is modeled as the sum of the tones on their known sweeps, each envelope held to a slowly varying curve over cycles cycles of its own instantaneous frequency. Because the solve is joint, crossing sweeps are separated by their frequency histories instead of each reading the other as noise. Tones far apart in frequency are solved separately (SEPARATION_BANDWIDTHS), and the record is solved one chunk at a time, so the memory needed is a chunk's whatever the record's length.

cycles None is automatic (suggest_cycles): the smoothing is increased until the predicted scatter of the readings is under target_db, measured from the recording itself. The smoothing used is stored on the result as SineLevelSet.cycles.

The magnitude is debiased. A noisy envelope's magnitude reads high, so the noise power the smoothing lets through, measured in the residual beside the tone (SIDE_CORNERS filter corners above and below it) and averaged over the filter's equivalent averaging length, is subtracted from the squared magnitude before the square root. A planted amplitude under four times its own RMS of noise reads back within a fraction of a dB. Where the tone is under that noise, the reading is reported at the floor and flagged (SineLevel.below_floor) rather than reported as zero. The controller's own tracking reading includes this bias, so under noise it reads higher than the extracted level.

With refine (default True), the sweep clock is checked against the recording: each tone's envelope phase slope is fitted chunk by chunk, and where the implied frequency offset is more than REFINE_FRACTION of the filter's bandwidth at either end of the sweep, the argument is moved by it and the solve repeated, up to three solves in all. The offset applied at the end of each tone's sweep is stored as SineLevel.drift_hz, zero when none was needed.

workers is how many processes the pieces are spread over. None uses the cores up to MAX_WORKERS, and spreads the work only when it is more than PARALLEL_FLOOR samples times channels, since each worker takes about a second to start; 1 does everything in this process. The numbers are the same either way, since each piece and channel is one task and a task runs the serial code. progress, when given, is called with (done, total) as the work proceeds.

The envelope is read every window/points_per_window samples along the sweep (default 2), each reading nearly independent of the next. Returns a SineLevelSet with one SineLevel per tone, frequencies ascending whichever way the tone swept, each line with the second it was measured. A recording that ends before a tone does gives the lines it reached, which is the coverage the comparison reports. Raises ValueError when the recording is not evenly sampled, lacks a control channel, or holds less than one smoothing window of a tone.