\chapter{Exact algorithms and reproducible verification} \label{ch:implementation} The software has two purposes: to construct checkable designs for finite instances and to expose failures of the stated guarantees. It is deliberately small enough that its data flow can be inspected. The core, planner, and exact verifier use only Python's standard library. The optional plotting program uses NumPy and Matplotlib, and its floating-point singular values are separated from the exact rank and decoding certificates. The implementation is not a raw-data causal learner. Its input is a known DAG, trusted calibrated linear constraints, and a finite specification of the admissible sensor rows. It computes the residual ambiguity spaces dictated by those inputs. If the inputs were estimated incorrectly, an exact answer to the resulting algebraic problem need not be an accurate answer about the physical system. The measurement bridge and the data contract must therefore be checked before interpreting a planner output as an experimental guarantee. \section{Data model and basis conventions} The file \path{code/calibration_core.py} implements rational elimination, residual spaces, numerical and generic failure profiles, certified row selection, positive dense completion, and exact decoding. The file \path{code/plan_robust_calibration.py} exposes the design calculations through a JSON command-line interface. The file \path{code/verify_robust.py} executes the finite regression suite and writes the detailed result record. Every exact scalar is converted to \texttt{fractions.Fraction}. Integers may be supplied directly. Nonintegral rational coefficients should be supplied as strings, such as \texttt{"1/3"}. A JSON floating-point number is first parsed as a Python floating-point value; converting it to a fraction preserves that binary value, which may differ from the decimal rational a reader intended. The examples use integers or explicit rational strings, so their meaning does not depend on a numerical tolerance. A basis in the code is a list of ambient vectors, each stored as a row-shaped Python list. If \texttt{E} contains $d$ vectors of length $q$, the mathematical matrix $Z$ has those vectors as its columns and has shape $q\times d$. The function \texttt{restrict\_rows(C,E)} returns $CZ$, a matrix with one row per sensor and one column per basis vector. This convention avoids constructing a separate transposed array but must be kept in mind when comparing the code with displayed formulas. Each sensor entry in \texttt{sensor\_spaces} is likewise a list of ambient row vectors. It describes a linear subspace $H_a$ of allowed rows, rather than several already installed channels. Selecting one vector from $H_a$ supplies one channel. An empty list represents the zero subspace and therefore a channel whose only allowed row is zero. Repeated basis vectors or linearly dependent spanning lists are harmless: the search first replaces each list by an exact reduced row basis. Trusted constraints are stored separately in \texttt{trusted\_rows}. They are not part of the failed-channel budget. Their rows may represent calibrated readouts, known incoming gain constraints, or known baseline rows after those resources have been translated into the left-constraint matrix. The planner does not infer which physical resource a numerical row came from. That interpretation belongs in the input provenance. \section{A complete small input} The following is the actual four-leaf star example, written compactly. The root is vertex zero, and its four children are vertices one through four. The two trusted rows leave a two-dimensional root-column kernel. The four sensor spaces permit the four individual leaf coordinates to be read separately. \begin{lstlisting} { "n": 5, "edges": [[0,1], [0,2], [0,3], [0,4]], "trusted_rows": [[0,1,0,1,1], [0,0,1,1,-1]], "sensor_spaces": [ [[0,1,0,0,0]], [[0,0,1,0,0]], [[0,0,0,1,0]], [[0,0,0,0,1]] ], "erasures": 0, "errors": 1, "seed": 13371337 } \end{lstlisting} This input is available as \path{examples/star_spark_three.json}. Its architecture distance is three, so one arbitrary corrupted channel can be corrected. The planner returns a selected matrix, residual bases, generic cut profiles, numerical profiles for the selected matrix, and a Boolean comparison of the optimal distance with the requested fault budget. A successful tolerance comparison is a statement about the specified architecture and exact residual spaces; it does not imply that a finite random search has already found the realizing matrix. Those are separate output fields. The planner rejects cyclic graphs, invalid or duplicate edges, inconsistent row widths, and negative fault budgets. Its public interface limits architectures to sixteen channels because it explicitly enumerates all channel subsets. This is an implementation limit, not a mathematical impossibility at seventeen channels. Users requiring larger instances need an algorithm adapted to their architecture rather than an unqualified increase of the enumeration cap. \section{Residual-space construction} For each graph vertex $j$, the code computes the surrounded support \[ I_j=\{i:j\to i\text{ and }\operatorname{ch}(i) \subseteq\operatorname{ch}(j)\}. \] A topological traversal checks acyclicity but does not silently relabel the vertices. The support lists use the original input labels. The matrix $M[:,I_j]$ is then assembled from the trusted rows, and exact elimination returns a basis of its kernel. Each local kernel vector is extended by zeros outside $I_j$, giving a basis of $E_j$ in the original ambient coordinates. The dimension reported for a column is therefore exactly \[ |I_j|-\operatorname{rank}M[:,I_j]. \] The sum of these dimensions counts residual matrix parameters, while their maximum is the freely designed noiseless channel count. The program reports both so that the two different resources cannot be accidentally equated. Empty supports and zero-dimensional kernels produce empty basis lists. When all lists are empty, the output identifies the model as already calibrated and requires no new channels. The elimination implementation performs row operations with exact fractions and records pivot columns. A null vector assigns one free coordinate the value one and all other free coordinates zero, then solves the pivot coordinates. Its correctness can be checked directly by multiplying the original constraint matrix by each returned vector. No numerical singular-value threshold is involved in deciding whether a pivot is zero. \section{Computing every generic subset rank} For one residual space $E$ of dimension $d$, let $W_a$ be the restriction of $H_a$ to $E^*$. The first stage computes \[ r(T)=\dim\sum_{a\in T}W_a \] for every channel subset $T$. The code represents a subset by an integer bit mask, with bit $a$ indicating channel $a$. It stacks the corresponding restricted basis rows and computes their rational rank. This stage makes $2^m$ rank-oracle calls for an architecture with $m$ channels; its running time includes the bit complexity of rational elimination. Classical independent-representative theory gives the maximal selectable-row rank on a retained set $K$ as \[ \rho(K)=\min_{T\subseteq K}\bigl(|K\setminus T|+r(T)\bigr). \] A direct evaluation would enumerate sub-subsets separately for every $K$. The implementation instead initializes $g(T)=r(T)-|T|$ and applies a subset-minimum transform. For each channel index $a$, it replaces the current value at every mask containing $a$ by the smaller of that value and the value with bit $a$ removed. After all indices have been processed, the value at $K$ is \[ \min_{T\subseteq K}(r(T)-|T|). \] Adding $|K|$ gives $\rho(K)$. The transform requires $O(m2^m)$ comparisons and $O(2^m)$ stored values after the rank table has been computed. This does not make the whole algorithm polynomial in $m$; it removes an unnecessary second subset enumeration. A useful audit invariant is $0\le\rho(K)\le\min(d,|K|)$. The rank table is monotone under inclusion, and $\rho(\varnothing)=0$. The finite tests check the actual values against an independent determinant calculation in two dimensions, rather than only checking these necessary invariants. \section{From subset ranks to complete failure profiles} For a selected numerical matrix $C$, the program computes the rank of $C_K|_E$ for every retained set $K$. The $k$th deletion threshold is \[ w_k(C;E)=\min\{m-|K|:\operatorname{rank}(C_K|_E)\le d-k\}. \] The numerical routine finds a retained set of largest cardinality satisfying this condition. It returns the removed channels and a complete basis of the surviving kernel. That basis may have more than $k$ vectors; the guarantee is that at least $k$ ambiguity dimensions survive. The generic routine evaluates the architecture cut formula \[ w_k^{\rm gen}(E)=\max\left(0, \min_{\substack{T\subseteq[m]\\r(T)\le d-k}} \bigl(m-|T|+r(T)-d+k\bigr)\right). \] A returned cut records $T$, its available rank, and the untruncated expression. The truncation at zero matters when some ambiguity dimensions are already invisible before any deletion. An empty profile means $d=0$; the associated distance field is \texttt{null}, rather than a fabricated finite failure threshold. A numerical kernel witness is easy to verify: check that every displayed vector belongs to $E$, that it is annihilated by all retained sensor rows, and that the displayed vectors are independent. These checks certify failure after the reported deletion. Certifying minimality also needs an argument excluding smaller deletions. In this implementation that argument is the exhaustive subset-rank table, or the proved generic bound together with a selected matrix attaining all generic ranks. A single failure vector alone is not an optimality certificate. \section{Certified finite search} The routine \texttt{common\_generic\_design} draws integer coefficients in exact reduced bases of the allowed sensor spaces. The pseudorandom seed makes the sequence reproducible. For every proposed matrix, it computes every subset rank for every active residual space and compares the complete table with the generic table. A matrix is returned as certified only if every comparison agrees. Positive coefficients in an arbitrary basis of $H_a$ do not imply that the resulting physical row has positive coordinates. The generic architecture search promises membership in the specified linear row space and exact rank attainment. The separate \texttt{dense\_completion} routine implements the positive moment-curve construction and supplies the stronger coordinatewise positivity property when dense rows are allowed. The search has a finite attempt budget. If it stops without a certificate, its status is \texttt{search\_exhausted\_not\_infeasible}. This wording is intentional. Generic existence proves that good parameters occur outside a proper algebraic exceptional set, but a particular bounded search need not encounter them. Architectural infeasibility is instead determined by the exact generic distance: no choice of rows can meet a requested fault tolerance when that optimum does not exceed the combined budget. \begin{proposition}[Meaning of a successful design certificate] Suppose a proposed matrix has each row in its allowed space, and for every residual space and retained channel subset its numerical rank equals the corresponding generic rank table. Then it simultaneously attains every generic deletion threshold and the largest achievable minimum distance of the architecture. \end{proposition} \begin{proof} Every deletion threshold is a minimum over retained subsets satisfying a rank inequality. Equality of every subset rank makes those feasible subset collections identical for the proposed matrix and the generic table. Their minima are therefore equal for every threshold index. The first threshold is the minimum nonzero measurement support on a nontrivial residual space, and taking the minimum over the column spaces gives the architecture distance. Membership of each row in its allowed space establishes that this is an admissible realization of the upper bound. \end{proof} The certificate remains exact even though the candidate generator is pseudorandom. Randomness chooses what to test; it does not determine whether a tested matrix is accepted. Rechecking the rank equalities is sufficient to validate the returned algebraic guarantee independently of the seed or the search history. \section{Exact decoding and a corrected failure mode} The reference decoder is exhaustive. For a known residual space, it enumerates candidate corrupted-channel sets of size at most $t$ among the unerased rows. For each set it solves the remaining equations. Inconsistent systems are discarded. A consistent full-rank system gives one candidate, which is checked against all unerased observations and accepted only when at most $t$ readings disagree. Distinct accepted candidates imply nonuniqueness. There is a second source of nonuniqueness: a retained system can be consistent but rank deficient. Every vector in its nontrivial affine solution family agrees on all rows outside the hypothesized corruption set. Its other readings may be changed arbitrarily within the permitted error budget. Thus that entire family is feasible, and the decoder must reject uniqueness immediately. This case exposed and corrected a real implementation error during verification. The preliminary routine skipped rank-deficient systems. With $E=\mathbb R^2$, $C=I_2$, zero observations, and one allowed error, its no-error branch found zero while its one-error branches were skipped. It could consequently return zero as if it were unique, although every vector on either coordinate axis has a feasible one-error explanation. The released routine checks consistency before rank and rejects a consistent rank-deficient family. The verifier includes this counterexample as a permanent regression test. When the distance exceeds the stated erasure and error budget, all these rejection conditions are excluded for data obeying the model, and the true vector is returned. Below the threshold, failure of uniqueness is a legitimate output. The decoder also validates nonnegative error budgets, observation lengths, and erased indices. It does not claim to detect a mistaken causal model, distinguish model mismatch from adversarial corruption, or perform polynomial-time decoding at the information limit. \section{The executed finite suite} The main architecture test uses $E=\mathbb R^2$ and three sensor positions. Each position independently receives one of six allowed spaces: \[ \{0\},\quad\operatorname{span}(e_1),\quad \operatorname{span}(e_2),\quad\operatorname{span}(e_1+e_2),\quad \operatorname{span}(e_1-e_2),\quad\mathbb R^2. \] This gives $6^3=216$ architectures. A full two-dimensional sensor is assigned each of four candidate directions; a line sensor has its prescribed direction and a zero sensor has the zero row. Across the architectures, there are $729$ candidate matrices. Every one of their eight subset ranks is compared with a separate two-dimensional determinant oracle, giving $5{,}832$ comparisons. All subset ranks and deletion profiles obeyed the theoretical upper bounds, and every architecture attained them. In total, $449$ candidate matrices attained all subset ranks simultaneously. The suite then asks the generic search for one common design for five spaces: the plane and the four displayed lines. Every one of the $216$ architectures returned a certificate. Rechecking all eight subset ranks on all five spaces produced another $8{,}640$ comparisons. The largest search count was eleven attempts. This is a bounded reproducibility result, not a complexity bound on other instances. For the complete four-node DAG, the exact residual dimensions are $[3,2,1,0]$. The constructed six-row matrix is $(1,u,u^2,u^3)$ for $u=1,\ldots,6$, and its profiles are $[4,5,6]$, $[5,6]$, $[6]$, and the empty profile. The decoder was exercised on $115$ fault scenarios, covering every zero-or-one erasure location and every zero-or-one corruption location with the three tested rational error amplitudes. Decoding three active columns in each scenario gave $345$ successful exact recoveries. Arbitrary real error magnitudes are handled by the theorem, not exhausted by these three finite values. At five rows the suite constructs two distinct exact explanations for the same data with one erasure and one error. The star examples verify distance three and profile $[3,4]$, while the duplicated parity construction verifies distance six and profile $[6,8]$. Two positive parity matrices with identical entry supports give different distances, three and two, confirming numerical dependence beyond a sparsity diagram. Six complete planner inputs and their certificates check both feasible and infeasible requested tolerances. The regression section additionally contains five decoder and input-validation checks. \section{Reproduction and interpretation} From the package root, run: \begin{lstlisting} python code/verify_robust.py python code/plan_robust_calibration.py examples/star_spark_three.json --output results/star_planning.json \end{lstlisting} The first command writes \path{results/robust_results.json}, regenerates the six example inputs and certificates, and prints a compact count summary. The second demonstrates a standalone planner call. The output paths are ordinary local files; the scripts do not publish results, transmit measurements, or require an account token. The optional figure command is: \begin{lstlisting} python code/plot_results.py \end{lstlisting} It reads the exact result record for the failure-profile and equal-support figures. Its third figure evaluates singular values numerically for five positive convex-average channels approaching parallel rows. The accompanying \path{results/figure_data.json} explicitly labels that series as a floating-point illustration. All three PDF figures are saved under \path{figures/}. The exact claims remain testable without installing plotting dependencies. The full runtime includes subset enumeration, rational arithmetic, and exhaustive error-support search. Rational numerator and denominator sizes can grow during elimination. The row-selection routine may require many candidates, and dense moment construction checks a combinatorial family of restrictions. These limitations are consistent with the hardness results rather than evidence of an efficient general solution. The executed suite supports the correctness of the implementations, the displayed examples, and the particular certificates delivered with this release. It is not a proof assistant, an external audit, or a substitute for the general arguments. Conversely, the proofs do not excuse a software error: the corrected decoder example illustrates why constructive mathematics benefits from adversarial tests that deliberately leave the regime of guaranteed success.