mobiu-ad 1.3.1
Anomaly Detection using Soft Algebra - Same math as Mobiu-Q optimizer
Requires Python: >=3.8
Keywords: anomaly-detection, soft-algebra, time-series, monitoring, streaming, machine-learning, quantum-inspired

# Mobiu-AD 🔍

**Anomaly Detection using Soft Algebra**

[![PyPI version](https://badge.fury.io/py/mobiu-ad.svg)](https://pypi.org/project/mobiu-ad/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Uses the **same mathematical foundation** as [Mobiu-Q](https://github.com/mobiuai/mobiu-q) quantum optimizer.

## 🎯 What Makes Mobiu-AD Different?

Standard anomaly detectors (Z-Score, LOF, Isolation Forest) only find **outlier values**.

Mobiu-AD detects **changes in system behavior** - even when values look normal!

| Capability | Z-Score | Mobiu-AD |
|------------|---------|----------|
| Spike Detection | ✅ | ✅ |
| **Pattern Change** (Random→Trending) | ❌ | ✅ |
| **Early Warning** (Before spike) | ❌ | ✅ |
| **Regime Transitions** | ❌ | ✅ |

## 🧪 Real Test Results

### Pattern Change Detection
System changes from random to trending - values stay normal but dynamics change:

```
Z-Score:  0 detections  ❌
Mobiu-AD: 9 detections  ✅
```

### Precursor Detection (Early Warning)
Mobiu-AD detects "tension buildup" before a spike occurs:

```
Early warnings before spike: 6
✅ Got 6 warnings BEFORE the anomaly happened!
```

## Installation

```bash
pip install mobiu-ad
```

## Quick Start

```python
from mobiu_ad import MobiuAD

detector = MobiuAD(license_key="your-key")

# Stream detection
for value in data_stream:
    result = detector.detect(value)
    if result.is_anomaly:
        print(f"🚨 Anomaly! Δ†={result.delta_dagger:.4f}")
```

## 🔬 The Math Behind It

Both Mobiu-Q and Mobiu-AD share the same Soft Algebra core:

```
┌────────────────────────────────────────┐
│      SOFT ALGEBRA CORE (Shared)        │
│                                        │
│  SoftNumber: S = a·ε + b, ε²=0        │
│  Multiply: (a,b)×(c,d) = (ad+bc, bd)   │
│  Evolution: S_new = (γ·S)×Δ + Δ        │
│  Super-Equation: Δ†                    │
└──────────────────┬─────────────────────┘
                   │
        ┌──────────┴──────────┐
        │                     │
   ┌────▼────┐          ┌─────▼─────┐
   │ Mobiu-Q │          │ Mobiu-AD  │
   │Optimizer│          │ Detector  │
   └─────────┘          └───────────┘
```

### Why This Works

**Standard methods** look at `value` only:
- Is this value far from the mean? → Anomaly

**Mobiu-AD** tracks two components:
- `at` (potential): Is the system's **pattern** changing? (trend, variance)
- `bt` (deviation): Is the **value** unusual?

The nilpotent multiplication `(a,b)×(c,d) = (ad+bc, bd)` accumulates "tension" over time, enabling:
- **Early warning** before spikes (variance increasing)
- **Pattern detection** even when values look normal (trending behavior)

## Detection Methods

| Method | Best For | Description |
|--------|----------|-------------|
| `deep` | General use | Super-Equation Δ† **(recommended)** |
| `standard` | Simple spikes | Trust Ratio based |
| `transition` | Regime changes | 0→peak→0 profile detection |
| `auto` | Don't know | Automatically selects method |

```python
# Recommended: deep method
detector = MobiuAD(license_key="key", method="deep")

# For regime change detection
detector = MobiuAD(license_key="key", method="transition")

# Let Mobiu-AD choose
detector = MobiuAD(license_key="key", method="auto")
```

## Understanding Results

```python
result = detector.detect(42.5)

print(f"at (pattern):    {result.at:.4f}")       # Pattern change signal
print(f"bt (deviation):  {result.bt:.4f}")       # Value deviation signal
print(f"Δ† (score):      {result.delta_dagger:.4f}")  # Combined score
print(f"Trust:           {result.trust_ratio:.2%}")   # Confidence
print(f"Is Anomaly:      {result.is_anomaly}")
```

## Use Cases

### 🖥️ Server Monitoring
```python
# Detect when server behavior changes, not just spikes
for cpu_value in cpu_stream:
    result = detector.detect(cpu_value)
    if result.is_anomaly:
        alert("CPU pattern changed!")
```

### 📈 Financial Data
```python
# Early warning before market moves
for price in price_stream:
    result = detector.detect(price)
    if result.is_anomaly:
        print("Market tension building!")
```

### 🏥 Medical Monitoring
```python
# Detect regime changes in vital signs
for heart_rate in ecg_stream:
    result = detector.detect(heart_rate)
    if result.is_anomaly:
        alert("Patient state changing!")
```

## Batch Detection

```python
from mobiu_ad import detect_anomalies

result = detect_anomalies(values, license_key="your-key")
print(f"Anomalies at indices: {result.anomaly_indices}")
```

## 🛡️ TrainGuard: Mobiu-Q + Mobiu-AD Integration

Combine **optimization** (Q) and **monitoring** (AD) for safer ML training!

TrainGuard calls both Mobiu-Q and Mobiu-AD APIs directly - included in the mobiu-ad package.

```bash
pip install mobiu-ad
```

```python
from mobiu_ad import TrainGuard

guard = TrainGuard(license_key="your-key")

for epoch in range(epochs):
    loss = train_step()
    val_loss = validate()
    
    # One call does both Q and AD!
    result = guard.step(
        loss=loss,
        gradient=model.get_gradients(),
        val_loss=val_loss
    )
    
    # Mobiu-Q: Use optimized gradient
    model.apply_gradients(result.adjusted_gradient)
    
    # Mobiu-AD: Check for alerts
    if result.alert:
        print(f"⚠️ {result.alert_type}: {result.alert_message}")
        
        if result.alert_type == 'OVERFITTING':
            reduce_learning_rate()
        elif result.alert_type == 'EXPLOSION':
            print("🔥 Stopping training!")
            break
```

### TrainGuard Alert Types

| Alert | Meaning | Recommended Action |
|-------|---------|-------------------|
| `OVERFITTING` | Val loss pattern changed while train improves | Reduce LR / Early stop |
| `EXPLOSION` | Training loss increasing rapidly | Stop training |
| `PLATEAU` | Training loss stagnating | Reduce LR / Change optimizer |
| `CRITICAL` | Both train and val alerting | Investigate immediately |

### TrainGuard Results

```
┌─────────────────────────────────────────────────────────┐
│  Test                    │  Detection                   │
├──────────────────────────┼──────────────────────────────┤
│  Gradient Explosion      │  ✅ Detected within 5 steps  │
│  Overfitting            │  ✅ Detected within 2 steps! │
│  Loss Plateau           │  ✅ Detected                  │
└─────────────────────────────────────────────────────────┘
```

## Local Detection (No API)

```python
from mobiu_ad import MobiuADLocal

detector = MobiuADLocal(method="deep")

for value in data:
    result = detector.detect(value)
    if result.is_anomaly:
        print(f"Anomaly: {value}")
```

## Licensing

Same license works for both Mobiu-Q and Mobiu-AD!

| Tier | Limit |
|------|-------|
| Free | 500 points/month |
| Pro | Unlimited |

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

## Links

- **Website**: [mobiu.ai](https://mobiu.ai)
- **License Portal**: [app.mobiu.ai](https://app.mobiu.ai)
- **Mobiu-Q Optimizer**: [github.com/mobiuai/mobiu-q](https://github.com/mobiuai/mobiu-q)
- **PyPI**: [pypi.org/project/mobiu-ad](https://pypi.org/project/mobiu-ad/)

## License

MIT License - Copyright (c) 2025 Ido Angel / Mobiu Technologies

Based on Soft Logic by Dr. Moshe Klein and Prof. Oded Maimon (Tel Aviv University)