Datasets:
Formats:
csv
Languages:
English
Size:
< 1K
Tags:
mathematics
homogenization
spectral-theory
variational-methods
matrix-analysis
scientific-computing
Download research/code/verify_capacity.py from PureOne/EVE-QELTHA: direct link, hf CLI and curl.
- Browser
- Download file 8.88 kB
-
https://huggingface.co/datasets/PureOne/EVE-QELTHA/resolve/main/research/code/verify_capacity.py
- Command line
-
hf download hf://datasets/PureOne/EVE-QELTHA/research/code/verify_capacity.py
-
curl -L -o verify_capacity.py https://huggingface.co/datasets/PureOne/EVE-QELTHA/resolve/main/research/code/verify_capacity.py
8.88 kB
| #!/usr/bin/env python3 | |
| """Independent pressure FEM for compactly supported matrix drainage. | |
| Functional: E[P] = integral (x**-2 |P'|**2 + x**-.8 P* M(x) P) dx. | |
| The inlet value is prescribed. Drainage vanishes beyond x=3, and the | |
| finite-energy tail is constant; hence the natural endpoint condition is | |
| Q(3)=0. Every element stiffness is assembled by Gaussian quadrature, | |
| and the inlet capacity is its Schur complement. No Bessel formula or | |
| analytic matrix capacity is used. | |
| Run from any directory; output defaults to ../results/capacity.json. | |
| Requires Python 3, NumPy, SciPy. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from numpy.polynomial.legendre import leggauss | |
| from scipy.sparse import coo_matrix | |
| from scipy.sparse.linalg import splu | |
| def profile_matrix(midpoint: float, rotating: bool) -> np.ndarray: | |
| angle = np.pi / 4 if rotating and midpoint > 2 else 0.0 | |
| v = np.array([np.cos(angle), np.sin(angle)]) | |
| return np.outer(v, v) | |
| def assemble(cells: int, rotating: bool): | |
| if cells % 2: | |
| raise ValueError("An even cell count places the interface x=2 on a node.") | |
| x = np.linspace(1.0, 3.0, cells + 1) | |
| xi, wi = leggauss(8) | |
| rows, cols, values = [], [], [] | |
| for element in range(cells): | |
| left, right = x[element : element + 2] | |
| h = right - left | |
| points = (left + right) / 2 + h * xi / 2 | |
| weights = h * wi / 2 | |
| phi = np.column_stack([(1 - xi) / 2, (1 + xi) / 2]) | |
| # Exact integral of x^-2 avoids unnecessary quadrature error here. | |
| diffusion = (1 / left - 1 / right) / h**2 | |
| reaction = np.einsum("q,qi,qj->ij", weights * points**-0.8, phi, phi) | |
| local = np.kron(diffusion * np.array([[1, -1], [-1, 1]]), np.eye(2)) | |
| local += np.kron(reaction, profile_matrix((left + right) / 2, rotating)) | |
| dofs = np.arange(2 * element, 2 * element + 4) | |
| for i, di in enumerate(dofs): | |
| for j, dj in enumerate(dofs): | |
| rows.append(di) | |
| cols.append(dj) | |
| values.append(local[i, j]) | |
| size = 2 * (cells + 1) | |
| return x, coo_matrix((values, (rows, cols)), shape=(size, size)).tocsc() | |
| def capacity(stiffness, tail_conductance: float = 0.0, dirichlet_tail=False): | |
| """Return inlet Schur complement and minimizing fields for basis inputs.""" | |
| k = stiffness.copy().tolil() | |
| n = k.shape[0] | |
| if tail_conductance: | |
| k[n - 2, n - 2] += tail_conductance | |
| k[n - 1, n - 1] += tail_conductance | |
| k = k.tocsc() | |
| free = np.arange(2, n - 2 if dirichlet_tail else n) | |
| rhs = k[free, :2].toarray() | |
| solver = splu(k[free, :][:, free]) | |
| u = np.zeros((n, 2)) | |
| u[:2] = np.eye(2) | |
| u[free] = -solver.solve(rhs) | |
| raw = k[:2, :] @ u | |
| c = (raw + raw.T) / 2 | |
| residual = np.max(np.abs(k[free, :] @ u)) | |
| energy_error = np.max(np.abs(u.T @ (k @ u) - c)) | |
| return c, u, {"maximum_free_equation_residual": float(residual), | |
| "boundary_energy_discrepancy": float(energy_error)} | |
| def eigenvalues(a): | |
| return np.linalg.eigvalsh(a).tolist() | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--output", type=Path, | |
| default=Path(__file__).resolve().parents[1] / "results/capacity.json") | |
| args = parser.parse_args() | |
| results = { | |
| "model": {"R": "x^2", "G": "x^(-4/5)", "interval": [1, 3], | |
| "drainage": "v v^T; v=(1,0) on [1,2], rotated by pi/4 on [2,3]; zero beyond 3", | |
| "tail_condition": "natural Q(3)=0; finite-energy pressure tail may be constant", | |
| "method": "linear pressure FEM, 8-point reaction quadrature; inlet Schur complement"}, | |
| "mesh_refinement": [], | |
| } | |
| finest = {} | |
| for cells in [100, 200, 400, 800]: | |
| entry = {"cells": cells} | |
| for rotating, name in [(False, "fixed"), (True, "rotating")]: | |
| x, k = assemble(cells, rotating) | |
| c, u, diagnostics = capacity(k) | |
| entry[name] = {"capacity": c.tolist(), "eigenvalues": eigenvalues(c), **diagnostics} | |
| finest[name] = (k, c, u) | |
| results["mesh_refinement"].append(entry) | |
| g1 = 5 * (2**0.2 - 1) | |
| g2 = 5 * (3**0.2 - 2**0.2) | |
| h_fixed = np.diag([g1 + g2, 0.0]) | |
| v2 = np.array([1.0, 1.0]) / np.sqrt(2) | |
| h_rotating = np.diag([g1, 0.0]) + g2 * np.outer(v2, v2) | |
| s, g = (3**3 - 1) / 3, g1 + g2 | |
| bound_fixed = h_fixed / (2 * (1 + s * g)) | |
| bound_rotating = h_rotating / (2 * (1 + s * g)) | |
| c_fixed = finest["fixed"][1] | |
| c_rotating = finest["rotating"][1] | |
| results["common_kernel"] = { | |
| "theorem": "ker C = {z: M(x) z=0 for almost every x}; compact support, finite interval with natural tail", | |
| "proof": "Zero minimum energy forces P'=0 a.e. and M^(1/2)P=0 a.e.; conversely a constant common-kernel vector has zero energy.", | |
| "fixed_common_kernel_dimension": 1, | |
| "rotating_common_kernel_dimension": 0, | |
| "fixed_capacity_null_residual": float(np.linalg.norm(c_fixed @ np.array([0.0, 1.0]))), | |
| "rotating_smallest_capacity_eigenvalue": float(np.linalg.eigvalsh(c_rotating)[0]), | |
| "fixed_gram_eigenvalues": eigenvalues(h_fixed), | |
| "rotating_gram_eigenvalues": eigenvalues(h_rotating), | |
| } | |
| results["gram_lower_bound"] = { | |
| "formula": "C >= H / [2(1+S*g)], H=int G*M, S=int R, g=int G*||M||", | |
| "S": s, "g": g, | |
| "fixed_bound": bound_fixed.tolist(), | |
| "rotating_bound": bound_rotating.tolist(), | |
| "fixed_difference_eigenvalues": eigenvalues(c_fixed - bound_fixed), | |
| "rotating_difference_eigenvalues": eigenvalues(c_rotating - bound_rotating), | |
| } | |
| k = finest["fixed"][0] | |
| cutoff = [] | |
| for endpoint in [3, 4, 6, 10, 30, 100]: | |
| if endpoint == 3: | |
| c, _, diagnostics = capacity(k, dirichlet_tail=True) | |
| tail_kappa = None | |
| else: | |
| tail_kappa = 3 / (endpoint**3 - 3**3) | |
| c, _, diagnostics = capacity(k, tail_conductance=tail_kappa) | |
| expected_dark = 3 / (endpoint**3 - 1) | |
| cutoff.append({"Dirichlet_cutoff": endpoint, | |
| "exact_tail_conductance_at_3": tail_kappa, | |
| "capacity_eigenvalues": eigenvalues(c), | |
| "capacity_distance_from_natural": float(np.linalg.norm(c - c_fixed, 2)), | |
| "dark_capacity": float(c[1, 1]), | |
| "exact_dark_capacity": expected_dark, | |
| "relative_dark_error": float(abs(c[1, 1] - expected_dark) / expected_dark), | |
| **diagnostics}) | |
| results["finite_Dirichlet_cutoffs"] = cutoff | |
| results["tail_explanation"] = { | |
| "exact_scalar_tail_cost": "|P(3)|^2 / integral_3^T R = 3|P(3)|^2/(T^3-27)", | |
| "reason": "Cauchy-Schwarz yields the bound; P' proportional to R attains it.", | |
| "limit": "Cost vanishes as T tends to infinity. Imposing P(3)=0 adds artificial conductance; imposing decay only at infinity has the same infimum, potentially without an attained minimizer.", | |
| } | |
| max_diag = max(max(item[name]["maximum_free_equation_residual"], | |
| item[name]["boundary_energy_discrepancy"]) | |
| for item in results["mesh_refinement"] for name in ["fixed", "rotating"]) | |
| checks = { | |
| "fixed_common_kernel_is_null": results["common_kernel"]["fixed_capacity_null_residual"] < 2e-8, | |
| "rotating_rank_one_drainage_is_full_capacity": np.linalg.eigvalsh(c_rotating)[0] > 0.01, | |
| "fixed_gram_bound": min(eigenvalues(c_fixed - bound_fixed)) > -2e-8, | |
| "rotating_gram_bound": min(eigenvalues(c_rotating - bound_rotating)) > 0, | |
| "mesh_refines": np.linalg.norm(np.array(results["mesh_refinement"][-1]["rotating"]["capacity"]) - | |
| np.array(results["mesh_refinement"][-2]["rotating"]["capacity"])) < 1e-5, | |
| "Euler_and_energy_consistency": max_diag < 2e-7, | |
| "finite_cutoff_dark_cost": max(row["relative_dark_error"] for row in cutoff) < 5e-5, | |
| "cutoff_artifact_decays": all(cutoff[i + 1]["capacity_distance_from_natural"] < | |
| cutoff[i]["capacity_distance_from_natural"] for i in range(len(cutoff) - 1)), | |
| } | |
| results["checks"] = {key: bool(value) for key, value in checks.items()} | |
| results["all_passed"] = all(checks.values()) | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text(json.dumps(results, indent=2) + "\n") | |
| print(json.dumps({"all_passed": results["all_passed"], | |
| "fixed_eigenvalues": eigenvalues(c_fixed), | |
| "rotating_eigenvalues": eigenvalues(c_rotating), | |
| "checks": results["checks"]}, indent=2)) | |
| if not results["all_passed"]: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |