File costas_core.h¶
FileList > costas > costas_core.h
Go to the source code of this file
Costas carrier-tracking loop (integer-NCO de-rotation + PI loop). More...
#include "doppler/clib_common.h"#include "doppler/dp_state.h"#include "doppler/jm_perf.h"#include "doppler/lo/lo_core.h"#include "doppler/lockdet/lockdet_core.h"#include "doppler/loop_filter/loop_filter_core.h"#include "doppler/state_filter/state_filter_core.h"#include "doppler/dp_tlm/dp_tlm_core.h"#include <math.h>#include "doppler/telemetry/telemetry_core.h"
Classes¶
| Type | Name |
|---|---|
| struct | costas_tlm_t Telemetry attachment: a borrowed context + this object's probe ids. NULL ctx (the default) means detached — every probe site is then a single predicted-not-taken branch per symbol. Zeroed in state blobs and preserved across set_state (DP_DEFINE_POD_STATE_TLM). |
| struct | dp_costas_state_t Costas loop state. |
Public Functions¶
| Type | Name |
|---|---|
| JM_FORCEINLINE JM_HOT void | costas_update (dp_costas_state_t * s, float _Complex P) Per-symbol carrier update: discriminator -> loop filter -> steer NCO. |
| JM_FORCEINLINE JM_HOT float _Complex | costas_wipeoff (dp_costas_state_t * s, float _Complex x) Per-sample carrier wipe-off: de-rotate x by the NCO, advance it. |
| int | dp_costas_configure (dp_costas_state_t * state, double bn, double zeta) Recompute the loop-filter gains for a new ( bn ,zeta ) without disturbing the frequency/phase estimate. |
| void | dp_costas_configure_lock (dp_costas_state_t * state, double up_thresh, double down_thresh, uint32_t n_up, uint32_t n_down) Re-tune the carrier lock detector's thresholds and verify counts. |
| dp_costas_state_t * | dp_costas_create (double bn, double zeta, double init_norm_freq, size_t tsamps, double bn_fll) Create a Costas instance. |
| void | dp_costas_destroy (dp_costas_state_t * state) Destroy a Costas instance and release all memory. |
| double | dp_costas_get_bn (const dp_costas_state_t * state) PLL loop noise bandwidth currently in use. |
| double | dp_costas_get_bn_fll (const dp_costas_state_t * state) FLL-assist bandwidth. |
| double | dp_costas_get_last_error (const dp_costas_state_t * state) Last PLL discriminator output, the loop stress. |
| double | dp_costas_get_lock_metric (const dp_costas_state_t * state) Lock-metric EMA: |Re P|/|P| smoothed by COSTAS_LOCK_ALPHA. |
| dp_lockdet_rule_t | dp_costas_get_lock_rule (const dp_costas_state_t * state) The rule the carrier lock decision is made by: the lock metric's declare and drop levels and their verify counts, as dp_costas_configure_lock() last set them. |
| int | dp_costas_get_locked (const dp_costas_state_t * state) Current carrier lock decision (1 = locked, 0 = not), from the verify-counted detector on the lock-metric EMA (see dp_costas_configure_lock). |
| double | dp_costas_get_nco_freq (const dp_costas_state_t * state) Effective NCO frequency command (loop-filter output = integrator + proportional), cycles/sample. Mean rides a ramp with no lag, unlike the integrator-only get_norm_freq. |
| double | dp_costas_get_nco_phase_ahead (const dp_costas_state_t * state, size_t ahead) The carrier phase the NCO will apply ahead samples from now, with no loop update in between. |
| double | dp_costas_get_norm_freq (const dp_costas_state_t * state) Tracked carrier frequency: the NCO frequency register. |
| double | dp_costas_get_norm_rate (const dp_costas_state_t * state) The carrier's rate the third-order filter holds, in cycles per sample per sample ( R / fs^2 forR Hz/s at a sample ratefs ). |
| int | dp_costas_get_order (const dp_costas_state_t * state) The active loop filter's order: 2 (the PI loop) or 3 (StateFilter), as dp_costas_set_order() selected it. |
| void | dp_costas_get_state (const dp_costas_state_t * state, void * blob) Serialize the full loop state into blob . |
| void | dp_costas_init (dp_costas_state_t * s, double bn, double zeta, double init_norm_freq, size_t tsamps, double bn_fll) Initialise a Costas loop in place (no allocation). |
| void | dp_costas_reset (dp_costas_state_t * state) Re-seed the loop to its create-time frequency/phase; keep config. |
| int | dp_costas_set_bn (dp_costas_state_t * state, double val) Retune bn, keeping zeta: dp_costas_configure() 's refusal and status. As a writable property a refusal raises ValueError and the value stays put (doppler#1987). |
| int | dp_costas_set_bn_fll (dp_costas_state_t * state, double val) Set the FLL-assist bandwidth live; the FLL gain becomes 4 * val . |
| void | dp_costas_set_norm_freq (dp_costas_state_t * state, double val) Re-seed the loop at a new carrier frequency. |
| int | dp_costas_set_norm_rate (dp_costas_state_t * state, double val) Seed the third-order filter's carrier rate, as dp_costas_set_norm_freq() seeds the frequency. |
| int | dp_costas_set_order (dp_costas_state_t * state, int order, double bn) Select the active loop filter on a live loop: order 2 (the PI loop every Costas starts on) or order 3 (StateFilter, which also tracks the carrier's rate), at loop bandwidth bn . |
| int | dp_costas_set_state (dp_costas_state_t * state, const void * blob) Restore a state written by dp_costas_get_state() . |
| int | dp_costas_set_telemetry (dp_costas_state_t * state, dp_tlm_t * tlm, const char * prefix, uint32_t decim) Attach (or detach) a telemetry context and register the carrier loop's probes on it. Registers seven probes, emitted once per dumped symbol and further thinned by decim: "<prefix>.lock" (the |Re P|/|P| lock-metric EMA, 1 = phase-locked), "<prefix>.e" (the PLL discriminator output — the loop stress), "<prefix>.freq" (the NCO's frequency register, which holds the loop filter's integrator: the loop's frequency memory, cycles/sample), "<prefix>.locked" (the verify-counted lock decision, 0/1 — see dp_costas_configure_lock) and "<prefix>.nco" (the complete loop-filter output, the integrator plus the proportional term, cycles/sample — dp_costas_get_nco_freq() ; its mean rides a frequency ramp with no lag, where ".freq" lags by the loop's ramp error), "<prefix>.freq_rate" (the norm_rate property: the third-order filter's rate, cycles/sample^2 —dp_costas_get_norm_rate() ; a loop's complete output includes every integrator) and "<prefix>.order" (the order property, 2 or 3, so a capture shows when a switch happened). Both are registered and emitted at either order, ".freq_rate" reading exactly 0 at order 2, which holds no rate: the order can change on a live, attached loop (dp_costas_set_order() ), so a probe present only at order 3 would make the probe table depend on when the attach happened. Passing NULL detaches. Setup path, never hot: call before the producer thread starts stepping; the context is borrowed and must outlive the attachment (SPSC rules indp_tlm/dp_tlm_core.h ). |
| size_t | dp_costas_state_bytes (const dp_costas_state_t * state) Serialized-state byte size. |
| size_t | dp_costas_steps (dp_costas_state_t * state, const float _Complex * x, size_t x_len, float _Complex * out, size_t max_out) De-rotate a cf32 block with the carrier NCO, integrate-and-dump each symbol, and emit one decision-directed Costas prompt per symbol. |
| size_t | dp_costas_steps_max_out (dp_costas_state_t * state) Output capacity hint for dp_costas_steps() : always 0. |
| void | dp_costas_tlm_flush (const dp_costas_state_t * s) Emit the carrier loop's telemetry records for the symbol just dumped. |
Macros¶
| Type | Name |
|---|---|
| define | COSTAS_EPS 1e-12fNumerical guard added to |P| in the discriminator and lock metric so a zero prompt cannot divide by zero (not tunable). |
| define | COSTAS_LOCK_ALPHA 0.1EMA smoothing factor (per symbol) for the |Re P|/|P| lock metric, the input to the lock detector. |
| define | COSTAS_STATE_MAGIC [**DP\_FOURCC**](dp__state_8h.md#define-dp_fourcc)('C', 'S', 'T', 'S')State-blob magic for the Costas loop (FourCC "CSTS"). |
| define | COSTAS_STATE_VERSION 4u /\* v4: sf + order \*/State-blob layout version (v4 added the third-order filter and the active order; v3 the lockdet decision rule). |
Detailed Description¶
A continuous BPSK carrier-recovery loop: per sample it de-rotates the input with the integer-phase lo NCO (carrier wipe-off); every tsamps samples it dumps the coherent integrate-and-dump accumulator, runs a decision-directed Costas phase discriminator, filters the error through the active loop filter the embedded 2nd-order dp_loop_filter_state_t every loop starts on, or, after dp_costas_set_order(), the 3rd-order StateFilter, which also tracks the carrier's rate and holds a frequency ramp with no steady phase error and steers the NCO frequency + phase. It tracks a small residual carrier offset (the bulk Doppler is removed upstream by FFT acquisition); the steering NCO is lo, so the phase is bounded and exactly reproducible (no double-accumulator drift).
The block API (dp_costas_steps) is the Python face; the JM_FORCEINLINE costas_wipeoff()/costas_update() are the C composition API a despreader / tracking channel inlines into its own sample loop.
Lifecycle: dp_costas_create -> (steps / configure / reset)* -> dp_costas_destroy, or embed by value with dp_costas_init().
Set bn_fll > 0 to enable FLL assist (a wide-pull-in frequency-lock loop aiding the PLL) for large or fast-moving residuals; bn_fll = 0 is a pure Costas PLL.
dp_costas_state_t *c = dp_costas_create(0.05, 0.707, 0.01, 64, 0.0);
float _Complex sym[16];
size_t k = dp_costas_steps(c, rx, rx_len, sym, 16); // one prompt per symbol
double f = c->nco.norm_freq; // tracked residual
dp_costas_destroy(c);
Public Functions Documentation¶
function costas_update¶
Per-symbol carrier update: discriminator -> loop filter -> steer NCO.
Runs the decision-directed BPSK Costas discriminator on the prompt P, filters it, and writes the new frequency (dp_lo_set_norm_freq) plus a proportional phase nudge into the NCO. Updates the lock metric and last_error (the instantaneous loop stress). Inline for composition.
Parameters:
sCostas state. Must be non-NULL.PThe dumped integrate-and-dump prompt for this symbol.
function costas_wipeoff¶
Per-sample carrier wipe-off: de-rotate x by the NCO, advance it.
x * conj(lo_step(nco)) — strips the (tracked) carrier ahead of the matched-filter integrate-and-dump. Inline, zero call overhead.
Parameters:
sCostas state. Must be non-NULL.xOne input sample.
Returns:
The de-rotated sample to feed the integrator.
Note:
C only, with costas_update(): the bodies call lo_step() and the C99 complex library (crealf, cabsf), which C++ does not have (dp_complex.h, "From C++"). A C++ caller uses dp_costas_steps().
function dp_costas_configure¶
Recompute the loop-filter gains for a new ( bn ,zeta ) without disturbing the frequency/phase estimate.
Re-derives the PI coefficients from the loop bandwidth and damping and installs them live. The NCO frequency, phase and loop integrator are left untouched, so a converged loop keeps tracking straight through the re-tune — narrow the bandwidth once pulled in for lower phase jitter, or widen it to chase a faster-moving residual.
Parameters:
stateCostas state. Must be non-NULL.bnLoop noise bandwidth, normalised to the symbol rate.zetaDamping factor (1.0 = critical; 0.707 usual). At order 3 both filters are retuned and both keep their estimates (frequency, and the third-order filter's rate); zeta reaches only the second-order filter, which has the damping argument.
Returns:
DP_OK, or DP_ERR_INVALID for a (bn, zeta) outside dp_loop_filter_params_ok(), or at order 3 a bn outside dp_state_filter_params_ok() at t = 1 (bn up to 0.12); a refusal changes nothing, so the bandwidth the getter reports is always the one the loop runs (doppler#2112).
function dp_costas_configure_lock¶
Re-tune the carrier lock detector's thresholds and verify counts.
void dp_costas_configure_lock (
dp_costas_state_t * state,
double up_thresh,
double down_thresh,
uint32_t n_up,
uint32_t n_down
)
The always-on lock decision steps a verify-counted detector (lockdet_core.h) on the |Re P|/|P| lock-metric EMA once per dumped symbol: locked flips up after n_up consecutive symbols with the metric above up_thresh and drops after n_down consecutive symbols below down_thresh. The defaults derive from the metric's own H0 statistics — with no carrier, |Re P|/|P| = |cos(theta)| for a uniform theta, whose mean is 2/pi (~0.637) and per-symbol std ~0.31; the COSTAS_LOCK_ALPHA = 0.1 EMA reduces that to ~0.071, so the default declare threshold 0.85 sits ~3 sigma above the no-carrier mean, with the drop threshold at 0.78 for level hysteresis and 8-up/32-down verify counts for time hysteresis (declare fast, drop reluctantly — the EMA already correlates adjacent looks, so the counts guard against band-edge dwell rather than compounding i.i.d. probabilities). A live lock survives the re-tune; the in-flight verify run restarts.
Parameters:
stateCostas state. Must be non-NULL.up_threshDeclare threshold on the lock-metric EMA.down_threshDrop threshold (<= up_thresh for level hysteresis).n_upConsecutive above-threshold symbols to declare; clamped to >= 1.n_downConsecutive below-threshold symbols to drop; clamped to >= 1.
function dp_costas_create¶
Create a Costas instance.
dp_costas_state_t * dp_costas_create (
double bn,
double zeta,
double init_norm_freq,
size_t tsamps,
double bn_fll
)
Parameters:
bnLoop noise bandwidth (default 0.05), of the closed loop given a unit-slope detector (see LoopFilter). The detector's slope is 1 per radian at every signal level and falls below 1 as the SNR per symbol falls (about 0.6 at 0 dB for BPSK), so the delivered loop is narrower at low SNR.zetaDamping factor (default 0.707).init_norm_freqSeed carrier frequency, cycles/sample (default 0.0).tsampsSamples per symbol (default 64).bn_fllFLL-assist bandwidth (default 0.0 = pure PLL).
Returns:
Heap-allocated state, or NULL if (bn, zeta) fails dp_loop_filter_params_ok(), if bn_fll fails dp_loop_filter_fll_bn_ok(), or on allocation failure.
Note:
Caller must call dp_costas_destroy() when done.
function dp_costas_destroy¶
Destroy a Costas instance and release all memory.
Parameters:
stateMay be NULL.
function dp_costas_get_bn¶
PLL loop noise bandwidth currently in use.
Parameters:
stateMust be non-NULL.
Returns:
bn, normalized to the symbol rate: the create() value or the last one dp_costas_configure() / dp_costas_set_bn() accepted.
function dp_costas_get_bn_fll¶
FLL-assist bandwidth.
Parameters:
stateMust be non-NULL.
Returns:
bn_fll, normalized to the symbol rate; 0 means pure PLL.
function dp_costas_get_last_error¶
Last PLL discriminator output, the loop stress.
Parameters:
stateMust be non-NULL.
Returns:
sign(Re P) * Im P / |P|, about the phase error in radians when small, between -1 and 1; 0 before the first symbol.
function dp_costas_get_lock_metric¶
Lock-metric EMA: |Re P|/|P| smoothed by COSTAS_LOCK_ALPHA.
Parameters:
stateMust be non-NULL.
Returns:
Value from 0 to 1; near 1 when phase-locked, ~2/pi with no carrier; 0 after create/reset until the first symbol.
function dp_costas_get_lock_rule¶
The rule the carrier lock decision is made by: the lock metric's declare and drop levels and their verify counts, as dp_costas_configure_lock() last set them.
Parameters:
stateMust be non-NULL.
Returns:
The rule (dp_lockdet_rule()).
function dp_costas_get_locked¶
Current carrier lock decision (1 = locked, 0 = not), from the verify-counted detector on the lock-metric EMA (see dp_costas_configure_lock).
Parameters:
stateMust be non-NULL.
Returns:
1 when locked, 0 otherwise (0 after create/reset).
function dp_costas_get_nco_freq¶
Effective NCO frequency command (loop-filter output = integrator + proportional), cycles/sample. Mean rides a ramp with no lag, unlike the integrator-only get_norm_freq.
Parameters:
stateMust be non-NULL.
Returns:
norm_freq + kp * last_error / (2 pi tsamps), in cycles/sample; equals the seed frequency before the first symbol.
function dp_costas_get_nco_phase_ahead¶
The carrier phase the NCO will apply ahead samples from now, with no loop update in between.
The phase costas_wipeoff() de-rotates the next sample by is the NCO's accumulator; ahead samples later it is that plus ahead increments, in the NCO's own 32-bit arithmetic, so the answer is exact for every sample before the next costas_update(). A composition that carries samples not yet wiped asks this for the phase at the newest sample it holds, which is what a caller comparing against the truth at that sample needs.
Parameters:
stateMust be non-NULL.aheadSamples from the next one to be wiped (0 = that one).
Returns:
Phase in cycles, in [0, 1).
function dp_costas_get_norm_freq¶
Tracked carrier frequency: the NCO frequency register.
Holds the active loop filter's integrator (the frequency memory); it excludes the proportional term. At order 2 it lags a frequency ramp by the Type-II ramp error (see dp_costas_get_nco_freq()); at order 3, which holds the rate, it does not.
Parameters:
stateMust be non-NULL.
Returns:
Frequency in cycles/sample; the seed frequency before the first symbol is dumped.
function dp_costas_get_norm_rate¶
The carrier's rate the third-order filter holds, in cycles per sample per sample ( R / fs^2 forR Hz/s at a sample ratefs ).
Parameters:
stateMust be non-NULL.
Returns:
The rate, cycles/sample^2; 0 at order 2, which holds none.
function dp_costas_get_order¶
The active loop filter's order: 2 (the PI loop) or 3 (StateFilter), as dp_costas_set_order() selected it.
Parameters:
stateMust be non-NULL.
Returns:
2 or 3.
function dp_costas_get_state¶
Serialize the full loop state into blob .
A whole-struct snapshot (config, NCO, loop filter, I&D accumulator, lock detector) with the telemetry attachment zeroed.
Parameters:
stateMust be non-NULL.blobCaller-owned buffer of at least dp_costas_state_bytes() bytes.
function dp_costas_init¶
Initialise a Costas loop in place (no allocation).
void dp_costas_init (
dp_costas_state_t * s,
double bn,
double zeta,
double init_norm_freq,
size_t tsamps,
double bn_fll
)
The by-value counterpart to dp_costas_create(): a tracking channel that embeds a dp_costas_state_t initialises it here. Seeds the NCO at init_norm_freq and the loop integrator to the matching per-symbol frequency so de-rotation is correct from the first sample.
Parameters:
sState to initialise. Must be non-NULL.bnLoop noise bandwidth, normalised to the symbol rate.zetaDamping factor (1.0 = critical; 0.707 usual).init_norm_freqSeed carrier frequency, cycles/sample.tsampsSamples per symbol (the integrate-and-dump period).bn_fllFLL-assist bandwidth (0 = pure PLL).
Unguarded, as the by-value path: the caller checks (bn, zeta) with dp_loop_filter_params_ok() first. Outside it the loop's gains go NaN (doppler#2103).
function dp_costas_reset¶
Re-seed the loop to its create-time frequency/phase; keep config.
Drops the lock and rewinds the NCO, loop integrator and integrate-and-dump accumulators to the create-time seed frequency, while retaining the configured loop bandwidth, damping, lock-detector thresholds and loop order. At order 3 the rate is zeroed as well. Reprocess the same input after a reset and the output is bit-identical.
Parameters:
stateMust be non-NULL.>>> import numpy as np >>> from doppler.track import Costas >>> tsamps = 16 >>> rng = np.random.default_rng(3) >>> bits = rng.integers(0, 2, 1500) * 2 - 1 >>> sig = np.repeat(bits.astype(np.complex64), tsamps) >>> k = np.arange(len(sig)) >>> rx = (sig * np.exp(2j * np.pi * 0.002 * k)).astype(np.complex64) >>> c = Costas(bn=0.05, zeta=0.707, tsamps=tsamps) >>> _ = c.steps(rx) >>> round(c.norm_freq, 4) != 0.0 # loop pulled onto the residual True >>> c.reset() >>> c.norm_freq # back to the create-time seed 0.0 >>> c.lock_metric 0.0
function dp_costas_set_bn¶
Retune bn, keeping zeta: dp_costas_configure() 's refusal and status. As a writable property a refusal raises ValueError and the value stays put (doppler#1987).
Parameters:
stateMust be non-NULL.valNew loop noise bandwidth, normalized to the symbol rate.
Returns:
DP_OK, or DP_ERR_INVALID if (val, zeta) fails dp_loop_filter_params_ok(), or at order 3 val fails dp_state_filter_params_ok() at t = 1 (bn up to 0.12); nothing changes.
function dp_costas_set_bn_fll¶
Set the FLL-assist bandwidth live; the FLL gain becomes 4 * val .
A value outside dp_loop_filter_fll_bn_ok() (negative, NaN, or one whose gain overflows) is refused and nothing changes.
Parameters:
stateMust be non-NULL. Refused too whenval> 0 at order 3: a first-order frequency pull into a loop that holds a rate is a different loop from the one StateFilter's stability range was derived for, and it has not been measured (docs/design/costas.md section 3.2).valFLL bandwidth, normalized to the symbol rate (0 = off).
Returns:
DP_OK, or DP_ERR_INVALID when val is refused: outside dp_loop_filter_fll_bn_ok(), or positive at order 3.
function dp_costas_set_norm_freq¶
Re-seed the loop at a new carrier frequency.
Not a gentle nudge: it resets the loop filter, re-initializes the NCO (phase included) at val, clears the integrate-and-dump accumulator, the lock metric and the lock decision, and makes val the frequency a later dp_costas_reset() returns to. It keeps the loop order; at order 3 it zeroes the rate.
Parameters:
stateMust be non-NULL.valNew carrier frequency, cycles/sample. Taken as given, as every frequency is: a NaN gives a NaN loop, not a refusal.
function dp_costas_set_norm_rate¶
Seed the third-order filter's carrier rate, as dp_costas_set_norm_freq() seeds the frequency.
val is the rate of the carrier frequency in cycles per sample per sample: R / fs^2 for R Hz/s at a sample rate fs. It is stored as the filter's own rate, 2 pi val tsamps^2 radians per update per update.
Parameters:
stateMust be non-NULL.valCarrier rate, cycles/sample^2, taken as given, as set_norm_freq takes a frequency.
Returns:
DP_OK, or DP_ERR_INVALID with nothing changed at order 2 (that loop holds no rate).
function dp_costas_set_order¶
Select the active loop filter on a live loop: order 2 (the PI loop every Costas starts on) or order 3 (StateFilter, which also tracks the carrier's rate), at loop bandwidth bn .
What carries across (docs/design/costas.md section 3.2):
* 2 to 3: the third-order filter is initialised at bn and takes the frequency estimate lf.integ; its rate starts at 0 (dp_costas_set_norm_rate() seeds one).
* 3 to 2: the PI loop takes the third-order filter's frequency estimate; the rate is dropped.
* Either way, and to the same order: lf is retuned to (bn, the retained zeta), keeping its estimate; the NCO's phase and frequency, the lock metric and decision, the FLL's previous prompt and the integrate-and-dump are untouched, so the NCO frequency is continuous.
Costas never chooses the order; the embedder does.
Parameters:
stateMust be non-NULL.order2 or 3.bnLoop noise bandwidth per update: in dp_loop_filter_params_ok() at the retained zeta, and at order 3 also in dp_state_filter_params_ok() att = 1, which bounds it at 0.12.
Returns:
DP_OK, or DP_ERR_INVALID with nothing changed for another order, a bn outside those domains, or order 3 while bn_fll > 0.
>>> from doppler.track import Costas
>>> c = Costas(bn=0.05, zeta=0.707, init_norm_freq=0.01, tsamps=16)
>>> c.set_order(3, 0.02)
>>> c.order, round(c.norm_freq, 6), c.bn # the estimate carries across
(3, 0.01, 0.02)
>>> c.norm_rate = 1e-9 # seed the carrier's rate
>>> round(c.norm_rate * 1e9, 9)
1.0
>>> c.set_order(2, 0.05) # back to the PI loop
>>> c.order, c.norm_rate # the rate is dropped
(2, 0.0)
function dp_costas_set_state¶
Restore a state written by dp_costas_get_state() .
Restores every field, config included, but keeps the receiver's own telemetry attachment. The payload is decoded into a temporary and checked first, so on rejection state is untouched.
Parameters:
stateMust be non-NULL.blobBlob from dp_costas_get_state().
Returns:
DP_OK, or DP_ERR_INVALID on a magic, version, endian or size mismatch or a payload the object's check refuses.
function dp_costas_set_telemetry¶
Attach (or detach) a telemetry context and register the carrier loop's probes on it. Registers seven probes, emitted once per dumped symbol and further thinned by decim: "<prefix>.lock" (the |Re P|/|P| lock-metric EMA, 1 = phase-locked), "<prefix>.e" (the PLL discriminator output — the loop stress), "<prefix>.freq" (the NCO's frequency register, which holds the loop filter's integrator: the loop's frequency memory, cycles/sample), "<prefix>.locked" (the verify-counted lock decision, 0/1 — see dp_costas_configure_lock) and "<prefix>.nco" (the complete loop-filter output, the integrator plus the proportional term, cycles/sample — dp_costas_get_nco_freq() ; its mean rides a frequency ramp with no lag, where ".freq" lags by the loop's ramp error), "<prefix>.freq_rate" (the norm_rate property: the third-order filter's rate, cycles/sample^2 —dp_costas_get_norm_rate() ; a loop's complete output includes every integrator) and "<prefix>.order" (the order property, 2 or 3, so a capture shows when a switch happened). Both are registered and emitted at either order, ".freq_rate" reading exactly 0 at order 2, which holds no rate: the order can change on a live, attached loop (dp_costas_set_order() ), so a probe present only at order 3 would make the probe table depend on when the attach happened. Passing NULL detaches. Setup path, never hot: call before the producer thread starts stepping; the context is borrowed and must outlive the attachment (SPSC rules indp_tlm/dp_tlm_core.h ).
int dp_costas_set_telemetry (
dp_costas_state_t * state,
dp_tlm_t * tlm,
const char * prefix,
uint32_t decim
)
Parameters:
stateMust be non-NULL.tlmTelemetry context to attach, or NULL to detach.prefixProbe-name prefix, e.g. "car" or "ch0.car"; at most 21 characters, since "<prefix>.freq_rate" must fit the 31-character probe name.decimEmit every decim-th symbol; >= 1.
Returns:
DP_OK, or DP_ERR_INVALID when the prefix is longer than that or the probe table cannot take all seven probes (the attach fails whole; the object stays detached).
>>> import numpy as np
>>> from doppler.track import Costas
>>> from doppler.telemetry import Telemetry
>>> tlm = Telemetry(1 << 12)
>>> c = Costas(bn=0.05, zeta=0.707, tsamps=64)
>>> c.set_telemetry(tlm, "car")
>>> sorted(tlm.probe_names)
['car.e', 'car.freq', 'car.freq_rate', 'car.lock', 'car.locked', 'car.nco', 'car.order']
>>> x = np.ones(64 * 100, dtype=np.complex64)
>>> _ = c.steps(x)
>>> recs = tlm.read() # seven records per dumped symbol
>>> len(recs) == 7 * 100
True
function dp_costas_state_bytes¶
Serialized-state byte size.
Parameters:
stateMust be non-NULL (its contents do not affect the size).
Returns:
Bytes: the dp_state_hdr_t envelope plus the whole struct.
function dp_costas_steps¶
De-rotate a cf32 block with the carrier NCO, integrate-and-dump each symbol, and emit one decision-directed Costas prompt per symbol.
size_t dp_costas_steps (
dp_costas_state_t * state,
const float _Complex * x,
size_t x_len,
float _Complex * out,
size_t max_out
)
The streaming Python face of the loop. For every input sample it wipes the (tracked) carrier off x with the integer-phase NCO, sums the result into the coherent integrate-and-dump accumulator, and on each symbol boundary (one every tsamps samples) dumps the accumulator as the prompt, runs the BPSK Costas discriminator to steer the NCO frequency and phase, and appends the mean-scaled prompt to the output. Loop state carries across calls, so a long capture can be fed block by block; exactly one prompt symbol comes out per tsamps input samples.
Parameters:
stateCostas state. Must be non-NULL.xInput samples, one complex baseband sample each.x_lenNumber of input samples inx.outPrompt-symbol output buffer.max_outCapacity ofout, in symbols.
Returns:
Number of prompt symbols written to out (one per tsamps input samples). On the Python face this is the recovered-symbol array.
>>> import numpy as np
>>> from doppler.track import Costas
>>> tsamps = 16
>>> rng = np.random.default_rng(1)
>>> bits = rng.integers(0, 2, 4000) * 2 - 1
>>> sig = np.repeat(bits.astype(np.complex64), tsamps)
>>> k = np.arange(len(sig))
>>> rx = (sig * np.exp(2j * np.pi * 0.003 * k)).astype(np.complex64)
>>> c = Costas(bn=0.05, zeta=0.707, tsamps=tsamps)
>>> sym = c.steps(rx) # one prompt per tsamps samples
>>> sym.shape
(4000,)
>>> round(c.norm_freq, 4) # pulled onto the 0.003 residual
0.003
>>> c.lock_metric > 0.9
True
function dp_costas_steps_max_out¶
Output capacity hint for dp_costas_steps() : always 0.
The output is one prompt per tsamps inputs, so it never exceeds the input length; size out to the input length. A partial symbol carries across calls, so a block of n samples emits (acc_n + n) / tsamps prompts (integer division), up to one more than n / tsamps; a prompt past max_out still steers the loop but is dropped.
Parameters:
stateUnused.
Returns:
0 (no state-derived bound).
function dp_costas_tlm_flush¶
Emit the carrier loop's telemetry records for the symbol just dumped.
Out-of-line on purpose: the emit machinery must not inline into a per-sample hot loop (inlined ring-write expansions bloat the loop body and an extern call site forces per-iteration state reloads — both measured ~20% slower detached on other loops). Callers gate on s->tlm.ctx and call this once per dumped symbol. Records the seven probes dp_costas_set_telemetry() registers, in its order. A composing tracking channel (the DSSS despreader) calls this from its own per-epoch update.
Parameters:
sState with a non-NULL tlm.ctx (caller-checked).
Macro Definition Documentation¶
define COSTAS_EPS¶
Numerical guard added to |P| in the discriminator and lock metric so a zero prompt cannot divide by zero (not tunable).
define COSTAS_LOCK_ALPHA¶
EMA smoothing factor (per symbol) for the |Re P|/|P| lock metric, the input to the lock detector.
define COSTAS_STATE_MAGIC¶
State-blob magic for the Costas loop (FourCC "CSTS").
define COSTAS_STATE_VERSION¶
State-blob layout version (v4 added the third-order filter and the active order; v3 the lockdet decision rule).
The documentation for this class was generated from the following file native/inc/doppler/costas/costas_core.h