# Mobiu-Q v2.9.2

[![PyPI version](https://badge.fury.io/py/mobiu-q.svg)](https://badge.fury.io/py/mobiu-q)
[![License](https://img.shields.io/badge/License-Proprietary-blue)](https://mobiu.ai)

**Mobiu-Q** wraps your existing optimizer with **Soft Algebra** and the new **Frustration Engine** to filter noise, detect stagnation, and improve convergence. Same API, better results.

---

## 🆕 What's New in v2.9.2

**Frustration Engine** - Client-side adaptive mechanism that:
- Detects when optimization is stuck
- Automatically boosts learning rate 3x
- Achieves **+60% improvement** over base Soft Algebra on LunarLander

```python
# Frustration Engine activates automatically!
opt = MobiuOptimizer(base_opt, method="adaptive", maximize=True)
```

---

## ⚡ Quick Start

```python
from mobiu_q import MobiuOptimizer

# PyTorch (RL, LLM, Deep Learning)
base_opt = torch.optim.Adam(model.parameters(), lr=0.0003)
opt = MobiuOptimizer(base_opt, license_key="YOUR_KEY", method="adaptive")

# RL with Frustration Engine (maximize=True for rewards)
opt = MobiuOptimizer(base_opt, license_key="YOUR_KEY", method="adaptive", maximize=True)

# Quantum (VQE, QAOA) - pass params instead of optimizer
params = np.random.randn(10)
opt = MobiuOptimizer(params, license_key="YOUR_KEY", method="standard", mode="simulation")
```

> **Note:** `MobiuOptimizer` auto-detects PyTorch optimizers vs numpy arrays and uses the appropriate backend.

---

## 🔧 Configuration

### Methods

| Method | Best For | Default LR |
|--------|----------|------------|
| `standard` | VQE, Chemistry, smooth landscapes | 0.01 (sim) / 0.02 (hw) |
| `deep` | QAOA, combinatorial, rugged landscapes | 0.1 |
| `adaptive` | RL, LLM, high-variance problems | 0.0003 |

### Modes (Quantum only)

| Mode | When to Use | Gradient Method |
|------|-------------|-----------------|
| `simulation` | Clean simulator (Qiskit Aer, PennyLane default) | Finite Difference (2N evals) |
| `hardware` | Real quantum hardware, FakeFez, noisy backends | SPSA (2 evals, noise-resilient) |

**Rule of thumb:** If your backend has noise → use `hardware`. If it's a perfect simulator → use `simulation`.

### New: maximize Parameter (v2.9.0)

```python
# For Loss minimization (default)
opt = MobiuOptimizer(base_opt, maximize=False)

# For Reward maximization (RL)
opt = MobiuOptimizer(base_opt, maximize=True)
```

### A/B Testing Parameter

```python
# For fair comparisons, toggle Soft Algebra:
opt = MobiuOptimizer(base_opt, use_soft_algebra=True)   # Default - SA + Frustration Engine
opt = MobiuOptimizer(base_opt, use_soft_algebra=False)  # Baseline - SA disabled
```

---

## 📦 Installation

```bash
pip install mobiu-q
```

---

## 🎯 Usage Examples

### PyTorch (RL with Frustration Engine)

```python
import torch
from mobiu_q import MobiuOptimizer

LICENSE_KEY = "your-license-key"

policy = PolicyNetwork()
base_opt = torch.optim.Adam(policy.parameters(), lr=0.0003)

opt = MobiuOptimizer(
    base_opt,
    license_key=LICENSE_KEY,
    method="adaptive",
    maximize=True,           # NEW: For RL rewards
    use_soft_algebra=True,   # Enables Frustration Engine
    verbose=True
)

for episode in range(1000):
    reward = run_episode(policy)
    loss = compute_policy_loss(...)
    loss.backward()
    opt.step(reward)  # Frustration Engine auto-detects stagnation
    opt.zero_grad()

opt.end()
```

### PyTorch (Loss Minimization)

```python
opt = MobiuOptimizer(
    base_opt,
    license_key=LICENSE_KEY,
    method="adaptive",
    maximize=False,          # Default: minimize loss
    sync_interval=50,
)

for epoch in range(100):
    loss = criterion(model(x), y)
    loss.backward()
    opt.step(loss.item())
    opt.zero_grad()

opt.end()
```

### Quantum VQE (Simulation)

```python
from mobiu_q import MobiuOptimizer
import numpy as np

params = np.random.randn(10)

opt = MobiuOptimizer(
    params,
    license_key=LICENSE_KEY,
    method="standard",
    mode="simulation",
)

for step in range(100):
    params = opt.step(params, energy_fn)

opt.end()
```

### Standalone Frustration Engine

```python
from mobiu_q import UniversalFrustrationEngine

engine = UniversalFrustrationEngine(base_lr=0.001)

for step in range(1000):
    metric = evaluate()
    factor = engine.get_lr_factor(metric)
    current_lr = base_lr * factor  # 1.0x, 2.0x, or 3.0x
    
    # Use current_lr in your optimizer
```

---

## 🔑 License Key

Get your key at [app.mobiu.ai](https://app.mobiu.ai)

```python
# Option 1: Pass directly
opt = MobiuOptimizer(base_opt, license_key="your-key")

# Option 2: Environment variable
export MOBIU_Q_LICENSE_KEY="your-key"

# Option 3: Save to file (one time)
from mobiu_q import save_license_key
save_license_key("your-key")
```

---

## 🏆 Verified Benchmark Results

All benchmarks use fair A/B testing: **Soft Algebra ON vs OFF**, same seeds, same conditions.

### 🆕 Frustration Engine Results (v2.9.0)

| Configuration | LunarLander Score | vs Vanilla |
|---------------|-------------------|------------|
| Vanilla Adam | -98.3 | - |
| Soft Algebra Only | -70.9 | +27.9% |
| **SA + Frustration Engine** | **-27.6** | **+71.9%** |

**Frustration Engine adds +60% improvement on top of Soft Algebra!**

- Win rate: 5/5 seeds (100%)
- p-value: 0.03125

### 🎮 Reinforcement Learning

| Environment | Improvement | Win Rate | p-value | Cohen's d |
|-------------|-------------|----------|---------|-----------|
| **LunarLander-v3** | **+146.9%** | 93.3% | < 0.000001 | +1.50 |
| **Atari Breakout** | **+54.2%** | 100% | - | - |

*LunarLander: 30 seeds, 1000 episodes each. Atari: 3 seeds, 200 episodes each.*

### 💰 Portfolio Optimization

| Noise Level | Improvement | Win Rate | p-value | Cohen's d |
|-------------|-------------|----------|---------|-----------|
| **1%** | **+16.8%** | 100% | < 0.000001 | +0.94 |
| **10%** | **+13.7%** | 100% | < 0.000001 | +0.99 |
| **50%** | **+12.8%** | 100% | < 0.000001 | +0.98 |

*100 seeds per noise level. Sharpe ratio optimization on AAPL, GOOGL, MSFT, AMZN, TSLA.*

**Overall: 300/300 wins (100%), average improvement +14.5%**

### ⚛️ Quantum VQE on IBM FakeFez

| Molecule | Qubits | Improvement | Win Rate |
|----------|--------|-------------|----------|
| **H₂** | 2 | **+52.5%** | 100% |
| **BeH₂** | 6 | **+55.1%** | 100% |
| **LiH** | 4 | **+34.5%** | 100% |

### 🎯 QAOA on IBM FakeFez

| Problem | Improvement | p-value |
|---------|-------------|---------|
| **MaxCut** | **+45.1%** | 0.0003 |

---

## 🛠️ Troubleshooting

### Not Improving?

1. **Try maximize=True**: For RL rewards, set `maximize=True`
2. **Switch optimizer**: Try `NAdam` or `Momentum` (Quantum mode)
3. **Switch method**: `standard` ↔ `adaptive` ↔ `deep`
4. **Adjust LR**: Diverging → lower by 2-5x, stuck → raise by 2x
5. **Reduce sync_interval**: Try `sync_interval=1` for more frequent updates

### Frustration Engine Not Triggering?

- Check if `use_soft_algebra=True` (default)
- Engine needs 20+ steps to detect stagnation
- Verify `maximize` parameter matches your metric

---

## 📖 API Reference

### MobiuOptimizer (Universal)

```python
MobiuOptimizer(
    optimizer_or_params,          # torch.optim.Optimizer OR np.ndarray
    license_key: str,
    method: str = "adaptive",     # "standard", "deep", "adaptive"
    mode: str = "simulation",     # "simulation", "hardware"
    use_soft_algebra: bool = True,
    sync_interval: int = 50,      # Cloud sync frequency (PyTorch only)
    maximize: bool = False,       # NEW: True for RL rewards
    verbose: bool = True
)
```

### UniversalFrustrationEngine (NEW in v2.9.0)

```python
UniversalFrustrationEngine(
    base_lr: float,               # Base learning rate
    sensitivity: float = 0.05    # Stagnation sensitivity
)

# Methods:
engine.get_lr_factor(metric)     # Returns 1.0, 2.0, or 3.0
engine.reset()                   # Reset for new run
```

---

## 🔬 How It Works

### Soft Algebra (Klein/Maimon Theory)

```
SoftNumber multiplication (ε²=0):
(a, b) × (c, d) = (ad + bc, bd)
```

The **Super-Equation Δ†** detects emergence moments for adaptive scaling.

### Frustration Engine (v2.9.0)

```
┌─────────────────────┐
│   Performance       │
│   History (50 steps)│
└─────────┬───────────┘
          │
          ▼
┌─────────────────────┐     Stagnation     ┌─────────────────────┐
│   Stagnation        │ ──── Detected ────▶│   LR Boost (3x)     │
│   Detection         │                    │   for 30 steps      │
└─────────────────────┘                    └─────────────────────┘
          │
          ▼ Normal
┌─────────────────────┐
│   LR Factor = 1.0   │
└─────────────────────┘
```

---

## 💰 Pricing

| Tier | Price | Runs |
|------|-------|------|
| **Free** | $0 | 20 runs/month |
| **Pro** | $19/month | Unlimited |

Get your key at [app.mobiu.ai](https://app.mobiu.ai)

---

## 🧑‍🔬 Scientific Foundation

Based on **Soft Numbers** theory developed by **Dr. Moshe Klein** and **Prof. Oded Maimon** (Tel Aviv University), as presented in their book on Soft Logic and Soft Numbers.

---

## 📚 Links

- **Website**: [mobiu.ai](https://mobiu.ai)
- **App**: [app.mobiu.ai](https://app.mobiu.ai)
- **PyPI**: [pypi.org/project/mobiu-q](https://pypi.org/project/mobiu-q)

---

© 2025-2026 Mobiu Technologies. All rights reserved.