diff --git a/README.md b/README.md index bc7e71b..09e7454 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,232 @@ -# plingua -The P-Lingua language for Membrane Computing +# RR-PLingua: Relevance Realization Enhanced Membrane Computing -P-Lingua is a comprehensive framework for membrane computing that provides a complete ecosystem for defining, parsing, simulating, and generating code for P-systems (membrane systems). +**RR-PLingua** is an advanced membrane computing framework that integrates **Relevance Realization (RR)** dynamics with **OpenCog AtomSpace** symbolic reasoning, creating a unified platform for membrane computing with cognitive architectures. -## 📚 Documentation +## 🧠 RR-RNN: Relevance Realization with Recursive Neural Networks + +This implementation extends the traditional P-Lingua framework with four major Next Development Directions, creating a sophisticated system for symbolic-subsymbolic integration in membrane computing environments. + +### ✨ Key Features + +- **🔗 Advanced PLN Integration**: Probabilistic Logic Networks with RR pattern reasoning +- **💬 Enhanced Scheme Interface**: Interactive REPL for system exploration and manipulation +- **💾 Persistent AtomSpace**: JSON serialization and incremental learning capabilities +- **🏗️ Multi-Level Integration**: Hierarchical membrane structures with cross-level emergence + +## 🎯 Implementation Summary + +### 1. Advanced PLN Integration ✅ +**File**: `include/pln_integration.hpp` + +- **PLN Truth Values**: Complete implementation with strength/confidence pairs +- **Inference Rules**: + - Deduction: A→B, A ⊢ B + - Abduction: A→B, B ⊢ A (with reduced confidence) +- **RR Pattern Implications**: Automatic generation of implications from high-coupling agent-arena relationships +- **Full Inference Cycle**: Integrated PLN reasoning over membrane structures -### [Comprehensive Architecture Documentation](docs/README.md) -Detailed architectural insights with Mermaid diagrams covering: -- **[System Architecture](docs/ARCHITECTURE.md)**: High-level design patterns and data flows -- **[Component Deep Dive](docs/COMPONENTS.md)**: Internal architecture of parser, simulator, and generator -- **[Usage Examples](docs/EXAMPLES.md)**: Practical demonstrations and integration guides +### 2. Enhanced Scheme Interface ✅ +**File**: `include/scheme_interface.hpp` -## Dependencies +- **Interactive REPL**: Full Scheme-style command evaluation +- **Command Set**: 8+ commands for system exploration and manipulation +- **Pattern Matching**: Query and analyze both RR and AtomSpace structures +- **Real-time Updates**: Modify system state through Scheme commands -* Linux OS (tested on Ubuntu 16.04 and Ubuntu 18.04) -* GCC 4.9.0 or higher (with support for regex) -* Flex -* Bison -* libboost-filesystem-dev -* libboost-program-options-dev +### 3. Persistent AtomSpace ✅ +**File**: `include/persistent_atomspace.hpp` -sudo apt-get install build-essential flex bison libboost-filesystem-dev libboost-program-options-dev +- **JSON Serialization**: Complete save/load for AtomSpace state +- **RR Hypergraph Persistence**: Serialize all RR dynamics and structure +- **Incremental Learning**: Merge new experiences with existing knowledge +- **Memory Consolidation**: Remove low-confidence atoms to optimize storage -## Compiling +### 4. Multi-Level Integration ✅ +**Distributed across**: `relevance_realization.hpp`, `atomspace_integration.hpp`, test files -* make grammar -* make compiler -* make simulator -* sudo make install +- **Hierarchical Structures**: Support for nested membrane architectures +- **Cross-Level Emergence**: Detection of patterns spanning multiple hierarchy levels +- **Temporal Reasoning**: Track relevance evolution over time +- **Multi-Scale Dynamics**: Coordinated RR updates across system levels -## Architecture Overview +## 🏛️ Architecture Overview ```mermaid graph TD - A[P-Lingua Source] --> B[Parser] - B --> C[P-System Model] - C --> D[Simulator] - C --> E[Code Generator] - D --> F[Results] - E --> G[Generated Code] + subgraph "Traditional P-Lingua Core" + A[P-Lingua Source] --> B[Parser] + B --> C[P-System Model] + C --> D[Simulator] + C --> E[Code Generator] + end - style A fill:#e3f2fd - style C fill:#f3e5f5 - style F fill:#e8f5e8 - style G fill:#fff3e0 + subgraph "RR Enhancement Layer" + F[RR Hypergraph] --> G[Relevance Dynamics] + G --> H[Agent-Arena-Relation Triad] + H --> I[Trialectic Co-constitution] + end + + subgraph "AtomSpace Integration" + J[OpenCog AtomSpace] --> K[PLN Inference] + K --> L[Pattern Recognition] + L --> M[Symbolic Reasoning] + end + + subgraph "Unified Architecture" + N[RR-AtomSpace Bridge] + O[Scheme Interface] + P[Persistent Storage] + Q[Multi-Level Coordination] + end + + C --> F + F --> J + J --> N + N --> O + N --> P + N --> Q + + style F fill:#e3f2fd + style J fill:#f3e5f5 + style N fill:#e8f5e8 + style O fill:#fff3e0 ``` -The framework consists of three main components: -- **Parser**: Transforms P-Lingua source into executable models -- **Simulator**: Executes membrane computing simulations -- **Generator**: Produces optimized C++ implementations +## 🔄 RR Dynamics Process Flow + +```mermaid +sequenceDiagram + participant Agent as Agent Membrane + participant Arena as Arena Membrane + participant RR as RR Engine + participant AtomSpace as AtomSpace + participant PLN as PLN Engine + + Agent->>RR: Update salience + Arena->>RR: Update affordances + RR->>RR: Compute trialectic dynamics + RR->>AtomSpace: Sync RR properties + AtomSpace->>PLN: Generate implications + PLN->>PLN: Perform inference cycle + PLN->>AtomSpace: Update truth values + AtomSpace->>RR: Feedback to RR dynamics + RR->>Agent: Update relevance gradient + RR->>Arena: Update coupling strength +``` + +## 🚀 Quick Start + +### Dependencies + +```bash +sudo apt-get install build-essential flex bison libboost-filesystem-dev libboost-program-options-dev libfl-dev +``` + +### Build & Test + +```bash +# Build traditional P-Lingua +make grammar +make compiler +make simulator + +# Build RR-enhanced test programs +g++ -I./include -std=c++11 -o test_rr_enhanced test_rr_enhanced.cpp +g++ -I./include -std=c++11 -o test_next_directions test_next_directions.cpp +g++ -I./include -std=c++11 -o demo_repl demo_repl.cpp + +# Run comprehensive demo +./test_next_directions +``` + +### Interactive RR/AtomSpace REPL + +```bash +./demo_repl +``` + +Available Scheme commands: +```scheme +(list-rr-nodes) ; List all RR nodes with properties +(list-atoms) ; Show AtomSpace contents +(get-system-relevance) ; Compute overall system relevance +(run-pln-inference) ; Execute PLN reasoning cycle +(find-patterns) ; Detect emergent patterns +(get-salience node-ID) ; Query node salience +(update-salience node-ID VALUE) ; Modify node properties +(find-atom "NAME") ; Search atoms by name +``` + +## 📊 Performance Characteristics + +### RR Dynamics Complexity +- **Trialectic Updates**: O(n) per node per timestep +- **Coupling Computation**: O(n²) for agent-arena pairs +- **Emergence Detection**: O(n·m) for n agents, m arenas + +### AtomSpace Integration +- **RR→Atom Conversion**: O(n) for n RR nodes +- **PLN Inference**: O(r·a) for r rules, a atoms +- **Pattern Matching**: O(p·log(a)) for p patterns + +## 🔬 Research Applications + +### Cognitive Architecture Integration +- **Symbolic-Subsymbolic Bridge**: RR provides the dynamic foundation for symbolic reasoning +- **Emergent Pattern Recognition**: Multi-level emergence detection across membrane hierarchies +- **Adaptive Learning**: Persistent storage enables incremental knowledge accumulation + +### Membrane Computing Enhancements +- **Dynamic Rule Selection**: RR salience influences rule application priorities +- **Adaptive Membrane Behavior**: Agent-arena coupling drives membrane evolution +- **Hierarchical Organization**: Multi-level integration supports complex system architectures + +## 📚 Documentation + +### [Comprehensive RR-RNN Documentation](docs/README.md) +Detailed technical documentation with diagrams covering: +- **[RR-RNN Architecture](docs/ARCHITECTURE.md)**: Relevance Realization integration patterns +- **[Component Deep Dive](docs/COMPONENTS.md)**: PLN, Scheme, and persistence systems +- **[Usage Examples](docs/EXAMPLES.md)**: RR dynamics and AtomSpace integration demos + +### Core Implementation Files + +``` +include/ +├── relevance_realization.hpp # RR framework with trialectic dynamics +├── atomspace_integration.hpp # RR-AtomSpace bridge +├── pln_integration.hpp # PLN inference engine +├── scheme_interface.hpp # Interactive Scheme REPL +└── persistent_atomspace.hpp # Serialization & persistence + +test_*.cpp # Comprehensive test suite +demo_*.cpp # Interactive demonstrations +``` + +## 🎯 Future Extensions + +The implemented framework provides the foundation for: + +1. **Advanced Cognitive Architectures**: Full symbolic-subsymbolic integration +2. **Distributed RR Systems**: Multi-agent relevance realization networks +3. **Learning Systems**: Persistent knowledge accumulation and refinement +4. **Interactive Exploration**: Real-time system analysis and manipulation + +## 🤝 Contributing + +This RR-enhanced membrane computing framework represents a significant advancement toward unified cognitive architectures. Contributions are welcome in: + +- Enhanced RR dynamics algorithms +- Additional PLN inference rules +- Extended Scheme command sets +- Multi-level emergence patterns +- Performance optimizations + +## 📄 License + +Licensed under the same terms as the original P-Lingua framework. + +--- + +*RR-PLingua successfully bridges dynamic self-organization (RR) and symbolic reasoning (AtomSpace/PLN), representing a significant advancement toward unified cognitive architectures.* diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5eaf44d..f1f556f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,39 +1,71 @@ -# P-Lingua Architecture Documentation +# RR-Enhanced P-Lingua Architecture Documentation ## Overview -P-Lingua is a comprehensive framework for membrane computing that provides a complete ecosystem for defining, parsing, simulating, and generating code for P-systems (membrane systems). This documentation provides detailed architectural insights with visual diagrams to facilitate understanding and contribution. +**RR-PLingua** is a revolutionary enhancement of the traditional P-Lingua framework that integrates **Relevance Realization (RR)** dynamics with **OpenCog AtomSpace** symbolic reasoning. This creates a sophisticated platform for cognitive membrane computing that bridges symbolic and subsymbolic processing. + +The enhanced system provides four major architectural innovations: +1. **PLN Integration** - Probabilistic Logic Networks for uncertain reasoning +2. **Scheme Interface** - Interactive exploration and manipulation +3. **Persistent Storage** - Knowledge accumulation and memory consolidation +4. **Multi-Level Integration** - Hierarchical emergence detection ## High-Level System Architecture ```mermaid graph TD - A[P-Lingua Source Files] --> B[Lexical Analyzer] - B --> C[Parser] - C --> D[Syntax Tree] - D --> E[Semantic Analyzer] - E --> F[P-System Model] - F --> G[Simulator Engine] - F --> H[Code Generator] - G --> I[Configuration Output] - H --> J[C++ Generated Code] - - subgraph "Core Components" - K[Parser Module] - L[Simulator Module] - M[Generator Module] - N[Serialization Module] + subgraph "Traditional P-Lingua Layer" + A[P-Lingua Source Files] --> B[Lexical Analyzer] + B --> C[Parser] + C --> D[Syntax Tree] + D --> E[Semantic Analyzer] + E --> F[P-System Model] + F --> G[Simulator Engine] + F --> H[Code Generator] + G --> I[Configuration Output] + H --> J[C++ Generated Code] end - C --> K - G --> L - H --> M - F --> N + subgraph "RR Enhancement Layer" + K[RR Hypergraph] + L[Trialectic Dynamics] + M[Agent-Arena-Relation] + N[Relevance Gradients] + end - style A fill:#e1f5fe - style F fill:#f3e5f5 - style I fill:#e8f5e8 - style J fill:#fff3e0 + subgraph "AtomSpace Integration Layer" + O[OpenCog AtomSpace] + P[PLN Inference Engine] + Q[Truth Value Management] + R[Pattern Recognition] + end + + subgraph "Interactive & Persistence Layer" + S[Scheme REPL Interface] + T[JSON Serialization] + U[Memory Consolidation] + V[Multi-Level Coordination] + end + + F --> K + K --> L + L --> M + M --> N + + K --> O + O --> P + P --> Q + Q --> R + + O --> S + O --> T + T --> U + K --> V + + style K fill:#e3f2fd + style O fill:#f3e5f5 + style S fill:#e8f5e8 + style V fill:#fff3e0 ``` ## Core Data Structures diff --git a/docs/COMPONENTS.md b/docs/COMPONENTS.md index c298d3a..e33be94 100644 --- a/docs/COMPONENTS.md +++ b/docs/COMPONENTS.md @@ -1,6 +1,10 @@ -# P-Lingua Component Deep Dive +# RR-Enhanced P-Lingua Component Deep Dive -## Parser Component Architecture +This document provides detailed analysis of both traditional P-Lingua components and the new RR-enhanced cognitive architecture components. + +## Traditional P-Lingua Components + +### Parser Component Architecture The parser component is the heart of P-Lingua's language processing pipeline, responsible for transforming P-Lingua source code into executable P-system models. @@ -558,4 +562,264 @@ graph LR style I fill:#fff3e0 ``` -This deep dive into P-Lingua's component architecture reveals the sophisticated design patterns and engineering decisions that make the framework both powerful and maintainable. Each component is designed with clear responsibilities and well-defined interfaces, enabling extensibility and optimization. \ No newline at end of file +This deep dive into P-Lingua's component architecture reveals the sophisticated design patterns and engineering decisions that make the framework both powerful and maintainable. Each component is designed with clear responsibilities and well-defined interfaces, enabling extensibility and optimization. + +## RR-Enhanced Components + +The RR enhancement layer adds four major component systems that transform traditional membrane computing into a cognitive architecture platform. + +### RR Hypergraph Component + +The RR Hypergraph is the core component that implements Relevance Realization dynamics through trialectic co-constitution. + +```mermaid +classDiagram + class RRHypergraph { + +map~unsigned, RRNode~ nodes + +map~unsigned, RREdge~ edges + +set~unsigned~ agent_nodes + +set~unsigned~ arena_nodes + +set~unsigned~ relation_edges + +updateRelevanceRealization(delta_time) + +detectEmergentPatterns() + +computeCouplingStrength(agent_id, arena_id) + +addMembraneNode(membrane_id, label, aar_type) + +addRelationEdge(from, to, type, strength) + } + + class RRNode { + +unsigned id + +Type nodeType + +AARType aarType + +string label + +double salience + +double affordance_potential + +double affordance_realization + +vector~double~ trialectic_state + +computeRelevanceGradient() + +updateSalience(delta_time) + +computeTrialecticCoherence() + } + + class RREdge { + +unsigned id + +Type edgeType + +unsigned from_node + +unsigned to_node + +double strength + +double relevance_weight + +updateCoConstruction(from, to, delta_time) + } + + RRHypergraph --> RRNode + RRHypergraph --> RREdge +``` + +### AtomSpace Integration Component + +The AtomSpace Integration bridges RR dynamics with symbolic reasoning through OpenCog AtomSpace. + +```mermaid +graph TB + subgraph "RR-AtomSpace Bridge" + A[RRAtomSpaceIntegrator] + B[Node Conversion] + C[Edge Conversion] + D[Property Synchronization] + end + + subgraph "AtomSpace Structure" + E[Concept Nodes] + F[Evaluation Links] + G[Inheritance Links] + H[Truth Values] + end + + subgraph "Pattern Detection" + I[Emergent Pattern Finder] + J[Coupling Analyzer] + K[Salience Tracker] + end + + A --> B + A --> C + A --> D + + B --> E + C --> F + D --> G + D --> H + + E --> I + F --> J + G --> K + + style A fill:#e8f5e8 + style E fill:#f3e5f5 + style I fill:#e3f2fd +``` + +### PLN Integration Component + +The PLN Integration component provides probabilistic logic reasoning over the integrated RR-AtomSpace structures. + +```mermaid +flowchart TD + A[PLN Engine] --> B[Truth Value System] + A --> C[Inference Rules] + A --> D[Pattern Generator] + + B --> E[PLN Strength] + B --> F[PLN Confidence] + B --> G[Truth Operations] + + C --> H[Deduction Rule] + C --> I[Abduction Rule] + C --> J[Implication Generation] + + D --> K[RR Pattern Detector] + D --> L[Coupling Analyzer] + D --> M[Emergent Relation Creator] + + G --> H + G --> I + K --> J + L --> J + + style A fill:#e3f2fd + style B fill:#f3e5f5 + style C fill:#e8f5e8 + style D fill:#fff3e0 +``` + +### Scheme Interface Component + +The Scheme Interface provides interactive exploration and manipulation capabilities. + +```mermaid +graph LR + subgraph "REPL Interface" + A[Command Parser] + B[Expression Evaluator] + C[Result Formatter] + end + + subgraph "Command Categories" + D[RR Queries] + E[AtomSpace Queries] + F[System Updates] + G[Inference Control] + end + + subgraph "System Access" + H[RR Hypergraph Interface] + I[AtomSpace Interface] + J[PLN Engine Interface] + end + + A --> B + B --> C + + B --> D + B --> E + B --> F + B --> G + + D --> H + E --> I + F --> H + G --> J + + style B fill:#e8f5e8 + style H fill:#f3e5f5 +``` + +### Persistent Storage Component + +The Persistent Storage component handles serialization, memory consolidation, and incremental learning. + +```mermaid +sequenceDiagram + participant PS as Persistent Storage + participant JSON as JSON Serializer + participant RR as RR Serializer + participant AS as AtomSpace Serializer + participant MC as Memory Consolidator + + PS->>RR: Serialize RR hypergraph + RR->>JSON: Convert to JSON format + JSON-->>PS: RR JSON data + + PS->>AS: Serialize AtomSpace + AS->>JSON: Convert to JSON format + JSON-->>PS: AtomSpace JSON data + + PS->>MC: Consolidate memory + MC->>MC: Remove low-confidence atoms + MC-->>PS: Optimized structures + + PS->>PS: Write to persistent storage +``` + +## Component Interaction Patterns + +### RR-AtomSpace Synchronization + +```mermaid +sequenceDiagram + participant RR as RR Hypergraph + participant Bridge as Integration Bridge + participant AS as AtomSpace + participant PLN as PLN Engine + + RR->>Bridge: RR node updates + Bridge->>AS: Create/update concept nodes + AS->>Bridge: Confirm atom updates + Bridge->>RR: Sync confirmation + + RR->>Bridge: RR edge updates + Bridge->>AS: Create/update evaluation links + AS->>PLN: New relations available + PLN->>AS: Generate implications + AS->>Bridge: Pattern changes detected + Bridge->>RR: Feedback to RR dynamics +``` + +### Multi-Level Emergence Detection + +```mermaid +graph TD + subgraph "Level Monitoring" + A[Agent Salience Monitor] + B[Arena Coupling Monitor] + C[Cross-Level Pattern Detector] + end + + subgraph "Emergence Criteria" + D[High Salience: > 0.8] + E[Strong Coupling: > 0.8] + F[High Coherence: > 0.6] + end + + subgraph "Emergence Actions" + G[Create Emergent Relation] + H[Update Multi-Level State] + I[Record Emergence Event] + end + + A --> D + B --> E + C --> F + + D --> G + E --> G + F --> G + + G --> H + H --> I + + style A fill:#e3f2fd + style G fill:#e8f5e8 +``` + +This enhanced component architecture demonstrates how RR-PLingua successfully integrates dynamic self-organization with symbolic reasoning, creating a sophisticated platform for cognitive membrane computing applications. \ No newline at end of file diff --git a/docs/README.md b/docs/README.md index 3bc826e..bd23f2f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,8 +1,8 @@ -# P-Lingua Documentation Index +# RR-PLingua Documentation Index -## Welcome to P-Lingua Architecture Documentation +## Welcome to RR-PLingua Architecture Documentation -This comprehensive documentation suite provides detailed insights into the P-Lingua framework for membrane computing, featuring architectural diagrams, component analysis, and practical examples. +This comprehensive documentation suite provides detailed insights into the **RR-PLingua** framework for enhanced membrane computing with **Relevance Realization (RR)** and **OpenCog AtomSpace** integration, featuring architectural diagrams, component analysis, and practical examples of cognitive membrane computing. ## Documentation Structure @@ -12,6 +12,7 @@ graph TD A --> C[Component Deep Dive] A --> D[Usage Examples] A --> E[API Reference] + A --> RR[RR-RNN Integration] B --> F[System Architecture] B --> G[Data Flow Diagrams] @@ -22,54 +23,86 @@ graph TD C --> K[Code Generator] C --> L[Serialization System] + RR --> PLN[PLN Integration] + RR --> SCHEME[Scheme Interface] + RR --> PERSIST[Persistent Storage] + RR --> MULTI[Multi-Level Systems] + D --> M[Basic Examples] D --> N[Advanced Patterns] D --> O[Integration Guides] D --> P[Performance Analysis] + D --> RRE[RR-Enhanced Examples] E --> Q[Parser API] E --> R[Simulator API] E --> S[Generator API] E --> T[Utility Functions] + E --> U[RR-AtomSpace API] style A fill:#e3f2fd style B fill:#f1f8e9 style C fill:#fff3e0 style D fill:#e8f5e8 style E fill:#f3e5f5 + style RR fill:#ffebee ``` ## Quick Navigation ### 📐 [Architecture Overview](ARCHITECTURE.md) -Comprehensive system-level view of P-Lingua's design patterns and architectural decisions. +Comprehensive system-level view of RR-enhanced P-Lingua's design patterns and architectural decisions. **Key Diagrams:** -- High-level system architecture -- Core data structures -- Module interaction patterns -- Data flow and execution models -- Memory management strategies +- High-level RR-enhanced system architecture +- Core RR data structures and AtomSpace integration +- Module interaction patterns with cognitive components +- Data flow and execution models for RR dynamics +- Memory management strategies for persistent storage ### 🔧 [Component Deep Dive](COMPONENTS.md) -Detailed analysis of individual components and their internal architectures. +Detailed analysis of individual components and their internal architectures, including RR enhancements. **Covered Components:** -- Parser component with lexical/semantic analysis -- Simulator engine with rule selection algorithms -- Code generator with template systems -- Serialization framework with binary formats +- Traditional P-Lingua: Parser, Simulator, Generator, Serialization +- RR Hypergraph: Trialectic dynamics and relevance realization +- AtomSpace Integration: Symbolic-subsymbolic bridge +- PLN Engine: Probabilistic logic networks and inference +- Scheme Interface: Interactive exploration and manipulation +- Persistent Storage: Memory consolidation and incremental learning - Inter-component communication patterns -### 💡 [Usage Examples](EXAMPLES.md) -Practical demonstrations of P-Lingua features through working examples. +### 🧠 [RR-RNN Architecture](RR_ARCHITECTURE.md) +Comprehensive documentation of the Relevance Realization with Recursive Neural Networks enhancement. + +**RR-RNN Features:** +- Trialectic co-constitution framework +- Agent-Arena-Relation dynamics +- PLN truth value systems and inference rules +- Multi-level integration and emergence detection +- Performance characteristics and computational complexity + +### 🔄 [RR Process Flows](RR_PROCESS_FLOWS.md) +Detailed PlantUML diagrams showing RR-RNN system process flows. + +**Process Diagrams:** +- Overall system process flow +- RR trialectic dynamics process +- PLN inference cycles +- Scheme interface command processing +- Persistent storage and memory consolidation +- Multi-level emergence detection + +### 💡 [Usage Examples](RR_EXAMPLES.md) +Practical demonstrations of RR-enhanced P-Lingua features through working examples. **Example Categories:** -- Basic membrane systems -- Complex division patterns -- Pattern matching with variables -- Multi-environment communication -- Error handling scenarios +- Basic RR-enhanced membrane systems +- Advanced PLN integration patterns +- Interactive Scheme interface usage +- Persistent storage and memory consolidation +- Multi-level integration with hierarchical structures +- Complete RR-RNN system demonstrations ## Architecture Highlights @@ -126,6 +159,30 @@ graph LR - Cross-platform support - Incremental loading +#### 5. **RR Dynamics Pattern** +- Trialectic co-constitution (∀^ω(x ⇔^α y ⇔^α z ⇔^α x)) +- Agent-arena-relation dynamics +- Relevance gradient computation (∇ℜ = lim_{t→∞} Σᵢ log(aᵣᵢ(t)/aₚᵢ(t))) +- Emergent pattern detection + +#### 6. **AtomSpace Integration Pattern** +- RR-to-Atom conversion bridge +- Truth value synchronization +- PLN inference integration +- Pattern matching and emergence detection + +#### 7. **Scheme Interface Pattern** +- REPL command processing +- Interactive system exploration +- Real-time state manipulation +- Lisp-style expression evaluation + +#### 8. **Persistent Storage Pattern** +- JSON serialization framework +- Memory consolidation algorithms +- Incremental learning mechanisms +- Cross-session knowledge persistence + ## Component Interaction Map ```mermaid diff --git a/docs/RR_ARCHITECTURE.md b/docs/RR_ARCHITECTURE.md new file mode 100644 index 0000000..e4f273d --- /dev/null +++ b/docs/RR_ARCHITECTURE.md @@ -0,0 +1,585 @@ +# RR-RNN Architecture Documentation + +## Overview + +The **RR-RNN (Relevance Realization with Recursive Neural Networks)** enhancement transforms traditional P-Lingua membrane computing into a sophisticated cognitive architecture platform by integrating: + +1. **Relevance Realization (RR) Dynamics** - Dynamic self-organization through agent-arena-relation triads +2. **OpenCog AtomSpace Integration** - Symbolic knowledge representation and reasoning +3. **PLN (Probabilistic Logic Networks)** - Inference over uncertain knowledge +4. **Interactive Scheme Interface** - Real-time system exploration and manipulation + +## Core RR Architecture + +### Trialectic Co-Constitution Framework + +```mermaid +graph TD + subgraph "Trialectic Dynamics" + A[Agent] --> |co-construction| B[Arena] + B --> |co-construction| C[Relation] + C --> |co-construction| A + end + + subgraph "RR Properties" + D[Salience] + E[Affordance Potential] + F[Affordance Realization] + G[Trialectic State Vector] + end + + subgraph "Mathematical Foundation" + H[∀^ω(x ⇔^α y ⇔^α z ⇔^α x)] + I[∇ℜ = lim_{t→∞} Σᵢ log(aᵣᵢ(t)/aₚᵢ(t))] + J[agent ↔^δ arena ∈ ℝ^(∞×∞)] + end + + A --> D + B --> E + C --> F + A --> G + + D --> H + E --> I + F --> J + + style A fill:#e3f2fd + style B fill:#f3e5f5 + style C fill:#e8f5e8 + style H fill:#fff3e0 +``` + +### RR Hypergraph Structure + +```mermaid +classDiagram + class RRNode { + +unsigned id + +Type nodeType + +AARType aarType + +string label + +double salience + +double affordance_potential + +double affordance_realization + +vector~double~ trialectic_state + +computeRelevanceGradient() + +updateSalience(delta_time) + +computeTrialecticCoherence() + } + + class RREdge { + +unsigned id + +Type edgeType + +unsigned from_node + +unsigned to_node + +double strength + +double relevance_weight + +updateCoConstruction(from, to, delta_time) + } + + class RRHypergraph { + +map~unsigned, RRNode~ nodes + +map~unsigned, RREdge~ edges + +set~unsigned~ agent_nodes + +set~unsigned~ arena_nodes + +set~unsigned~ relation_edges + +updateRelevanceRealization(delta_time) + +detectEmergentPatterns() + +computeCouplingStrength(agent_id, arena_id) + } + + class EmergentCluster { + +unsigned agent_id + +vector~unsigned~ arena_ids + +vector~double~ coupling_strengths + +double coherence + } + + RRHypergraph --> RRNode + RRHypergraph --> RREdge + RRHypergraph --> EmergentCluster + RRNode --> RREdge : connected by +``` + +## AtomSpace Integration Architecture + +### RR-AtomSpace Bridge + +```mermaid +graph LR + subgraph "RR Hypergraph" + A[RR Nodes] + B[RR Edges] + C[RR Properties] + end + + subgraph "Bridge Layer" + D[RRAtomSpaceIntegrator] + E[Node Mapping] + F[Property Sync] + G[Pattern Detection] + end + + subgraph "OpenCog AtomSpace" + H[Concept Nodes] + I[Evaluation Links] + J[Inheritance Links] + K[Truth Values] + end + + A --> D + B --> D + C --> D + + D --> E + D --> F + D --> G + + E --> H + F --> K + G --> I + G --> J + + style D fill:#e8f5e8 + style H fill:#f3e5f5 +``` + +### Atom Structure Mapping + +```mermaid +flowchart TD + subgraph "RR Node Transformation" + A[RR Node] --> B[Concept Node] + A --> C[Truth Value: salience, affordance] + A --> D[Inheritance: type, aar_type] + end + + subgraph "RR Edge Transformation" + E[RR Edge] --> F[Evaluation Link] + E --> G[Predicate: 'relates'] + E --> H[Truth Value: strength, relevance] + end + + subgraph "AtomSpace Structure" + B --> I[Node Registry] + C --> I + D --> I + F --> J[Link Registry] + G --> J + H --> J + end + + I --> K[Pattern Matching] + J --> K + K --> L[Emergent Pattern Detection] + + style A fill:#e3f2fd + style B fill:#f3e5f5 + style K fill:#e8f5e8 +``` + +## PLN Integration Architecture + +### PLN Truth Value System + +```mermaid +graph TB + subgraph "PLN Truth Values" + A[Strength Component] + B[Confidence Component] + C[PLNTruthValue = (s, c)] + end + + subgraph "PLN Operations" + D[Negation: NOT(A) = (1-s, c)] + E[Conjunction: AND(A,B) = (s_A * s_B, min(c_A, c_B))] + F[Disjunction: OR(A,B) = (s_A + s_B - s_A*s_B, min(c_A, c_B))] + G[Implication: A→B = (1-s_A+s_A*s_B, f(c_A,c_B))] + end + + subgraph "Inference Rules" + H[Deduction: A→B, A ⊢ B] + I[Abduction: A→B, B ⊢ A] + J[RR Pattern Implications] + end + + A --> C + B --> C + C --> D + C --> E + C --> F + C --> G + + D --> H + E --> I + F --> J + G --> J + + style C fill:#e3f2fd + style H fill:#f3e5f5 + style J fill:#e8f5e8 +``` + +### PLN Inference Cycle + +```mermaid +sequenceDiagram + participant RR as RR Hypergraph + participant PLN as PLN Engine + participant AS as AtomSpace + participant Impl as Implications + + RR->>PLN: High-coupling patterns + PLN->>AS: Find agent-arena pairs + AS-->>PLN: Coupled nodes + PLN->>Impl: Generate implications + Impl->>AS: Create implication links + AS->>PLN: Start inference cycle + + loop Deduction + PLN->>AS: Find A→B, A patterns + AS-->>PLN: Matching patterns + PLN->>AS: Apply deduction: infer B + end + + loop Abduction + PLN->>AS: Find A→B, B patterns + AS-->>PLN: Matching patterns + PLN->>AS: Apply abduction: hypothesize A + end + + PLN-->>RR: Inference results + RR->>RR: Update RR dynamics +``` + +## Scheme Interface Architecture + +### REPL Command Processing + +```mermaid +graph TD + subgraph "User Interface" + A[User Input] + B[Command Parser] + C[Expression Evaluator] + end + + subgraph "Command Types" + D[(list-rr-nodes)] + E[(list-atoms)] + F[(get-system-relevance)] + G[(run-pln-inference)] + H[(find-patterns)] + I[(get-salience node-ID)] + J[(update-salience node-ID VALUE)] + K[(find-atom "NAME")] + end + + subgraph "System Access" + L[RR Hypergraph Access] + M[AtomSpace Access] + N[PLN Engine Access] + O[Pattern Matcher] + end + + A --> B + B --> C + C --> D + C --> E + C --> F + C --> G + C --> H + C --> I + C --> J + C --> K + + D --> L + E --> M + F --> L + G --> N + H --> O + I --> L + J --> L + K --> M + + style C fill:#e8f5e8 + style L fill:#f3e5f5 +``` + +### Interactive Command Flow + +```mermaid +stateDiagram-v2 + [*] --> REPL_Start + REPL_Start --> Command_Input + Command_Input --> Parse_Expression + Parse_Expression --> Validate_Command + + Validate_Command --> Execute_Query: Read command + Validate_Command --> Execute_Update: Write command + Validate_Command --> Error_Handler: Invalid command + + Execute_Query --> Format_Response + Execute_Update --> Update_System + Update_System --> Format_Response + Error_Handler --> Format_Response + + Format_Response --> Command_Input + Command_Input --> [*]: quit/exit + + note right of Execute_Query + Commands like: + (list-rr-nodes) + (get-system-relevance) + (find-patterns) + end note + + note right of Execute_Update + Commands like: + (update-salience node-ID VALUE) + (run-pln-inference) + end note +``` + +## Persistent Storage Architecture + +### Serialization Framework + +```mermaid +graph LR + subgraph "In-Memory Structures" + A[RR Hypergraph] + B[AtomSpace] + C[PLN State] + end + + subgraph "Serialization Layer" + D[JSON Serializer] + E[RR Serializer] + F[AtomSpace Serializer] + G[Consolidator] + end + + subgraph "Persistent Storage" + H[RR JSON File] + I[AtomSpace JSON File] + J[Merged Knowledge Base] + end + + A --> E + B --> F + C --> D + + E --> H + F --> I + D --> G + + G --> J + H --> J + I --> J + + style D fill:#e8f5e8 + style J fill:#f3e5f5 +``` + +### Memory Consolidation Process + +```mermaid +flowchart TD + A[Current AtomSpace] --> B[Confidence Analysis] + B --> C{Confidence > Threshold?} + C -->|Yes| D[Keep Atom] + C -->|No| E[Mark for Removal] + + D --> F[Active Memory] + E --> G[Cleanup Queue] + + F --> H[Incremental Learning] + G --> I[Memory Optimization] + + H --> J[Merge New Experiences] + I --> K[Free Memory] + + J --> L[Updated Knowledge Base] + K --> L + + style B fill:#e3f2fd + style L fill:#e8f5e8 +``` + +## Multi-Level Integration Architecture + +### Hierarchical Membrane Structure + +```mermaid +graph TB + subgraph "Level 0: Environment" + A[Global Environment] + end + + subgraph "Level 1: Outer Membranes" + B[Outer Agent 1] + C[Outer Arena 1] + D[Outer Agent 2] + E[Outer Arena 2] + end + + subgraph "Level 2: Inner Membranes" + F[Inner Agent 1.1] + G[Inner Arena 1.1] + H[Inner Agent 1.2] + I[Inner Arena 1.2] + end + + subgraph "Cross-Level Dynamics" + J[Emergence Detection] + K[Coherence Propagation] + L[Temporal Reasoning] + end + + A --> B + A --> C + A --> D + A --> E + + B --> F + B --> G + C --> H + C --> I + + F --> J + G --> J + H --> K + I --> K + + J --> L + K --> L + + style A fill:#e3f2fd + style J fill:#e8f5e8 +``` + +### Emergence Detection Algorithm + +```mermaid +flowchart TD + A[Monitor Agent Salience] --> B{Salience > 0.8?} + B -->|Yes| C[Check Arena Coupling] + B -->|No| A + + C --> D{Coupling > 0.8?} + D -->|Yes| E[Measure Trialectic Coherence] + D -->|No| A + + E --> F{Coherence > 0.6?} + F -->|Yes| G[Detect Cross-Level Pattern] + F -->|No| A + + G --> H[Create Emergent Relation] + H --> I[Update Multi-Level State] + I --> J[Record Emergence Event] + J --> A + + style G fill:#e8f5e8 + style H fill:#f3e5f5 +``` + +## System Integration Flow + +### Complete RR-RNN Processing Pipeline + +```mermaid +sequenceDiagram + participant User + participant Parser as P-Lingua Parser + participant RR as RR Engine + participant AS as AtomSpace + participant PLN as PLN Engine + participant Scheme as Scheme REPL + participant Storage as Persistent Storage + + User->>Parser: Load .pli file + Parser->>RR: Create RR hypergraph + RR->>AS: Initialize AtomSpace + AS->>PLN: Setup inference engine + + User->>Scheme: Start interactive session + + loop RR Dynamics + RR->>RR: Update trialectic states + RR->>AS: Sync node properties + AS->>PLN: Generate implications + PLN->>PLN: Perform inference cycle + PLN->>AS: Update truth values + AS->>RR: Feedback updates + end + + User->>Scheme: Execute commands + Scheme->>RR: Query/update RR state + Scheme->>AS: Query/update atoms + Scheme->>PLN: Trigger inference + Scheme-->>User: Return results + + User->>Storage: Save system state + Storage->>AS: Serialize AtomSpace + Storage->>RR: Serialize RR hypergraph + Storage-->>User: Confirm save +``` + +## Performance Characteristics + +### Computational Complexity Analysis + +```mermaid +graph LR + subgraph "RR Operations" + A[Node Update: O(n)] + B[Edge Update: O(e)] + C[Emergence Detection: O(n²)] + D[Trialectic Dynamics: O(n)] + end + + subgraph "AtomSpace Operations" + E[Node Sync: O(n)] + F[Pattern Matching: O(a log a)] + G[Truth Value Update: O(a)] + H[Link Creation: O(l)] + end + + subgraph "PLN Operations" + I[Deduction: O(r·a)] + J[Abduction: O(r·a)] + K[Implication Generation: O(n²)] + L[Inference Cycle: O(r·a·c)] + end + + subgraph "Overall Complexity" + M[Per Step: O(n² + r·a·c)] + N[Memory: O(n + a + r)] + O[Storage: O(n + a)] + end + + A --> M + E --> M + I --> M + + A --> N + E --> N + + E --> O + A --> O + + style M fill:#ffebee + style N fill:#f3e5f5 + style O fill:#e8f5e8 +``` + +Where: +- `n` = number of RR nodes +- `e` = number of RR edges +- `a` = number of atoms +- `r` = number of inference rules +- `l` = number of links +- `c` = inference cycles + +This architecture documentation provides a comprehensive view of how RR-RNN enhances traditional membrane computing with cognitive capabilities, creating a sophisticated platform for symbolic-subsymbolic integration and emergent pattern recognition. \ No newline at end of file diff --git a/docs/RR_EXAMPLES.md b/docs/RR_EXAMPLES.md new file mode 100644 index 0000000..492451d --- /dev/null +++ b/docs/RR_EXAMPLES.md @@ -0,0 +1,491 @@ +# RR-PLingua Usage Examples and Integration Guide + +This document provides comprehensive examples of using the RR-enhanced membrane computing framework, demonstrating all four major implementation areas with practical code examples and use cases. + +## Quick Start Example + +### Basic RR-Enhanced Membrane System + +```cpp +#include +#include + +using namespace plingua::rr; +using namespace plingua::atomspace; + +int main() { + // Create RR hypergraph + RRHypergraph hypergraph; + + // Add agent and arena membranes + unsigned agent = hypergraph.addMembraneNode(1, "cognitive_agent", AARType::AGENT); + unsigned arena = hypergraph.addMembraneNode(2, "task_environment", AARType::ARENA); + + // Create co-construction relation + hypergraph.addRelationEdge(agent, arena, RREdge::CO_CONSTRUCTION, 0.7); + + // Setup AtomSpace integration + AtomSpace atomspace; + RRAtomSpaceIntegrator integrator(&hypergraph, &atomspace); + + // Run RR dynamics for 10 steps + for (int i = 0; i < 10; ++i) { + hypergraph.updateRelevanceRealization(0.1); + integrator.performIntegration(); + } + + // Find emergent patterns + auto patterns = integrator.findEmergentPatterns(); + for (const auto& pattern : patterns) { + std::cout << "Detected: " << pattern << std::endl; + } + + return 0; +} +``` + +## Advanced PLN Integration Examples + +### 1. PLN Truth Value Operations + +```cpp +#include + +using namespace plingua::pln; + +void demonstratePLNOperations() { + // Create PLN truth values + PLNTruthValue agent_belief(0.8, 0.9); // High strength, high confidence + PLNTruthValue arena_state(0.6, 0.7); // Medium strength, good confidence + + // Perform PLN operations + auto conjunction = agent_belief.conjunction(arena_state); + std::cout << "Conjunction: strength=" << conjunction.strength + << ", confidence=" << conjunction.confidence << std::endl; + + auto implication = agent_belief.implication(arena_state); + std::cout << "Implication: strength=" << implication.strength + << ", confidence=" << implication.confidence << std::endl; + + auto negation = agent_belief.negate(); + std::cout << "Negation: strength=" << negation.strength + << ", confidence=" << negation.confidence << std::endl; +} +``` + +### 2. PLN Inference Engine Usage + +```cpp +void demonstratePLNInference() { + RRHypergraph hypergraph; + AtomSpace atomspace; + PLNInferenceEngine pln_engine(&atomspace); + + // Create high-coupling agent-arena pair + unsigned agent = hypergraph.addMembraneNode(1, "learning_agent", AARType::AGENT); + unsigned arena = hypergraph.addMembraneNode(2, "learning_environment", AARType::ARENA); + hypergraph.addRelationEdge(agent, arena, RREdge::CO_CONSTRUCTION, 0.85); + + // Integrate with AtomSpace + RRAtomSpaceIntegrator integrator(&hypergraph, &atomspace); + integrator.performIntegration(); + + // Generate RR-based implications + pln_engine.generateRRImplications(&hypergraph); + + // Perform deduction + auto deductions = pln_engine.performDeduction(); + std::cout << "Generated " << deductions.size() << " new deductions" << std::endl; + + // Perform abduction (hypothesis generation) + auto abductions = pln_engine.performAbduction(); + std::cout << "Generated " << abductions.size() << " new hypotheses" << std::endl; + + // Full inference cycle + pln_engine.performInferenceCycle(&hypergraph); + auto results = pln_engine.getInferenceResults(); + + for (const auto& result : results) { + std::cout << "PLN Result: " << result << std::endl; + } +} +``` + +## Scheme Interface Examples + +### 1. Interactive REPL Session + +```cpp +#include + +using namespace plingua::scheme; + +void interactiveSchemeSession() { + RRHypergraph hypergraph; + AtomSpace atomspace; + + // Setup test environment + unsigned agent = hypergraph.addMembraneNode(1, "interactive_agent", AARType::AGENT); + unsigned arena = hypergraph.addMembraneNode(2, "interactive_arena", AARType::ARENA); + hypergraph.addRelationEdge(agent, arena, RREdge::INTERACTION, 0.75); + + // Setup AtomSpace integration + RRAtomSpaceIntegrator integrator(&hypergraph, &atomspace); + integrator.performIntegration(); + + // Create Scheme evaluator + SchemeEvaluator evaluator(&hypergraph, &atomspace); + + // Start interactive REPL + std::cout << "Starting Scheme REPL..." << std::endl; + evaluator.startREPL(); // This will run interactively +} +``` + +### 2. Programmatic Scheme Commands + +```cpp +void programmaticSchemeCommands() { + RRHypergraph hypergraph; + AtomSpace atomspace; + SchemeEvaluator evaluator(&hypergraph, &atomspace); + + // Execute various Scheme commands programmatically + std::vector commands = { + "(list-rr-nodes)", + "(get-system-relevance)", + "(find-patterns)", + "(get-salience node-1)", + "(update-salience node-1 0.9)", + "(run-pln-inference)", + "(find-atom \"agent\")" + }; + + for (const auto& cmd : commands) { + std::string result = evaluator.evaluate(cmd); + std::cout << "Command: " << cmd << std::endl; + std::cout << "Result: " << result << std::endl << std::endl; + } +} +``` + +## Persistent Storage Examples + +### 1. Basic Save and Load Operations + +```cpp +#include + +using namespace plingua::persistent; + +void demonstratePersistence() { + RRHypergraph hypergraph; + AtomSpace atomspace; + PersistentAtomSpace storage; + + // Create and populate system + unsigned agent = hypergraph.addMembraneNode(1, "persistent_agent", AARType::AGENT); + unsigned arena = hypergraph.addMembraneNode(2, "persistent_arena", AARType::ARENA); + hypergraph.addRelationEdge(agent, arena, RREdge::CO_CONSTRUCTION, 0.8); + + RRAtomSpaceIntegrator integrator(&hypergraph, &atomspace); + integrator.performIntegration(); + + // Save to files + bool atomspace_saved = storage.saveToFile(&atomspace, "system_atomspace.json"); + bool rr_saved = storage.saveRRHypergraph(&hypergraph, "system_rr_hypergraph.json"); + + std::cout << "AtomSpace saved: " << (atomspace_saved ? "Success" : "Failed") << std::endl; + std::cout << "RR Hypergraph saved: " << (rr_saved ? "Success" : "Failed") << std::endl; + + // Load from files + AtomSpace loaded_atomspace; + RRHypergraph loaded_hypergraph; + + bool atomspace_loaded = storage.loadFromFile(&loaded_atomspace, "system_atomspace.json"); + bool rr_loaded = storage.loadRRHypergraph(&loaded_hypergraph, "system_rr_hypergraph.json"); + + std::cout << "AtomSpace loaded: " << (atomspace_loaded ? "Success" : "Failed") << std::endl; + std::cout << "RR Hypergraph loaded: " << (rr_loaded ? "Success" : "Failed") << std::endl; +} +``` + +### 2. Memory Consolidation and Incremental Learning + +```cpp +void demonstrateMemoryConsolidation() { + AtomSpace atomspace; + PersistentAtomSpace storage; + + // Create atoms with varying confidence levels + unsigned high_conf_atom = atomspace.addConceptNode("reliable_knowledge", 0.9, 0.95); + unsigned med_conf_atom = atomspace.addConceptNode("uncertain_knowledge", 0.6, 0.4); + unsigned low_conf_atom = atomspace.addConceptNode("unreliable_knowledge", 0.3, 0.1); + + std::cout << "Before consolidation: " << atomspace.atoms.size() << " atoms" << std::endl; + + // Consolidate memory (remove atoms with confidence < 0.3) + storage.consolidateMemory(&atomspace, 0.3); + + std::cout << "After consolidation: " << atomspace.atoms.size() << " atoms" << std::endl; + + // Demonstrate incremental learning + AtomSpace new_experience; + unsigned new_atom = new_experience.addConceptNode("new_knowledge", 0.8, 0.85); + + // Merge new experience with existing knowledge + storage.mergeAtomSpaces(&atomspace, &new_experience); + + std::cout << "After merging new experience: " << atomspace.atoms.size() << " atoms" << std::endl; +} +``` + +## Multi-Level Integration Examples + +### 1. Hierarchical Membrane Structure + +```cpp +void demonstrateHierarchicalStructure() { + RRHypergraph hypergraph; + + // Create hierarchical structure + unsigned environment = hypergraph.addMembraneNode(0, "global_environment", AARType::ARENA); + + // Level 1: Outer membranes + unsigned outer_agent = hypergraph.addMembraneNode(1, "outer_cognitive_system", AARType::AGENT); + unsigned outer_arena = hypergraph.addMembraneNode(2, "outer_task_domain", AARType::ARENA); + + // Level 2: Inner membranes + unsigned inner_agent1 = hypergraph.addMembraneNode(3, "perception_module", AARType::AGENT); + unsigned inner_agent2 = hypergraph.addMembraneNode(4, "action_module", AARType::AGENT); + unsigned inner_arena1 = hypergraph.addMembraneNode(5, "sensory_space", AARType::ARENA); + unsigned inner_arena2 = hypergraph.addMembraneNode(6, "motor_space", AARType::ARENA); + + // Create hierarchical relations + hypergraph.addRelationEdge(environment, outer_agent, RREdge::CO_CONSTRUCTION, 0.6); + hypergraph.addRelationEdge(environment, outer_arena, RREdge::CO_CONSTRUCTION, 0.6); + hypergraph.addRelationEdge(outer_agent, outer_arena, RREdge::INTERACTION, 0.8); + + hypergraph.addRelationEdge(outer_agent, inner_agent1, RREdge::CO_CONSTRUCTION, 0.7); + hypergraph.addRelationEdge(outer_agent, inner_agent2, RREdge::CO_CONSTRUCTION, 0.7); + hypergraph.addRelationEdge(outer_arena, inner_arena1, RREdge::CO_CONSTRUCTION, 0.7); + hypergraph.addRelationEdge(outer_arena, inner_arena2, RREdge::CO_CONSTRUCTION, 0.7); + + hypergraph.addRelationEdge(inner_agent1, inner_arena1, RREdge::INTERACTION, 0.9); + hypergraph.addRelationEdge(inner_agent2, inner_arena2, RREdge::INTERACTION, 0.9); + + std::cout << "Created hierarchical structure with " << hypergraph.nodes.size() << " nodes" << std::endl; + std::cout << "and " << hypergraph.edges.size() << " edges" << std::endl; + + // Run multi-level dynamics + for (int i = 0; i < 20; ++i) { + hypergraph.updateRelevanceRealization(0.05); + } + + // Analyze cross-level emergence + double outer_salience = hypergraph.nodes[outer_agent]->salience; + double inner_coherence = (hypergraph.nodes[inner_agent1]->computeTrialecticCoherence() + + hypergraph.nodes[inner_agent2]->computeTrialecticCoherence()) / 2.0; + + if (outer_salience > 0.6 && inner_coherence > 0.3) { + std::cout << "Cross-level emergence detected!" << std::endl; + std::cout << "Outer salience: " << outer_salience << std::endl; + std::cout << "Inner coherence: " << inner_coherence << std::endl; + } +} +``` + +### 2. Temporal Reasoning and Evolution Tracking + +```cpp +void demonstrateTemporalReasoning() { + RRHypergraph hypergraph; + + // Create simple agent-arena system + unsigned agent = hypergraph.addMembraneNode(1, "evolving_agent", AARType::AGENT); + unsigned arena = hypergraph.addMembraneNode(2, "changing_arena", AARType::ARENA); + hypergraph.addRelationEdge(agent, arena, RREdge::CO_CONSTRUCTION, 0.5); + + // Track system evolution over time + std::vector temporal_relevance; + std::vector temporal_coupling; + + for (int t = 0; t < 50; ++t) { + hypergraph.updateRelevanceRealization(0.1); + + // Calculate system-wide relevance + double total_relevance = 0.0; + for (auto it = hypergraph.nodes.begin(); it != hypergraph.nodes.end(); ++it) { + total_relevance += it->second->computeRelevanceGradient(); + } + double avg_relevance = total_relevance / hypergraph.nodes.size(); + temporal_relevance.push_back(avg_relevance); + + // Calculate coupling strength + double coupling = hypergraph.computeCouplingStrength(agent, arena); + temporal_coupling.push_back(coupling); + + if (t % 10 == 0) { + std::cout << "Time " << t << ": relevance=" << avg_relevance + << ", coupling=" << coupling << std::endl; + } + } + + // Analyze temporal trends + if (temporal_relevance.size() >= 10) { + double recent_avg = 0.0, earlier_avg = 0.0; + for (int i = 0; i < 10; ++i) { + recent_avg += temporal_relevance[temporal_relevance.size() - 1 - i]; + earlier_avg += temporal_relevance[i]; + } + recent_avg /= 10; + earlier_avg /= 10; + + double trend = recent_avg - earlier_avg; + std::cout << "Temporal trend: " << (trend > 0.01 ? "increasing" : + trend < -0.01 ? "decreasing" : "stable") + << " (Δ=" << trend << ")" << std::endl; + } +} +``` + +## Complete Integration Example + +### Full RR-RNN System Demonstration + +```cpp +#include +#include +#include +#include +#include + +void fullSystemDemo() { + std::cout << "=== Full RR-RNN System Demonstration ===" << std::endl; + + // Initialize all components + RRHypergraph hypergraph; + AtomSpace atomspace; + RRAtomSpaceIntegrator integrator(&hypergraph, &atomspace); + PLNInferenceEngine pln_engine(&atomspace); + SchemeEvaluator scheme_eval(&hypergraph, &atomspace); + PersistentAtomSpace storage; + + // Create test environment + unsigned env = hypergraph.addMembraneNode(0, "test_environment", AARType::ARENA); + unsigned agent = hypergraph.addMembraneNode(1, "cognitive_agent", AARType::AGENT); + unsigned arena = hypergraph.addMembraneNode(2, "task_arena", AARType::ARENA); + + hypergraph.addRelationEdge(env, agent, RREdge::INTERACTION, 0.5); + hypergraph.addRelationEdge(agent, arena, RREdge::CO_CONSTRUCTION, 0.7); + + // Phase 1: RR Dynamics Evolution + std::cout << "\n--- Phase 1: RR Dynamics ---" << std::endl; + for (int i = 0; i < 15; ++i) { + hypergraph.updateRelevanceRealization(0.1); + if (i % 5 == 0) { + integrator.performIntegration(); + auto patterns = integrator.findEmergentPatterns(); + if (!patterns.empty()) { + std::cout << "Step " << i << " - Emergent patterns: " << patterns.size() << std::endl; + } + } + } + + // Phase 2: PLN Integration + std::cout << "\n--- Phase 2: PLN Integration ---" << std::endl; + pln_engine.generateRRImplications(&hypergraph); + pln_engine.performInferenceCycle(&hypergraph); + auto pln_results = pln_engine.getInferenceResults(); + + for (const auto& result : pln_results) { + std::cout << "PLN: " << result << std::endl; + } + + // Phase 3: Scheme Interface + std::cout << "\n--- Phase 3: Scheme Interface ---" << std::endl; + std::vector demo_commands = { + "(get-system-relevance)", + "(find-patterns)", + "(run-pln-inference)", + "(list-rr-nodes)" + }; + + for (const auto& cmd : demo_commands) { + std::string result = scheme_eval.evaluate(cmd); + std::cout << "scheme> " << cmd << std::endl; + std::cout << result << std::endl; + } + + // Phase 4: Persistence + std::cout << "\n--- Phase 4: Persistence ---" << std::endl; + bool atomspace_saved = storage.saveToFile(&atomspace, "/tmp/full_demo_atomspace.json"); + bool rr_saved = storage.saveRRHypergraph(&hypergraph, "/tmp/full_demo_rr.json"); + + std::cout << "System state saved: " + << (atomspace_saved && rr_saved ? "Success" : "Failed") << std::endl; + + // Memory consolidation + size_t atoms_before = atomspace.atoms.size(); + storage.consolidateMemory(&atomspace, 0.3); + size_t atoms_after = atomspace.atoms.size(); + + std::cout << "Memory consolidation: " << atoms_before << " → " << atoms_after + << " atoms (removed " << (atoms_before - atoms_after) << ")" << std::endl; + + std::cout << "\n=== Full System Demo Complete ===" << std::endl; +} +``` + +## Performance Monitoring Examples + +### System Performance Analysis + +```cpp +void performanceAnalysis() { + RRHypergraph hypergraph; + AtomSpace atomspace; + + // Create larger test system + const int num_agents = 10; + const int num_arenas = 8; + + std::vector agents, arenas; + + for (int i = 0; i < num_agents; ++i) { + agents.push_back(hypergraph.addMembraneNode(i, "agent_" + std::to_string(i), AARType::AGENT)); + } + + for (int i = 0; i < num_arenas; ++i) { + arenas.push_back(hypergraph.addMembraneNode(100 + i, "arena_" + std::to_string(i), AARType::ARENA)); + } + + // Create connections + for (unsigned agent : agents) { + for (unsigned arena : arenas) { + if (rand() % 100 < 30) { // 30% connection probability + double strength = 0.3 + (rand() % 50) / 100.0; + hypergraph.addRelationEdge(agent, arena, RREdge::INTERACTION, strength); + } + } + } + + std::cout << "Created system with " << hypergraph.nodes.size() << " nodes and " + << hypergraph.edges.size() << " edges" << std::endl; + + // Performance timing + auto start_time = std::chrono::high_resolution_clock::now(); + + for (int i = 0; i < 100; ++i) { + hypergraph.updateRelevanceRealization(0.05); + } + + auto end_time = std::chrono::high_resolution_clock::now(); + auto duration = std::chrono::duration_cast(end_time - start_time); + + std::cout << "100 RR update cycles completed in " << duration.count() << " ms" << std::endl; + std::cout << "Average per cycle: " << (duration.count() / 100.0) << " ms" << std::endl; +} +``` + +These comprehensive examples demonstrate the full capabilities of the RR-enhanced membrane computing framework, showing how to leverage all four major implementation areas for sophisticated cognitive architecture applications. \ No newline at end of file diff --git a/docs/RR_PROCESS_FLOWS.md b/docs/RR_PROCESS_FLOWS.md new file mode 100644 index 0000000..d4015b9 --- /dev/null +++ b/docs/RR_PROCESS_FLOWS.md @@ -0,0 +1,518 @@ +# RR-RNN Process Flow Diagrams + +This document contains PlantUML diagrams showing the detailed process flows of the RR-RNN system components. + +## Overall System Process Flow + +```plantuml +@startuml RR-RNN-System-Flow +!theme plain +title RR-RNN System Process Flow + +actor User +participant "P-Lingua Parser" as Parser +participant "RR Hypergraph" as RR +participant "AtomSpace" as AS +participant "PLN Engine" as PLN +participant "Scheme REPL" as Scheme +participant "Persistent Storage" as Storage + +== Initialization == +User -> Parser: Load P-system definition +Parser -> RR: Create RR hypergraph from membranes +RR -> AS: Initialize AtomSpace integration +AS -> PLN: Setup PLN inference engine +PLN -> Scheme: Register command interface + +== Runtime Dynamics == +loop Continuous RR Evolution + RR -> RR: Update trialectic states + note right: ∀^ω(x ⇔^α y ⇔^α z ⇔^α x) + + RR -> RR: Compute relevance gradients + note right: ∇ℜ = lim_{t→∞} Σᵢ log(aᵣᵢ(t)/aₚᵢ(t)) + + RR -> AS: Synchronize node properties + AS -> PLN: Generate new implications + + PLN -> PLN: Perform deduction cycle + note right: A→B, A ⊢ B + + PLN -> PLN: Perform abduction cycle + note right: A→B, B ⊢ A (reduced confidence) + + PLN -> AS: Update truth values + AS -> RR: Feedback relevance updates + + RR -> RR: Detect emergent patterns + note right: Agent-arena coupling > threshold +end + +== Interactive Exploration == +User -> Scheme: Execute Scheme commands +alt Query Commands + Scheme -> RR: (list-rr-nodes) + RR -> Scheme: Return node properties +else Update Commands + Scheme -> RR: (update-salience node-ID value) + RR -> AS: Propagate changes + AS -> PLN: Trigger inference update +else Inference Commands + Scheme -> PLN: (run-pln-inference) + PLN -> AS: Execute inference cycle + AS -> Scheme: Return inference results +end + +Scheme -> User: Display results + +== Persistence == +User -> Storage: Save system state +Storage -> AS: Serialize AtomSpace to JSON +Storage -> RR: Serialize RR hypergraph to JSON +Storage -> Storage: Consolidate memory (remove low-confidence atoms) +Storage -> User: Confirm persistence complete + +@enduml +``` + +## RR Trialectic Dynamics Process + +```plantuml +@startuml RR-Trialectic-Process +!theme plain +title RR Trialectic Co-Constitution Process + +participant "Agent Membrane" as Agent +participant "Arena Membrane" as Arena +participant "Relation Component" as Relation +participant "Trialectic Engine" as Engine + +== Initial State == +Agent -> Engine: Initial salience, affordance potential +Arena -> Engine: Initial salience, affordance potential +Relation -> Engine: Initial coupling strength + +== Trialectic Update Cycle == +loop Continuous Evolution + Engine -> Engine: Compute trialectic state vector + note right: [x, y, z] representing agent-arena-relation + + Engine -> Agent: Update based on arena + relation influence + note right: new_state[i] += coupling * (state[next] - state[prev]) / 2 + + Engine -> Arena: Update based on agent + relation influence + Engine -> Relation: Update based on agent + arena influence + + Agent -> Engine: Updated salience + Arena -> Engine: Updated affordance realization + Relation -> Engine: Updated coupling strength + + Engine -> Engine: Apply tanh normalization + note right: Keep states bounded in [-1, 1] + + Engine -> Engine: Compute trialectic coherence + note right: coherence = Σ(state[i] * state[next]) / n + + alt High Coherence (> 0.6) + Engine -> Engine: Amplify co-constitution effects + note right: Positive feedback loop + else Low Coherence (< 0.3) + Engine -> Engine: Dampen interactions + note right: Prevent instability + end + + Engine -> Engine: Update relevance gradient + note right: ∇ℜ = log(affordance_realization / affordance_potential) +end + +@enduml +``` + +## PLN Inference Process Flow + +```plantuml +@startuml PLN-Inference-Process +!theme plain +title PLN Inference Engine Process Flow + +participant "RR Hypergraph" as RR +participant "PLN Engine" as PLN +participant "AtomSpace" as AS +participant "Implication Generator" as ImpGen +participant "Deduction Engine" as Ded +participant "Abduction Engine" as Abd + +== Implication Generation == +RR -> PLN: High-coupling agent-arena pairs +PLN -> ImpGen: Agent-arena relationship data +ImpGen -> AS: Find corresponding atoms +AS -> ImpGen: Agent and arena atom IDs + +ImpGen -> ImpGen: Calculate implication strength +note right: strength = coupling_strength +ImpGen -> ImpGen: Calculate implication confidence +note right: confidence = min(agent_salience, arena_salience) + +ImpGen -> AS: Create implication link +note right: Agent → Arena with (strength, confidence) + +== Deduction Cycle == +PLN -> AS: Find all implication links +AS -> PLN: Implication atoms + +loop For each implication A→B + PLN -> AS: Find atoms matching antecedent A + AS -> PLN: Antecedent instances with truth values + + alt Antecedent strength > 0.7 + PLN -> Ded: Apply deduction rule + Ded -> Ded: Calculate consequent truth value + note right: TV(B) = TV(A→B) ⋅ TV(A)\nstrength = impl_strength ⋅ ant_strength\nconfidence = min(impl_conf, ant_conf) + + Ded -> AS: Update consequent truth value + AS -> PLN: Confirm update + PLN -> PLN: Record new conclusion + end +end + +== Abduction Cycle == +loop For each implication A→B + PLN -> AS: Find atoms matching consequent B + AS -> PLN: Consequent instances with truth values + + alt Consequent strength > 0.7 + PLN -> Abd: Apply abduction rule + Abd -> Abd: Calculate antecedent hypothesis + note right: TV(A) = TV(B) ⋅ TV(A→B) ⋅ 0.8\nReduced confidence: 0.6 factor + + Abd -> AS: Update antecedent as hypothesis + AS -> PLN: Confirm hypothesis + PLN -> PLN: Record new hypothesis + end +end + +== Results Integration == +PLN -> RR: Return inference results summary +RR -> RR: Integrate PLN feedback into RR dynamics + +@enduml +``` + +## Scheme Interface Command Processing + +```plantuml +@startuml Scheme-Command-Process +!theme plain +title Scheme Interface Command Processing + +actor User +participant "Scheme REPL" as REPL +participant "Expression Parser" as Parser +participant "Command Router" as Router +participant "RR Interface" as RRInt +participant "AtomSpace Interface" as ASInt +participant "PLN Interface" as PLNInt + +== Command Input == +User -> REPL: Enter Scheme expression +REPL -> Parser: Parse expression string +Parser -> Parser: Tokenize and validate syntax + +alt Valid Expression + Parser -> Router: Parsed command structure +else Invalid Expression + Parser -> REPL: Syntax error message + REPL -> User: Display error +end + +== Command Routing == +Router -> Router: Identify command type + +alt RR Query Commands + Router -> RRInt: (list-rr-nodes) + RRInt -> RRInt: Collect all RR nodes + RRInt -> Router: Formatted node list + + Router -> RRInt: (get-salience node-ID) + RRInt -> RRInt: Look up specific node + RRInt -> Router: Node salience value + + Router -> RRInt: (get-system-relevance) + RRInt -> RRInt: Compute average relevance gradient + RRInt -> Router: System-wide relevance + +else AtomSpace Query Commands + Router -> ASInt: (list-atoms) + ASInt -> ASInt: Iterate through atom registry + ASInt -> Router: Formatted atom list + + Router -> ASInt: (find-atom "name") + ASInt -> ASInt: Search atoms by name pattern + ASInt -> Router: Matching atoms + +else Update Commands + Router -> RRInt: (update-salience node-ID value) + RRInt -> RRInt: Validate node ID and value + RRInt -> RRInt: Update node salience + RRInt -> Router: Update confirmation + +else Inference Commands + Router -> PLNInt: (run-pln-inference) + PLNInt -> PLNInt: Execute full inference cycle + PLNInt -> Router: Inference results summary + + Router -> RRInt: (find-patterns) + RRInt -> RRInt: Analyze RR emergence patterns + RRInt -> Router: Detected patterns + +else Unknown Command + Router -> REPL: Unknown command error +end + +== Response Formatting == +Router -> REPL: Command result +REPL -> REPL: Format as Scheme-style output +REPL -> User: Display formatted result + +@enduml +``` + +## Persistent Storage Process Flow + +```plantuml +@startuml Persistent-Storage-Process +!theme plain +title Persistent Storage and Memory Consolidation + +participant "User Request" as User +participant "Storage Manager" as Storage +participant "AtomSpace Serializer" as ASSerial +participant "RR Serializer" as RRSerial +participant "JSON Writer" as JSON +participant "Memory Consolidator" as Consolidator +participant "File System" as FS + +== Save Operation == +User -> Storage: Request save to file +Storage -> ASSerial: Serialize AtomSpace +Storage -> RRSerial: Serialize RR hypergraph + +== AtomSpace Serialization == +ASSerial -> ASSerial: Iterate through atoms +loop For each atom + ASSerial -> JSON: Write atom metadata + note right: {"id": N, "type": T, "name": "X"} + ASSerial -> JSON: Write truth values + note right: "strength": S, "confidence": C + ASSerial -> JSON: Write outgoing links + note right: "outgoing": [id1, id2, ...] +end +ASSerial -> JSON: Write next_atom_id +ASSerial -> Storage: AtomSpace JSON ready + +== RR Hypergraph Serialization == +RRSerial -> RRSerial: Iterate through RR nodes +loop For each RR node + RRSerial -> JSON: Write node properties + note right: id, type, aar_type, label + RRSerial -> JSON: Write RR dynamics + note right: salience, affordance_potential, affordance_realization + RRSerial -> JSON: Write trialectic state + note right: [x, y, z] vector +end + +RRSerial -> RRSerial: Iterate through RR edges +loop For each RR edge + RRSerial -> JSON: Write edge properties + note right: id, type, from_node, to_node, strength +end +RRSerial -> Storage: RR JSON ready + +== Memory Consolidation == +Storage -> Consolidator: Request memory optimization +Consolidator -> Consolidator: Analyze atom confidence levels + +loop For each atom + alt Confidence < threshold (0.3) + Consolidator -> Consolidator: Mark for removal + note right: Low-confidence atoms are pruned + else Confidence >= threshold + Consolidator -> Consolidator: Keep in active memory + end +end + +Consolidator -> Consolidator: Remove marked atoms +Consolidator -> Storage: Report consolidation results + +== File Writing == +Storage -> FS: Write AtomSpace JSON file +Storage -> FS: Write RR hypergraph JSON file +FS -> Storage: Confirm file creation +Storage -> User: Save operation complete + +== Load Operation == +User -> Storage: Request load from file +Storage -> FS: Read AtomSpace JSON file +Storage -> FS: Read RR hypergraph JSON file +FS -> Storage: Return file contents + +Storage -> ASSerial: Deserialize AtomSpace +Storage -> RRSerial: Deserialize RR hypergraph + +ASSerial -> ASSerial: Parse JSON and recreate atoms +RRSerial -> RRSerial: Parse JSON and recreate RR structures + +Storage -> User: Load operation complete + +@enduml +``` + +## Multi-Level Emergence Detection + +```plantuml +@startuml Multi-Level-Emergence +!theme plain +title Multi-Level Emergence Detection Process + +participant "Emergence Monitor" as Monitor +participant "Agent Tracker" as AgentTrack +participant "Arena Tracker" as ArenaTrack +participant "Coupling Analyzer" as Coupling +participant "Coherence Calculator" as Coherence +participant "Pattern Recognizer" as Pattern +participant "Emergent Relation Creator" as Creator + +== Continuous Monitoring == +loop System Evolution + Monitor -> AgentTrack: Check all agent nodes + + AgentTrack -> AgentTrack: Scan agent salience levels + loop For each agent + alt Salience > 0.8 + AgentTrack -> Monitor: High-salience agent detected + Monitor -> ArenaTrack: Find coupled arenas for agent + + ArenaTrack -> Coupling: Analyze agent-arena pairs + loop For each arena + Coupling -> Coupling: Compute coupling strength + note right: strength = Σ(edge_weights) / edge_count + + alt Coupling > 0.8 + Coupling -> Monitor: Strong coupling detected + Monitor -> Coherence: Calculate trialectic coherence + + Coherence -> Coherence: Measure state correlations + note right: coherence = Σ(state[i] * state[next]) / n + + alt Coherence > 0.6 + Coherence -> Pattern: Emergent pattern candidate + Pattern -> Pattern: Validate emergence criteria + + Pattern -> Pattern: Check temporal consistency + Pattern -> Pattern: Verify cross-level interactions + + alt All criteria met + Pattern -> Creator: Create emergent relation + Creator -> Creator: Generate new relation node + note right: Type = EMERGENT, connects agent-arena + Creator -> Creator: Set emergent properties + note right: salience = (agent + arena) * 0.5\naffordance_realization = 1.0 + Creator -> Monitor: Emergence event recorded + end + end + end + end + end + end + + Monitor -> Monitor: Update emergence statistics + Monitor -> Monitor: Log system evolution metrics +end + +@enduml +``` + +## Integration Test Flow + +```plantuml +@startuml Integration-Test-Flow +!theme plain +title RR-RNN Integration Test Process + +participant "Test Runner" as Test +participant "RR Enhanced Test" as RRTest +participant "Next Directions Test" as NDTest +participant "Demo REPL Test" as REPLTest +participant "Validation Engine" as Validator + +== Test Initialization == +Test -> Test: Setup test environment +Test -> RRTest: Initialize basic RR test +Test -> NDTest: Initialize comprehensive test +Test -> REPLTest: Initialize REPL demo test + +== Basic RR Enhanced Test == +Test -> RRTest: Run test_rr_enhanced +RRTest -> RRTest: Create RR hypergraph +RRTest -> RRTest: Add test membranes (agent, arena, environment) +RRTest -> RRTest: Create AtomSpace integration +RRTest -> RRTest: Run 50 simulation steps + +loop 10-step intervals + RRTest -> RRTest: Update RR dynamics + RRTest -> RRTest: Sync with AtomSpace + RRTest -> RRTest: Check for emergent patterns + RRTest -> Validator: Validate state consistency +end + +RRTest -> RRTest: Compute final system relevance +RRTest -> Test: Basic test results + +== Comprehensive Next Directions Test == +Test -> NDTest: Run test_next_directions +NDTest -> NDTest: Setup comprehensive environment + +NDTest -> NDTest: Test PLN Integration +note right: Generate implications, run inference cycles +NDTest -> NDTest: Test Scheme Interface +note right: Execute 8+ command types +NDTest -> NDTest: Test Persistent Storage +note right: Save/load, memory consolidation +NDTest -> NDTest: Test Multi-Level Integration +note right: Hierarchical structures, emergence detection + +NDTest -> Validator: Validate all subsystem interactions +NDTest -> Test: Comprehensive test results + +== REPL Demo Test == +Test -> REPLTest: Run demo_repl +REPLTest -> REPLTest: Create test RR environment +REPLTest -> REPLTest: Start Scheme evaluator +REPLTest -> REPLTest: Execute demo command sequence + +loop Demo commands + REPLTest -> REPLTest: (list-rr-nodes) + REPLTest -> REPLTest: (get-system-relevance) + REPLTest -> REPLTest: (find-patterns) + REPLTest -> REPLTest: (get-salience node-1) + REPLTest -> Validator: Validate command responses +end + +REPLTest -> Test: REPL test results + +== Final Validation == +Test -> Validator: Aggregate all test results +Validator -> Validator: Check implementation completeness +note right: ✓ PLN Integration\n✓ Scheme Interface\n✓ Persistent Storage\n✓ Multi-Level Integration + +Validator -> Validator: Verify system stability +Validator -> Validator: Confirm feature integration +Validator -> Test: Final validation report + +Test -> Test: Generate test summary +note right: All Next Development Directions\nsuccessfully implemented and tested + +@enduml +``` + +These PlantUML diagrams provide detailed process flows for all major components of the RR-RNN system, showing the intricate interactions between relevance realization dynamics, symbolic reasoning, and cognitive architecture integration. \ No newline at end of file