ProseGuard-ML / rust_src /src /cooccur_graph.rs
ElderRyan's picture
Release ProseGuard-ML
99fb72f verified
Raw History Blame Contribute Delete
5.56 kB
//! Word & Ideographic Bigram Co-occurrence Complex Network Topology (`cooccur_graph`).
//!
//! Basis: Models lexical adjacency inside a single document as a bounded undirected graph
//! $G = (V, E)$ ($|V| \le 384$) and extracts topological invariants (local clustering coefficient,
//! Newman degree assortativity, edge density, and hub dominance) invariant to synonym substitution.
use std::collections::{BTreeMap, BTreeSet};
/// Topological invariants of a document's lexical co-occurrence graph.
#[derive(Debug, Clone, Copy)]
pub struct CooccurGraphMetrics {
/// Watts-Strogatz mean local clustering coefficient $C \in [0, 1]$.
pub clustering_coeff: f64,
/// Newman degree assortativity coefficient $r \in [-1, 1]$.
pub degree_assortativity: f64,
/// Undirected edge-to-vertex ratio $|E| / |V|$.
pub edge_density: f64,
/// Maximum node degree divided by mean node degree $\max_v d_v / \bar{d}$.
pub hub_dominance: f64,
}
impl Default for CooccurGraphMetrics {
fn default() -> Self {
Self {
clustering_coeff: 0.12,
degree_assortativity: -0.05,
edge_density: 1.5,
hub_dominance: 2.5,
}
}
}
/// Builds a bounded co-occurrence network (window radius 2, up to `384` unique content tokens)
/// and computes its four structural invariants in deterministic $O(N)$ time.
#[must_use]
pub fn analyze_cooccurrence_graph(tokens: &[String]) -> CooccurGraphMetrics {
const MAX_NODES: usize = 384;
if tokens.len() < 6 {
return CooccurGraphMetrics::default();
}
let mut vocab: BTreeMap<&str, usize> = BTreeMap::new();
let mut seq: Vec<usize> = Vec::with_capacity(tokens.len().min(2_400));
for tok in tokens.iter().take(2_400) {
if tok.chars().count() < 2 {
continue;
}
let next_id = vocab.len();
let node_id = if let Some(&existing) = vocab.get(tok.as_str()) {
existing
} else if next_id < MAX_NODES {
vocab.insert(tok.as_str(), next_id);
next_id
} else {
continue;
};
seq.push(node_id);
}
let v_count = vocab.len();
if v_count < 5 || seq.len() < 5 {
return CooccurGraphMetrics::default();
}
let mut adj: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); v_count];
let mut edges: Vec<(usize, usize)> = Vec::new();
for (idx, &u) in seq.iter().enumerate() {
for step in 1..=2usize {
let Some(&v) = seq.get(idx + step) else {
continue;
};
if u == v {
continue;
}
let (a, b) = if u < v { (u, v) } else { (v, u) };
let inserted = if let Some(neighbors) = adj.get_mut(a) {
neighbors.insert(b)
} else {
false
};
if inserted {
if let Some(neighbors_b) = adj.get_mut(b) {
neighbors_b.insert(a);
}
edges.push((a, b));
}
}
}
if edges.is_empty() {
return CooccurGraphMetrics::default();
}
let degrees: Vec<usize> = adj.iter().map(BTreeSet::len).collect();
let mean_deg = (degrees.iter().copied().sum::<usize>() as f64) / (v_count as f64);
let max_deg = degrees.iter().copied().max().unwrap_or(1) as f64;
let hub_dominance = max_deg / mean_deg.max(0.5);
let edge_density = (edges.len() as f64) / (v_count as f64);
let clustering_coeff = compute_mean_clustering(&adj);
let degree_assortativity = compute_assortativity(&edges, &degrees);
CooccurGraphMetrics {
clustering_coeff,
degree_assortativity,
edge_density,
hub_dominance,
}
}
fn compute_mean_clustering(adj: &[BTreeSet<usize>]) -> f64 {
let mut sum_c = 0.0f64;
let mut eligible = 0usize;
for neighbors in adj {
let k = neighbors.len();
if !(2..=48).contains(&k) {
continue;
}
let nb_vec: Vec<usize> = neighbors.iter().copied().collect();
let mut triangles = 0usize;
for (i, &u) in nb_vec.iter().enumerate() {
let Some(u_set) = adj.get(u) else {
continue;
};
for &w in nb_vec.get(i + 1..).unwrap_or(&[]) {
if u_set.contains(&w) {
triangles = triangles.saturating_add(1);
}
}
}
let possible = k * (k - 1) / 2;
if possible > 0 {
sum_c += (triangles as f64) / (possible as f64);
eligible = eligible.saturating_add(1);
}
}
if eligible == 0 {
0.0
} else {
(sum_c / (eligible as f64)).clamp(0.0, 1.0)
}
}
fn compute_assortativity(edges: &[(usize, usize)], degrees: &[usize]) -> f64 {
if edges.len() < 3 {
return 0.0;
}
let m = edges.len() as f64;
let mut sum_jk = 0.0f64;
let mut sum_j_plus_k = 0.0f64;
let mut sum_j2_plus_k2 = 0.0f64;
for &(u, v) in edges {
let j = degrees.get(u).copied().unwrap_or(1) as f64;
let k = degrees.get(v).copied().unwrap_or(1) as f64;
sum_jk += j * k;
sum_j_plus_k += 0.5 * (j + k);
sum_j2_plus_k2 += 0.5 * (j * j + k * k);
}
let mean_half = sum_j_plus_k / m;
let sq_term = mean_half * mean_half;
let num = (sum_jk / m) - sq_term;
let den = (sum_j2_plus_k2 / m) - sq_term;
if den.abs() <= 1e-9 {
0.0
} else {
(num / den).clamp(-1.0, 1.0)
}
}