File size: 4,553 Bytes
347a3de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""Weighted quotient and positive-graph inverse covariance design.

These routines check the declared linear algebra; actuator realizability,
force/power conversion, and first-passage optimality are separate questions.
"""
import numpy as np
from scipy.linalg import null_space, solve_continuous_lyapunov


def shape_basis(weights):
    w=np.asarray(weights,dtype=float)
    if w.ndim!=1 or len(w)<2 or not np.isfinite(w).all() or np.any(w<=0):
        raise ValueError('finite positive weights for at least two strands required')
    q=np.sqrt(w/w.sum())
    return null_space(q[None,:])


def graph_laplacian(n,edges,gains):
    if not isinstance(n,(int,np.integer)) or n<2:
        raise ValueError('integer n>=2 required')
    g=np.asarray(gains,dtype=float)
    if len(edges)!=len(g) or not np.isfinite(g).all() or np.any(g<0):
        raise ValueError('finite nonnegative gain for each edge required')
    L=np.zeros((n,n))
    for (i,j),gain in zip(edges,g):
        if i==j or min(i,j)<0 or max(i,j)>=n:
            raise ValueError('edge indices must be distinct and in range')
        L[i,i]+=gain;L[j,j]+=gain;L[i,j]-=gain;L[j,i]-=gain
    return L


def symmetric_inverse_drift(Sigma,Q):
    S=np.asarray(Sigma,dtype=float);Q=np.asarray(Q,dtype=float)
    if S.ndim!=2 or S.shape[0]!=S.shape[1] or Q.shape!=S.shape:
        raise ValueError('matching square matrices required')
    if not np.isfinite(S).all() or not np.isfinite(Q).all():
        raise ValueError('finite matrices required')
    if not np.allclose(S,S.T,atol=1e-12) or not np.allclose(Q,Q.T,atol=1e-12):
        raise ValueError('symmetric matrices required')
    vals,O=np.linalg.eigh(S)
    if vals.min()<=0 or np.linalg.eigvalsh(Q).min()<=0:
        raise ValueError('positive definite Sigma and Q required')
    transformed=O.T@Q@O
    return O@(transformed/(vals[:,None]+vals[None,:]))@O.T


def positive_graph_target(Sigma,Q,weights,kappa,allowed_edges=None,tol=1e-10):
    """Target test with reported numerical sign/residual tolerance.

    This is floating feasibility information, not an exact sign oracle.
    """
    if not np.isfinite(kappa) or kappa<=0 or not np.isfinite(tol) or tol<0:
        raise ValueError('positive kappa and nonnegative finite tol required')
    w=np.asarray(weights,dtype=float);U=shape_basis(w)
    A=symmetric_inverse_drift(Sigma,Q)
    if A.shape!=(len(w)-1,len(w)-1):
        raise ValueError('target shape dimension mismatch')
    R=np.sqrt(w)[:,None]*U
    L=R@(A-kappa*np.eye(len(w)-1))@R.T
    n=len(w)
    allowed={tuple(sorted(x)) for x in allowed_edges} if allowed_edges is not None else None
    feasible=True;gains={};violations=[]
    for i in range(n):
        for j in range(i+1,n):
            if L[i,j]>tol:
                feasible=False;violations.append({'edge':[i,j],'positive_off_diagonal':float(L[i,j])})
            if allowed is not None and (i,j) not in allowed and abs(L[i,j])>tol:
                feasible=False;violations.append({'edge':[i,j],'forbidden_nonzero':float(L[i,j])})
            gains[f'{i},{j}']=-float(L[i,j])
    residual=np.linalg.norm(A@Sigma+Sigma@A.T-Q,ord=2)
    return {'feasible_at_tolerance':feasible,'lift':L,'gains':gains,
            'violations':violations,'lyapunov_residual':float(residual),'tolerance':tol}


def stationary_covariance(A,Q):
    A=np.asarray(A,dtype=float);Q=np.asarray(Q,dtype=float)
    if A.ndim!=2 or A.shape[0]!=A.shape[1] or Q.shape!=A.shape:
        raise ValueError('matching square matrices required')
    if not np.isfinite(A).all() or not np.isfinite(Q).all():
        raise ValueError('finite matrices required')
    if np.min(np.linalg.eigvals(A).real)<=0:
        raise ValueError('positive-real-part drift required')
    if not np.allclose(Q,Q.T,atol=1e-12) or np.min(np.linalg.eigvalsh(Q))<-1e-12:
        raise ValueError('symmetric positive semidefinite noise required')
    return solve_continuous_lyapunov(A,Q)


def weighted_action_split(velocities,weights):
    v=np.asarray(velocities,dtype=float);w=np.asarray(weights,dtype=float)
    shape_basis(w)  # validation only
    if v.ndim!=2 or v.shape[0]!=len(w) or not np.isfinite(v).all():
        raise ValueError('finite [strand,coordinate] velocities required')
    centroid=np.sum(w[:,None]*v,axis=0)/w.sum()
    lab=np.sum(w[:,None]*v*v)
    shape=np.sum(w[:,None]*(v-centroid)**2)
    translation=w.sum()*float(centroid@centroid)
    return {'lab_density':float(lab),'shape_density':float(shape),
            'translation_density':translation,'weighted_centroid_velocity':centroid}