JSPM

prime-radiant-advanced-wasm

0.1.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 575
  • Score
    100M100P100Q108859F
  • License MIT OR Apache-2.0

Advanced mathematical AI interpretability: Category Theory, Homotopy Type Theory, Spectral Analysis, Causal Inference, Quantum Topology, and Sheaf Cohomology for WebAssembly. Implements functorial retrieval, univalence axioms, Cheeger bounds, do-calculus, persistent homology, and coboundary operators.

Package Exports

  • prime-radiant-advanced-wasm
  • prime-radiant-advanced-wasm/prime_radiant_advanced_wasm.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (prime-radiant-advanced-wasm) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

prime-radiant-advanced-wasm

npm version License WebAssembly TypeScript

Advanced mathematical frameworks for AI interpretability, memory coherence, and neural network analysis — compiled to WebAssembly for high-performance browser and Node.js execution.

Introduction

Prime-Radiant Advanced WASM brings cutting-edge mathematical foundations to JavaScript/TypeScript applications. Built in Rust and compiled to WebAssembly, it provides 6 powerful mathematical engines for:

  • AI Interpretability — Understand and verify neural network behavior
  • Memory Coherence — Ensure consistent retrieval in RAG systems
  • Causal Reasoning — Perform interventions and counterfactual analysis
  • Topological Analysis — Detect structural patterns and anomalies

Features

Engine Mathematical Foundation Use Cases
CohomologyEngine Sheaf Cohomology, Coboundary Operators Memory coherence validation, attention analysis
SpectralEngine Eigenvalues, Cheeger Constants, Lanczos Collapse prediction, graph clustering
CausalEngine Do-Calculus, SCMs, Counterfactuals Causal inference, intervention analysis
QuantumEngine Persistent Homology, Betti Numbers Topological data analysis, pattern detection
CategoryEngine Functors, Natural Transformations Type-safe transformations, compositional AI
HottEngine Homotopy Type Theory, Univalence Formal verification, proof transport

Installation

npm install prime-radiant-advanced-wasm

Quick Start

import init, {
  CohomologyEngine,
  SpectralEngine,
  CausalEngine,
  QuantumEngine,
  CategoryEngine,
  HottEngine
} from 'prime-radiant-advanced-wasm';

// Initialize WASM module
await init();

// Create engines
const cohomology = new CohomologyEngine(128);  // 128-dimensional embeddings
const spectral = new SpectralEngine();
const causal = new CausalEngine();
const quantum = new QuantumEngine();
const category = new CategoryEngine();
const hott = new HottEngine();

API Reference

CohomologyEngine

Sheaf cohomology for memory coherence analysis.

Method Description Returns
new CohomologyEngine(dim) Create engine with embedding dimension CohomologyEngine
add_node(id, embedding) Add a node with vector embedding void
add_edge(source, target, weight) Connect nodes with weighted edge void
compute_coboundary(chain) Compute coboundary operator δ Float64Array
compute_cohomology_dimension(degree) Get Betti number for degree number
sheaf_laplacian_energy() Compute total coherence energy number

SpectralEngine

Eigenvalue analysis and collapse prediction.

Method Description Returns
new SpectralEngine() Create spectral analyzer SpectralEngine
add_node(id) Add graph node void
add_edge(source, target, weight) Add weighted edge void
compute_fiedler_value() Get algebraic connectivity λ₂ number
compute_cheeger_constant() Get Cheeger constant h(G) number
predict_collapse_risk() Collapse risk score [0,1] number
get_spectral_gap() Gap between λ₁ and λ₂ number

CausalEngine

Causal inference with do-calculus.

Method Description Returns
new CausalEngine() Create causal model CausalEngine
add_variable(name, is_observed) Add variable to SCM void
add_causal_edge(cause, effect) Add causal relationship void
do_intervention(variable, value) Perform do(X=x) void
compute_ate(treatment, outcome) Average Treatment Effect number
is_identifiable(treatment, outcome) Check if effect is identifiable boolean
get_adjustment_set(treatment, outcome) Get backdoor adjustment set string[]

QuantumEngine

Topological data analysis and persistent homology.

Method Description Returns
new QuantumEngine() Create quantum/topology engine QuantumEngine
add_point(coordinates) Add point to point cloud void
compute_persistence(max_dim) Compute persistence diagram PersistencePair[]
get_betti_numbers(threshold) Get Betti numbers at scale number[]
compute_bottleneck_distance(other) Distance between diagrams number

CategoryEngine

Category theory for compositional transformations.

Method Description Returns
new CategoryEngine() Create category CategoryEngine
add_object(name) Add object to category void
add_morphism(name, source, target) Add morphism (arrow) void
compose(f, g) Compose morphisms g ∘ f string
identity(object) Get identity morphism string
is_isomorphism(morphism) Check if invertible boolean

HottEngine

Homotopy Type Theory for formal verification.

Method Description Returns
new HottEngine() Create HoTT environment HottEngine
define_type(name, definition) Define a type void
check_type(term, expected_type) Type check a term boolean
transport(path, point) Transport along path Term
path_induction(path, base_case) Apply J-eliminator Term
univalence(equiv) Apply univalence axiom Path

Tutorials

Tutorial 1: Memory Coherence Validation

Validate that retrieved documents in a RAG system are semantically coherent:

import init, { CohomologyEngine } from 'prime-radiant-advanced-wasm';

await init();

// Create coherence validator for 768-dim embeddings (e.g., sentence-transformers)
const coherence = new CohomologyEngine(768);

// Add retrieved documents as nodes
const docs = [
  { id: 'doc1', embedding: embed("The capital of France is Paris.") },
  { id: 'doc2', embedding: embed("Paris is known for the Eiffel Tower.") },
  { id: 'doc3', embedding: embed("Python is a programming language.") }  // outlier!
];

docs.forEach(doc => coherence.add_node(doc.id, doc.embedding));

// Connect documents based on retrieval order
coherence.add_edge('doc1', 'doc2', 0.9);  // high similarity
coherence.add_edge('doc2', 'doc3', 0.2);  // low similarity (incoherent!)

// Compute coherence energy (lower = more coherent)
const energy = coherence.sheaf_laplacian_energy();
console.log(`Coherence energy: ${energy}`);  // High energy indicates inconsistency

// Check cohomological obstruction
const h1 = coherence.compute_cohomology_dimension(1);
console.log(`H¹ dimension: ${h1}`);  // Non-zero indicates "holes" in coherence

Tutorial 2: Collapse Prediction

Detect when a system is approaching instability:

import init, { SpectralEngine } from 'prime-radiant-advanced-wasm';

await init();

const spectral = new SpectralEngine();

// Build interaction graph (e.g., agent communication network)
['agent1', 'agent2', 'agent3', 'agent4'].forEach(id => spectral.add_node(id));

spectral.add_edge('agent1', 'agent2', 1.0);
spectral.add_edge('agent2', 'agent3', 1.0);
spectral.add_edge('agent3', 'agent4', 1.0);
spectral.add_edge('agent4', 'agent1', 1.0);  // ring topology

// Analyze stability
const fiedler = spectral.compute_fiedler_value();
const cheeger = spectral.compute_cheeger_constant();
const risk = spectral.predict_collapse_risk();

console.log(`Fiedler value (λ₂): ${fiedler}`);  // Low = weak connectivity
console.log(`Cheeger constant: ${cheeger}`);     // Low = easy to partition
console.log(`Collapse risk: ${(risk * 100).toFixed(1)}%`);

// Cheeger inequality: λ₂/2 ≤ h(G) ≤ √(2λ₂)
if (risk > 0.7) {
  console.warn('High collapse risk detected! Consider adding redundant connections.');
}

Tutorial 3: Causal Inference

Determine causal effects with do-calculus:

import init, { CausalEngine } from 'prime-radiant-advanced-wasm';

await init();

const causal = new CausalEngine();

// Define variables in the causal model
causal.add_variable('Treatment', true);   // observed
causal.add_variable('Outcome', true);     // observed
causal.add_variable('Confounder', true);  // observed
causal.add_variable('Mediator', true);    // observed

// Define causal structure (DAG)
causal.add_causal_edge('Confounder', 'Treatment');
causal.add_causal_edge('Confounder', 'Outcome');
causal.add_causal_edge('Treatment', 'Mediator');
causal.add_causal_edge('Mediator', 'Outcome');

// Check if causal effect is identifiable
const identifiable = causal.is_identifiable('Treatment', 'Outcome');
console.log(`Effect identifiable: ${identifiable}`);  // true

// Get adjustment set for backdoor criterion
const adjustmentSet = causal.get_adjustment_set('Treatment', 'Outcome');
console.log(`Adjust for: ${adjustmentSet}`);  // ['Confounder']

// Perform intervention do(Treatment=1)
causal.do_intervention('Treatment', 1.0);

// Compute Average Treatment Effect
const ate = causal.compute_ate('Treatment', 'Outcome');
console.log(`ATE: ${ate}`);

Tutorial 4: Topological Pattern Detection

Find persistent structural patterns in data:

import init, { QuantumEngine } from 'prime-radiant-advanced-wasm';

await init();

const tda = new QuantumEngine();

// Add points (e.g., embedding vectors reduced to 2D/3D)
const points = [
  [0, 0], [1, 0], [0.5, 0.866],  // triangle
  [3, 0], [4, 0], [3.5, 0.866],  // another triangle
  [1.5, 0.433]  // bridge point
];

points.forEach(p => tda.add_point(new Float64Array(p)));

// Compute persistent homology up to dimension 1
const persistence = tda.compute_persistence(1);

console.log('Persistence pairs (birth, death):');
persistence.forEach(pair => {
  const lifetime = pair.death - pair.birth;
  console.log(`  H${pair.dimension}: [${pair.birth.toFixed(2)}, ${pair.death.toFixed(2)}] (lifetime: ${lifetime.toFixed(2)})`);
});

// Get Betti numbers at a specific scale
const betti = tda.get_betti_numbers(0.5);
console.log(`Betti numbers at ε=0.5: β₀=${betti[0]}, β₁=${betti[1]}`);
// β₀ = connected components, β₁ = 1-dimensional holes (loops)

Tutorial 5: Compositional Transformations

Build type-safe transformation pipelines:

import init, { CategoryEngine } from 'prime-radiant-advanced-wasm';

await init();

const cat = new CategoryEngine();

// Define objects (types)
cat.add_object('RawText');
cat.add_object('Tokens');
cat.add_object('Embeddings');
cat.add_object('Attention');
cat.add_object('Output');

// Define morphisms (transformations)
cat.add_morphism('tokenize', 'RawText', 'Tokens');
cat.add_morphism('embed', 'Tokens', 'Embeddings');
cat.add_morphism('attend', 'Embeddings', 'Attention');
cat.add_morphism('decode', 'Attention', 'Output');

// Compose transformations
const embed_then_attend = cat.compose('embed', 'attend');
console.log(`embed ; attend = ${embed_then_attend}`);

// Full pipeline composition
const tokenize_embed = cat.compose('tokenize', 'embed');
const full_pipeline = cat.compose(
  cat.compose(tokenize_embed, 'attend'),
  'decode'
);
console.log(`Full pipeline: RawText → Output`);

// Verify identity laws
const id_tokens = cat.identity('Tokens');
const should_equal_embed = cat.compose(id_tokens, 'embed');
console.log(`id_Tokens ; embed = embed: ${should_equal_embed === 'embed'}`);

Tutorial 6: Formal Verification with HoTT

Use homotopy type theory for proof transport:

import init, { HottEngine } from 'prime-radiant-advanced-wasm';

await init();

const hott = new HottEngine();

// Define types
hott.define_type('Nat', 'inductive(zero, succ)');
hott.define_type('Vec', 'dependent(Nat, Type)');
hott.define_type('List', 'inductive(nil, cons)');

// Type checking
const wellTyped = hott.check_type('succ(succ(zero))', 'Nat');
console.log(`2 : Nat is well-typed: ${wellTyped}`);  // true

// Path types (equality proofs)
// If we have a proof that n = m, we can transport properties
const path_2_eq_2 = hott.reflexivity('succ(succ(zero))');

// Transport: if P(n) and n = m, then P(m)
// This is the foundation of proof reuse
const transported = hott.transport(path_2_eq_2, 'property_at_2');
console.log('Transported proof successfully');

// Univalence: equivalent types can be treated as equal
// (A ≃ B) ≃ (A = B)
// This allows swapping implementations transparently

Mathematical Background

Sheaf Cohomology

Sheaf cohomology measures global obstructions to local consistency. For a graph G with sheaf F:

  • Coboundary operator: δ: C^n(G,F) → C^{n+1}(G,F)
  • Cohomology groups: H^n(G,F) = ker(δ_n) / im(δ_{n-1})
  • Sheaf Laplacian: L_F = δδ* + δ*δ
  • Energy: E(x) = x^T L_F x measures coherence

Spectral Graph Theory

The graph Laplacian L = D - A has eigenvalues 0 = λ₁ ≤ λ₂ ≤ ... ≤ λₙ:

  • Fiedler value (λ₂): Measures algebraic connectivity
  • Cheeger constant: h(G) = min_S |∂S| / min(|S|, |S̄|)
  • Cheeger inequality: λ₂/2 ≤ h(G) ≤ √(2λ₂)

Do-Calculus

Pearl's three rules for causal inference:

  1. Insertion/deletion of observations: P(y|do(x),z,w) = P(y|do(x),w) if (Y ⊥ Z | X,W)_{G_X̄}
  2. Action/observation exchange: P(y|do(x),do(z),w) = P(y|do(x),z,w) if (Y ⊥ Z | X,W)_{G_X̄Z̄}
  3. Insertion/deletion of actions: P(y|do(x),do(z),w) = P(y|do(x),w) if (Y ⊥ Z | X,W)_{G_X̄Z̄(W)}

Persistent Homology

Tracks topological features across scales:

  • Filtration: ∅ = K₀ ⊆ K₁ ⊆ ... ⊆ Kₙ = K
  • Persistence pairs: (birth, death) for each feature
  • Betti numbers: β_k = rank(H_k) counts k-dimensional holes

Homotopy Type Theory

Unifies types and spaces:

  • Path types: Id_A(x,y) represents equality proofs
  • J-eliminator: Induction principle for paths
  • Univalence: (A ≃ B) ≃ (A = B) — equivalent types are equal
  • Transport: Move proofs along paths

Performance

All computations run in WebAssembly for near-native performance:

Operation Typical Latency
Cohomology (100 nodes) ~2ms
Spectral analysis (1000 nodes) ~15ms
Persistence (500 points) ~8ms
Type checking <1ms

Browser Support

Works in all modern browsers with WebAssembly support:

  • Chrome 57+
  • Firefox 52+
  • Safari 11+
  • Edge 16+

License

MIT OR Apache-2.0

Contributing

Contributions welcome! See GitHub repository for issues and PRs.