ruvector/examples/prime-radiant/wasm/pkg/example.ts
rUv 572e893258 feat(prime-radiant): Advanced Mathematical Frameworks + fix(router): VectorDb Deadlock (#133) (#132)
* docs(coherence-engine): add ADR-014 and DDD for sheaf Laplacian coherence engine

Add comprehensive architecture documentation for ruvector-coherence crate:

- ADR-014: Sheaf Laplacian-based coherence witnessing architecture
  - Universal coherence object with domain-agnostic interpretation
  - 5-layer architecture (Application → Gate → Computation → Governance → Storage)
  - 4-tier compute ladder (Reflex → Retrieval → Heavy → Human)
  - Full ruvector ecosystem integration (10+ crates)
  - 15 internal architectural decisions

- DDD: Domain-Driven Design with 10 bounded contexts
  - Tile Fabric (cognitum-gate-kernel)
  - Adaptive Learning (sona)
  - Neural Gating (ruvector-nervous-system)
  - Learned Restriction Maps (ruvector-gnn)
  - Hyperbolic Coherence (ruvector-hyperbolic-hnsw)
  - Incoherence Isolation (ruvector-mincut)
  - Attention-Weighted Coherence (ruvector-attention)
  - Distributed Consensus (ruvector-raft)

Key concept: "This is not prediction. It is a continuously updated field
of coherence that shows where action is safe and where action must stop."

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(prime-radiant): implement sheaf Laplacian coherence engine

Implement the complete Prime-Radiant crate based on ADR-014:

Core Modules:
- substrate/: SheafGraph, SheafNode, SheafEdge, RestrictionMap (SIMD-optimized)
- coherence/: CoherenceEngine, energy computation, spectral drift detection
- governance/: PolicyBundle, WitnessRecord, LineageRecord (Blake3 hashing)
- execution/: CoherenceGate, ComputeLane, ActionExecutor

Ecosystem Integrations (feature-gated):
- tiles/: cognitum-gate-kernel 256-tile WASM fabric adapter
- sona_tuning/: Adaptive threshold learning with EWC++
- neural_gate/: Biologically-inspired gating with HDC encoding
- learned_rho/: GNN-based learned restriction maps
- attention/: Topology-gated attention, MoE routing, PDE diffusion
- distributed/: Raft-based multi-node coherence

Testing:
- 138 tests (integration, property-based, chaos)
- 8 benchmarks covering ADR-014 performance targets

Stats: 91 files, ~30K lines of Rust code

"This is not prediction. It is a continuously updated field of coherence
that shows where action is safe and where action must stop."

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs(adr): add RuvLLM integration to ADR-014 v0.4

- Add coherence-gated LLM inference architecture diagram
- Add 5 integration modules with code examples:
  - SheafCoherenceValidator (replaces heuristic scoring)
  - UnifiedWitnessLog (merged audit trail)
  - PatternToRestrictionBridge (ReasoningBank → learned ρ)
  - MemoryCoherenceLayer (context as sheaf nodes)
  - CoherenceConfidence (energy → confidence mapping)
- Add 7 integration ADRs (ADR-CE-016 through ADR-CE-022)
- Add ruvllm to crate integration matrix and dependencies
- Add 4 LLM-specific benefits to consequences
- Add ruvllm feature flag

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs(adr): add 22 coherence engine internal ADRs

Create detailed ADR files for all internal coherence engine decisions:

Core Architecture (ADR-CE-001 to ADR-CE-008):
- 001: Sheaf Laplacian defines coherence witness
- 002: Incremental computation with stored residuals
- 003: PostgreSQL + ruvector hybrid storage
- 004: Signed event log with deterministic replay
- 005: First-class governance objects
- 006: Coherence gate controls compute ladder
- 007: Thresholds auto-tuned from traces
- 008: Multi-tenant isolation boundaries

Universal Coherence (ADR-CE-009 to ADR-CE-015):
- 009: Single coherence object (one math, many interpretations)
- 010: Domain-agnostic nodes and edges
- 011: Residual = contradiction energy
- 012: Gate = refusal mechanism with witness
- 013: Not prediction (coherence field, not forecasting)
- 014: Reflex lane default (most ops stay fast)
- 015: Adapt without losing control

RuvLLM Integration (ADR-CE-016 to ADR-CE-022):
- 016: CoherenceValidator uses sheaf energy
- 017: Unified audit trail (WitnessLog + governance)
- 018: Pattern-to-restriction bridge (ReasoningBank)
- 019: Memory as nodes (agentic, working, episodic)
- 020: Confidence from energy (sigmoid mapping)
- 021: Shared SONA between ruvllm and prime-radiant
- 022: Failure learning (ErrorPatternLearner → ρ maps)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(prime-radiant): implement RuvLLM integration layer (ADR-014 v0.4)

Implement complete Prime-Radiant + RuvLLM integration per ADR-CE-016 through ADR-CE-022:

Core Integration Modules:
- coherence_validator.rs: SheafCoherenceValidator using sheaf energy
- witness_log.rs: UnifiedWitnessLog with hash chain for tamper evidence
- pattern_bridge.rs: PatternToRestrictionBridge learning from verdicts
- memory_layer.rs: MemoryCoherenceLayer tracking context as sheaf nodes
- confidence.rs: CoherenceConfidence with sigmoid energy→confidence mapping

Supporting Infrastructure:
- mod.rs: Public API, re-exports, convenience constructors
- error.rs: Comprehensive error types for each ADR
- config.rs: LlmCoherenceConfig, thresholds, policies
- gate.rs: LlmCoherenceGate high-level interface
- adapter.rs: RuvLlmAdapter bridging type systems
- bridge.rs: PolicyBridge, SonaBridge for synchronization
- witness.rs: WitnessAdapter for correlation
- traits.rs: Trait definitions for loose coupling

Testing:
- 22 integration tests covering all modules
- Self-contained mock implementations
- Feature-gated with #[cfg(feature = "ruvllm")]

Feature Flags:
- ruvllm feature in Cargo.toml
- Optional dependency on ruvllm crate
- Added to "full" feature set

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs(prime-radiant): add comprehensive README with examples

Add user-friendly documentation covering:
- Introduction explaining coherence vs confidence
- Core concepts (coherence field, compute ladder)
- Features overview (engine, governance, RuvLLM integration)
- Quick start code examples:
  - Basic coherence check
  - LLM response validation
  - Memory consistency tracking
  - Confidence from energy
- Application tiers (today, near-term, future)
- Domain examples (AI, finance, medical, robotics, security)
- Feature flags reference
- Performance targets
- Architecture diagram

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs(adr): add ADR-015 Coherence-Gated Transformer (Sheaf Attention)

Propose novel low-latency transformer architecture using coherence energy:

Core Innovation:
- Route tokens to compute lanes based on coherence energy, not confidence
- Sparse attention using residual energy (skip coherent pairs)
- Early exit when energy converges (not confidence threshold)
- Restriction maps replace QKV projections

Architecture:
- Lane 0 (Reflex): 1-2 layers, local attention, <0.1ms
- Lane 1 (Standard): 6 layers, sparse sheaf attention, ~1ms
- Lane 2 (Deep): 12+ layers, full + MoE, ~5ms
- Lane 3 (Escalate): Return uncertainty

Performance Targets:
- 5-10x latency reduction (10ms → 1-2ms for 128 tokens)
- 2.5x memory reduction
- <5% quality degradation
- Provable coherence bound on output

Mathematical Foundation:
- Attention weight ∝ exp(-β × residual_energy)
- Token routing via E(t) = Σ w_e ||ρ_t(x) - ρ_ctx(x)||²
- Early exit when ΔE < ε (energy converged)

Target: ruvector-attention crate with sheaf/ and coherence_gated/ modules

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(prime-radiant): implement coherence engine with CGT attention

Complete implementation of Prime-Radiant coherence engine and
Coherence-Gated Transformer (CGT) sheaf attention module.

Core Features:
- Sheaf Laplacian energy computation with restriction maps
- 4-lane compute ladder (Reflex/Retrieval/Heavy/Human)
- Cryptographic witness chains for audit trails
- Policy bundles with multi-party approval

Storage Backends:
- InMemoryStorage with KNN search
- FileStorage with Write-Ahead Logging (WAL)
- PostgresStorage with full schema (feature-gated)
- HybridStorage combining file + optional PostgreSQL

CGT Sheaf Attention (ruvector-attention):
- RestrictionMap with residual/energy computation
- SheafAttention layer: A_ij = exp(-β×E_ij)/Z
- TokenRouter with compute lane routing
- SparseResidualAttention with energy-based masking
- EarlyExit with energy convergence detection

Performance Optimizations:
- Zero-allocation hot paths (apply_into, compute_residual_norm_sq)
- SIMD-friendly 4-way unrolled loops
- Branchless lane routing
- Pre-allocated buffers for batch operations

RuvLLM Integration:
- SheafCoherenceValidator for LLM response validation
- UnifiedWitnessLog linking inference + coherence
- MemoryCoherenceLayer for contradiction detection
- CoherenceConfidence for interpretable uncertainty

Tests: 202 passing in ruvector-attention, 180+ in prime-radiant

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(prime-radiant): add GPU acceleration, SIMD optimizations, and benchmarks

GPU Acceleration (wgpu-rs):
- GpuCoherenceEngine with automatic CPU fallback
- GpuDevice: adapter/device management with high-perf selection
- GpuDispatcher: kernel execution with pipeline caching and buffer pooling
- GpuBufferManager: typed buffer management with pooling
- Compute kernels: residuals, energy reduction, sheaf attention, token routing

WGSL Compute Shaders (6 files, 1,412 lines):
- compute_residuals.wgsl: parallel edge residual computation
- compute_energy.wgsl: two-phase parallel reduction
- sheaf_attention.wgsl: energy-based attention weights A_ij = exp(-beta * E_ij)
- token_routing.wgsl: branchless lane assignment
- sparse_mask.wgsl: sparse attention mask generation
- types.wgsl: shared GPU struct definitions

SIMD Optimizations (wide crate):
- Runtime CPU feature detection (AVX2, AVX-512, SSE4.2, NEON)
- f32x8 vectorized operations
- simd/vectors.rs: dot_product_simd, norm_squared_simd, subtract_simd
- simd/matrix.rs: matmul_simd, matvec_simd, transpose_simd
- simd/energy.rs: batch_residuals_simd, weighted_energy_sum_simd
- 38 unit tests verifying SIMD correctness

Benchmarks (criterion):
- coherence_benchmarks.rs: core operations, graph scaling
- simd_benchmarks.rs: SIMD vs naive comparisons
- gpu_benchmarks.rs: CPU vs GPU performance

Tests:
- 18 GPU coherence tests (16 active, 2 perf ignored)
- GPU-CPU consistency within 1% relative error
- Error handling and fallback verification

README improvements:
- "What Prime-Radiant is NOT" section
- Concrete numeric example with arithmetic
- Flagship LLM hallucination refusal walkthrough
- Infrastructure positioning

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* perf(prime-radiant): optimize SIMD and core computation patterns

SIMD Optimizations:
- Replace element-by-element load_f32x8 with try_into for direct memory copy
- Fix redundant SIMD comparisons in lane assignment (compute masks once, use blend)
- Apply across vectors.rs, matrix.rs, and energy.rs

Core Computation Patterns:
- Replace i % 4 modulo with chunks_exact() for proper auto-vectorization
- Fix edge.rs: residual_norm_squared, residual_with_energy
- Fix node.rs: norm_squared, dot product

Graph API:
- Add get_node_ref() for zero-copy node access via DashMap reference
- Add with_node() closure API for efficient read-only operations

Benchmark findings:
- Incremental updates meet target (<100us): 59us actual
- Linear O(n) scaling confirmed
- Further SIMD/parallelization needed for <1us/edge target

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* perf(prime-radiant): add CSR sparse matrix, GPU buffer prealloc, thread-local scratch

Performance optimizations for Prime-Radiant coherence engine:

CSR Sparse Matrix (restriction.rs):
- Full CsrMatrix struct with row_ptr, col_indices, values
- COO to CSR conversion with from_coo() and from_coo_arrays()
- Zero-allocation matvec_into() and matvec_add_into()
- SIMD-friendly 4-element loop unrolling
- 13 new tests covering all CSR operations

GPU Buffer Pre-allocation (engine.rs, kernels.rs):
- Pre-allocated params, energy_params, partial_sums, staging buffers
- Zero per-frame allocations in compute_energy()
- New create_bind_group_raw() methods for raw buffer references
- CSR matrix support in convert_restriction_map()

Thread-Local Scratch Buffers (edge.rs):
- EdgeScratch struct with 3 reusable Vec<f32> buffers
- thread_local! SCRATCH for zero-allocation hot paths
- residual_norm_squared_no_alloc() and weighted_residual_energy_no_alloc()
- 7 new tests for allocation-free energy computation

WGSL Vec4 Optimization (compute_residuals.wgsl):
- vec4-based processing loop with dot(r_vec, r_vec)
- store_residuals flag in GpuParams struct
- ~4x GPU throughput improvement

README Updates:
- Root README: 40 attention mechanisms, Prime-Radiant section, CGT Sheaf Attention
- WASM README: CGT Sheaf Attention API documentation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: SEO optimize package metadata for crates.io and npm

- prime-radiant: Enhanced description, keywords, categories
- ruvector-attention-wasm: Add version to path dep, SEO keywords
- package.json: 23 keywords, better description, engines config

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore(hyperbolic-hnsw): SEO optimize for crates.io publish

* chore(prime-radiant): add version numbers to path dependencies for crates.io publish

* fix(prime-radiant): shorten keyword for crates.io compliance

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs(readme): add prime-radiant and ruvector-attention-wasm package references

- Add prime-radiant to Quantum Coherence section (sheaf Laplacian AI safety)
- Add ruvector-attention-wasm to npm WASM packages (Flash, MoE, Hyperbolic, CGT)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat(prime-radiant): implement 6 advanced mathematical frameworks

Comprehensive implementation of cutting-edge mathematical foundations:

## Modules Implemented

1. **Sheaf Cohomology** (10 files)
   - Coboundary operator, Cohomology groups, Betti numbers
   - Sheaf Laplacian, Obstruction detection, Diffusion
   - Sheaf Neural Networks with CohomologyPooling

2. **Category Theory/Topos** (12 files)
   - Category trait, Functors, Natural transformations
   - Topos with SubobjectClassifier, InternalLogic
   - 2-Category with Mac Lane coherence (pentagon/triangle)
   - BeliefTopos for probabilistic reasoning

3. **Homotopy Type Theory** (8 files)
   - Type/Term AST with Pi, Sigma, Identity types
   - Path operations, J-eliminator, Transport
   - Univalence axiom, Bidirectional type checker
   - Coherence as paths between belief states

4. **Spectral Invariants** (8 files)
   - Lanczos eigensolver for sparse matrices
   - Cheeger inequality bounds and sweep algorithm
   - Spectral clustering with k-means++
   - Collapse prediction and early warning system

5. **Causal Abstraction** (7 files)
   - Structural Causal Models with do-calculus
   - D-separation (Bayes Ball), Topological ordering
   - Counterfactuals: ATE, ITE, NDE, NIE
   - Causal abstraction verification

6. **Quantum/Algebraic Topology** (10 files)
   - Quantum states, Density matrices, Channels
   - Simplicial complexes, Persistent homology
   - Topological codes (surface, toric, stabilizer)
   - Structure-preserving quantum encodings

## Supporting Infrastructure

- **Security Module**: 17 issues fixed, path traversal prevention
- **WASM Bindings**: 6 engines with TypeScript definitions
- **Benchmarks**: 4,762 lines of criterion benchmarks
- **Documentation**: 6 ADRs + DDD domain model (3,141 lines)
- **Tests**: 191+ tests passing

## Mathematical Foundations

- Sheaf Laplacian: E(S) = Σ w_e ||ρ_u(x_u) - ρ_v(x_v)||²
- Cheeger inequality: λ₂/2 ≤ h(G) ≤ √(2λ₂)
- Univalence: (A ≃ B) ≃ (A = B)
- Do-calculus: P(Y|do(X)) identification

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(router-core): resolve HNSW index deadlock on second insert (#133)

The insert() method was holding write locks on graph and entry_point
while calling search_knn_internal(), which tries to acquire read locks
on the same RwLocks. Since parking_lot::RwLock is NOT reentrant, this
caused a deadlock on the second insert.

Fix: Release all locks before calling search_knn_internal(), then
re-acquire for modifications.

Added regression tests:
- test_hnsw_multiple_inserts_no_deadlock
- test_hnsw_concurrent_inserts

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: bump versions for v2.0.1 release

- Rust workspace: 2.0.0 -> 2.0.1
- npm @ruvector/router: 0.1.25 -> 0.1.26
- npm platform packages: -> 0.1.26
- Added darwin-x64 to optional dependencies

Contains fix for HNSW deadlock issue #133

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-24 12:30:59 -05:00

446 lines
15 KiB
TypeScript

/**
* Prime-Radiant Advanced WASM - JavaScript/TypeScript API Example
*
* This example demonstrates usage of all 6 mathematical engines:
* - CohomologyEngine: Sheaf cohomology computations
* - CategoryEngine: Functorial retrieval and topos operations
* - HoTTEngine: Type checking and path operations
* - SpectralEngine: Eigenvalue computation and Cheeger bounds
* - CausalEngine: Causal inference and interventions
* - QuantumEngine: Topological invariants and quantum simulation
*/
import init, {
CohomologyEngine,
SpectralEngine,
CausalEngine,
QuantumEngine,
CategoryEngine,
HoTTEngine,
getVersion,
initModule,
type SheafGraph,
type SheafNode,
type SheafEdge,
type Graph,
type CausalModel,
type QuantumState,
type Complex,
type Category,
type CatObject,
type Morphism,
type HoTTType,
type HoTTTerm,
type HoTTPath,
} from './prime_radiant_advanced_wasm';
// ============================================================================
// Initialization
// ============================================================================
async function main() {
// Initialize WASM module
await init();
initModule();
console.log(`Prime-Radiant Advanced WASM v${getVersion()}`);
console.log('='.repeat(50));
// Run all examples
await cohomologyExample();
await spectralExample();
await causalExample();
await quantumExample();
await categoryExample();
await hottExample();
console.log('\nAll examples completed successfully!');
}
// ============================================================================
// Cohomology Engine Example
// ============================================================================
async function cohomologyExample() {
console.log('\n--- Cohomology Engine Example ---');
const cohomology = new CohomologyEngine();
// Create a belief graph with consistent sections
const consistentGraph: SheafGraph = {
nodes: [
{ id: 0, label: 'Belief A', section: [1.0, 0.5], weight: 1.0 },
{ id: 1, label: 'Belief B', section: [1.0, 0.5], weight: 1.0 },
{ id: 2, label: 'Belief C', section: [1.0, 0.5], weight: 1.0 },
],
edges: [
{
source: 0,
target: 1,
restriction_map: [1.0, 0.0, 0.0, 1.0], // Identity map
source_dim: 2,
target_dim: 2,
},
{
source: 1,
target: 2,
restriction_map: [1.0, 0.0, 0.0, 1.0],
source_dim: 2,
target_dim: 2,
},
],
};
// Compute cohomology
const result = cohomology.computeCohomology(consistentGraph);
console.log('Cohomology of consistent graph:');
console.log(` H^0 dimension: ${result.h0_dim}`);
console.log(` H^1 dimension: ${result.h1_dim}`);
console.log(` Euler characteristic: ${result.euler_characteristic}`);
console.log(` Is consistent: ${result.is_consistent}`);
// Create an inconsistent graph
const inconsistentGraph: SheafGraph = {
nodes: [
{ id: 0, label: 'Belief A', section: [1.0, 0.0], weight: 1.0 },
{ id: 1, label: 'Belief B', section: [0.0, 1.0], weight: 1.0 }, // Different!
],
edges: [
{
source: 0,
target: 1,
restriction_map: [1.0, 0.0, 0.0, 1.0],
source_dim: 2,
target_dim: 2,
},
],
};
// Detect obstructions
const obstructions = cohomology.detectObstructions(inconsistentGraph);
console.log(`\nDetected ${obstructions.length} obstruction(s):`);
for (const obs of obstructions) {
console.log(` ${obs.description}`);
}
// Compute consistency energy
const energy = cohomology.consistencyEnergy(inconsistentGraph);
console.log(` Consistency energy: ${energy.toFixed(6)}`);
}
// ============================================================================
// Spectral Engine Example
// ============================================================================
async function spectralExample() {
console.log('\n--- Spectral Engine Example ---');
const spectral = new SpectralEngine();
// Create a path graph: 0 -- 1 -- 2 -- 3 -- 4
const pathGraph: Graph = {
n: 5,
edges: [
[0, 1, 1.0],
[1, 2, 1.0],
[2, 3, 1.0],
[3, 4, 1.0],
],
};
// Compute Cheeger bounds
const cheeger = spectral.computeCheegerBounds(pathGraph);
console.log('Cheeger bounds for path graph:');
console.log(` Lower bound: ${cheeger.lower_bound.toFixed(6)}`);
console.log(` Upper bound: ${cheeger.upper_bound.toFixed(6)}`);
console.log(` Fiedler value (λ₂): ${cheeger.fiedler_value.toFixed(6)}`);
// Compute spectral gap
const gap = spectral.computeSpectralGap(pathGraph);
console.log(`\nSpectral gap analysis:`);
console.log(` λ₁ = ${gap.lambda_1.toFixed(6)}`);
console.log(` λ₂ = ${gap.lambda_2.toFixed(6)}`);
console.log(` Gap = ${gap.gap.toFixed(6)}`);
console.log(` Ratio = ${gap.ratio.toFixed(6)}`);
// Predict minimum cut
const prediction = spectral.predictMinCut(pathGraph);
console.log(`\nMin-cut prediction:`);
console.log(` Predicted cut: ${prediction.predicted_cut.toFixed(6)}`);
console.log(` Confidence: ${(prediction.confidence * 100).toFixed(1)}%`);
console.log(` Cut nodes: [${prediction.cut_nodes.join(', ')}]`);
// Create a barbell graph (two cliques connected by single edge)
const barbellGraph: Graph = {
n: 6,
edges: [
// First clique
[0, 1, 1.0], [0, 2, 1.0], [1, 2, 1.0],
// Second clique
[3, 4, 1.0], [3, 5, 1.0], [4, 5, 1.0],
// Bridge
[2, 3, 1.0],
],
};
const barbellGap = spectral.computeSpectralGap(barbellGraph);
console.log(`\nBarbell graph spectral gap: ${barbellGap.gap.toFixed(6)}`);
console.log('(Small gap indicates bottleneck structure)');
}
// ============================================================================
// Causal Engine Example
// ============================================================================
async function causalExample() {
console.log('\n--- Causal Engine Example ---');
const causal = new CausalEngine();
// Build a causal model: Age -> Income, Education -> Income, Income -> Savings
const model: CausalModel = {
variables: [
{ name: 'Age', var_type: 'continuous' },
{ name: 'Education', var_type: 'discrete' },
{ name: 'Income', var_type: 'continuous' },
{ name: 'Savings', var_type: 'continuous' },
],
edges: [
{ from: 'Age', to: 'Income' },
{ from: 'Education', to: 'Income' },
{ from: 'Income', to: 'Savings' },
],
};
// Check if valid DAG
const isValid = causal.isValidDag(model);
console.log(`Model is valid DAG: ${isValid}`);
// Get topological order
const order = causal.topologicalOrder(model);
console.log(`Topological order: ${order.join(' -> ')}`);
// Check d-separation
const dSep = causal.checkDSeparation(model, 'Age', 'Savings', ['Income']);
console.log(`\nD-separation test:`);
console.log(` Age ⊥ Savings | Income: ${dSep.d_separated}`);
const dSep2 = causal.checkDSeparation(model, 'Age', 'Savings', []);
console.log(` Age ⊥ Savings | ∅: ${dSep2.d_separated}`);
// Find confounders
const confounders = causal.findConfounders(model, 'Education', 'Savings');
console.log(`\nConfounders between Education and Savings: [${confounders.join(', ')}]`);
// Compute causal effect
const effect = causal.computeCausalEffect(model, 'Income', 'Savings', 10000);
console.log(`\nCausal effect of do(Income = 10000) on Savings:`);
console.log(` Effect: ${effect.causal_effect}`);
console.log(` Affected variables: [${effect.affected_variables.join(', ')}]`);
}
// ============================================================================
// Quantum Engine Example
// ============================================================================
async function quantumExample() {
console.log('\n--- Quantum Engine Example ---');
const quantum = new QuantumEngine();
// Create GHZ state (maximally entangled)
const ghz = quantum.createGHZState(3);
console.log(`GHZ state (3 qubits):`);
console.log(` Dimension: ${ghz.dimension}`);
console.log(` |000⟩ amplitude: ${ghz.amplitudes[0].re.toFixed(4)}`);
console.log(` |111⟩ amplitude: ${ghz.amplitudes[7].re.toFixed(4)}`);
// Create W state
const w = quantum.createWState(3);
console.log(`\nW state (3 qubits):`);
console.log(` |001⟩ amplitude: ${w.amplitudes[1].re.toFixed(4)}`);
console.log(` |010⟩ amplitude: ${w.amplitudes[2].re.toFixed(4)}`);
console.log(` |100⟩ amplitude: ${w.amplitudes[4].re.toFixed(4)}`);
// Compute fidelity between states
const fidelity = quantum.computeFidelity(ghz, w);
console.log(`\nFidelity between GHZ and W states:`);
console.log(` Fidelity: ${fidelity.fidelity.toFixed(6)}`);
console.log(` Trace distance: ${fidelity.trace_distance.toFixed(6)}`);
// Compute entanglement entropy
const entropy = quantum.computeEntanglementEntropy(ghz, 1);
console.log(`\nEntanglement entropy of GHZ (split at qubit 1): ${entropy.toFixed(6)}`);
// Compute topological invariants of a simplicial complex
// Triangle: vertices {0,1,2}, edges {01,12,02}, face {012}
const simplices = [
[0], [1], [2], // 0-simplices (vertices)
[0, 1], [1, 2], [0, 2], // 1-simplices (edges)
[0, 1, 2], // 2-simplex (face)
];
const invariants = quantum.computeTopologicalInvariants(simplices);
console.log(`\nTopological invariants of filled triangle:`);
console.log(` Euler characteristic: ${invariants.euler_characteristic}`);
console.log(` Is connected: ${invariants.is_connected}`);
// Apply Hadamard gate
const hadamard: Complex[][] = [
[{ re: 1 / Math.sqrt(2), im: 0 }, { re: 1 / Math.sqrt(2), im: 0 }],
[{ re: 1 / Math.sqrt(2), im: 0 }, { re: -1 / Math.sqrt(2), im: 0 }],
];
const ground: QuantumState = {
amplitudes: [{ re: 1, im: 0 }, { re: 0, im: 0 }],
dimension: 2,
};
const result = quantum.applyGate(ground, hadamard, 0);
console.log(`\nHadamard on |0⟩:`);
console.log(` |0⟩ amplitude: ${result.amplitudes[0].re.toFixed(4)}`);
console.log(` |1⟩ amplitude: ${result.amplitudes[1].re.toFixed(4)}`);
}
// ============================================================================
// Category Engine Example
// ============================================================================
async function categoryExample() {
console.log('\n--- Category Engine Example ---');
const category = new CategoryEngine();
// Create a simple category with vector spaces
const vecCategory: Category = {
name: 'Vect',
objects: [
{ id: 'R2', dimension: 2, data: [1.0, 0.0] },
{ id: 'R3', dimension: 3, data: [1.0, 0.0, 0.0] },
],
morphisms: [],
};
// Create morphisms (linear maps)
const projection: Morphism = {
source: 'R3',
target: 'R2',
matrix: [1, 0, 0, 0, 1, 0], // Project to first two coordinates
source_dim: 3,
target_dim: 2,
};
const embedding: Morphism = {
source: 'R2',
target: 'R3',
matrix: [1, 0, 0, 1, 0, 0], // Embed in first two coordinates
source_dim: 2,
target_dim: 3,
};
// Apply morphism
const data = [1.0, 2.0, 3.0];
const projected = category.applyMorphism(projection, data);
console.log(`Projection of [${data.join(', ')}]: [${projected.map(x => x.toFixed(2)).join(', ')}]`);
// Compose morphisms (embedding then projection = identity)
const composed = category.composeMorphisms(embedding, projection);
console.log(`\nComposed morphism (P ∘ E):`);
console.log(` Source: ${composed.source}`);
console.log(` Target: ${composed.target}`);
console.log(` Matrix: [${composed.matrix.map(x => x.toFixed(2)).join(', ')}]`);
// Verify category laws
vecCategory.morphisms.push(projection);
const lawsValid = category.verifyCategoryLaws(vecCategory);
console.log(`\nCategory laws verified: ${lawsValid}`);
// Functorial retrieval
const docsCategory: Category = {
name: 'Docs',
objects: [
{ id: 'doc1', dimension: 3, data: [1.0, 0.0, 0.0] },
{ id: 'doc2', dimension: 3, data: [0.9, 0.1, 0.0] },
{ id: 'doc3', dimension: 3, data: [0.0, 1.0, 0.0] },
{ id: 'doc4', dimension: 3, data: [0.0, 0.0, 1.0] },
],
morphisms: [],
};
const query = [1.0, 0.0, 0.0];
const results = category.functorialRetrieve(docsCategory, query, 2);
console.log(`\nFunctorial retrieval for query [${query.join(', ')}]:`);
for (const r of results) {
console.log(` ${r.object_id}: similarity = ${r.similarity.toFixed(4)}`);
}
}
// ============================================================================
// HoTT Engine Example
// ============================================================================
async function hottExample() {
console.log('\n--- HoTT Engine Example ---');
const hott = new HoTTEngine();
// Create terms
const star: HoTTTerm = { kind: 'star', children: [] };
const zero: HoTTTerm = { kind: 'zero', children: [] };
const one: HoTTTerm = { kind: 'succ', children: [zero] };
const pair: HoTTTerm = { kind: 'pair', children: [zero, star] };
// Infer types
console.log('Type inference:');
const starType = hott.inferType(star);
console.log(` ★ : ${starType.inferred_type?.kind}`);
const zeroType = hott.inferType(zero);
console.log(` 0 : ${zeroType.inferred_type?.kind}`);
const oneType = hott.inferType(one);
console.log(` S(0) : ${oneType.inferred_type?.kind}`);
const pairType = hott.inferType(pair);
console.log(` (0, ★) : ${pairType.inferred_type?.name}`);
// Type checking
const natType: HoTTType = { name: 'Nat', level: 0, kind: 'nat', params: [] };
const checkResult = hott.typeCheck(zero, natType);
console.log(`\nType checking 0 : Nat: ${checkResult.is_valid}`);
const boolType: HoTTType = { name: 'Bool', level: 0, kind: 'bool', params: [] };
const checkResult2 = hott.typeCheck(zero, boolType);
console.log(`Type checking 0 : Bool: ${checkResult2.is_valid}`);
if (checkResult2.error) {
console.log(` Error: ${checkResult2.error}`);
}
// Path operations
const refl = hott.createReflPath(natType, zero);
console.log(`\nReflexivity path: refl(0) : 0 = 0`);
// Compose paths
const composed = hott.composePaths(refl, refl);
if (composed.is_valid) {
console.log('Path composition: refl ∙ refl is valid');
}
// Invert path
const inverted = hott.invertPath(refl);
if (inverted.is_valid) {
console.log('Path inversion: refl⁻¹ is valid');
}
// Check type equivalence
const nat1: HoTTType = { name: 'Nat', level: 0, kind: 'nat', params: [] };
const nat2: HoTTType = { name: 'Nat', level: 0, kind: 'nat', params: [] };
const equiv = hott.checkTypeEquivalence(nat1, nat2);
console.log(`\nType equivalence Nat ≃ Nat: ${equiv}`);
}
// ============================================================================
// Run Examples
// ============================================================================
main().catch(console.error);