grnmetrics 0.1.0rc4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- grnmetrics-0.1.0rc4/PKG-INFO +50 -0
- grnmetrics-0.1.0rc4/README.md +37 -0
- grnmetrics-0.1.0rc4/grnmetrics/__init__.py +3 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/__init__.py +0 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/absolute.py +128 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/arrs_v2.py +81 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/balanced.py +37 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/exact_fiber.py +67 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/grouped.cpp +68 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/grouped_backend.py +170 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/local_expectation.py +80 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/optimized.cpp +101 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/optimized.py +42 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/sparse.cpp +40 -0
- grnmetrics-0.1.0rc4/grnmetrics/_core/sparse_conditional.py +96 -0
- grnmetrics-0.1.0rc4/grnmetrics/api.py +342 -0
- grnmetrics-0.1.0rc4/grnmetrics/cli.py +9 -0
- grnmetrics-0.1.0rc4/grnmetrics/metrics.py +239 -0
- grnmetrics-0.1.0rc4/grnmetrics.egg-info/PKG-INFO +50 -0
- grnmetrics-0.1.0rc4/grnmetrics.egg-info/SOURCES.txt +24 -0
- grnmetrics-0.1.0rc4/grnmetrics.egg-info/dependency_links.txt +1 -0
- grnmetrics-0.1.0rc4/grnmetrics.egg-info/entry_points.txt +2 -0
- grnmetrics-0.1.0rc4/grnmetrics.egg-info/requires.txt +5 -0
- grnmetrics-0.1.0rc4/grnmetrics.egg-info/top_level.txt +1 -0
- grnmetrics-0.1.0rc4/pyproject.toml +32 -0
- grnmetrics-0.1.0rc4/setup.cfg +4 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: grnmetrics
|
|
3
|
+
Version: 0.1.0rc4
|
|
4
|
+
Summary: Evaluation metrics for gene regulatory network inference
|
|
5
|
+
Author: José Eduardo Henriques da Silva
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: numpy>=1.26.4
|
|
9
|
+
Requires-Dist: pandas>=2.2.3
|
|
10
|
+
Requires-Dist: scipy>=1.11
|
|
11
|
+
Requires-Dist: threadpoolctl>=3.1
|
|
12
|
+
Requires-Dist: arviz>=0.18
|
|
13
|
+
|
|
14
|
+
# grnmetrics
|
|
15
|
+
|
|
16
|
+
A Python package for evaluating gene regulatory network (GRN) inference methods. This is a pre-release (`0.1.0rc4`).
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
Once published on PyPI:
|
|
21
|
+
|
|
22
|
+
python -m pip install --pre grnmetrics
|
|
23
|
+
|
|
24
|
+
Python 3.11 or newer is declared; the complete compatibility matrix is not yet validated.
|
|
25
|
+
|
|
26
|
+
## Usage
|
|
27
|
+
|
|
28
|
+
from grnmetrics import mcc, auroc, ap, arrs, crrs, available_metrics
|
|
29
|
+
|
|
30
|
+
rankedEdges = "rankedEdges.csv"
|
|
31
|
+
refNetwork = "refNetwork.csv"
|
|
32
|
+
print(mcc(rankedEdges, refNetwork))
|
|
33
|
+
print(auroc(rankedEdges, refNetwork))
|
|
34
|
+
print(available_metrics())
|
|
35
|
+
|
|
36
|
+
Input reference columns: `Gene1`, `Gene2`. Ranked edge columns: `Gene1`, `Gene2`, `EdgeWeight`. Supply `genes=` when the reference does not contain the complete gene universe. The primary edge evaluation excludes self-loops; diagonal evaluation is separate. MCC uses a tie-inclusive top-k cutoff by default, with k equal to the reference edge count. `auprc` is an alias of average precision; `pr_auc_trapezoid` is distinct.
|
|
37
|
+
|
|
38
|
+
## Native components
|
|
39
|
+
|
|
40
|
+
Some structural evaluation paths compile bundled C++17 sources on first use. They require a compatible GNU C++ compiler (`g++`) on PATH or specified by the `CXX` environment variable. On Windows use native MinGW-w64 matching Python's architecture. Conventional edge metrics do not require a C++ compiler. The sparse C++ source uses standard headers to avoid an unnecessary filesystem inclusion that fails with some older MinGW-w64 compilers. Native support is not established for every platform. The compiled artifacts are cached locally (override with `GRNMETRICS_CACHE`).
|
|
41
|
+
|
|
42
|
+
## Command line
|
|
43
|
+
|
|
44
|
+
grnmetrics --help
|
|
45
|
+
|
|
46
|
+
The current CLI supports ARRS and CRRS. The convenience Python API accepts ranking first, reference second; the CLI and detailed `ARRS.evaluate` / `CRRS.evaluate` interfaces accept reference first, ranking second.
|
|
47
|
+
|
|
48
|
+
## Release status
|
|
49
|
+
|
|
50
|
+
Pre-release for testing. License and final authorship must be confirmed before public distribution.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# grnmetrics
|
|
2
|
+
|
|
3
|
+
A Python package for evaluating gene regulatory network (GRN) inference methods. This is a pre-release (`0.1.0rc4`).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
Once published on PyPI:
|
|
8
|
+
|
|
9
|
+
python -m pip install --pre grnmetrics
|
|
10
|
+
|
|
11
|
+
Python 3.11 or newer is declared; the complete compatibility matrix is not yet validated.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
from grnmetrics import mcc, auroc, ap, arrs, crrs, available_metrics
|
|
16
|
+
|
|
17
|
+
rankedEdges = "rankedEdges.csv"
|
|
18
|
+
refNetwork = "refNetwork.csv"
|
|
19
|
+
print(mcc(rankedEdges, refNetwork))
|
|
20
|
+
print(auroc(rankedEdges, refNetwork))
|
|
21
|
+
print(available_metrics())
|
|
22
|
+
|
|
23
|
+
Input reference columns: `Gene1`, `Gene2`. Ranked edge columns: `Gene1`, `Gene2`, `EdgeWeight`. Supply `genes=` when the reference does not contain the complete gene universe. The primary edge evaluation excludes self-loops; diagonal evaluation is separate. MCC uses a tie-inclusive top-k cutoff by default, with k equal to the reference edge count. `auprc` is an alias of average precision; `pr_auc_trapezoid` is distinct.
|
|
24
|
+
|
|
25
|
+
## Native components
|
|
26
|
+
|
|
27
|
+
Some structural evaluation paths compile bundled C++17 sources on first use. They require a compatible GNU C++ compiler (`g++`) on PATH or specified by the `CXX` environment variable. On Windows use native MinGW-w64 matching Python's architecture. Conventional edge metrics do not require a C++ compiler. The sparse C++ source uses standard headers to avoid an unnecessary filesystem inclusion that fails with some older MinGW-w64 compilers. Native support is not established for every platform. The compiled artifacts are cached locally (override with `GRNMETRICS_CACHE`).
|
|
28
|
+
|
|
29
|
+
## Command line
|
|
30
|
+
|
|
31
|
+
grnmetrics --help
|
|
32
|
+
|
|
33
|
+
The current CLI supports ARRS and CRRS. The convenience Python API accepts ranking first, reference second; the CLI and detailed `ARRS.evaluate` / `CRRS.evaluate` interfaces accept reference first, ranking second.
|
|
34
|
+
|
|
35
|
+
## Release status
|
|
36
|
+
|
|
37
|
+
Pre-release for testing. License and final authorship must be confirmed before public distribution.
|
|
File without changes
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Absolute Regulatory Reconstruction Skill (ARRS), candidate v1.
|
|
2
|
+
Complete unsigned directed no-loop universe; nonnegative scores, omitted=0.
|
|
3
|
+
"""
|
|
4
|
+
import itertools as it, math
|
|
5
|
+
from collections import Counter
|
|
6
|
+
import numpy as np
|
|
7
|
+
TEMPLATES={'edge':(2,((0,1),),1),'FFL':(3,((0,1),(1,2),(0,2)),1),'cycle2':(2,((0,1),(1,0)),2),'cycle3':(3,((0,1),(1,2),(2,0)),3),'cycle4':(4,((0,1),(1,2),(2,3),(3,0)),4),'bifan':(4,((0,2),(0,3),(1,2),(1,3)),4)}
|
|
8
|
+
TYPES=tuple(TEMPLATES)
|
|
9
|
+
def candidates(n,name):
|
|
10
|
+
k,es,aut=TEMPLATES[name]
|
|
11
|
+
for v in it.permutations(range(n),k):
|
|
12
|
+
if name.startswith('cycle') and v[0]!=min(v):continue
|
|
13
|
+
if name=='bifan' and (v[0]>v[1] or v[2]>v[3]):continue
|
|
14
|
+
yield tuple(v[i]*n+v[j] for i,j in es)
|
|
15
|
+
class SparseGraph:
|
|
16
|
+
def __init__(self,n,edges):
|
|
17
|
+
self.n=n;self.out=[set() for _ in range(n)];self.inc=[set() for _ in range(n)]
|
|
18
|
+
for i,j in edges:
|
|
19
|
+
if i==j or not(0<=i<n and 0<=j<n):raise ValueError('invalid edge')
|
|
20
|
+
self.out[i].add(j);self.inc[j].add(i)
|
|
21
|
+
self.edges=[(i,j) for i,a in enumerate(self.out) for j in sorted(a)];self.A=len(self.edges)
|
|
22
|
+
def instances(self,name):
|
|
23
|
+
n=self.n;out=self.out;inc=self.inc
|
|
24
|
+
if name=='edge':
|
|
25
|
+
for i,j in self.edges:yield (i*n+j,)
|
|
26
|
+
elif name=='FFL':
|
|
27
|
+
for i,j in self.edges:
|
|
28
|
+
for k in out[i]&out[j]:yield (i*n+j,j*n+k,i*n+k)
|
|
29
|
+
elif name=='cycle2':
|
|
30
|
+
for i,j in self.edges:
|
|
31
|
+
if i<j and i in out[j]:yield(i*n+j,j*n+i)
|
|
32
|
+
elif name=='cycle3':
|
|
33
|
+
for i,j in self.edges:
|
|
34
|
+
if j<=i:continue
|
|
35
|
+
for k in out[j]&inc[i]:
|
|
36
|
+
if k>i:yield(i*n+j,j*n+k,k*n+i)
|
|
37
|
+
elif name=='cycle4':
|
|
38
|
+
for i,j in self.edges:
|
|
39
|
+
if j<=i:continue
|
|
40
|
+
for k in out[j]:
|
|
41
|
+
if k<=i:continue
|
|
42
|
+
for l in out[k]&inc[i]:
|
|
43
|
+
if l>i and l!=j:yield(i*n+j,j*n+k,k*n+l,l*n+i)
|
|
44
|
+
elif name=='bifan':
|
|
45
|
+
pairs=Counter()
|
|
46
|
+
for target in range(n):
|
|
47
|
+
for i,j in it.combinations(sorted(inc[target]),2):pairs[i,j]+=1
|
|
48
|
+
for (i,j),cnt in pairs.items():
|
|
49
|
+
if cnt>=2:
|
|
50
|
+
for k,l in it.combinations(sorted(out[i]&out[j]),2):yield(i*n+k,i*n+l,j*n+k,j*n+l)
|
|
51
|
+
else:raise KeyError(name)
|
|
52
|
+
def counts(self):return np.array([sum(1 for _ in self.instances(m)) for m in TYPES],dtype=np.int64)
|
|
53
|
+
class Scores:
|
|
54
|
+
def __init__(self,n,positive,scores):
|
|
55
|
+
self.n=n;self.graph=SparseGraph(n,positive);self.positive={int(i)*n+int(j) for i,j in self.graph.edges};self.A=len(self.positive);self.B=n*(n-1)-self.A
|
|
56
|
+
if self.A==0 or self.B==0:raise ValueError('both edge classes required')
|
|
57
|
+
d={int(i)*n+int(j):float(v) for (i,j),v in scores.items() if v!=0}
|
|
58
|
+
if any(not np.isfinite(v) or v<0 for v in d.values()):raise ValueError('invalid score')
|
|
59
|
+
if any(k<0 or k>=n*n or k//n==k%n for k in d):raise ValueError('invalid candidate')
|
|
60
|
+
self.keys=np.array(sorted(d),dtype=np.int64);self.values=np.array([d[k] for k in self.keys]);self.pkeys=np.array(sorted(self.positive),dtype=np.int64)
|
|
61
|
+
pc=Counter();nc=Counter()
|
|
62
|
+
for k,v in d.items():(pc if k in self.positive else nc)[v]+=1
|
|
63
|
+
pc[0.]=self.A-sum(pc.values());nc[0.]=self.B-sum(nc.values())
|
|
64
|
+
self.levels=np.array(sorted(set(pc)|set(nc)));self.pc=np.array([pc[v] for v in self.levels],dtype=np.int64);self.nc=np.array([nc[v] for v in self.levels],dtype=np.int64);self.plo=np.cumsum(self.pc)-self.pc;self.nhi=self.B-np.cumsum(self.nc)
|
|
65
|
+
def lookup(self,ids):
|
|
66
|
+
if not len(self.keys):return np.zeros(ids.shape)
|
|
67
|
+
p=np.searchsorted(self.keys,ids);q=np.minimum(p,len(self.keys)-1);return np.where((p<len(self.keys))&(self.keys[q]==ids),self.values[q],0.)
|
|
68
|
+
def ispos(self,ids):
|
|
69
|
+
p=np.searchsorted(self.pkeys,ids);return (p<len(self.pkeys))&(self.pkeys[np.minimum(p,len(self.pkeys)-1)]==ids)
|
|
70
|
+
def losses(self,ids):
|
|
71
|
+
sc=self.lookup(ids);lab=self.ispos(ids);a=lab.sum(1);v=sc.min(1);eq=sc==v[:,None];t=eq.sum(1);at=(eq&lab).sum(1);idx=np.searchsorted(self.levels,v);pos=a==ids.shape[1];valid=(~pos)&(a<self.A)
|
|
72
|
+
lp=(self.nhi[idx]+self.nc[idx]*t/(t+1))/self.B;ln=(self.plo[idx]+(self.pc[idx]-at)/(t+1))/np.maximum(1,self.A-a)
|
|
73
|
+
return pos,valid,lp,ln,v,a
|
|
74
|
+
|
|
75
|
+
def blocks(iterator,r,chunk=8192):
|
|
76
|
+
while True:
|
|
77
|
+
x=list(it.islice(iterator,chunk))
|
|
78
|
+
if not x:break
|
|
79
|
+
yield np.asarray(x,dtype=np.int64).reshape(-1,r)
|
|
80
|
+
def uniform_candidates(n,k,ns,rng):
|
|
81
|
+
x=rng.integers(n,size=(ns,k),dtype=np.int64);bad=(np.diff(np.sort(x,axis=1),axis=1)==0).any(1)
|
|
82
|
+
while bad.any():
|
|
83
|
+
x[bad]=rng.integers(n,size=(bad.sum(),k));bad=(np.diff(np.sort(x,axis=1),axis=1)==0).any(1)
|
|
84
|
+
return x
|
|
85
|
+
|
|
86
|
+
def evaluate_type(s,name,exact_limit=250000,ns=40000,seed=0):
|
|
87
|
+
k,es,aut=TEMPLATES[name];r=len(es);M=math.perm(s.n,k)//aut if s.n>=k else 0
|
|
88
|
+
if not M:return dict(motif=name,T=0,F=0,ARRS=np.nan,mode='unavailable')
|
|
89
|
+
lp=ln=0.;T=F=invalid=0;ln2=0;mode='exact';attempts=0
|
|
90
|
+
if name=='edge':
|
|
91
|
+
loss=float(np.dot(s.pc,s.nhi+.5*s.nc)/(s.A*s.B));return dict(motif=name,T=s.A,F=s.B,loss_true=loss,loss_false=loss,ARRS=1-2*loss,mode='exact_histogram',false_samples=0,MC_SE=0.,Hoeffding95=0.)
|
|
92
|
+
if M<=exact_limit:
|
|
93
|
+
for ids in blocks(iter(candidates(s.n,name)),r):
|
|
94
|
+
p,v,x,y,_,_=s.losses(ids);T+=int(p.sum());F+=int(v.sum());invalid+=int((~p&~v).sum());lp+=x[p].sum();ln+=y[v].sum()
|
|
95
|
+
N=F;se=0.;half=0.
|
|
96
|
+
else:
|
|
97
|
+
mode='sample_false';rng=np.random.default_rng(seed)
|
|
98
|
+
for ids in blocks(iter(s.graph.instances(name)),r):
|
|
99
|
+
p,v,x,y,_,_=s.losses(ids);assert p.all();T+=len(ids);lp+=x.sum()
|
|
100
|
+
if s.A<=r:raise ValueError('large universe with too few external positive anchors')
|
|
101
|
+
F=M-T;N=0
|
|
102
|
+
if F:
|
|
103
|
+
while N<ns:
|
|
104
|
+
m=min(8192,max(1024,ns-N));vv=uniform_candidates(s.n,k,m,rng);ids=np.stack([vv[:,i]*s.n+vv[:,j] for i,j in es],axis=1);p,v,x,y,_,_=s.losses(ids);yy=y[v][:ns-N];N+=len(yy);ln+=yy.sum();ln2+=(yy**2).sum();attempts+=m
|
|
105
|
+
if attempts>max(100*ns,1000000) and N<ns:raise RuntimeError('false motifs too rare for rejection')
|
|
106
|
+
se=math.sqrt(max(0,(ln2-ln*ln/max(1,N))/max(1,N-1))/max(1,N));half=math.sqrt(math.log(2/.05)/(2*N)) if N else np.nan
|
|
107
|
+
if not T or not F:return dict(motif=name,T=T,F=F,invalid=invalid,ARRS=np.nan,mode=mode)
|
|
108
|
+
return dict(motif=name,T=T,F=F,invalid=invalid,loss_true=lp/T,loss_false=ln/N,ARRS=1-lp/T-ln/N,mode=mode,false_samples=N,MC_SE=se,Hoeffding95=half,attempts=attempts)
|
|
109
|
+
|
|
110
|
+
def histogram_metrics(p,n):
|
|
111
|
+
P=p.sum();N=n.sum()
|
|
112
|
+
if not P or not N:return np.nan,np.nan
|
|
113
|
+
tp=np.cumsum(p[::-1]);fp=np.cumsum(n[::-1]);ap=np.sum(p[::-1]*tp/np.maximum(1,tp+fp))/P;auc=np.dot(p,np.cumsum(n)-.5*n)/(P*N);return ap,auc
|
|
114
|
+
class SmallEvaluator:
|
|
115
|
+
def __init__(self,n,positive):
|
|
116
|
+
self.n=n;self.positive=list(positive);self.A=len(positive);self.B=n*(n-1)-self.A;self.edges=np.array([i*n+j for i in range(n) for j in range(n) if i!=j]);self.y=np.isin(self.edges,[i*n+j for i,j in positive]);self.posmap=np.zeros(n*n,bool);self.posmap[self.edges]=self.y
|
|
117
|
+
self.c={m:np.asarray(list(candidates(n,m)),dtype=np.int64) for m in TYPES if n>=TEMPLATES[m][0]};self.meta={m:(self.posmap[ids],self.posmap[ids].sum(1)) for m,ids in self.c.items()}
|
|
118
|
+
def evaluate(self,s):
|
|
119
|
+
lv,inv=np.unique(s,return_inverse=True);p=np.bincount(inv,weights=self.y,minlength=len(lv));n=np.bincount(inv,weights=~self.y,minlength=len(lv));plo=np.cumsum(p)-p;nhi=self.B-np.cumsum(n);levels=np.zeros(self.n*self.n,int);levels[self.edges]=inv;rows=[]
|
|
120
|
+
for m,ids in self.c.items():
|
|
121
|
+
labs,a=self.meta[m];sc=levels[ids];v=sc.min(1);eq=sc==v[:,None];t=eq.sum(1);at=(eq&labs).sum(1);good=a==ids.shape[1];valid=(~good)&(a<self.A);T=good.sum();F=valid.sum()
|
|
122
|
+
if not T or not F:continue
|
|
123
|
+
lp=np.mean((nhi[v[good]]+n[v[good]]*t[good]/(t[good]+1))/self.B);ln=np.mean((plo[v[valid]]+(p[v[valid]]-at[valid])/(t[valid]+1))/(self.A-a[valid]));ap,auc=histogram_metrics(np.bincount(v[good],minlength=len(lv)),np.bincount(v[~good],minlength=len(lv)));rows.append(dict(motif=m,T=T,F=F,loss_true=lp,loss_false=ln,ARRS=1-lp-ln,AP=ap,AUC=auc))
|
|
124
|
+
return rows
|
|
125
|
+
|
|
126
|
+
def aggregate(rows):
|
|
127
|
+
e=next(x for x in rows if x['motif']=='edge');mot=[x for x in rows if x['motif']!='edge' and np.isfinite(x['ARRS'])];sm=np.mean([x['ARRS'] for x in mot]) if mot else np.nan
|
|
128
|
+
return dict(ARRS_edge=e['ARRS'],ARRS_struct=sm,ARRS=(e['ARRS']+sm)/2 if mot else np.nan,AP=e.get('AP',np.nan),AUROC=e.get('AUC',np.nan),motif_AP=np.mean([x.get('AP',np.nan) for x in mot]) if mot else np.nan,motif_AUC=np.mean([x.get('AUC',np.nan) for x in mot]) if mot else np.nan,loss_true_struct=np.mean([x['loss_true'] for x in mot]) if mot else np.nan,loss_false_struct=np.mean([x['loss_false'] for x in mot]) if mot else np.nan,types=len(mot))
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import sys,math,pathlib
|
|
2
|
+
import numpy as np
|
|
3
|
+
from .absolute import Scores,SparseGraph,TEMPLATES,TYPES,blocks,SmallEvaluator
|
|
4
|
+
from .balanced import cap_mean
|
|
5
|
+
from .sparse_conditional import histogram
|
|
6
|
+
|
|
7
|
+
def ratio(l,n,h):return math.prod((l-i)/(n-i) for i in range(h)) if h<=l and h<=n else 0.
|
|
8
|
+
def anchor(h,p,l,n):return (1-h/(h+p+1)*math.prod((l+i)/(n+i) for i in range(1,p+2)))/(p+1)
|
|
9
|
+
def mu_parts(A,B,hist):
|
|
10
|
+
r=len(hist)-1;b=min(A,B);return float(cap_mean(0,B,r,b)/b),sum(hist[a]*ratio(b,B,r-a)*anchor(r-a,a,b,B) for a in range(r) if a<A)/hist[-1]
|
|
11
|
+
def cutoff(nc,nhi,b):
|
|
12
|
+
z=int(np.flatnonzero((nhi<b)&(nhi+nc>=b))[0]);return z,b-int(nhi[z])
|
|
13
|
+
def losses(sc,lab,pc,nc,plo,nhi,A,B,z,l,conditional=False):
|
|
14
|
+
b=min(A,B);a=lab.sum(1);v=sc.min(1);eq=sc==v[:,None];t=eq.sum(1);at=(eq&lab).sum(1);good=a==sc.shape[1];valid=(~good)&(a<A)
|
|
15
|
+
plus=cap_mean(nhi[v[good]],nc[v[good]],t[good],b)/b
|
|
16
|
+
ss=sc[valid];ll=lab[valid];vv=v[valid];aa=a[valid];tt=t[valid];pp=at[valid];h=((ss==z)&~ll).sum(1);ok=(ll|(ss>=z)).all(1)
|
|
17
|
+
vals=(plo[vv]+(pc[vv]-pp)/(tt+1))/(A-aa)
|
|
18
|
+
for hh in range(1,sc.shape[1]+1):
|
|
19
|
+
mask=h==hh
|
|
20
|
+
if not mask.any():continue
|
|
21
|
+
cut=mask&(vv==z)
|
|
22
|
+
for p in range(sc.shape[1]-hh+1):
|
|
23
|
+
m=cut&(pp==p);vals[m]=(plo[z]+(pc[z]-p)*anchor(hh,p,l,int(nc[z])))/(A-aa[m])
|
|
24
|
+
if not conditional:vals[mask]*=ratio(l,int(nc[z]),hh)
|
|
25
|
+
vals*=ok
|
|
26
|
+
return plus,vals
|
|
27
|
+
|
|
28
|
+
def result(m,T,p,f,u,w,**kw):return dict(motif=m,T=T,delay=p,false_burden=f,null_delay=u,null_false=w,ARRS2=1-(p+f)/(u+w),delay_contrib=(u-p)/(u+w),false_contrib=(w-f)/(u+w),**kw)
|
|
29
|
+
class Eval(SmallEvaluator):
|
|
30
|
+
def __init__(self,n,positive):
|
|
31
|
+
super().__init__(n,positive);self.hist={m:np.bincount(a,minlength=ids.shape[1]+1).tolist() for m,ids in self.c.items() for _,a in [self.meta[m]]};self.mu={m:mu_parts(self.A,self.B,h) for m,h in self.hist.items() if h[-1] and sum(h[:-1])}
|
|
32
|
+
def evaluate(self,s):
|
|
33
|
+
lv,inv=np.unique(s,return_inverse=True);pc=np.bincount(inv,weights=self.y,minlength=len(lv)).astype(int);nc=np.bincount(inv,weights=~self.y,minlength=len(lv)).astype(int);plo=np.cumsum(pc)-pc;nhi=self.B-np.cumsum(nc);z,l=cutoff(nc,nhi,min(self.A,self.B));scmap=np.zeros(self.n*self.n,int);scmap[self.edges]=inv;rows=[]
|
|
34
|
+
for m,ids in self.c.items():
|
|
35
|
+
if m not in self.mu:continue
|
|
36
|
+
lab,a=self.meta[m];p,f=losses(scmap[ids],lab,pc,nc,plo,nhi,self.A,self.B,z,l);T=self.hist[m][-1];rows.append(result(m,T,p.mean(),f.sum()/T,*self.mu[m]))
|
|
37
|
+
return rows
|
|
38
|
+
|
|
39
|
+
def aggregate(rows):
|
|
40
|
+
e=next(x for x in rows if x['motif']=='edge');m=[x for x in rows if x['motif']!='edge'];sm=np.mean([x['ARRS2'] for x in m]);return dict(ARRS2_edge=e['ARRS2'],ARRS2_struct=sm,ARRS2=(e['ARRS2']+sm)/2,ARRS2_struct_delay=np.mean([x['delay_contrib'] for x in m]),ARRS2_struct_false=np.mean([x['false_contrib'] for x in m]))
|
|
41
|
+
|
|
42
|
+
def sparse_eval(s,draws=32,seed=0,active_cap=200000):
|
|
43
|
+
A,B=s.A,s.B;b=min(A,B);pc,nc,plo,nhi=s.pc,s.nc,s.plo,s.nhi;z,l=cutoff(nc,nhi,b);cut=s.levels[z];pmin=s.levels[np.flatnonzero(pc)[0]]
|
|
44
|
+
negkeys=s.keys[~s.ispos(s.keys)];negvals=s.lookup(negkeys);strict=negkeys[negvals>cut];boundary=negkeys[negvals==cut];T={};mu={};delay={};rng=np.random.default_rng(seed)
|
|
45
|
+
def to_rank(x):return (x//s.n)*(s.n-1)+x%s.n-(x%s.n>x//s.n)
|
|
46
|
+
def to_id(x):i=x//(s.n-1);j=x%(s.n-1);return i*s.n+j+(j>=i)
|
|
47
|
+
for m in TYPES:
|
|
48
|
+
hist=histogram(s.graph,m);T[m]=hist[-1]
|
|
49
|
+
if not T[m] or not sum(hist[:-1]):continue
|
|
50
|
+
mu[m]=mu_parts(A,B,hist);tot=0.
|
|
51
|
+
for ids in blocks(iter(s.graph.instances(m)),len(TEMPLATES[m][1])):
|
|
52
|
+
sc=np.searchsorted(s.levels,s.lookup(ids));v=sc.min(1);t=(sc==v[:,None]).sum(1);tot+=cap_mean(nhi[v],nc[v],t,b).sum()/b
|
|
53
|
+
delay[m]=tot/T[m]
|
|
54
|
+
skip=cut<pmin
|
|
55
|
+
if cut==0 and not skip:
|
|
56
|
+
excluded=np.unique(to_rank(np.r_[s.pkeys,negkeys]));offset=excluded-np.arange(len(excluded));assert B-len(negkeys)==nc[z]
|
|
57
|
+
def sample_boundary():
|
|
58
|
+
x=rng.choice(int(nc[z]),l,replace=False);return to_id(x+np.searchsorted(offset,x,side='right'))
|
|
59
|
+
else:
|
|
60
|
+
def sample_boundary():return rng.choice(boundary,l,replace=False)
|
|
61
|
+
exact=skip or (A+len(strict)+int(nc[z])<=active_cap and cut>0) or (cut==0 and not skip and A+B<=active_cap)
|
|
62
|
+
if exact:
|
|
63
|
+
if skip:pool=strict
|
|
64
|
+
elif cut>0:pool=np.r_[strict,boundary]
|
|
65
|
+
else:
|
|
66
|
+
x=np.arange(int(nc[z]));pool=np.r_[strict,to_id(x+np.searchsorted(offset,x,side='right'))]
|
|
67
|
+
subsets=[pool]
|
|
68
|
+
else:subsets=(np.r_[strict,sample_boundary()] for _ in range(draws))
|
|
69
|
+
vals=[]
|
|
70
|
+
for pool in subsets:
|
|
71
|
+
graph=SparseGraph(s.n,[(int(x)//s.n,int(x)%s.n) for x in np.r_[s.pkeys,pool]]);row={}
|
|
72
|
+
for m in delay:
|
|
73
|
+
total=0.
|
|
74
|
+
for ids in blocks(iter(graph.instances(m)),len(TEMPLATES[m][1])):
|
|
75
|
+
sc=np.searchsorted(s.levels,s.lookup(ids));lab=s.ispos(ids);_,f=losses(sc,lab,pc,nc,plo,nhi,A,B,z,l,conditional=not exact);total+=f.sum()
|
|
76
|
+
row[m]=total/T[m]
|
|
77
|
+
vals.append(row)
|
|
78
|
+
rows=[]
|
|
79
|
+
for m,p in delay.items():
|
|
80
|
+
x=np.array([d[m] for d in vals]);f=x.mean();u,w=mu[m];rows.append(result(m,T[m],p,f,u,w,mode='exact_sparse' if exact else 'iid_boundary',draws=len(x),SE=0 if exact else x.std(ddof=1)/math.sqrt(len(x))/(u+w)))
|
|
81
|
+
return rows
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Reference-cardinality anchored extension of ARRS; no score threshold.
|
|
2
|
+
Primary balanced negative-anchor budget b=min(A,B); full b=B recovers original.
|
|
3
|
+
"""
|
|
4
|
+
import math
|
|
5
|
+
import numpy as np
|
|
6
|
+
from .absolute import *
|
|
7
|
+
|
|
8
|
+
def cap_mean(j,m,t,b):
|
|
9
|
+
# J=j+Y; CDF(Y<=u)=C(u+t,t)/C(m+t,t), exact expectation of min(J,b).
|
|
10
|
+
j,m,t=np.broadcast_arrays(np.asarray(j,float),np.asarray(m,float),np.asarray(t,int));c=np.maximum(0,b-j);d=np.minimum(c,m);ratio=np.ones_like(d,dtype=float)
|
|
11
|
+
for i in range(1,int(t.max(initial=1))+1):ratio*=np.where(t>=i,(d+i)/(m+i),1.)
|
|
12
|
+
# C(d+t,t+1)/C(m+t,t) = d/(t+1) * product_{i=1}^t (d+i)/(m+i)
|
|
13
|
+
# If c>=m, d=m: d-d/(t+1) is E[Y].
|
|
14
|
+
return np.minimum(j,b)+d-d/(t+1)*ratio
|
|
15
|
+
|
|
16
|
+
def baseline(B,r,b):return float(cap_mean(0,B,r,b)/b)+1/(r+1)
|
|
17
|
+
|
|
18
|
+
class BalancedSmall(SmallEvaluator):
|
|
19
|
+
def evaluate(self,s):
|
|
20
|
+
lv,inv=np.unique(s,return_inverse=True);p=np.bincount(inv,weights=self.y,minlength=len(lv));n=np.bincount(inv,weights=~self.y,minlength=len(lv));plo=np.cumsum(p)-p;nhi=self.B-np.cumsum(n);levels=np.zeros(self.n*self.n,int);levels[self.edges]=inv;rows=[];b=min(self.A,self.B)
|
|
21
|
+
for m,ids in self.c.items():
|
|
22
|
+
labs,a=self.meta[m];sc=levels[ids];v=sc.min(1);eq=sc==v[:,None];t=eq.sum(1);at=(eq&labs).sum(1);good=a==ids.shape[1];valid=(~good)&(a<self.A);T=good.sum();F=valid.sum();r=ids.shape[1]
|
|
23
|
+
if not T or not F:continue
|
|
24
|
+
lp=np.mean((nhi[v[good]]+n[v[good]]*t[good]/(t[good]+1))/self.B);lb=np.mean(cap_mean(nhi[v[good]],n[v[good]],t[good],b)/b);ln=np.mean((plo[v[valid]]+(p[v[valid]]-at[valid])/(t[valid]+1))/(self.A-a[valid]));ap,auc=histogram_metrics(np.bincount(v[good],minlength=len(lv)),np.bincount(v[~good],minlength=len(lv)));mu=baseline(self.B,r,b);rows.append(dict(motif=m,T=T,F=F,loss_true=lp,loss_true_balanced=lb,loss_false=ln,ARRS=1-lp-ln,ARRS_B=1-(lb+ln)/mu,mu_B=mu,AP=ap,AUC=auc))
|
|
25
|
+
return rows
|
|
26
|
+
|
|
27
|
+
def balanced_sparse(s,name,exact_limit=250000,ns=40000,seed=0):
|
|
28
|
+
res=evaluate_type(s,name,exact_limit,ns,seed)
|
|
29
|
+
if not np.isfinite(res['ARRS']):return dict(**res,ARRS_B=np.nan)
|
|
30
|
+
r=len(TEMPLATES[name][1]);b=min(s.A,s.B);v=0;T=0
|
|
31
|
+
for ids in blocks(iter(s.graph.instances(name)),r):
|
|
32
|
+
sc=s.lookup(ids);mn=sc.min(1);t=(sc==mn[:,None]).sum(1);idx=np.searchsorted(s.levels,mn);v+=cap_mean(s.nhi[idx],s.nc[idx],t,b).sum()/b;T+=len(ids)
|
|
33
|
+
lb=v/T;mu=baseline(s.B,r,b);return dict(**res,loss_true_balanced=lb,ARRS_B=1-(lb+res['loss_false'])/mu,mu_B=mu,Hoeffding95_B=res['Hoeffding95']/mu)
|
|
34
|
+
|
|
35
|
+
def aggregate_B(rows):
|
|
36
|
+
a=aggregate(rows);e=next(x for x in rows if x['motif']=='edge');mot=[x for x in rows if x['motif']!='edge' and np.isfinite(x['ARRS_B'])];sm=np.mean([x['ARRS_B'] for x in mot]) if mot else np.nan
|
|
37
|
+
return dict(**a,ARRS_B_edge=e['ARRS_B'],ARRS_B_struct=sm,ARRS_B=(e['ARRS_B']+sm)/2 if mot else np.nan,loss_true_balanced_struct=np.mean([x['loss_true_balanced'] for x in mot]) if mot else np.nan)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Exact uniform fiber sampler via independent alternating SCCs and row-margin DP."""
|
|
2
|
+
import itertools as it, math, time
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
import numpy as np
|
|
5
|
+
from scipy.sparse.csgraph import connected_components
|
|
6
|
+
from scipy.sparse import csr_matrix
|
|
7
|
+
class Limit(Exception): pass
|
|
8
|
+
class Component:
|
|
9
|
+
def __init__(self,mask,row,col,cap=12000,seconds=.2):
|
|
10
|
+
order=sorted(range(len(row)),key=lambda i:math.comb(int(mask[i].sum()),int(row[i])))
|
|
11
|
+
self.order=order;self.row=row[order];self.mask=mask[order];self.col=tuple(map(int,col));self.n=len(col);self.m=len(row)
|
|
12
|
+
self.choices=[list(it.combinations(np.flatnonzero(self.mask[i]).tolist(),int(self.row[i]))) for i in range(self.m)]
|
|
13
|
+
self.remaining=np.vstack([np.cumsum(self.mask[::-1],axis=0)[::-1],np.zeros((1,self.n),int)])
|
|
14
|
+
self.states=0;deadline=time.monotonic()+seconds
|
|
15
|
+
@lru_cache(None)
|
|
16
|
+
def count(i,c):
|
|
17
|
+
self.states+=1
|
|
18
|
+
if self.states>cap or (self.states%128==0 and time.monotonic()>deadline):raise Limit()
|
|
19
|
+
if i==self.m:return int(not any(c))
|
|
20
|
+
if any(v<0 or v>self.remaining[i,j] for j,v in enumerate(c)):return 0
|
|
21
|
+
return sum(count(i+1,cc) for _,cc in self.options(i,c))
|
|
22
|
+
self.count=count;self.total=count(0,self.col);assert self.total>0
|
|
23
|
+
def options(self,i,c):
|
|
24
|
+
mandatory={j for j,v in enumerate(c) if v>self.remaining[i+1,j]}
|
|
25
|
+
for a in self.choices[i]:
|
|
26
|
+
if not mandatory.issubset(a) or any(c[j]==0 for j in a):continue
|
|
27
|
+
cc=list(c)
|
|
28
|
+
for j in a:cc[j]-=1
|
|
29
|
+
yield a,tuple(cc)
|
|
30
|
+
def sample(self,rng):
|
|
31
|
+
y=np.zeros((self.m,self.n),np.int64);c=self.col
|
|
32
|
+
for i in range(self.m):
|
|
33
|
+
r=rng.randrange(self.count(i,c))
|
|
34
|
+
for a,cc in self.options(i,c):
|
|
35
|
+
w=self.count(i+1,cc)
|
|
36
|
+
if r<w:y[self.order[i],list(a)]=1;c=cc;break
|
|
37
|
+
r-=w
|
|
38
|
+
else:raise RuntimeError('invalid sample')
|
|
39
|
+
return y
|
|
40
|
+
def enumerate(self):
|
|
41
|
+
y=np.zeros((self.m,self.n),np.int64)
|
|
42
|
+
def recurse(i,c):
|
|
43
|
+
if i==self.m:yield y.copy();return
|
|
44
|
+
for a,cc in self.options(i,c):
|
|
45
|
+
if not self.count(i+1,cc):continue
|
|
46
|
+
y[self.order[i],:]=0;y[self.order[i],list(a)]=1
|
|
47
|
+
yield from recurse(i+1,cc)
|
|
48
|
+
yield from recurse(0,self.col)
|
|
49
|
+
class Fiber:
|
|
50
|
+
def __init__(self,x,mask,cap=12000,seconds=.2):
|
|
51
|
+
n=len(x);adj=np.zeros((2*n,2*n),np.uint8);adj[:n,n:]=x;adj[n:,:n]=(mask-x).T
|
|
52
|
+
_,lab=connected_components(csr_matrix(adj),directed=True,connection='strong');self.base=x.copy();self.components=[];self.total=1;self.states=0
|
|
53
|
+
for labid in np.unique(lab):
|
|
54
|
+
rr=np.flatnonzero(lab[:n]==labid);cc=np.flatnonzero(lab[n:]==labid)
|
|
55
|
+
if not len(rr) or not len(cc):continue
|
|
56
|
+
ix=np.ix_(rr,cc);xx=x[ix];mm=mask[ix];comp=Component(mm,xx.sum(1),xx.sum(0),cap,seconds);self.components.append((ix,comp));self.total*=comp.total;self.states+=comp.states
|
|
57
|
+
def sample(self,rng):
|
|
58
|
+
y=self.base.copy()
|
|
59
|
+
for ix,c in self.components:y[ix]=c.sample(rng)
|
|
60
|
+
return y
|
|
61
|
+
def enumerate(self):
|
|
62
|
+
y=self.base.copy()
|
|
63
|
+
def go(i):
|
|
64
|
+
if i==len(self.components):yield y.copy();return
|
|
65
|
+
ix,c=self.components[i]
|
|
66
|
+
for m in c.enumerate():y[ix]=m;yield from go(i+1)
|
|
67
|
+
yield from go(0)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
|
|
2
|
+
#include <algorithm>
|
|
3
|
+
#include <vector>
|
|
4
|
+
#include <array>
|
|
5
|
+
#include <cstdint>
|
|
6
|
+
using namespace std;
|
|
7
|
+
struct P{int v,a,h,t,p,s;};
|
|
8
|
+
struct Acc{long double d=0,f=0; long long c=0,T=0;};
|
|
9
|
+
struct E{
|
|
10
|
+
int A,B,b,z,l;const int64_t *pc,*nc,*plo,*nhi; double R[5];
|
|
11
|
+
E(int A_,int B_,int z_,int l_,const int64_t*pc_,const int64_t*nc_,const int64_t*plo_,const int64_t*nhi_):A(A_),B(B_),b(min(A,B)),z(z_),l(l_),pc(pc_),nc(nc_),plo(plo_),nhi(nhi_){R[0]=1;for(int h=1;h<=4;h++)R[h]=(h<=l&&h<=nc[z])?R[h-1]*(l-h+1)/double(nc[z]-h+1):0;}
|
|
12
|
+
void add(Acc&o,int v,int a,int h,int t,int p,long long c,int rsize=4)const{
|
|
13
|
+
if(!c)return;o.c+=c;
|
|
14
|
+
if(a==rsize){o.T+=c;double j=nhi[v],m=nc[v],d=min(max(0.,b-j),m),r=1;for(int i=1;i<=t;i++)r*=(d+i)/(m+i);o.d+=(long double)c*(min(j,double(b))+d-d/(t+1)*r)/b;}
|
|
15
|
+
else if(a<A){double f=(plo[v]+(pc[v]-p)/double(t+1))/(A-a);
|
|
16
|
+
if(h&&v==z){double q=1;for(int i=1;i<=p+1;i++)q*=(double(l)+i)/(nc[z]+i);f=(plo[z]+(pc[z]-p)*(1-h/double(h+p+1)*q)/(p+1))/(A-a);}
|
|
17
|
+
o.f+=(long double)c*f*R[h];}
|
|
18
|
+
}
|
|
19
|
+
void pair(Acc&o,P x,P y,long long c)const{if(x.v>y.v)swap(x,y);add(o,x.v,x.a+y.a,x.h+y.h,x.t+(x.v==y.v?y.t:0),x.p+(x.v==y.v?y.p:0),c);}
|
|
20
|
+
};
|
|
21
|
+
int code(P p){return ((p.a*3+p.h)*3+p.t)*3+p.p;}
|
|
22
|
+
void aggregate(vector<P>&v,bool cross,const E&e,Acc&o){
|
|
23
|
+
if(v.size()<2)return;
|
|
24
|
+
sort(v.begin(),v.end(),[](P a,P b){return a.v<b.v;});
|
|
25
|
+
long long suffix[2][3][3]={};for(P p:v)suffix[p.s][p.a][p.h]++;
|
|
26
|
+
for(size_t i=0,j;i<v.size();i=j){
|
|
27
|
+
j=i+1;while(j<v.size()&&v[j].v==v[i].v)j++;
|
|
28
|
+
long long cnt[2][81]={};P groups[2][81];int ng[2]={};
|
|
29
|
+
for(size_t k=i;k<j;k++){P p=v[k];suffix[p.s][p.a][p.h]--;int c=code(p);if(!cnt[p.s][c]++)groups[p.s][ng[p.s]++]=p;}
|
|
30
|
+
for(int s=0;s<(cross?2:1);s++)for(int k=0;k<ng[s];k++){P x=groups[s][k];long long c=cnt[s][code(x)];int other=cross?1-s:0;
|
|
31
|
+
for(int a=0;a<=2;a++)for(int h=0;h<=2-a;h++)if(suffix[other][a][h])e.add(o,x.v,x.a+a,x.h+h,x.t,x.p,c*suffix[other][a][h]);}
|
|
32
|
+
if(cross){for(int k=0;k<ng[0];k++)for(int m=0;m<ng[1];m++){P x=groups[0][k],y=groups[1][m];e.pair(o,x,y,cnt[0][code(x)]*cnt[1][code(y)]);}}
|
|
33
|
+
else{for(int k=0;k<ng[0];k++)for(int m=k;m<ng[0];m++){P x=groups[0][k],y=groups[0][m];long long c=cnt[0][code(x)],d=cnt[0][code(y)];e.pair(o,x,y,k==m?c*(c-1)/2:c*d);}}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
extern "C" void grouped(int n,int rows,const int32_t*rank,const uint8_t*lab,const uint8_t*active,int A,int B,int z,int l,const int64_t*pc,const int64_t*nc,const int64_t*plo,const int64_t*nhi,int motif,double*out){
|
|
37
|
+
E e(A,B,z,l,pc,nc,plo,nhi);Acc o;vector<vector<int>> adj(n),inc(n);
|
|
38
|
+
for(int u=0;u<rows;u++)for(int v=0;v<n;v++)if(active[u*n+v]){adj[u].push_back(v);inc[v].push_back(u);}
|
|
39
|
+
auto part=[&](int u,int v,int a,int b,int s){int i=u*n+v,j=a*n+b,r=rank[i],q=rank[j],m=min(r,q);return P{m,lab[i]+lab[j],(r==z&&!lab[i])+(q==z&&!lab[j]),(r==m)+(q==m),(r==m&&lab[i])+(q==m&&lab[j]),s};};
|
|
40
|
+
vector<P> v;vector<int>x,y;long long parts=0,pairs=0;
|
|
41
|
+
for(int u=0;u<rows;u++)for(int t=u+1;t<rows;t++){
|
|
42
|
+
if(adj[u].empty()||adj[t].empty())continue;x.clear();y.clear();v.clear();
|
|
43
|
+
if(!motif){set_intersection(adj[u].begin(),adj[u].end(),adj[t].begin(),adj[t].end(),back_inserter(x));if(x.size()<2)continue;for(int k:x)v.push_back(part(u,k,t,k,0));aggregate(v,false,e,o);}
|
|
44
|
+
else{if(inc[u].empty()||inc[t].empty())continue;set_intersection(adj[u].begin(),adj[u].end(),inc[t].begin(),inc[t].end(),back_inserter(x));set_intersection(adj[t].begin(),adj[t].end(),inc[u].begin(),inc[u].end(),back_inserter(y));if(x.empty()||y.empty())continue;
|
|
45
|
+
for(int k:x)v.push_back(part(u,k,k,t,0));for(int k:y)v.push_back(part(t,k,k,u,1));aggregate(v,true,e,o);
|
|
46
|
+
size_t i=0,j=0;while(i<x.size()&&j<y.size()){if(x[i]<y[j])i++;else if(x[i]>y[j])j++;else{int k=x[i];e.pair(o,part(u,k,k,t,0),part(t,k,k,u,1),-1);i++;j++;}}}
|
|
47
|
+
parts+=v.size();pairs++;
|
|
48
|
+
}
|
|
49
|
+
int scale=motif?2:1;out[0]=double(o.d/scale);out[1]=double(o.f/scale);out[2]=double(o.c)/scale;out[3]=double(o.T)/scale;out[4]=parts;out[5]=pairs;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
extern "C" void simple(int n,int rows,const int32_t*rank,const uint8_t*lab,const uint8_t*active,int A,int B,int z,int l,const int64_t*pc,const int64_t*nc,const int64_t*plo,const int64_t*nhi,int motif,double*out){
|
|
53
|
+
E e(A,B,z,l,pc,nc,plo,nhi);Acc o;vector<vector<int>> adj(n);
|
|
54
|
+
for(int u=0;u<rows;u++)for(int v=0;v<n;v++)if(active[u*n+v])adj[u].push_back(v);
|
|
55
|
+
auto add=[&](int i,int j,int k){
|
|
56
|
+
int a=0,h=0,t=0,p=0,v=min(rank[i],rank[j]),r=k<0?2:3;
|
|
57
|
+
if(k>=0)v=min(v,rank[k]);
|
|
58
|
+
for(int x:{i,j,k})if(x>=0){a+=lab[x];h+=(rank[x]==z&&!lab[x]);t+=(rank[x]==v);p+=(rank[x]==v&&lab[x]);}
|
|
59
|
+
e.add(o,v,a,h,t,p,1,r);
|
|
60
|
+
};
|
|
61
|
+
for(int u=0;u<rows;u++)for(int v:adj[u]){
|
|
62
|
+
if(v>=rows)continue;
|
|
63
|
+
if(motif==1){if(u<v&&active[v*n+u])add(u*n+v,v*n+u,-1);}
|
|
64
|
+
else if(motif==2){if(u<v)for(int w:adj[v])if(w>u&&w<rows&&active[w*n+u])add(u*n+v,v*n+w,w*n+u);}
|
|
65
|
+
else for(int w:adj[v])if(active[u*n+w])add(u*n+v,v*n+w,u*n+w);
|
|
66
|
+
}
|
|
67
|
+
out[0]=o.d;out[1]=o.f;out[2]=o.c;out[3]=o.T;out[4]=0;out[5]=0;
|
|
68
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Exact dense bounded backend; rectangular source rows or arbitrary square mask."""
|
|
2
|
+
import math, os, pathlib, tempfile, hashlib, subprocess, ctypes as C, sys, functools, shutil
|
|
3
|
+
import numpy as np
|
|
4
|
+
from scipy.stats import hypergeom
|
|
5
|
+
from threadpoolctl import threadpool_limits
|
|
6
|
+
from .absolute import TYPES,TEMPLATES
|
|
7
|
+
from .arrs_v2 import mu_parts,cutoff,result,losses
|
|
8
|
+
from .balanced import cap_mean
|
|
9
|
+
MOT=TYPES[1:]; RS=[len(TEMPLATES[m][1]) for m in MOT]
|
|
10
|
+
I24=np.array([[24,0,0,0,0],[-50,96,-72,32,-6],[35,-104,114,-56,11],[-10,36,-48,28,-6],[1,-4,6,-4,1]],dtype=np.int64)
|
|
11
|
+
|
|
12
|
+
def universe_counts(n,t):
|
|
13
|
+
return [t*(t-1)*(n-2), math.comb(t,2), math.perm(t,3)//3, math.perm(t,4)//4, math.comb(t,2)*math.comb(n-2,2)]
|
|
14
|
+
|
|
15
|
+
def counts(W):
|
|
16
|
+
# TFs are first t columns, source rows match their target indices.
|
|
17
|
+
t,n=W.shape
|
|
18
|
+
# Conservative bound for intermediate sums of products with weights <=4.
|
|
19
|
+
if 4**4 * max(1,t*t*n*n,t**4)*4 >= 2**53: raise ValueError('integer exactness guard exceeded')
|
|
20
|
+
Q=W[:,:t]; B=Q@Q; R=Q*Q.T; r=R.sum(1)
|
|
21
|
+
Z=W@W.T; W2=W*W; S=W2@W2.T
|
|
22
|
+
raw=np.array([((Q@W)*W).sum(),R.sum()/2,(B*Q.T).sum()/3,((B*B.T).sum()-2*(r*r).sum()+(R*R).sum())/4,np.triu(Z*Z-S,1).sum()/2])
|
|
23
|
+
if np.any(raw!=np.rint(raw)) or np.any(raw<0):raise AssertionError(raw)
|
|
24
|
+
return raw.astype(np.int64)
|
|
25
|
+
|
|
26
|
+
def hist(base,marked):
|
|
27
|
+
vals=np.stack([counts(base+i*marked) for i in range(5)])
|
|
28
|
+
if np.max(vals)>np.iinfo(np.int64).max//300:raise ValueError('interpolation overflow guard')
|
|
29
|
+
h=I24@vals
|
|
30
|
+
if np.any(h%24) or np.any(h<0):raise AssertionError('invalid integer coefficients')
|
|
31
|
+
out=(h//24).T
|
|
32
|
+
if np.any(out.sum(1)!=counts(base+marked)):raise AssertionError('histogram sum')
|
|
33
|
+
return out
|
|
34
|
+
|
|
35
|
+
def incl(N,k,r):
|
|
36
|
+
if r==0:return 1.
|
|
37
|
+
if r>k or r>N:return 0.
|
|
38
|
+
return math.prod((k-i)/(N-i) for i in range(r))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BackendLimit(ValueError): pass
|
|
42
|
+
|
|
43
|
+
def guard(t,n,max_bytes):
|
|
44
|
+
if not (0<t<=n): raise ValueError("invalid shape")
|
|
45
|
+
if t*n>2**31-1 or 4**4*max(1,t*t*n*n,t**4)*4>=2**53:
|
|
46
|
+
raise BackendLimit("integer exactness/index guard exceeded")
|
|
47
|
+
# Conservative estimate for dense input, unique/histogram and BLAS temporaries.
|
|
48
|
+
# Not a measured or guaranteed RSS bound.
|
|
49
|
+
if 160*t*n+64*t*t>max_bytes: raise BackendLimit("dense workspace estimate exceeds budget")
|
|
50
|
+
|
|
51
|
+
def _native_flags(platform, windows):
|
|
52
|
+
if windows:
|
|
53
|
+
# Native MinGW-w64 GCC: prefer static compiler runtimes. The output
|
|
54
|
+
# remains a shared DLL, not a static archive.
|
|
55
|
+
return ".dll", ["-shared", "-static", "-static-libgcc", "-static-libstdc++"]
|
|
56
|
+
if platform == "darwin":
|
|
57
|
+
return ".dylib", ["-dynamiclib"]
|
|
58
|
+
return ".so", ["-shared", "-fPIC"]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _load_native_library(dest, compiler, windows):
|
|
62
|
+
# Python 3.8+ uses an explicit DLL search policy on Windows. Merely
|
|
63
|
+
# having the MinGW bin directory on PATH need not resolve dependencies.
|
|
64
|
+
try:
|
|
65
|
+
if windows:
|
|
66
|
+
compiler_path = shutil.which(compiler)
|
|
67
|
+
if compiler_path:
|
|
68
|
+
with os.add_dll_directory(str(pathlib.Path(compiler_path).resolve().parent)):
|
|
69
|
+
return C.CDLL(str(dest))
|
|
70
|
+
return C.CDLL(str(dest))
|
|
71
|
+
except OSError as exc:
|
|
72
|
+
raise RuntimeError(
|
|
73
|
+
f"Cannot load grnmetrics native library {dest}; exists={dest.is_file()}; "
|
|
74
|
+
f"compiler={compiler!r}; Python={C.sizeof(C.c_void_p)*8}-bit. "
|
|
75
|
+
"On Windows use a native MinGW-w64 g++ matching Python's architecture, "
|
|
76
|
+
"not an MSYS/Cygwin compiler. Check dependent DLLs and the compiler bin directory. "
|
|
77
|
+
"For small supported problems, backend='legacy' is an alternative."
|
|
78
|
+
) from exc
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@functools.lru_cache(maxsize=1)
|
|
82
|
+
def native():
|
|
83
|
+
src=pathlib.Path(__file__).with_name("grouped.cpp").resolve()
|
|
84
|
+
compiler=os.environ.get("CXX","g++")
|
|
85
|
+
compiler=shutil.which(compiler) or compiler
|
|
86
|
+
ext,flags=_native_flags(sys.platform,os.name=="nt")
|
|
87
|
+
tag=hashlib.sha256(src.read_bytes()+repr((compiler,flags,sys.platform)).encode()).hexdigest()[:20]
|
|
88
|
+
folder=pathlib.Path(os.environ.get("GRNMETRICS_CACHE",str(pathlib.Path.home()/".cache/grnmetrics"))).expanduser().resolve()
|
|
89
|
+
folder.mkdir(parents=True,exist_ok=True); dest=folder/("grouped-"+tag+ext)
|
|
90
|
+
if not dest.exists():
|
|
91
|
+
with tempfile.TemporaryDirectory(dir=folder) as td:
|
|
92
|
+
tmp=pathlib.Path(td)/dest.name
|
|
93
|
+
try:
|
|
94
|
+
subprocess.run([compiler,"-O3","-std=c++17",*flags,str(src),"-o",str(tmp)],check=True,capture_output=True,text=True,errors="replace")
|
|
95
|
+
except FileNotFoundError as exc:
|
|
96
|
+
raise RuntimeError(f"C++17 compiler {compiler!r} not found. Set CXX to its executable path.") from exc
|
|
97
|
+
except subprocess.CalledProcessError as exc:
|
|
98
|
+
raise RuntimeError(f"Failed to compile grouped native library with {compiler!r}:\n{exc.stderr}") from exc
|
|
99
|
+
os.replace(tmp,dest)
|
|
100
|
+
lib=_load_native_library(dest,compiler,os.name=="nt")
|
|
101
|
+
for f in (lib.grouped,lib.simple):
|
|
102
|
+
f.argtypes=[C.c_int,C.c_int]+[C.c_void_p]*3+[C.c_int]*4+[C.c_void_p]*4+[C.c_int,C.c_void_p]
|
|
103
|
+
f.restype=None
|
|
104
|
+
return lib
|
|
105
|
+
|
|
106
|
+
def inputs(P,K,S,max_bytes):
|
|
107
|
+
P=np.asarray(P);K=np.asarray(K);S=np.asarray(S)
|
|
108
|
+
if P.ndim!=2 or P.shape!=K.shape or P.shape!=S.shape: raise ValueError("invalid shapes")
|
|
109
|
+
t,n=P.shape;guard(t,n,max_bytes)
|
|
110
|
+
if not np.isin(P,[0,1]).all() or not np.isin(K,[0,1]).all():raise ValueError("masks must be binary")
|
|
111
|
+
P=P.astype(bool);K=K.astype(bool);S=S.astype(float)
|
|
112
|
+
if np.any(np.diag(K[:,:t])) or np.any(P&~K) or not np.isfinite(S[K]).all():raise ValueError("invalid mask or scores")
|
|
113
|
+
A=int(P.sum());B=int(K.sum())-A
|
|
114
|
+
if not A or not B:raise ValueError("both classes required")
|
|
115
|
+
vals,iv=np.unique(S[K],return_inverse=True);y=P[K]
|
|
116
|
+
pc=np.bincount(iv[y],minlength=len(vals)).astype(np.int64)
|
|
117
|
+
nc=np.bincount(iv[~y],minlength=len(vals)).astype(np.int64)
|
|
118
|
+
return P,K,S,A,B,vals,iv,pc,nc
|
|
119
|
+
|
|
120
|
+
def data_arrays(d,max_bytes):
|
|
121
|
+
guard(d.n,d.n,max_bytes)
|
|
122
|
+
P=np.zeros((d.n,d.n),bool);K=~np.eye(d.n,dtype=bool);S=np.zeros(P.shape)
|
|
123
|
+
for u,v in d.ref:P[u,v]=True
|
|
124
|
+
for (u,v),s in d.scores.items():S[u,v]=s
|
|
125
|
+
return P,K,S
|
|
126
|
+
|
|
127
|
+
def arrs_rows(P,K,S,max_bytes=512*1024**2):
|
|
128
|
+
P,K,S,A,B,vals,iv,pc,nc=inputs(P,K,S,max_bytes)
|
|
129
|
+
t,n=P.shape;plo=np.cumsum(pc)-pc;nhi=B-np.cumsum(nc);b=min(A,B);z,l=cutoff(nc,nhi,b)
|
|
130
|
+
with threadpool_limits(limits=1,user_api="blas"):
|
|
131
|
+
H=hist((K&~P).astype(float),P.astype(float))
|
|
132
|
+
u,w=mu_parts(A,B,[B,A])
|
|
133
|
+
levels=np.flatnonzero(nc);_,ef=losses(levels[:,None],np.zeros((len(levels),1),bool),pc,nc,plo,nhi,A,B,z,l)
|
|
134
|
+
rows=[result("edge",A,float(np.dot(pc,cap_mean(nhi,nc,1,b))/A/b),float(nc[levels]@ef/A),u,w,mode="exact_grouped",draws=1,SE=0.)]
|
|
135
|
+
rank=np.zeros(P.shape,np.int32);rank[K]=iv
|
|
136
|
+
active=P|(K&(rank>=z));skip=z<np.flatnonzero(pc)[0]
|
|
137
|
+
if skip:active=P|(K&(rank>z))
|
|
138
|
+
lab=np.ascontiguousarray(P,dtype=np.uint8);active=np.ascontiguousarray(active,dtype=np.uint8)
|
|
139
|
+
lib=native() if len(vals)>1 else None
|
|
140
|
+
for j,(m,r) in enumerate(zip(MOT,RS)):
|
|
141
|
+
h=H[j,:r+1].tolist();T=h[-1]
|
|
142
|
+
if not T or not sum(h[:-1]):continue
|
|
143
|
+
u,w=mu_parts(A,B,h)
|
|
144
|
+
if len(vals)==1:p,f=u,w
|
|
145
|
+
else:
|
|
146
|
+
res=np.zeros(6);idx={"bifan":0,"cycle4":1,"FFL":0,"cycle2":1,"cycle3":2}[m]
|
|
147
|
+
fn=lib.grouped if m in ("bifan","cycle4") else lib.simple
|
|
148
|
+
fn(n,t,rank.ctypes.data,lab.ctypes.data,active.ctypes.data,A,B,z,l,pc.ctypes.data,nc.ctypes.data,plo.ctypes.data,nhi.ctypes.data,idx,res.ctypes.data)
|
|
149
|
+
if not np.isfinite(res).all() or res[3]!=T or res[0]<-1e-8 or res[1]<-1e-8:raise ArithmeticError("grouped count/loss audit failed")
|
|
150
|
+
p,f=res[:2]/T
|
|
151
|
+
rows.append(result(m,T,float(p),float(f),u,w,mode="exact_grouped",draws=1,SE=0.))
|
|
152
|
+
return rows
|
|
153
|
+
|
|
154
|
+
def crrs_moments(P,K,S,k=None,max_bytes=512*1024**2):
|
|
155
|
+
P,K,S,A,B,vals,iv,pc,nc=inputs(P,K,S,max_bytes)
|
|
156
|
+
k=A if k is None else int(k)
|
|
157
|
+
if not 0<k<=A+B:raise ValueError("invalid budget")
|
|
158
|
+
i=len(vals)-1-int(np.searchsorted(np.cumsum((pc+nc)[::-1]),k));cut=vals[i]
|
|
159
|
+
hi=K&(S>cut);tie=K&(S==cut);nt=int(tie.sum());ell=k-int(hi.sum());pt=int((tie&P).sum());q0=int((hi&P).sum())
|
|
160
|
+
qv=np.arange(max(0,ell-(nt-pt)),min(ell,pt)+1);w=hypergeom.pmf(qv,nt,pt,ell);w/=w.sum()
|
|
161
|
+
with threadpool_limits(limits=1,user_api="blas"):
|
|
162
|
+
H=hist((K&~P).astype(float),P.astype(float))
|
|
163
|
+
HT=hist(hi.astype(float),tie.astype(float));HP=hist((hi&P).astype(float),(tie&P).astype(float))
|
|
164
|
+
le=[];lo=[]
|
|
165
|
+
for j,r in enumerate(RS):
|
|
166
|
+
h=H[j,:r+1];T=int(h[-1]);pinc=np.array([incl(nt,ell,a) for a in range(r+1)])
|
|
167
|
+
tot=float(HT[j,:r+1]@pinc);tp=float(HP[j,:r+1]@pinc)
|
|
168
|
+
lo.append(T+tot-2*tp)
|
|
169
|
+
le.append(sum(prob*(T*(1-incl(A,q0+int(x),r))+sum(int(h[a])*incl(A,q0+int(x),a)*incl(B,k-q0-int(x),r-a) for a in range(r))) for x,prob in zip(qv,w)))
|
|
170
|
+
return np.maximum(le,0),np.maximum(lo,0),dict(k=k,cut=float(cut),tie_size=nt,tie_selected=ell,A=A,B=B,TP_expected=q0+ell*pt/nt)
|