Generated reference › Magnitude Squared Coherence — Control Systems/Spectral Measurements
kind: generated#block#control-systems-spectral-measurements

Magnitude Squared Coherence — Control Systems/Spectral Measurements

Cxy

Control_Systems/Spectral_Measurements/Magnitude_Squared_Coherence · 2 input / 1 output port(s) at insert · exports to Python, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog, PLC Structured Text

Description#

The block's own DESCRIPTION_HTML, rendered verbatim — the same text the config dialog's info panel and the library navigator show. Fix a wrong sentence in the block's .cpp (R-D9), never here.

Magnitude-Squared Coherence

Control Systems / Spectral Measurements

Welch's magnitude-squared coherence between two scalar streams, over a sliding window: Cxy(f) = |Pxy(f)|² / (Pxx(f)·Pyy(f)), one value per frequency bin and always between 0 and 1. This is MATLAB's mscohere(x, y, window, noverlap, nfft), transcribed from its source.

It answers how much of y at each frequency is linearly explained by x: near 1 where the two are related by a fixed gain and phase, near 0 where they are independent or the relation is nonlinear. The block keeps the last W samples of each input, splits them into K overlapping segments, windows and transforms every one, and averages the three spectra before dividing.

Ports

  • x – the first stream, a scalar. The reference, in the sense that the answer says how much of y it explains.
  • y – the second stream, a scalar.
  • Cxy – the coherence, a column of L/2 + 1 entries: one per frequency bin from DC to Nyquist, where L is the segment length. Entry m is the bin at m/L cycles per sample – m·fs/L hertz at a sampling rate of fs.

Parameters

  • Segment Length – L, the transform length, an even whole number from 4 to 32. It sets the frequency resolution and the number of output bins.
  • Segments – K, how many segments are averaged, from 2 to 8. One is refused: with a single segment the ratio above is an identity and the answer is a flat 1 on every signal. More segments mean a steadier estimate and a longer window.
  • Segment Overlap – how far the segments overlap.
    • None (0%) – the hop is L.
    • Half (50%) – the hop is L/2. MATLAB's default, and this block's.
    • Three quarters (75%) – the hop is L/4; needs L divisible by four.
    The window the block holds is W = L + (K−1)·hop samples long.
  • Window – the taper applied to each segment: Hamming (MATLAB's default), Hann or Rectangular. Both tapers are the symmetric form, which is what hamming and hann return unless asked otherwise.
  • Sampling Time (s) – zero or less inherits the solver's rate; a positive value runs the block at that period.

Code export

All ten targets: Python, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog and PLC Structured Text. Every transform is a fixed weighted sum of window taps, and the weights are computed once at export time, so no emitted core contains a sine, a cosine or a loop over data. The two windows become shift registers. Nothing is exposed as a tunable parameter: changing the window or the segmentation changes the whole coefficient table, which is structural.

The three HDL targets are simulation-only: they carry the arithmetic in real and quantize only at the port boundary. The answer is a ratio of two run-time quantities, each a sum of squares spanning several decades, which does not belong in a Q16.16 datapath. VHDL additionally carries each bin in an emitted function, because a clocked process here has no place to keep the eight running sums a bin needs.

Simulink bridge

No equivalent (Support::None), so nothing crosses in either direction, and no parity testbench is owed. Measured rather than assumed: mscohere is a Signal Processing Toolbox function, that toolbox ships no Simulink library at all, and a find_system sweep with LookUnderMasks over the DSP System Toolbox and Simulink library roots matched no coherence block – that library has a cross-spectrum estimator and nothing that divides by the two auto-spectra. No configuration of it crosses either, including "Sampling Time (s)", which has no counterpart to be written to. Code export verification still covers the block across all ten languages.

Notes

  • Stateful and inherently discrete: two shift registers of W samples, advanced once per sample. There is no derivative to integrate, so the block runs on the discrete path whatever the model's solver is (setDiscreteOnlyBlock(true)), and its period comes from its own "Sampling Time (s)" – or, when that is zero or less, from the model's global sampling time. The first W−1 samples of a run are read against a zero-prefilled window, as every sliding-window block here is, so the estimate is only complete once the window has filled – and until the second segment holds a sample, it necessarily reads 1.
  • The averaging IS the measurement. A single segment gives |X*Y|² = |X|²|Y|² bin by bin – Cauchy-Schwarz with equality – so K = 1 would report perfect coherence for any two signals whatever. That is why one segment is refused rather than allowed.
  • Welch's normalizing constants are not computed, because they cancel: the segment count and the window power each appear once above and once below. The answer matches MATLAB's; the intermediate sums do not.
  • It measures a LINEAR relation. A perfectly repeatable nonlinear link reads low, and that is the finding, not a fault.
  • A silent window answers zero, not a NaN: the denominator is floored, and below the floor the bin reports 0.
  • Related blocks. Correlation And Convolution / Cross-Correlation answers the same question in the time domain and over all lags at once; Spectral Measurements / Band Power reports how much power a band carries, which this block deliberately says nothing about.

Code facts#

FactValue
registered typeControl_Systems/Spectral_Measurements/Magnitude_Squared_Coherence
familyControl_Systems/Spectral_Measurements
solver environment classICoreBlock_0_Control_Systems_1_Spectral_Measurements_2_Magnitude_Squared_Coherence
sourcesrc/ICoreBlocks/ICoreBlockLibrary/Blocks/Control_Systems/Spectral_Measurements/Magnitude_Squared_Coherence/ICoreBlock_0_Control_Systems_1_Spectral_Measurements_2_Magnitude_Squared_Coherence.cpp
headersrc/ICoreBlocks/ICoreBlockLibrary/Blocks/Control_Systems/Spectral_Measurements/Magnitude_Squared_Coherence/ICoreBlock_0_Control_Systems_1_Spectral_Measurements_2_Magnitude_Squared_Coherence.h
default size on canvas160 × 86 px
ports at insert2 in, 1 out
code generators implementedPython, MATLAB, Java, Rust, C, C++, VHDL, Verilog, SystemVerilog, PLC Structured Text

Ports#

#DirectionSignal typeDescription label
1inICoreDoublex
2inICoreDoubley
3outICoreDoubleCxy

Ports the constructor creates. A block whose port list changes with its configuration adds or removes ports at load time; the count above is the one a freshly inserted block has.

Configuration variables#

Config variableDefaultSimulink parameter
Segment Length8—
Segments4—
Segment OverlapNone (0%)%~%Half (50%)%~%Three quarters (75%)~~Half (50%)—
WindowHamming%~%Hann%~%Rectangular~~Hamming—

Every block also carries Sampling Time (s) from ICoreBlockSolverEnvironment: zero or less inherits the solver's rate, a positive value runs the block at that period.

supportSupport::None
Simulink path—
port-count rulePortsParam::None
SampleTime parameteryes

Caveat (shown to the user): no Simulink equivalent. mscohere is a Signal Processing Toolbox MATLAB function, not a block; that toolbox ships no Simulink library, and a find_system sweep of 8001 blocks across 26 library roots at depth 6 with LookUnderMasks carries a cross-spectrum estimator but no coherence block

Catalog contract: src/ICoreBlocks/ICoreCoder/ICoreCommandSystem/SimulinkBridge/ICoreSimulinkBlockCatalog.h

Description vs code#

The lists agree. check_block_descriptions.py finds no disagreement between the description's Ports, Parameters, Code export and Simulink bridge lists and the code's.

The verdict above is tools/docs/check_block_descriptions.py (P7.1), which compares LISTS. It cannot read a sentence: "stateless" on a block with a state, an initial-value semantic the recursion does not implement, a "not synthesizable" caveat the HDL banner contradicts. That is the agent audit (P7.3) on BLOCK_DESCRIPTION_AUDIT.md, and this tool's green is not a substitute for one.

File banner (developer view)#

The top comment of the block's .cpp — the maths, the realization and the export strategy, addressed to whoever changes it. It must not contradict the description above (P7.5).

Magnitude-Squared Coherence -- Welch's Cxy of two scalar streams over a sliding window (MATLAB mscohere(x, y, window, noverlap, nfft)). Cxy(m) = |SUM_s Xs(m)* . Ys(m)|^2 / ( SUM_s |Xs(m)|^2 . SUM_s |Ys(m)|^2 )

ONE COEFFICIENT TABLE, TEN IDENTICAL BODIES. Every transform in that expression is a fixed weighted sum of window taps: coefficient (m, n) is w(n)*cos(2*pi*m*n/L) for the real part and -w(n)*sin(...) for the imaginary one, and the window, the segment length, the hop and the bin count are all settled before the run starts. So the whole table is built once when the configuration is read, and each emitted core is a fixed list of multiply-accumulates with no trigonometry, no loop over data and no moving array index.

⚠ THE NORMALISING CONSTANTS CANCEL, AND THAT IS WHY THIS AGREES WITH MATLAB WITHOUT COMPUTING THEM. Welch divides each of the three averaged spectra by the same segment count and the same window power. Both factors appear once in the numerator's square and once in the denominator's product, so the ratio is exactly the ratio of the RAW sums. A core that carried them would answer the same numbers and do more arithmetic to get there.

⚠ ONE SEGMENT ANSWERS A FLAT 1 ON EVERY SIGNAL. With K = 1 the expression above is Cauchy-Schwarz with equality: |X* Y|^2 = |X|^2 |Y|^2 for two complex numbers, bin by bin. That is not "perfect coherence", it is an identity, and it is why K = 1 is refused here rather than allowed to produce a plausible-looking constant. The averaging IS the measurement.

MEASURED AGAINST R2026a BEFORE ANY OF THIS WAS WRITTEN. Three windows and two overlaps were run through the installed mscohere on a 20- and a 32-sample record and reproduced by a Python stand-in of the statement list below:

L = 8, K = 4, 50 % overlap (W = 20), hamming -> worst relative error 4.2e-15 hann -> 4.0e-15 rectwin -> 1.4e-14 L = 8, K = 4, 0 % overlap (W = 32), hamming -> 1.1e-15

The rectangular row is the loosest because one of its five bins answers 0.0018, where the numerator is a near-cancellation; the absolute agreement there is 2.6e-17.

⚠ THE WINDOWS ARE THE SYMMETRIC FORM, which is what MATLAB's hamming() and hann() return by default: w(n) = 0.54 - 0.46*cos(2*pi*n/(L-1)) and 0.5*(1 - cos(2*pi*n/(L-1))). The periodic form divides by L instead of L-1 and is a different window -- on an 8-point hann it moves the second tap from 0.188 to 0.146, and every bin of the answer with it.

Sample results#

Magnitude Squared Coherence — Step: 0 -> 1 at t = 1 sMagnitude Squared Coherence — Step: 0 -> 1 at t = 1 s00.51012345t (s)in ICoreDouble-Out-0in ICoreDouble-Out-0out ICoreDouble-Out-0 [5x1] entry 0

The same rig also ran:

StimulusWhat it isOutput range
impulseImpulse: one sample of 1 at k = 5, 0 elsewhere (Repeating Sequence Stair)0 … 1
rampRamp: slope 1 from t = 00 … 1
sineSine Wave: amplitude 1, 2 rad/s, no phase, no bias0 … 1
tableRepeating Sequence Stair: [-2 -1 -0.5 0 0.5 1 2 3], one entry per sample1 … 1

Plotted: step — Step: 0 -> 1 at t = 1 s

Category dynamic · sample time 0.1 · 60 steps · commit 3c100aff6f27235305db4ad4d572f32e342718ad · produced by docsSample --out <folder> --blocks Spectral_Entropy Octave_Spectrum Magnitude_Squared_Coherence --steps 60 · data docs/generated/samples/Control_Systems__Spectral_Measurements__Magnitude_Squared_Coherence.json · the SVG is generated from those numbers by tools/docs/plot_svg.py, so it is a run and not a drawing (R-D10).