Metadata-Version: 2.4
Name: resonant-swarm
Version: 0.1.0
Summary: Kuramoto phase coupling for Oasis social simulation and ghostsignals prediction markets
Author-email: Nick Flachsenhaar <nick@nickflach.com>
License: Apache-2.0
Project-URL: Homepage, https://github.com/kannaka-labs/resonant-swarm
Project-URL: Documentation, https://github.com/kannaka-labs/resonant-swarm/blob/main/README.md
Project-URL: Repository, https://github.com/kannaka-labs/resonant-swarm.git
Project-URL: Issues, https://github.com/kannaka-labs/resonant-swarm/issues
Keywords: prediction-markets,social-simulation,kuramoto,lmsr,swarm-intelligence
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24.0
Requires-Dist: asyncio-periodic
Requires-Dist: aiohttp>=3.8.0
Requires-Dist: websockets>=11.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: textblob>=0.17.1
Requires-Dist: scipy>=1.11.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: isort>=5.12.0; extra == "dev"
Requires-Dist: mypy>=1.5.0; extra == "dev"
Dynamic: license-file

# resonant-swarm

> Kuramoto phase coupling meets LMSR prediction markets via Oasis social simulation

**resonant-swarm** is the glue layer that connects [Oasis social simulation](https://github.com/camel-ai/oasis) with Kuramoto phase coupling and [ghostsignals-rs](https://github.com/kannaka-labs/ghostsignals-rs) prediction markets. It transforms social media simulations into collective prediction engines.

## What It Does

1. **Phase-Coupled Social Agents**: Extends Oasis's `SocialAgent` with Kuramoto oscillator dynamics. Agents' phases influence what content they see and how they behave.

2. **Sentiment → Market Trades**: Automatically converts agent posts, likes, and comments into prediction market trades based on sentiment analysis.

3. **Convergence Detection**: Monitors both market price stability and phase synchronization to determine when the swarm has reached consensus.

4. **Live Visualization**: WebSocket publisher for real-time dashboards showing phase dynamics and market evolution.

## Architecture

```
Seed Question → MiroFish → Oasis + Kuramoto → ghostsignals → Prediction
     │              │           │                  │            │
   Document      Profiles    Social Sim         LMSR Market  Consensus
                              + Phases          + Trades     Probability
```

- **MiroFish**: Generates agent personas from seed documents (existing)
- **Oasis**: LLM-driven social media simulation (existing)
- **Kuramoto**: Phase oscillators create emergent coupling between agents
- **ghostsignals**: LMSR prediction markets aggregate opinions into probabilities
- **resonant-swarm**: The integration layer (this package)

## Quick Start

```python
from resonant_swarm import ResonantSwarmExperiment

# Define your prediction question
config = {
    "question": "Will the Federal Reserve cut interest rates in Q3 2026?",
    "outcomes": ["Yes, rate cut", "No change", "Rate increase"],
    "seed_document": "Fed has maintained rates at 5.25% for 8 months...",
    "agents": {"count": 10, "coupling_k": 1.5},
    "simulation": {"rounds": 20, "platform": "twitter"},
}

# Run the experiment
experiment = ResonantSwarmExperiment(config)
result = await experiment.run()

print(f"Prediction: {result.market_prices}")
print(f"Confidence: {result.convergence_score}")
print(f"Report: {result.report}")
```

## Core Components

### 1. KuramotoPhaseManager

Manages oscillator phases for all agents:

```python
from resonant_swarm import KuramotoPhaseManager

phase_manager = KuramotoPhaseManager(coupling_k=1.5, dt=0.1)
phase_manager.add_agent("agent_1", initial_phase=0.5, natural_freq=1.0)
phase_manager.add_agent("agent_2", initial_phase=1.2, natural_freq=0.8)

# Run one Kuramoto step
state = phase_manager.step()
print(f"Order parameter: {state['order_parameter_r']}")  # 0 = chaos, 1 = sync
```

### 2. ResonantSocialAgent

Drop-in replacement for Oasis's `SocialAgent` with phase coupling:

```python
from resonant_swarm import ResonantSocialAgent

agent = ResonantSocialAgent(
    agent_id=1,
    user_info=user_info,
    phase_manager=phase_manager,
    # ... same args as SocialAgent
)

# Before each LLM decision, agent gets phase-coupled context:
# "You sense strong agreement with 3 other voices on this topic"
# or "The community seems divided with passionate arguments"
```

### 3. ActionToTradeMapper

Converts social actions into market trades:

```python
from resonant_swarm import ActionToTradeMapper, MarketEngine

market_engine = MarketEngine()
market_id = market_engine.create_market(
    "Will X happen?", 
    ["Yes", "No"], 
    liquidity=100.0
)

mapper = ActionToTradeMapper(market_engine)

# Agent posts "I think this will definitely happen!"
trade = mapper.map_action(
    agent_id="agent_1",
    action={"type": "create_post", "content": "I think this will definitely happen!"},
    market_id=market_id
)
# → Large trade on "Yes" outcome
```

### 4. LMSRMarket (Pure Python)

LMSR implementation mirroring the ghostsignals-rs API:

```python
from resonant_swarm import LMSRMarket

market = LMSRMarket(
    question="Will it rain tomorrow?",
    outcomes=["Yes", "No"],
    liquidity=100.0
)

# Initial prices are equal
print(market.prices())  # {"Yes": 0.5, "No": 0.5}

# Execute trades
trade = market.trade("trader_1", "Yes", amount=10.0)
print(market.prices())  # {"Yes": 0.52, "No": 0.48} (example)
```

## Installation

```bash
git clone https://github.com/kannaka-labs/resonant-swarm.git
cd resonant-swarm
pip install -e .
```

For development:
```bash
pip install -e .[dev]
```

## Example: 10-Agent Prediction

See `experiments/simple_prediction.py` for a complete example that:

1. Generates 10 agent profiles from a seed document
2. Runs 20 rounds of Twitter simulation with Kuramoto coupling
3. Converts posts/likes into market trades
4. Outputs final probability + confidence score

```bash
cd experiments
python simple_prediction.py --question "Will X happen?" --agents 10 --rounds 20
```

## Integration with Existing Systems

### With MiroFish
```python
# MiroFish generates profiles (existing code)
profiles = mirofish.generate_profiles(seed_document, agent_count=10)

# Add phase information
for profile in profiles:
    profile.initial_phase = random.uniform(0, 2*π)

# Use ResonantSocialAgent instead of SocialAgent in Oasis
```

### With ghostsignals-rs
```python
# Start with Python LMSR (this package)
market_engine = MarketEngine()

# Later: swap for Rust performance
# market_engine = GhostSignalsRust(api_url="http://localhost:3000")
```

### With kannaka-radio
```python
from resonant_swarm import SwarmVisualizer

viz = SwarmVisualizer(websocket_port=8765)
await viz.publish_state(phases, prices, actions, order_param)
# Dashboard shows live phase circle + price charts
```

## Mathematical Foundation

The system implements the Kuramoto model for coupled oscillators:

```
dθᵢ/dt = ωᵢ + (K/N) Σⱼ sin(θⱼ - θᵢ)
```

Where:
- `θᵢ` = phase of agent i
- `ωᵢ` = natural frequency (posting rhythm)
- `K` = coupling strength (adjustable)
- `N` = number of agents

**Order parameter** measures synchronization:
```
r = |1/N * Σⱼ exp(iθⱼ)|
```
- `r = 0`: completely incoherent (chaos)
- `r = 1`: fully synchronized (consensus)

**Action feedback**: Agent behavior updates phases:
- Positive sentiment (posts, likes) → pull toward mean phase
- Negative sentiment (arguments, dislikes) → push away from mean

## Testing

```bash
pytest tests/
```

Test coverage includes:
- Kuramoto math (phase wrapping, order parameter, coupling)
- LMSR market mechanics (cost function, price normalization)
- Sentiment extraction and action mapping
- Convergence detection algorithms

## Contributing

This is research code. If you find bugs or have ideas for improvements, please open an issue or PR.

## License

Apache 2.0

## Related Projects

- [Oasis](https://github.com/camel-ai/oasis) - LLM social media simulation
- [ghostsignals-rs](https://github.com/kannaka-labs/ghostsignals-rs) - LMSR prediction markets in Rust
- [MiroFish](https://github.com/flaukowski/MiroFish) - Ontology extraction and profile generation
- [kannaka](https://github.com/kannaka-labs/kannaka-memory) - Wave dynamics memory system

## Citation

```bibtex
@software{resonant_swarm,
  title={resonant-swarm: Kuramoto Phase Coupling for Social Prediction Markets},
  author={Flachsenhaar, Nick},
  year={2026},
  url={https://github.com/kannaka-labs/resonant-swarm}
}
```
