Metadata-Version: 2.4
Name: living-memory-dynamics
Version: 1.3.0
Summary: Living Memory Dynamics - A Novel Framework for Narrative-Generating Episodic Memory with Creative Leaps and Language Grounding
Author-email: "Joshua R. Thomas" <mordiaky@gmail.com>
License: Living Memory Dynamics (LMD) License
        Version 1.1, January 2026
        
        Copyright (c) 2026 Joshua R. Thomas. All rights reserved.
        
        PATENT NOTICE
        =============
        Living Memory Dynamics (LMD) and its associated algorithms, including but not
        limited to the Joshua R. Thomas Memory Equation, Creative Leap Operators (Analogical
        Transfer, Manifold Walking, Orthogonal Composition, Void Extrapolation),
        Hierarchical Ideas with Grafting, and Active Curiosity Probing, may be subject
        to pending or granted patent applications.
        
        GRANT OF LICENSE
        ================
        Subject to the terms and conditions of this License, the copyright holder
        hereby grants you a non-exclusive, royalty-free license to:
        
        1. USE the Software for personal, educational, and non-commercial research
           purposes.
        
        2. MODIFY and create derivative works of the Software for the purposes
           described in (1).
        
        3. DISTRIBUTE copies of the Software and derivative works, provided that:
           a. You include a copy of this License with any distribution
           b. You clearly mark any modifications as your own work
           c. You do not remove or alter any patent notices or copyright notices
        
        RESTRICTIONS
        ============
        Without prior written permission from the copyright holder, you MAY NOT:
        
        1. Use the Software or any derivative work for commercial purposes, including
           but not limited to: incorporating into commercial products, offering as a
           service (SaaS), or using in production systems that generate revenue.
        
        2. Sublicense, sell, or transfer the Software or patent rights to third
           parties.
        
        3. Use the name "Living Memory Dynamics", "LMD", "Joshua R. Thomas Memory
           Equation", or related trademarks in any commercial context without permission.
        
        TRADEMARK AND NAMING
        ====================
        The following names and marks are reserved and may NOT be used without prior
        written permission from the copyright holder:
        
        - "Living Memory Dynamics" or "LMD"
        - "Joshua R. Thomas Memory Equation"
        - "Creative Leap Operators"
        - Any confusingly similar names or variations
        
        For derivative works and forks:
        
        1. You MUST use a distinctly different name for your project
        2. You MUST include a prominent notice stating:
           "This project is not affiliated with, endorsed by, or officially
           connected to Living Memory Dynamics (LMD) or Joshua R. Thomas."
        3. You MAY NOT use "LMD" or "Living Memory" in your project name, domain
           name, or organizational name
        4. You MAY state that your project is "based on" or "derived from" LMD,
           provided it is accompanied by the non-affiliation notice above
        
        COMMERCIAL LICENSING
        ====================
        For commercial use, enterprise licensing, or patent licensing inquiries,
        please contact: mordiaky@gmail.com
        
        PATENT GRANT (LIMITED)
        ======================
        Subject to the restrictions above, the copyright holder grants you a limited,
        non-exclusive, royalty-free patent license to make, use, and practice the
        patented methods SOLELY for non-commercial purposes as described in the
        Grant of License section.
        
        This patent grant does NOT extend to:
        - Commercial use of any kind
        - Use in production systems
        - Sublicensing or transfer of patent rights
        - Creation of competing commercial products
        
        TERMINATION
        ===========
        This License and the rights granted hereunder will terminate automatically
        if you fail to comply with any of its terms. Upon termination, you must
        destroy all copies of the Software in your possession.
        
        DISCLAIMER
        ==========
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
        GOVERNING LAW AND JURISDICTION
        ==============================
        This License shall be governed by and construed in accordance with the laws
        of the State of California, United States, without regard to its conflict of
        law provisions. Any legal action or proceeding arising under this License
        shall be brought exclusively in the federal or state courts located in
        California, and the parties hereby consent to personal jurisdiction and
        venue therein.
        
        ---
        
        For a fully open-source version (Apache 2.0), this license will automatically
        convert on: [DATE - typically 3-4 years from release]
        
        Or upon any of the following conditions:
        - The software is not commercialized within 3 years
        - Written permission is granted by the copyright holder
        - The patent applications are abandoned or not granted
        
Project-URL: Homepage, https://github.com/mordiaky/living-memory-dynamics
Project-URL: Documentation, https://github.com/mordiaky/living-memory-dynamics#readme
Project-URL: Repository, https://github.com/mordiaky/living-memory-dynamics
Project-URL: Issues, https://github.com/mordiaky/living-memory-dynamics/issues
Keywords: memory,episodic-memory,narrative,creative-ai,embedding,cognitive-architecture,neural-network,imagination,creativity
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0.0
Requires-Dist: numpy>=1.20.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Provides-Extra: cuda
Requires-Dist: triton>=2.0.0; extra == "cuda"
Provides-Extra: language
Requires-Dist: sentence-transformers>=2.2.0; extra == "language"
Provides-Extra: llm
Requires-Dist: ollama>=0.1.0; extra == "llm"
Requires-Dist: openai>=1.0.0; extra == "llm"
Provides-Extra: all
Requires-Dist: living-memory-dynamics[cuda,dev,language,llm]; extra == "all"
Dynamic: license-file

# Living Memory Dynamics (LMD)

> **A Novel Framework for Narrative-Generating Episodic Memory with Creative Leaps and Language Grounding**

[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![PyTorch](https://img.shields.io/badge/PyTorch-2.0+-ee4c2c.svg)](https://pytorch.org/)
[![License](https://img.shields.io/badge/license-Custom-orange.svg)](LICENSE)
[![Version](https://img.shields.io/badge/version-1.3.0-green.svg)]()

## What Makes LMD Different?

Traditional memory systems store static embeddings. **LMD treats memories as living entities** that:

- **Breathe**: Memories have metabolic energy (vivid, active, dormant, fading, ghost)
- **Feel**: Emotional trajectories, not single valence tags
- **Tell Stories**: Narrative phases (setup → conflict → climax → resolution)
- **Resonate**: Memories couple and influence each other through resonance fields
- **Create**: Generate novel ideas through internal creative leaps

## The Joshua R. Thomas Memory Equation

```
dM/dt = ∇φ(N) + Σⱼ Γᵢⱼ R(vᵢ, vⱼ) + A(M, ξ) + κη(t)
```

Where:
- `∇φ(N)` = Narrative potential (story attractor landscape)
- `R(vᵢ, vⱼ)` = Resonance function (emotional coupling between memories)
- `A(M, ξ)` = Activation function (contextual triggering)
- `κη(t)` = Creative noise (generative stochasticity)

## Creative Leaps (v1.1.0)

LMD doesn't just store—it **invents**. Four internal operators enable human-like creative jumps:

| Operator | What It Does | Example |
|----------|-------------|---------|
| **Analogical Transfer** | Transplants patterns between distant domains | "dragon fire" + "glass refraction" → "prismatic breath weapon" |
| **Manifold Walker** | Diffuses through embedding space | Gradual concept morphing |
| **Orthogonal Composer** | Gram-Schmidt perpendicular merges | Combines concepts along independent axes |
| **Void Extrapolator** | Ray-traces into unexplored territory | Discovers genuinely novel concepts |

```python
from lmd import CreativeLeapEngine, LivingMemory

engine = CreativeLeapEngine(content_dim=256)
memories = [LivingMemory.create(embedding) for embedding in my_embeddings]

# Generate creative leaps
leaps = engine.batch_leap(memories, n_leaps=5, dopamine=0.8)
for leap in leaps:
    print(f"{leap.leap_type}: novelty={leap.novelty:.2f}")
```

## Language Grounding (v1.3.0)

**The Problem**: LMD creates ideas as vectors - you can't read what they mean.

**The Solution**: Language Grounding bridges vectors and human-readable text.

```
Text Input --> Embedding --> Creative Leap --> New Embedding --> Text Output
"dragon"   --> [0.2, 0.8..] --> ORTHOGONAL --> [0.5, 0.3..] --> "prismatic creature"
```

### Does LMD work without Language Grounding?

**Yes!** Language Grounding is **100% optional**. Core LMD works fine without it:
- Core LMD: `pip install living-memory-dynamics` (vectors only)
- With Language: `pip install living-memory-dynamics[language]` (text in/out)

### Quick Example

```python
from lmd import create_grounding, CreativeLeapEngine

# Create grounding (downloads MiniLM model ~80MB first time)
grounding = create_grounding(encoder="minilm")

# Encode text to embeddings
dragon = grounding.encode("fire-breathing dragon")
glass = grounding.encode("crystalline glass structure")

# Build a corpus for decoding
grounding.add_to_corpus("fire-breathing dragon")
grounding.add_to_corpus("crystalline glass structure")
grounding.add_to_corpus("stained glass window")
grounding.add_to_corpus("dragon scales armor")

# Blend two concepts
blended = (dragon + glass) / 2
blended = blended / blended.norm()

# Decode back to text
result = grounding.decode(blended, top_k=3)
print(result.interpolated_description)
# Output: "blend of 'crystalline glass structure' (50%) and 'fire-breathing dragon' (50%)"
```

### Generate New Ideas with Text Output

```python
# Create leap engine matching embedding dimension
engine = CreativeLeapEngine(content_dim=grounding.embedding_dim)

# Encode source concepts
sources = [
    grounding.encode("volcanic eruption").cpu(),
    grounding.encode("frozen ice sculpture").cpu(),
    grounding.encode("rainbow spectrum").cpu(),
]

# Generate creative leap
leap = engine.leap(sources, dopamine=0.7)

# Describe what was created
description = grounding.describe_leap(
    leap_type=leap.leap_type.name,
    sources=sources,
    result=leap.embedding,
)
print(description.synthesized_description)
# Output: "Extrapolated beyond 'volcanic eruption' + 'frozen ice' + 'rainbow' into [novel concept]"
print(f"Novelty: {description.novelty_score}")
# Output: "Novelty: 1.0" (completely new!)
```

### Ground Living Memories to Readable Text

```python
from lmd import LivingMemory, ValenceTrajectory, NarrativePhase

# Create a memory from text
embedding = grounding.encode("ancient dragon guarding treasure")
memory = LivingMemory(
    id="memory_0",
    content=embedding,
    energy=0.8,
    valence=ValenceTrajectory(points=torch.tensor([0.5, 0.7, 0.6])),
    phase=NarrativePhase.SETUP,
)

# Later, decode what the memory represents
grounded = grounding.ground_memory(memory)
print(grounded.text)
# Output: "blend of 'ancient dragon guarding treasure' (64%) and 'ancient mythical creature' (36%)"
```

### Run the Full Demo

```bash
# Install with language support
pip install living-memory-dynamics[language]

# Run the demo
python -c "from lmd.examples import language_grounding; language_grounding.main()"
# Or clone and run:
git clone https://github.com/mordiaky/LMD.git
cd LMD
pip install -e ".[language]"
python examples/language_grounding.py
```

## Installation

```bash
# Core only (vectors, no text)
pip install living-memory-dynamics

# With language grounding (text in/out)
pip install living-memory-dynamics[language]

# With GPU acceleration (Triton CUDA kernels)
pip install living-memory-dynamics[cuda]

# Everything (language + cuda + dev tools)
pip install living-memory-dynamics[all]
```

Or from source:

```bash
git clone https://github.com/mordiaky/LMD.git
cd LMD
pip install -e ".[language]"  # or [all] for everything
```

## Quick Start

### 1. Create Living Memories

```python
import torch
from lmd import LivingMemory, ValenceTrajectory, NarrativePhase

# Memories are born with energy, emotion, and narrative phase
memory = LivingMemory(
    id="memory_001",
    content=torch.randn(256),  # Embedding vector
    energy=1.0,  # Metabolic energy (0-2)
    valence=ValenceTrajectory.from_arc(onset=0.3, peak=0.9, resolution=0.6),
    phase=NarrativePhase.SETUP
)
```

### 2. Let Memories Evolve

```python
from lmd import LMDDynamics, LMDConfig

config = LMDConfig(content_dim=256)
dynamics = LMDDynamics(config)

# Step the system forward
for t in range(100):
    dynamics.step(memories, dt=0.01)
    # Memories naturally evolve, couple, and generate narratives
```

### 3. Generate Creative Ideas

```python
from lmd import CreativeIdeationEngine, CreativeIdeationConfig

config = CreativeIdeationConfig(content_dim=256)
engine = CreativeIdeationEngine(config)

# Ideate with dopamine modulation
result = engine.ideate(memories, dopamine=0.7, n_ideas=10)

for idea in result.ideas[:5]:
    print(f"Form: {idea.form}, Novelty: {idea.novelty:.2f}, Score: {idea.total_score:.2f}")
```

### 4. Hierarchical Ideas with Grafting

```python
from lmd import HierarchicalIdeaFactory, IdeaGrafter

factory = HierarchicalIdeaFactory(content_dim=256)
grafter = IdeaGrafter(content_dim=256)

# Create tree-structured ideas
dragon = factory.from_embedding(dragon_embedding, depth=3)
crystal = factory.from_embedding(crystal_embedding, depth=3)

# Graft components between ideas
result = grafter.swap_component(dragon, crystal.root, target_id="fire_component")
# Result: dragon with crystalline properties
```

## Architecture

```
lmd/
├── living_memory.py       # Core LivingMemory datastructure
├── dynamics.py            # LMDDynamics engine
├── coupling.py            # Memory resonance fields
├── metabolism.py          # Energy dynamics
├── narrative.py           # Story generation
├── imagination.py         # Mental canvas & transforms
├── plausibility.py        # Reality grounding
├── creative_leaps.py      # 4 creative operators
├── hierarchical_ideas.py  # Tree-structured ideas
├── curiosity_prober.py    # Void exploration
├── creative_ideation.py   # Unified ideation engine
├── language_grounding.py  # Text <-> embedding bridge (v1.3.0)
└── safeguards.py          # Repulsion, anchoring, budgets
```

## Benchmarks

| Operation | Throughput | Memory |
|-----------|-----------|--------|
| Memory Evolution | ~10,000 steps/s | O(n) |
| Analogical Transfer | ~500 leaps/s | O(n²) |
| Orthogonal Composition | ~800 leaps/s | O(n) |
| Void Extrapolation | ~600 leaps/s | O(n) |
| Full Ideation Cycle | ~50 ideas/s | O(n²) |

*Benchmarked on NVIDIA GeForce RTX 5080 (16GB VRAM), CUDA 13.1, 256-dim embeddings, 100 memories*

## Key Features

- **No LLM Required**: All operations are internal to embedding space
- **Emergent Narratives**: Stories arise from memory dynamics
- **Creative Recombination**: Generates novel ideas by operating on stored memories (not from nothing)
- **Biologically Inspired**: Metabolic states, resonance, narrative arcs
- **GPU Accelerated**: Full CUDA support via Triton kernels
- **Thread Safe**: Concurrent access supported

## Research Paper

See [RESEARCH_PAPER_LMD.md](./docs/RESEARCH_PAPER_LMD.md) for the full technical paper including:
- Mathematical foundations
- Algorithm pseudocode
- Comprehensive benchmarks
- Comparison with existing systems

## Examples

```bash
# Run any example
python examples/<example_name>.py
```

| Example | Description | Requires |
|---------|-------------|----------|
| [basic_usage.py](examples/basic_usage.py) | Create and evolve memories | Core |
| [creative_leaps.py](examples/creative_leaps.py) | Generate inventions | Core |
| [hierarchical_ideas.py](examples/hierarchical_ideas.py) | Tree-structured concepts | Core |
| [language_grounding.py](examples/language_grounding.py) | Text in/out with real output | `[language]` |

## License

This project uses a custom license that allows free use for research and personal projects while reserving commercial rights. See [LICENSE](LICENSE) for details.

For commercial licensing inquiries, please contact the author.

## Citation

If you use LMD in your research, please cite:

```bibtex
@software{lmd2026,
  author = {Thomas, Joshua R.},
  title = {Living Memory Dynamics: A Novel Framework for Narrative-Generating Episodic Memory},
  year = {2026},
  version = {1.3.0},
  url = {https://github.com/mordiaky/LMD}
}
```

## Contributing

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

---

*Invented by Joshua R. Thomas, January 2026*

*Contact: mordiaky@gmail.com*
