Datasets:
Formats:
csv
Languages:
English
Size:
< 1K
Tags:
mathematics
homogenization
spectral-theory
variational-methods
matrix-analysis
scientific-computing
Download research/code/verify_coherence.py from PureOne/EVE-QELTHA: direct link, hf CLI and curl.
- Browser
- Download file 7.53 kB
-
https://huggingface.co/datasets/PureOne/EVE-QELTHA/resolve/main/research/code/verify_coherence.py
- Command line
-
hf download hf://datasets/PureOne/EVE-QELTHA/research/code/verify_coherence.py
-
curl -L -o verify_coherence.py https://huggingface.co/datasets/PureOne/EVE-QELTHA/resolve/main/research/code/verify_coherence.py
7.53 kB
| #!/usr/bin/env python3 | |
| """Independent checks of a two-path, partially coherent horn leakage model. | |
| This is an abstract passive transport model, not a fluid or molecular | |
| simulation. Run with Python 3.10+, NumPy, SciPy and mpmath. The script checks | |
| the exact matrix statements against directly assembled port amplitudes and | |
| numerical Hermitian eigensolvers, then tests the horn singularity using | |
| arbitrary-precision Bessel functions. It writes a JSON verification report. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import mpmath as mp | |
| import numpy as np | |
| def normalized_random(rng: np.random.Generator, n: int = 2) -> np.ndarray: | |
| x = rng.normal(size=n) + 1j * rng.normal(size=n) | |
| return x / np.linalg.norm(x) | |
| def directly_assembled(u: np.ndarray, v: np.ndarray, c: complex): | |
| """Assemble environmental ports before forming the leakage matrix. | |
| a=(1,0), b=(c,sqrt(1-|c|^2)) have inner product <a,b>=c. | |
| The output for pressure p is a<u,p>+b<v,p>. Thus M=L^dagger L. | |
| """ | |
| eps = max(0.0, 1.0 - abs(c) ** 2) | |
| a = np.array([1.0, 0.0], dtype=complex) | |
| b = np.array([c, np.sqrt(eps)], dtype=complex) | |
| L = np.outer(a, u.conj()) + np.outer(b, v.conj()) | |
| return L.conj().T @ L, L | |
| def exact_spectrum_from_invariants(u: np.ndarray, v: np.ndarray, c: complex): | |
| s = np.vdot(u, v) | |
| delta = max(0.0, 1.0 - abs(s) ** 2) | |
| epsilon = max(0.0, 1.0 - abs(c) ** 2) | |
| trace = float(2.0 + 2.0 * np.real(np.conj(c) * s)) | |
| determinant = delta * epsilon | |
| discriminant = max(0.0, trace * trace - 4.0 * determinant) | |
| upper = (trace + np.sqrt(discriminant)) / 2.0 | |
| lower = determinant / upper if upper > 0 else 0.0 | |
| return np.array([lower, upper]), trace, determinant | |
| def random_matrix_checks(seed: int = 20261020, cases: int = 512): | |
| rng = np.random.default_rng(seed) | |
| errors = dict(spectrum=0.0, trace=0.0, determinant=0.0, | |
| output_energy=0.0, gauge=0.0, destructive_spectrum=0.0, | |
| gram_assembly=0.0) | |
| for _ in range(cases): | |
| u, v = normalized_random(rng), normalized_random(rng) | |
| c = np.sqrt(rng.uniform(0.0, 0.999)) * np.exp(2j*np.pi*rng.random()) | |
| M, L = directly_assembled(u, v, c) | |
| spectrum, trace, determinant = exact_spectrum_from_invariants(u, v, c) | |
| eig = np.linalg.eigvalsh(M) | |
| errors['spectrum'] = max(errors['spectrum'], float(np.max(abs(eig-spectrum)))) | |
| errors['trace'] = max(errors['trace'], float(abs(np.trace(M)-trace))) | |
| errors['determinant'] = max(errors['determinant'], float(abs(np.linalg.det(M)-determinant))) | |
| V = np.column_stack([u, v]) | |
| C = np.array([[1, c], [np.conj(c), 1]], dtype=complex) | |
| errors['gram_assembly'] = max(errors['gram_assembly'], float(np.linalg.norm(M - V@C@V.conj().T))) | |
| p = rng.normal(size=2) + 1j*rng.normal(size=2) | |
| # Calculate the output vector directly, separately from L and M. | |
| a = np.array([1., 0.], dtype=complex) | |
| b = np.array([c, np.sqrt(1-abs(c)**2)], dtype=complex) | |
| output = a*np.vdot(u,p) + b*np.vdot(v,p) | |
| energy = np.vdot(p, M@p) | |
| errors['output_energy'] = max(errors['output_energy'], float(abs(np.vdot(output,output)-energy))) | |
| raw = rng.normal(size=(2,2)) + 1j*rng.normal(size=(2,2)) | |
| U, _ = np.linalg.qr(raw) | |
| Mg, _ = directly_assembled(U@u, U@v, c) | |
| errors['gauge'] = max(errors['gauge'], float(np.linalg.norm(Mg-U@M@U.conj().T))) | |
| s = np.vdot(u,v) | |
| d = abs(s) | |
| r = rng.uniform(0, .999) | |
| aligned_c = -r*s/d if d > 1e-14 else -r | |
| Md, _ = directly_assembled(u,v,aligned_c) | |
| factored = np.sort([(1+r)*(1-d), (1-r)*(1+d)]) | |
| errors['destructive_spectrum'] = max(errors['destructive_spectrum'], float(np.max(abs(np.linalg.eigvalsh(Md)-factored)))) | |
| assert max(errors.values()) < 2e-12, errors | |
| u, v = np.eye(2, dtype=complex).T | |
| incoherent, _ = directly_assembled(u,v,0.0) | |
| coherent, _ = directly_assembled(u,v,1.0) | |
| assert np.allclose(np.linalg.eigvalsh(incoherent), [1,1]) | |
| assert np.allclose(np.linalg.eigvalsh(coherent), [0,2]) | |
| return dict(seed=seed,cases=cases,max_absolute_errors=errors, | |
| orthogonal_path_example=dict(delta=1.0, | |
| independent_ports_eigenvalues=np.linalg.eigvalsh(incoherent).tolist(), | |
| identical_coherent_port_eigenvalues=np.linalg.eigvalsh(coherent).tolist())) | |
| def horn_log_impedance(lam): | |
| """n=4, p=2/5, A=B=1: ν=1/16, α=8/5.""" | |
| alpha = mp.mpf(8)/5 | |
| nu = mp.mpf(1)/16 | |
| k = mp.sqrt(lam)/alpha | |
| return mp.log(mp.besselk(1-nu,k)/(mp.sqrt(lam)*mp.besselk(nu,k))) | |
| def small_eigenvalue(theta, a, phase): | |
| delta = mp.sin(theta)**2 | |
| epsilon = theta**a | |
| r = mp.sqrt(1-epsilon) | |
| d = mp.cos(theta) | |
| # These rationalized differences avoid cancellation at θ→0. | |
| one_minus_d = delta/(1+d) | |
| one_minus_r = epsilon/(1+r) | |
| if phase == 'destructive_aligned': | |
| return min((1+r)*one_minus_d, one_minus_r*(1+d)) | |
| # Original SU(2) input e=(1,0), s=e^{-iθ} cos θ, c=r real. | |
| trace = 2 + 2*r*d*d | |
| D = delta*epsilon | |
| return 2*D/(trace+mp.sqrt(trace*trace-4*D)) | |
| def singularity_checks(): | |
| mp.mp.dps = 180 | |
| rows=[] | |
| for a_text in ('0.5','1','2','3'): | |
| a=mp.mpf(a_text) | |
| for phase in ('constructive','destructive_aligned'): | |
| predicted=(2+a)*mp.mpf(15)/16 if phase=='constructive' else max(mp.mpf(2),a)*mp.mpf(15)/16 | |
| values=[] | |
| for exponent in (16,32,64): | |
| theta=mp.power(10,-exponent) | |
| lam=small_eigenvalue(theta,a,phase) | |
| values.append((exponent,horn_log_impedance(lam)/mp.log(10))) | |
| slopes=[(values[i+1][1]-values[i][1])/(values[i+1][0]-values[i][0]) for i in (0,1)] | |
| err=abs(slopes[-1]-predicted) | |
| assert err < mp.mpf('0.00001'), (a_text,phase,slopes,predicted) | |
| rows.append(dict(epsilon_power=a_text,phase=phase, | |
| predicted_angular_impedance_exponent=float(predicted), | |
| measured_slopes=[float(x) for x in slopes], | |
| last_slope_absolute_error=float(err), | |
| samples=[dict(theta_log10=-e,impedance_log10=float(z)) for e,z in values])) | |
| return dict(decimal_precision=mp.mp.dps, | |
| model=dict(n=4,p='2/5',A=1,B=1,nu='1/16'), | |
| small_eigenvalue_constructive='lambda_min ~ Delta*epsilon/4', | |
| small_eigenvalue_destructive_aligned='lambda_min ~ min(Delta,epsilon)', | |
| note='These check limiting laws within the exact reduced model; they do not establish novelty or experimental validity.', | |
| cases=rows) | |
| def main(): | |
| parser=argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--out',type=Path,default=Path(__file__).resolve().parents[1]/'results'/'coherence.json') | |
| args=parser.parse_args() | |
| report=dict(status='PASS',matrix_checks=random_matrix_checks(),asymptotic_checks=singularity_checks()) | |
| args.out.parent.mkdir(parents=True,exist_ok=True) | |
| args.out.write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8') | |
| print(json.dumps(dict(status=report['status'],random_cases=report['matrix_checks']['cases'], | |
| max_matrix_error=max(report['matrix_checks']['max_absolute_errors'].values()), | |
| asymptotic_cases=len(report['asymptotic_checks']['cases']),output=str(args.out)),indent=2)) | |
| if __name__=='__main__': | |
| main() | |