Production-Grade Least Squares Adjustment for Control Networks in Python
Weighted least squares adjustment constitutes the definitive computational procedure for establishing survey-grade coordinate networks, calibrating local grids, and validating cadastral transformations. In production geospatial pipelines, the adjustment must be deterministic, tolerance-bound, and strictly compliant with ISO 19111:2019 coordinate reference system definitions and EPSG registry parameters. This guide details a procedural implementation for two-dimensional and three-dimensional control networks, emphasizing explicit residual thresholds, deterministic rounding, and integration-ready Python architecture. The methodology assumes prior datum alignment and focuses exclusively on mathematical adjustment, quality control, and deterministic output generation required for agency-grade deliverables.
The adjustment resolves the linearized observation equation
Precision Enforcement and Compliance Prerequisites
Production deployments require strict adherence to coordinate metadata and transformation parameters. All coordinate inputs must be validated against their declared CRS, with linear units explicitly normalized to meters prior to matrix operations. Deterministic rounding must be applied only at the final output stage, preserving full IEEE 754 double precision throughout the adjustment to prevent cumulative truncation error. Tolerance thresholds—typically 0.005 m for cadastral control and 0.001 m for high-precision engineering networks—must be enforced on both the a posteriori unit-weight standard deviation (
Implementation Architecture
The following routine provides a production-ready, tolerance-enforced least squares adjustment. It accepts pre-validated design matrices, observation vectors, and weight matrices, executing explicit floating-point casting, condition number verification, and deterministic fallback routing. Matrix inversion relies on NumPy linear algebra routines optimized for numerical stability in geospatial contexts.
import numpy as np
from numpy.typing import NDArray
from typing import Dict, Union, Optional
import logging
logger = logging.getLogger(__name__)
# Explicit precision constants
FLOAT_PRECISION = np.float64
CONDITION_THRESHOLD = 1e12
DEFAULT_SIGMA_TOLERANCE = 0.005 # meters (cadastral)
DEFAULT_RESIDUAL_TOLERANCE = 0.005 # meters
def adjust_control_network(
design_matrix: NDArray[FLOAT_PRECISION],
obs_minus_comp: NDArray[FLOAT_PRECISION],
weight_matrix: NDArray[FLOAT_PRECISION],
sigma_tolerance: float = DEFAULT_SIGMA_TOLERANCE,
residual_tolerance: float = DEFAULT_RESIDUAL_TOLERANCE,
epsg_code: Optional[int] = None
) -> Dict[str, Union[NDArray[FLOAT_PRECISION], float, bool, str]]:
"""
Executes weighted least squares adjustment for geospatial control networks.
Enforces ISO 19111 CRS validation, explicit float64 precision, and fallback routing.
"""
# 1. Explicit type and precision casting (prevents implicit float32 promotion)
A = np.asarray(design_matrix, dtype=FLOAT_PRECISION)
L = np.asarray(obs_minus_comp, dtype=FLOAT_PRECISION)
P = np.asarray(weight_matrix, dtype=FLOAT_PRECISION)
if A.shape[0] != L.shape[0]:
raise ValueError("Design matrix rows must match observation vector length.")
if P.shape != (A.shape[0], A.shape[0]):
raise ValueError("Weight matrix must be square and match observation count.")
# 2. CRS compliance validation (ISO 19111 / EPSG format check)
if epsg_code is not None:
if not isinstance(epsg_code, int) or epsg_code < 1000 or epsg_code > 99999:
raise ValueError(f"Invalid EPSG code: {epsg_code}. Must conform to EPSG registry format.")
logger.info(f"CRS validated against EPSG:{epsg_code} per ISO 19111 metadata requirements.")
# 3. Normal equation construction: N = A^T * P * A, U = A^T * P * L
N = A.T @ (P @ A)
U = A.T @ (P @ L)
# 4. Fallback routing for matrix inversion
try:
# Primary path: Direct solve for numerical stability
cond_num = np.linalg.cond(N)
if cond_num > CONDITION_THRESHOLD:
logger.warning(f"Ill-conditioned normal matrix (cond={cond_num:.2e}). Switching to pseudo-inverse.")
raise np.linalg.LinAlgError("Condition number exceeds threshold.")
X = np.linalg.solve(N, U)
except np.linalg.LinAlgError:
# Fallback path: Moore-Penrose pseudo-inverse with SVD
logger.info("Executing fallback routing via SVD-based pseudo-inverse.")
X = np.linalg.lstsq(N, U, rcond=None)[0]
# 5. Residual and precision computation
V = A @ X - L
dof = A.shape[0] - A.shape[1]
if dof <= 0:
raise ValueError("Insufficient degrees of freedom for variance estimation.")
sigma0_sq = (V.T @ P @ V) / dof
sigma0 = np.sqrt(sigma0_sq)
max_abs_residual = np.max(np.abs(V))
# 6. Tolerance enforcement
quality_pass = True
status_flags = []
if sigma0 > sigma_tolerance:
quality_pass = False
status_flags.append(f"Sigma0 {sigma0:.4f} exceeds tolerance {sigma_tolerance}")
if max_abs_residual > residual_tolerance:
quality_pass = False
status_flags.append(f"Max residual {max_abs_residual:.4f} exceeds tolerance {residual_tolerance}")
# 7. Deterministic output generation (rounding deferred to final stage)
return {
"corrections": X,
"residuals": V,
"sigma0": float(sigma0),
"max_residual": float(max_abs_residual),
"degrees_of_freedom": int(dof),
"quality_pass": quality_pass,
"status": "; ".join(status_flags) if status_flags else "PASS",
"crs_epsg": epsg_code
}
Operational Constraints and Pipeline Integration
The routine enforces strict separation between computational precision and deliverable formatting. All matrix operations execute in np.float64 without implicit casting, preserving IEEE 754 double precision through the adjustment cycle. Rounding occurs exclusively during export, typically via np.round(output_array, decimals=3) for metric deliverables or decimals=4 for millimeter-grade engineering networks.
Condition number verification (np.linalg.cond) acts as the primary diagnostic for network geometry. Values exceeding 1e12 indicate collinear control points, redundant baselines, or unit mismatches, triggering the SVD-based pseudo-inverse fallback. This routing guarantees pipeline continuity while flagging topological defects for manual review.
Tolerance thresholds must align with jurisdictional survey standards. Cadastral frameworks typically mandate
Audit Logging and Deliverable Generation
Production pipelines require immutable audit trails. Each adjustment execution must log the input matrix dimensions, condition number, fallback routing status, and tolerance verification results. Coordinate corrections (X) must be applied to initial approximations only after full quality validation. Final deliverables should export in structured formats (e.g., GeoPackage, LandXML) with embedded CRS metadata referencing the validated EPSG code. This ensures traceability from raw observations to adjusted coordinates, satisfying statutory requirements for cadastral registration and engineering certification. All transformation parameters and adjustment outputs must be version-controlled and archived alongside raw observation logs to maintain full chain-of-custody compliance.