Analyst comparing sensor readings with labeled NumPy correlation matrices on a monitor.

Your Correlation Matrix Has the Right Shape and the Wrong Axes

Sat, Dec 5, 2026

A four-sensor report puts +0.87038828 at the intersection of A and B. In the source readings, B equals 6 − 2A at every measurement. Each time A rises by one, B falls by two. Even before calculating a coefficient, an analyst can reject the positive sign. Yet the report has four rows, four columns, matching headers and a diagonal of ones. Which part of the calculation produced a positive number?

Read across the first two measurements and the number makes sense. NumPy has compared the four readings taken at M0 with the four readings taken at M1. The reporting code has put sensor names on the answer. Four measurements happen to occupy exactly as many positions as four sensors, so the renderer has a name available for every row it receives.

To authorize this report, follow two named pairs from their recorded readings through to the cells a reader sees. A/B gives an exact sign and magnitude. A/D gives a second value inside the interval, where a plausible positive coefficient could pass a casual inspection. Then move a measurement and move a sensor. Those changes have different consequences for the published matrix. Together they establish which calculation to release, what to repair in the existing path, and when the surviving records leave the question open.

Define which variables the report compares

Write the schema as a sentence the report owner can approve. Each input row represents one measurement event. Each input column represents one sensor. In the baseline report, the required events are M0, M1, M2 and M3, in that source order. The sensors are A, B, C and D. Every output row names a sensor, every output column names a sensor, and a cell contains the Pearson coefficient between its two named sensors over those same four events. There are six distinct off-diagonal pairs to display.

Take the A/D cell as an example. At each event, pair that event's A reading with its D reading. The event identifier supplies the pairing even if a later export sorts the records differently. A reader looking up D/A should reach the same coefficient. A reader looking for a measurement called M2 should be able to find it in the evidence for the cell, although M2 has no heading in the published matrix.

Keep two records with the report. The source record identifies the table revision, layout and ordered names on each input axis. The release record identifies the statistic, the output labels and the source record used to produce it. This lets another analyst establish what a cell is supposed to measure without reverse-engineering a chart. It also gives the report owner a precise reason to stop if a supplied file has lost its headers.

The population question has already been settled for this exercise. All sixteen values are present and every pair uses the same events with equal weight. If a review concerns which records contributed to a published coefficient, a separate example traces the row population behind each pandas correlation. Here an analyst can retrieve every expected reading and still publish the wrong answer by telling the numerical routine to compare measurements.

Build the four-by-four observation table

Measurement

A

B

C

D

M0

0

6

0

1

M1

1

4

1

3

M2

2

2

0

2

M3

3

0

2

4

Use this printed table as the source for the review. Reading down A gives a simple increasing series. Reading across M0 gives a different sequence that also has variation. Both are legitimate numerical vectors. The fixture needs variation in every row as well as every column so the mistaken calculation can finish with a finite result. An all-zero first row, for example, would reveal trouble for a different reason and weaken the test of orientation.

The Python blocks below, taken in order, are the complete contents of sensor_axis_review.py. Run the file in a local environment with NumPy installed, with Python assertions enabled. It reads no external data, has no random inputs and uses no plotting backend. The command below and every control in the article were executed with Python 3.12.16 and NumPy 2.3.5.

python sensor_axis_review.py
from dataclasses import dataclass, replace
from fractions import Fraction
from math import sqrt
from platform import python_version

import numpy as np

ATOL = 1e-12
LAYOUT = "observation_by_sensor"


@dataclass(frozen=True)
class Schema:
    source: str
    layout: str
    observations: tuple[str, ...]
    sensors: tuple[str, ...]


schema = Schema("fixture/v1", LAYOUT, ("M0", "M1", "M2", "M3"),
                ("A", "B", "C", "D"))
table = np.array([[0, 6, 0, 1],
                  [1, 4, 1, 3],
                  [2, 2, 0, 2],
                  [3, 0, 2, 4]], dtype=np.float64)
print("Python", python_version(), "NumPy", np.__version__)
print(schema, table.shape, table.dtype)

The first two output lines identify the runtime and the input. The integers in the printed table are exactly representable in the selected floating type. This choice lets the library use ordinary floating-point arithmetic while a second calculation can start from the original integer readings. Preserve the table at its source precision even when the final report rounds the coefficients for display.

Python 3.12.16 NumPy 2.3.5
Schema(source='fixture/v1', layout='observation_by_sensor', observations=('M0', 'M1', 'M2', 'M3'), sensors=('A', 'B', 'C', 'D')) (4, 4) float64

Preserve the names of both axes

In this lab the author of the fixture supplies the schema. For a collected table, its producer must be able to tie that declaration to the particular export being reviewed. The string identifying the source is a lookup key. Its value comes from the association between the declaration and the readings. Typing a source name into an old notebook after the headers have disappeared cannot establish that association.

Carry the measurement IDs and sensor IDs alongside the numeric table. Pearson coefficients are dimensionless. The identifiers in this fixture carry no physical units, and the report assigns none to the synthetic readings. If a transformation moves columns, apply the same index selection to the corresponding sensor IDs at the point where it moves the values. Guessing a familiar alphabetical order at rendering time loses the evidence of what happened. A related example of preserving feature identity at a model interface shows why positional data needs named context. Here the original columns already occupy their declared positions. The remaining question is which axis the statistical operation designates as its variables.

Calculate two coefficients without corrcoef

Derive the expected answers before calling NumPy. For a pair of equally weighted series, subtract each series' own mean from its values. Call the resulting vectors dx and dy. Sum their paired products to get Sxy and sum their squared components separately to get Sxx and Syy. The coefficient is Sxy divided by the square root of Sxx × Syy. With these complete observations, the common sample-covariance divisor cancels between numerator and denominator. The centered-product construction follows the unweighted case in the NumPy 2.3 covariance reference.

A has mean 1.5. Its deviations in measurement order are −1.5, −0.5, +0.5 and +1.5. Since B equals 6 − 2A, centering B removes the constant and leaves exactly −2 times each deviation of A. The squared deviations of A sum to 5. The cross-product sum is therefore −10, and the squared deviations of B sum to 20. The denominator is 10. A/B equals −1.

D has mean 2.5. Its deviations are −1.5, +0.5, −0.5 and +1.5. The four products with centered A are 2.25, −0.25, −0.25 and 2.25, which sum to 4. Both squared-length sums equal 5. A/D equals 4/5. D exchanges the middle two ranks relative to A, a visible reason to expect a positive coefficient below one.

Check the oracle’s assumptions

Each pair has four complete readings in the same event order, distinct sensor names, and positive squared lengths. The implementation below transcribes the three columns by hand from the named table. It has no access to the adapter's axis selector. Exact rational arithmetic preserves each centered sum through the assertions on the three terms. The probe converts to floating point only when it normalizes the result and compares it with the library output. Both baseline coefficients can also be expressed exactly as fractions. See the Python 3.13 fractions reference for the behavior of integer inputs to Fraction.

def products(x, y):
    assert len(x) == len(y) and len(x) >= 2
    mx = sum(map(Fraction, x)) / len(x)
    my = sum(map(Fraction, y)) / len(y)
    dx = [Fraction(v) - mx for v in x]
    dy = [Fraction(v) - my for v in y]
    return (sum(a*b for a, b in zip(dx, dy, strict=True)),
            sum(a*a for a in dx), sum(b*b for b in dy))


def pearson(terms):
    cross, xx, yy = terms
    assert xx > 0 and yy > 0
    return float(cross) / sqrt(float(xx * yy))


a, b, d = (0, 1, 2, 3), (6, 4, 2, 0), (1, 3, 2, 4)
ab, ad = products(a, b), products(a, d)
assert ab == (-10, 5, 20) and ad == (4, 5, 5)
expected = {("A", "B"): pearson(ab), ("A", "D"): pearson(ad)}


def close(actual, wanted):
    np.testing.assert_allclose(actual, wanted, rtol=0, atol=ATOL)

The application allows an absolute error of 10⁻¹² with relative tolerance zero. This is a declared comparison policy for these small float64 examples. Comparing displayed decimals would throw away information before the test runs. Checking only whether a result is positive would let numerous unrelated cells stand in for A/D. Checking both named pairs supplies a sharp diagnostic while keeping the arithmetic short enough to audit by hand.

Run the default call and label the mistake

The NumPy 2.3 corrcoef reference documents rowvar=True as the default. Each row supplies one variable and the columns supply its observations. With rowvar=False, each column supplies a variable and the rows supply its observations. Read the argument as a question about the current representation. “Does one row contain the full series for one variable?” For the table printed above, a row contains one reading from each of four sensors at a single event.

wrong = np.corrcoef(table)
assert wrong.shape == (4, 4)
close(wrong[0, 1], pearson(products((0, 6, 0, 1), (1, 4, 1, 3))))
assert wrong[0, 1] > 0 and expected["A", "B"] < 0
print(f"default M0/M1 {wrong[0, 1]:.8f}")

Both the preparation run and the reproduced run returned a 4×4 result from the default call. The code above also reconstructs the value at position [0,1] from the two measurement rows. That is a useful check when investigating a plausible number with the wrong sign. A calculation that starts from the alleged source of the error should reproduce the disputed value, as well as explain why the intended calculation gives a different one.

Report path

Label assigned to position [0,1]

Value shown

Readings used

Default call, labels derived from the variables consumed

M0/M1

+0.87038828

Two measurement rows

Default call, sensor headings supplied by renderer

A/B

+0.87038828

The same two rows

Source contract and independent calculation

A/B

−1.00000000

Two sensor columns

The middle row is the application defect. Multiplying the coefficient by −1 would still give the wrong magnitude, and replacing that one cell with −1 would leave the rest of the matrix without a valid interpretation. Locate the call that selected the variables and the step that attached the headings. For a consumer who received only a heat map, those steps can be several transformations upstream of the symptom.

A useful neighboring example is a NumPy shape mismatch that changes the compared pairs. Here the shapes match at input, output and rendering. Every sensor name even fits in the space allocated to it. The evidence that identifies this failure is the sequence of readings consumed for the disputed cell. Record that sequence before changing the call so the regression test captures the original defect.

Explain why structural checks still pass

Run finite correlation matrix checks on both candidates. Check the exact dimensions first, then check every entry for finiteness. Compare the matrix with its transpose within tolerance, compare the diagonal with ones, and test the magnitude of every coefficient against one plus the tolerance. The NumPy reference qualifies the ideal mathematical properties in floating-point arithmetic. The NumPy 2.3 corrcoef Notes discuss rounding, deviations on the diagonal and clipping. These checks implement the report owner's numerical policy for this fixture.

def check_structure(matrix, size):
    assert matrix.shape == (size, size)
    assert np.isfinite(matrix).all()
    close(matrix, matrix.T)
    close(matrix.diagonal(), np.ones(size))
    assert np.all(np.abs(matrix) <= 1 + ATOL)


check_structure(wrong, 4)

Structural test on the baseline

Default rows

Sensor columns

Exactly 4×4, all entries finite

Pass

Pass

Symmetric within 10⁻¹²

Pass

Pass

Diagonal within 10⁻¹² of one

Pass

Pass

Every magnitude at most 1 + 10⁻¹²

Pass

Pass

Each candidate describes correlations among four nonconstant vectors. A vector agrees with itself whichever set supplied it. Exchanging the members of a pair also preserves its coefficient in either interpretation. Even a visually excellent heat map with a mirrored color pattern and an unbroken diagonal can therefore be displaying the other question. Increasing the number of decimal places cannot expose an incorrect choice of vectors.

Decode one misleading cell

Comparison

First vector

Second vector

What a paired position represents

Default M0/M1

(0, 6, 0, 1)

(1, 4, 1, 3)

One sensor, observed at both events

Intended A/B

(0, 1, 2, 3)

(6, 4, 2, 0)

One event, observed by both sensors

Read the second paired position in the first line. The values 6 and 4 are both readings of B, taken at different events. In the second line the second paired position contains 1 and 4, readings of A and B at M1. The shared 4 belongs to the same input cell in both explanations, yet its partner has changed. This is a concrete question an analyst can ask of a renderer that exposes only indices. Which two readings contributed together at this position?

The high readings from B at both M0 and M1 help explain the positive row coefficient. For the sensor pair, the increasing series from A and declining series from B explain the negative sign. Both descriptions can be followed in the raw table. Only the second corresponds to the title of the sensor report.

Compute the intended sensor matrix

Pass the observed table and its separately declared schema to the adapter. The adapter accepts observations in rows and sets rowvar=False explicitly. It returns an ordered sensor tuple together with the coefficient array. One tuple supplies both output axes because the same sensors occur in the same order on each. The named lookup resolves its two arguments independently, so inspecting a pair uses the same row and column names the reader uses.

@dataclass(frozen=True)
class Report:
    labels: tuple[str, ...]  # Shared by both output axes
    matrix: np.ndarray

    def pair(self, left, right):
        return self.matrix[self.labels.index(left), self.labels.index(right)]


def sensor_report(data, spec):
    if spec is None or not spec.source:
        raise ValueError("missing provenance")
    if spec.layout != LAYOUT:
        raise ValueError("unknown or unsupported orientation")
    if data.ndim != 2 or data.dtype != np.float64:
        raise ValueError("expected a two-dimensional float64 table")
    rows, cols = data.shape
    if rows < 2 or cols < 2:
        raise ValueError("need two observations and two sensors")
    for labels, count in ((spec.observations, rows), (spec.sensors, cols)):
        if (len(labels) != count or len(set(labels)) != count
                or any(not isinstance(s, str) or not s.strip() for s in labels)):
            raise ValueError("invalid axis labels")
    if not np.isfinite(data).all():
        raise ValueError("nonfinite reading")
    for j, name in enumerate(spec.sensors):
        if np.all(data[:, j] == data[0, j]):
            raise ValueError(f"constant sensor {name}")
    matrix = np.corrcoef(data, rowvar=False)
    check_structure(matrix, cols)
    return Report(spec.sensors, matrix)


def check_pairs(report, references):
    for (left, right), wanted in references.items():
        close(report.pair(left, right), wanted)


accepted = sensor_report(table, schema)
assert accepted.labels == schema.sensors
check_pairs(accepted, expected)
print("sensor", accepted.labels)
for name, values in zip(accepted.labels, accepted.matrix, strict=True):
    print(name, (f"{v:.8f}" for v in values))

Sensor

A

B

C

D

A

1.00000000

−1.00000000

0.67419986

0.80000000

B

−1.00000000

1.00000000

−0.67419986

−0.80000000

C

0.67419986

−0.67419986

1.00000000

0.94387981

D

0.80000000

−0.80000000

0.94387981

1.00000000

This is the matrix printed by the successful run, rounded here to eight decimal places. The assertions use the underlying values. Follow row B to column D for a further reading check. Because centered B points exactly opposite centered A, its coefficient with D must have the opposite sign and the same magnitude as A/D. The table exhibits the same relation for the two entries involving C. C/D is particularly high in this fixture. Its magnitude alone gives no reason to attribute that cell to A/B.

To publish this representation, take the column headers from the returned labels and pair each output row with the corresponding entry in that same tuple. The last loop in the block does exactly that. A report writer can follow the loop into a table or CSV without consulting a separate list of display names. Store the full-precision array and the source record together for replay. A rounded display is sufficient for a reader who wants to look up a pair, but insufficient as the sole input to a later numerical comparison.

Numerical agreement on two cells is evidence specifically about those pairs. The declared orientation, verified order of labels and controls on the entire array extend the review to how the report is built. If a later transformation reorders the returned numbers, the producer of that transformation inherits responsibility for carrying the names with them.

Test an explicitly transposed representation

Transpose the source table and read its first row. It now contains 0, 1, 2 and 3, the entire A series. The row underneath contains the B series. One row of this representation does contain the full history of one variable, so rowvar=True is the matching setting. The NumPy 2.3 transpose reference describes this two-dimensional operation as an exchange of axes. The names and the meaning of each axis come from the source declaration.

same = np.corrcoef(table.T, rowvar=True)
back_to_rows = np.corrcoef(table.T, rowvar=False)
close(same, accepted.matrix)
close(back_to_rows, wrong)
assert not np.allclose(back_to_rows, accepted.matrix, rtol=0, atol=ATOL)

Array passed

Variable setting

Series selected

Full-matrix result in this run

Original table

Default, True

M0 through M3

Measurement matrix

Original table

False

A through D

Sensor matrix

Transposed table

True

A through D

Agreed with the sensor matrix

Transposed table

False

M0 through M3

Agreed with the measurement matrix

The last line is an important negative control. An upstream change that converts the data to sensor rows and a downstream change that forces rowvar=False can both be justified in isolation. Used together on this path, they restore the initial defect. The test checks where the result actually went by comparing it with the entire known measurement matrix. Merely asserting that the new result differs from the approved sensor matrix would also pass for a large class of unrelated errors.

Transposing an already computed result has a different effect. A correlation matrix is approximately symmetric, so that transpose exchanges the positions of M0/M1 and M1/M0 and leaves their numerical values essentially unchanged. To change the variables under comparison, make the coordinated choices at the input to the statistic. This distinction also matters when reviewing the matrix selected by NumPy eigh, where an input convention determines what numerical object the routine consumes.

Write the adapter’s orientation rule

Give the numerical adapter one accepted layout, observation_by_sensor. A caller holding a sensor-by-observation export can prepare that layout at its own boundary. First verify the producer's declaration that rows contain sensors. Then transpose once, exchange the roles of the ordered axis headers, and attach the canonical layout declaration to the resulting table. Pass that table to the same adapter used by every other caller. Retain the original declaration and transformation in the source record.

Avoid a second layout switch in the renderer. It has enough information to display the returned matrix using the returned names. It cannot establish from the result whether the caller already transposed its source. Where the caller lacks a declaration, leaving the report pending is a defensible outcome even if trying both orientations yields one answer that looks familiar.

Permute observations without changing the question

Move the measurement rows into the order M2, M0, M3, M1. Apply the same permutation to the measurement identifiers. An individual reading still belongs to the same sensor and the same event. In particular, the first pair for A/D is now the pair observed at M2, and the pair formerly first is now second. The four terms making up the centered-product sum have changed order. Their mathematical sum and the two squared lengths are unchanged.

p = [2, 0, 3, 1]
moved_rows = replace(schema, observations=tuple(schema.observations[i] for i in p))
shuffled = sensor_report(table[p, :], moved_rows)
close(shuffled.matrix, accepted.matrix)
row_result = np.corrcoef(table[p, :])
close(row_result, wrong[np.ix_(p, p)])
print(f"reordered rows: default [0,1] {row_result[0, 1]:.8f}")

For the sensor calculation the test compares the entire shuffled result to the baseline matrix in its original sensor order. All entries agreed within the stated tolerance. This is observation order invariance under a common permutation. It depends on moving every sensor's readings together. Sorting A and D independently would break the event pairing, even if each sensor retained exactly the same individual readings, mean and squared length.

The row calculation has its own predictable response. Moving measurements changes the order of the variables in that calculation. The value at [0,1] changed from 0.87038828 to 0.40618120. The latter value compares M2 with M0. The original M0/M1 coefficient survives at [1,3], the new positions of those two measurements. The probe uses the same permutation on both axes of the original measurement matrix to predict the complete reordered result.

This is a practical diagnostic for a report whose only recent change was sorting the source by a different event field. If the contract and readings are otherwise identical, a named sensor coefficient should survive that sort within tolerance. When its value instead follows a pair of event positions, reproduce the event permutation against the earlier matrix. Agreement supplies evidence about the suspected row-variable path. A lone changed number could also reflect a changed reading or a mismatched input revision.

Keep the reordered measurement IDs in the record even though the sensor matrix did not move. Their order allows a second analyst to replay the input exactly. Numerical invariance cannot certify that someone updated those IDs. A separate check against the source record establishes which measurements actually traveled with the rows.

Reorder sensors with their labels

Now leave the measurement rows alone and request the sensors in the order D, A, C, B. The column at input position zero now holds D. In the output, D must also occupy the first row and the first column. Moving input columns changes how to locate a pair in the result even though it preserves every pair's underlying readings. An equality check on the two arrays at identical positions would ask the wrong question for this control.

q = [3, 0, 2, 1]
moved_cols = replace(schema, sensors=tuple(schema.sensors[j] for j in q))
reordered = sensor_report(table[:, q], moved_cols)
assert reordered.labels == ("D", "A", "C", "B")
close(reordered.matrix, accepted.matrix[np.ix_(q, q)])
check_pairs(reordered, expected)
stale = Report(schema.sensors, reordered.matrix)
try:
    check_pairs(stale, expected)
except AssertionError:
    print(f"stale labels rejected: apparent A/B {stale.pair('A', 'B'):.8f}")
else:
    raise AssertionError("stale labels escaped the named-pair check")

The np.ix_ selection constructs the expected square subscript grid from the same ordered indices on both axes. Its [0,1] entry selects original row D and original column A. That predicts a value of 0.8 in the reordered display. The new location for A/B is [1,3], and A/D is at [1,0]. The program checks all sixteen numeric positions against the predicted permutation before examining the named pairs. No calculation of a replacement correlation matrix enters that prediction.

Use named pairs in the assertions

Published headings

Lookup requested

Physical position

Observed answer

D, A, C, B

A/B

[1,3]

−1.00

D, A, C, B

A/D

[1,0]

+0.80

Stale A, B, C, D

Apparent A/B

[0,1]

+0.80

For the stale-label control, wrap the correct reordered array in the original labels. The apparent A/B cell now contains D/A. The array still agrees perfectly with the numerical permutation because only its headings have changed. The named-pair comparison rejects this candidate, and the exception handler records the value it rejected. If that check ever stops rejecting the sample, the test itself fails. This keeps a label regression visible when a report writer or serialization layer changes.

A permutation with an observable consequence is worth choosing deliberately. Swapping two positions involved only in a self-comparison would leave a diagonal check green. An accidental equality between unrelated off-diagonal coefficients could also conceal a stale heading. This fixture puts two known, distinctly different values in the path of the lookup. A production review should still check the complete ordered label list against the manifest. Two pair checks cannot witness a naming error affecting only unexamined labels.

Expose the axis error with a fifth observation

Append M4 with readings 4, −2, 1 and 0 in sensor order. This creates a second input revision. The intended variables remain A through D, giving four output rows and four output columns. The default now sees five measurement rows as variables and yields a 5×5 matrix. A report writer with exactly four sensor headings can detect the size discrepancy before it renders anything. Truncating the new result to fit the four headings would discard the most conspicuous evidence of the error.

five = np.vstack((table, [4, -2, 1, 0]))
five_schema = replace(schema, source="fixture/v2", observations=(*schema.observations, "M4"))
ab5 = products((*a, 4), (*b, -2))
ad5 = products((*a, 4), (*d, 0))
assert ab5 == (-20, 10, 40) and ad5 == (-1, 10, 10)
expanded = sensor_report(five, five_schema)
check_pairs(expanded, {("A", "B"): pearson(ab5), ("A", "D"): pearson(ad5)})
wrong5 = np.corrcoef(five)
assert wrong5.shape == (5, 5)
close(wrong5[:4, :4], wrong)
print("M4 added:", expanded.matrix.shape, wrong5.shape,
      f"A/B {expanded.pair('A', 'B'):.2f} A/D {expanded.pair('A', 'D'):.2f}")

Input revision

Observations × sensors

Sensor output

Default output

Named A/B

Named A/D

Baseline

4 × 4

4 × 4

4 × 4

−1.00

+0.80

M4 included

5 × 4

4 × 4

5 × 5

−1.00

−0.10

Verify the new coefficients independently. A and D both have mean 2 over five observations. Their centered vectors are (−2, −1, 0, 1, 2) and (−1, 1, 0, 2, −2). Their products sum to 2 − 1 + 0 + 2 − 4, which is −1. Each squared length is 10, hence the expanded A/D coefficient is −1/10. B still equals 6 − 2A at every event. Its coefficient with A remains −1, with squared lengths of 10 and 40 and a cross-product sum of −20.

An additional check looks at the upper-left four-by-four block of the new default result. It agrees with the old default because the original four event vectors retain exactly the same four components. This explains what a truncating renderer would do. It could reproduce all its old numbers after adding an event that actually reverses the sign of A/D. A dashboard that appears stable across revisions can therefore be further evidence of the wrong axis.

Keep the square baseline as the release test. A program that detects only the five-versus-four mismatch would catch the expanded example and accept the original faulty report. Keep the fifth event as a separate control with its own expected coefficients. Using the baseline value 0.8 to qualify the five-event result would reject a correct calculation.

Reject inputs that cannot support this contract

The adapter checks the source declaration and layout before examining numerical values. It then requires a two-dimensional float64 table, at least two measurement rows and, for this matrix-of-pairs interface, at least two sensors. The length of each ordered label list must match its axis. Names on that axis must be unique, nonempty strings. A duplicated measurement identifier makes record references ambiguous. A duplicated sensor identifier makes a named lookup ambiguous even when the underlying array happens to contain different columns.

Every reading must be finite. A constant sensor has zero centered length, so any coefficient involving it would require division by zero. Once finiteness and a minimum row count are established, comparing each sensor's values with its first value detects a constant column directly. This check establishes positive variance mathematically for the admitted readings. The separate checks on the computed matrix catch unusable numerical results. For example, very large magnitudes introduce floating-point concerns outside the demonstrated range of these small integers.

bad_value = table.copy()
bad_value[1, 2] = np.nan
constant = table.copy()
constant[:, 2] = 7
cases = [
    (table, None, "missing provenance"),
    (table, replace(schema, source=""), "missing provenance"),
    (table, replace(schema, layout="unknown"), "unknown or unsupported orientation"),
    (table.ravel(), schema, "expected a two-dimensional float64 table"),
    (table.astype(np.int64), schema, "expected a two-dimensional float64 table"),
    (table[:1], replace(schema, observations=("M0",)), "need two observations and two sensors"),
    (table, replace(schema, observations=("M0",)*4), "invalid axis labels"),
    (table, replace(schema, sensors=("A", "B", "C")), "invalid axis labels"),
    (bad_value, schema, "nonfinite reading"),
    (constant, schema, "constant sensor C"),
]
for data, spec, reason in cases:
    try:
        sensor_report(data, spec)
    except ValueError as error:
        assert str(error) == reason
    else:
        raise AssertionError(f"accepted invalid input: {reason}")
print(f"{len(cases)} input rejections matched; all controls passed")

Return a reason that the owner can resolve

Reason returned

Evidence or repair needed from the owner

Missing provenance

Retrieve the matching source revision and its axis declaration.

Unknown or unsupported orientation

Establish which input axis indexes sensors. Normalize a documented alternate layout once.

Expected a two-dimensional float64 table

Retrieve the complete typed table in its declared layout.

Need two observations and two sensors

Establish an input that can support this report of sensor pairs.

Invalid axis labels

Reconcile ordered, unique names and their counts against the producer's manifest.

Nonfinite reading

Locate the affected reading in the source and resolve its status before recalculation.

Constant sensor C

Confirm C's readings and report that its Pearson coefficients are undefined for this input.

The run ended with 10 input rejections matched; all controls passed. All ten invalid-input cases produced their expected reasons. Each rejection occurred before the coefficient call. The ordinary Python assertions in the listing are executable review checks, so run the probe without optimization. If integrating these release checks into a service that can disable assertions, implement them as unconditional validation failures.

A declaration that passes a syntax check can still be false. In particular, swapping two same-length axis label lists and confidently describing the resulting table as canonical can satisfy a dimension check. The adapter relies on the source owner to establish provenance. With a square input, neither the smaller dimension nor a preference for the more plausible heat map can resolve an undocumented layout.

Recover reports produced with the wrong axis

Start with the report someone actually received. Record the matrix version, displayed headings, disputed pair and published value. Identify the job or notebook that supplied the values and the component that supplied the headings. A screenshot can establish what a reader saw. To reconstruct the calculation, locate the underlying table revision, its axis manifest and the orientation selected at the numerical call. Preserve the disputed version so a reviewer can compare the replacement against the original.

  1. Reproduce the old cell. For the baseline, follow the default path from the named source table to M0/M1, then apply the historical display labels. Recovering +0.87038828 explains how the report acquired its apparent A/B value. Check the rest of the old array if it is available at suitable precision.

  2. Compute the replacement. Run the corrected adapter from the same source revision. Check both named pairs, the full ordered headers and the controls. Use the baseline oracle for the archived baseline. A more recent export that includes M4 answers a different question.

  3. Version the correction. Retain the old report identifier, the new one, the common source revision and the changed orientation setting. Name the affected outputs explicitly, including exported tables or figures that copied numbers from the old report.

  4. Check the delivered view. Read the new headers and look up A/B and A/D in the final consumer format. Compare at the precision of that format. Keep the full-precision comparisons in the run record and link the replacement to the report it supersedes.

If the only surviving artifact is an unlabeled correlation matrix, place a hold on sensor interpretation. Each output coefficient summarizes two centered, normalized vectors. It omits the source readings, and its dimensions do not identify the entities represented by those vectors. Renaming its axes would supply an assertion of identity without supplying the missing evidence. Even knowing that the old job used a default call cannot reconstruct the sensor correlations from the surviving row coefficients alone.

For a report owner, a workable hold states what could release it. Identify who can retrieve the original export, which manifest must match it, and which report revision awaits the replay. If a different source revision is all that survives, qualify it as a new report with its own population and date. A valid new matrix does not settle what the historical report should have contained.

Approve the numerical and semantic evidence together

Use the correlation matrix release criteria on the object the reader will receive. First trace its axes to the producer's declaration. Then check the two named coefficients and the complete headings. Finally inspect the responses to the two permutations. A sensor matrix survives a common measurement reorder, and its two output axes move together under a sensor reorder. The negative controls show that the checks can reject the specific defects under review.

Evidence at review

Decision

Action authorized

Source and orientation established, both named pairs agree, headers match, structural and permutation controls pass, stale labels fail

Accept the sensor matrix

Release this labeled revision for the recorded observations.

Source established, measurement-row result reproduced, sensor headers attached to it

Repair variable-axis configuration

Recompute from source with the declared orientation, then rerun the release checks.

Sensor values pass in declared order, delivered headings are stale

Repair the label mapping within the repair route

Regenerate the labeled output and verify both named lookups at delivery.

Schema missing, source revision unresolved, or headers cannot be tied to the numerical input

Hold publication

Obtain provenance and replay before assigning sensor meaning.

Known layout with unexplained pair disagreement, failed permutation or inadmissible input

Hold publication

Resolve the specific discrepancy and repeat the affected review.

For this run, the first row authorizes the baseline matrix printed above. The conclusion is limited to four fully observed sensor series, the declared layout, the named runtime and the exercised controls. The recorded behavior agrees with the NumPy 2.3 documentation consulted on 5 December 2026. The rational arithmetic reference was the Python 3.13 library documentation, consulted on the same date. The executable used Python 3.12.16, and its exact centered products are given in the assertions.

The scientific interpretation belongs in a separate field of the review record. A/B equals −1 for the supplied readings. What that association might mean for the instruments requires evidence beyond the numerical interface. An analyst writing that part of a report can draw on statistical interpretation for data scientists. The release signature here covers the identity of each reported pair, its observations and the reproducibility of the calculation.

Practice reproducible statistical reviews

Give a colleague the printed input table, the source declaration and the published sensor matrix. Ask them to locate the two source columns behind A/D and write down the four paired products after centering. Then give them the reordered export with D first. They should be able to locate the same pair in the delivered table without reading the Python implementation. That short exercise tests whether the handoff carries enough information to review a cell from either end.

The baseline handoff can be brief. “For fixture/v1, observations occupy rows and sensors occupy columns. The released A/B is −1 and A/D is 0.8, and both named lookups survived the declared reorder tests.” Include the executable and its runtime record with that statement. Someone reviewing the expanded input can then see immediately why its A/D value of −0.1 belongs to a different revision.

For structured practice connecting variable definitions to analysis in Python, explore Refonte Learning’s Data Science Program, which includes Python Data Science and statistical modeling.