Here is a robust Python script using numpy designed to automatically validate structural stiffness matrix calculations generated by an AI model.
In structural engineering, a valid global stiffness matrix [K] must satisfy strict mathematical and physical laws: it must be square, symmetric (owing to Maxwell-Betti reciprocity), and positive semi-definite (or positive definite once boundary conditions are applied) to ensure structural stability.
Validation Script (stiffness_validator.py)
import numpy as np
def validate_stiffness_matrix(K_ai: np.ndarray, K_ref: np.ndarray = None, atol: float = 1e-4) -> dict:
"""
Validates an AI-generated structural stiffness matrix based on fundamental
mechanical properties and optional reference solutions.
Parameters:
- K_ai: np.ndarray, the stiffness matrix generated by the AI model.
- K_ref: np.ndarray, the trusted reference solution (optional).
- atol: float, absolute tolerance for floating-point comparisons.
Returns:
- dict: Validation status and detailed error diagnostics.
"""
report = {"passed": True, "errors": [], "warnings": []}
# 1. Dimensionality Check
if not isinstance(K_ai, np.ndarray):
K_ai = np.array(K_ai, dtype=float)
if K_ai.ndim != 2 or K_ai.shape[0] != K_ai.shape[1]:
report["passed"] = False
report["errors"].append(f"Invalid dimensions: Shape {K_ai.shape}. Matrix must be square (N x N).")
return report # Critical failure, stop further checks
n = K_ai.shape[0]
# 2. Symmetry Check (Maxwell-Betti Reciprocity: K = K^T)
if not np.allclose(K_ai, K_ai.T, atol=atol):
report["passed"] = False
report["errors"].append("Symmetry failure: Matrix [K] is not symmetric (violates reciprocity).")
# 3. Positive Semi-Definiteness Check (Eigenvalues >= 0)
# Using eigvalsh since the matrix is guaranteed to be symmetric in theory
eigenvalues = np.linalg.eigvalsh(K_ai)
# Allow a tiny numerical margin for floating-point inaccuracies near zero
if np.any(eigenvalues < -atol):
report["passed"] = False
report["errors"].append(
f"Stability failure: Negative eigenvalue detected ({np.min(eigenvalues):.4e}). "
"The structure is unstable or incorrectly formulated."
)
elif np.any(np.abs(eigenvalues) < 1e-9) and K_ref is None:
report["warnings"].append(
"Rigid-body motion warning: Zero eigenvalues detected. "
"Ensure boundary conditions (supports) are correctly applied if constraints are expected."
)
# 4. Numerical Accuracy Check against Reference Solution
if K_ref is not None:
if K_ai.shape != K_ref.shape:
report["passed"] = False
report["errors"].append(f"Shape mismatch: AI shape {K_ai.shape} does not match reference shape {K_ref.shape}.")
elif not np.allclose(K_ai, K_ref, atol=atol):
report["passed"] = False
max_diff = np.max(np.abs(K_ai - K_ref))
report["errors"].append(f"Accuracy failure: Maximum deviation from reference is {max_diff:.4e} (threshold: {atol}).")
return report
# --- Example Usage ---
if __name__ == "__main__":
# Reference stiffness matrix for a simple 1D spring/bar system or truss node
K_reference = np.array([
[ 500.0, -500.0, 0.0],
[-500.0, 1200.0, -700.0],
[ 0.0, -700.0, 700.0]
])
# Simulated correct AI output
K_generated_good = np.array([
[ 500.0, -500.0, 0.0],
[-500.0, 1200.0, -700.0],
[ 0.0, -700.0, 700.0]
])
# Simulated flawed AI output (e.g., asymmetric entry error)
K_generated_bad = np.array([
[ 500.0, -490.0, 0.0], # Asymmetric value (-490 vs -500)
[-500.0, 1200.0, -700.0],
[ 0.0, -700.0, 700.0]
])
print("--- Testing Good Matrix ---")
result_good = validate_stiffness_matrix(K_generated_good, K_reference)
print("Passed:", result_good["passed"])
print("Errors:", result_good["errors"])
print("\n--- Testing Flawed Matrix ---")
result_bad = validate_stiffness_matrix(K_generated_bad, K_reference)
print("Passed:", result_bad["passed"])
print("Errors:", result_bad["errors"])
Key Engineering Checks Explained
- Symmetry: If an AI model produces an asymmetric matrix due to a prompt misunderstanding or token generation error, it violates fundamental mechanics. The script checks
K == K.T. - Eigenvalue Analysis (
np.linalg.eigvalsh): A stiffness matrix cannot possess negative eigenvalues in a stable structural model. Negative values immediately flag an internal mechanics error (such as incorrect local coordinate transformation or structural instability). - Tolerance Control (
atol): Floating-point arithmetic in LLMs or downstream numerical code requires an absolute threshold (1e-4or1e-5) to avoid rejecting valid solutions due to minor rounding differences.