PureOne's picture
LHF v3.0.0: upload batch 7 of 7
e2dee71 verified
Raw History Blame Contribute Delete
2.82 kB
import math
import numpy as np
import pytest
from lhf.core import *
from lhf.recovery import *
from lhf.memory import prune_dominated
@pytest.mark.parametrize('budget',[0.,.01,.1,.3,math.log(2),1.,2.,5.])
def test_flagship_frontier(budget):
from lhf.core import flagship_contraction
family,_,_=flagship_family()
assert robust_floor(family,flagship_contraction(budget))==pytest.approx(flagship_frontier(budget),abs=1e-12)
@pytest.mark.parametrize('d',[1,2,3,4,8,12])
@pytest.mark.parametrize('budget',[0.,.1,1.,6.])
def test_determinant_and_contraction(d,budget):
y=np.diag(np.geomspace(.25,8,d))
c=contraction_from_lower_bound(y,budget)
assert np.linalg.slogdet(c)[1]==pytest.approx(-budget,abs=1e-9)
assert np.linalg.norm(c,2)<=1+1e-10
assert np.linalg.eigvalsh(c.T@y@c)[0]>=frontier_from_lower_bound(y,budget)-1e-10
@pytest.mark.parametrize('a,b',[(np.eye(2),2*np.eye(2)),(np.diag([4.,1]),np.diag([1.,4.])),
(np.array([[2.,2.],[2.,8.]]),np.array([[2.,-2.],[-2.,8.]]))])
def test_pair_duality(a,b):
y,z=envelope_pair(a,b)
assert logdet_dual_bound([a,b],z)==pytest.approx(np.linalg.slogdet(y)[1],abs=1e-10)
@pytest.mark.parametrize('invalid',[[],[np.zeros((2,2))],[np.array([[1.,2.],[0.,1.]])],
[np.eye(2),np.eye(3)],[np.array([[np.nan]])]])
def test_validation_rejects_bad_family(invalid):
with pytest.raises(ValueError):validate_family(invalid)
@pytest.mark.parametrize('budget',[-1.,float('inf'),float('nan')])
def test_budget_rejection(budget):
with pytest.raises(ValueError):contraction_from_lower_bound(np.eye(2),budget)
@pytest.mark.parametrize('d',[1,2,10,30])
@pytest.mark.parametrize('h',[0.,.01,.4,1.,2.])
def test_sobolev_radius(d,h):
r=sobolev_radius(d,1.,1.,h)
expected=1. if h>=1 else np.sqrt(h*h+(1-h*h)/(d+1)**2)
assert r==pytest.approx(expected)
def test_nonassociativity():
a,b=np.diag([4.,1.]),np.diag([1.,4.]); n=np.array([[4.,3.],[3.,4.]])/5
ab,_=envelope_pair(a,b); left,_=envelope_pair(ab,n)
bn,_=envelope_pair(b,n);right,_=envelope_pair(a,bn)
assert not np.allclose(left,right)
assert np.allclose(right,n)
def test_pruning_witnesses():
ms=[3*np.eye(2),np.diag([1.,2.]),np.eye(2),2*np.eye(2)]
keep,witnesses=prune_dominated(ms)
assert keep==[2]
for j,i in witnesses.items():
assert np.linalg.eigvalsh(ms[j]-ms[i])[0]>=-1e-10
def test_bad_dilation():
with pytest.raises(ValueError):unitary_dilation(2*np.eye(2))
def test_bad_requested_floor():
with pytest.raises(ValueError):contraction_from_lower_bound(np.eye(2),1.,floor=1.)
with pytest.raises(ValueError):contraction_from_lower_bound(np.eye(2),0.,floor=2.)
with pytest.raises(ValueError):contraction_from_lower_bound(np.eye(2),0.,floor=float("nan"))