# CXR Kernel Service

Model registry and core engine for CXR claim analysis models.

## Installation

```bash
pip install cxr-kernel-service
```

## Available Models

### cxr-k1 (Flagship)
Full 7-plane fusion with all 7 context types. Best precision and recall.

```python
from kernel_service import get_registry

registry = get_registry()
model = registry.get_model("cxr-k1")
result = model.analyze(claim, tenant_id)
```

### cxr-k2 (Premium)
Enhanced precision model with deeper analysis. Slower but more accurate.

```python
model = registry.get_model("cxr-k2")
```

### cxr-k-sim1 (Simulation)
Monte Carlo integration for financial forecasting.

```python
model = registry.get_model("cxr-k-sim1")
```

### cxr-k-lite1 (Speed)
Fast model with 3-plane fusion. Optimized for throughput.

```python
model = registry.get_model("cxr-k-lite1")
```

### cxr-k-audit1 (Compliance)
Compliance-focused model with enhanced policy retrieval.

```python
model = registry.get_model("cxr-k-audit1")
```

## Model Capabilities

| Model | Fusion Planes | Monte Carlo | Speed | Precision |
|-------|--------------|-------------|-------|-----------|
| k1    | 7            | No          | Balanced | Maximum |
| k2    | 7            | No          | Thorough | Enhanced |
| sim1  | 7            | Yes         | Balanced | Maximum |
| lite1 | 3            | No          | Fast | Standard |
| audit1| 7            | No          | Balanced | Maximum |

## Usage

```python
from kernel_service import get_registry

# Get default model (k1)
registry = get_registry()
model = registry.get_model()

# Analyze a claim
claim = {
    "claimId": "CLM-001",
    "patientId": "PAT-001",
    "providerId": "PROV-001",
    "serviceDate": "2024-01-15",
    "procedureCode": "99213",
    "billedAmount": 120.0,
    "metadata": {"reviewThreshold": 0.8}
}

result = model.analyze(claim, tenant_id="tenant-123")
print(result["verdict"])  # approved/denied/pending_review
print(result["explanation"])
print(result["financialImpact"])
```

## Model Registry

The registry manages all available models:

```python
from kernel_service import get_registry

registry = get_registry()

# List all models
models = registry.list_models()
for model_id, capabilities in models.items():
    print(f"{model_id}: {capabilities.fusion_planes} planes")

# Get capabilities
caps = registry.get_capabilities("cxr-k1")
print(f"Uses Monte Carlo: {caps.uses_monte_carlo}")

# Set default model
registry.set_default("cxr-k-lite1")
```

## Architecture

- **7-Plane Fusion**: Structured, Unstructured, Contextual, Patient, Provider, Payer, Temporal
- **Model Registry**: Central routing system for model variants
- **Monte Carlo**: Financial forecasting and risk modeling
- **Context Collection**: 7 types of contextual evidence

## Configuration

The kernel service requires database and Qdrant configuration. See [CONFIGURATION.md](CONFIGURATION.md) for details.

Quick setup:
```bash
export CXR_DB_SERVER="localhost"
export CXR_DB_NAME="cxr_kernel"
export CXR_DB_USER="sa"
export CXR_DB_PASSWORD="password"
export CXR_QDRANT_HOST="localhost"
```

Or use a `.env` file (see `env.example`).

## Development

### Setup

```bash
# Install in development mode
pip install -e .

# Install optional dependencies for full test coverage
# (or activate faiss_gpu1 venv which has them)
pip install qdrant-client sentence-transformers torch
```

### Testing

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=kernel_service --cov-report=html

# Run specific test categories
pytest tests/test_registry.py          # Registry tests
pytest tests/test_performance.py        # Performance benchmarks
pytest tests/test_integration.py        # Integration tests
```

### Test Environment

For full test coverage (including regression tests), use the `faiss_gpu1` virtual environment:
```bash
source ../faiss_gpu1/bin/activate
pytest
```

### Smoke Test

After installing SDK packages from PyPI, verify installation:

```bash
python tools/smoke_test.py
```

This checks that packages import correctly and can run basic analyses. It also reports configuration status.

## Architecture

### Components

- **Model Registry**: Central routing system for model variants
- **7-Plane Fusion**: Structured, Unstructured, Contextual, Patient, Provider, Payer, Temporal
- **Monte Carlo Simulator**: Financial forecasting and risk modeling
- **Context Collector**: 7 types of contextual evidence gathering
- **Configuration System**: Environment-based configuration for DB and Qdrant

### Model Variants

| Model | Fusion Planes | Monte Carlo | Speed | Precision | Use Case |
|-------|--------------|-------------|-------|-----------|----------|
| k1    | 7            | No          | Balanced | Maximum | Standard analysis |
| k2    | 7            | No          | Thorough | Enhanced | Premium analysis |
| sim1  | 7            | Yes         | Balanced | Maximum | Financial forecasting |
| lite1 | 3            | No          | Fast | Standard | High-throughput |
| audit1| 7            | No          | Balanced | Maximum | Compliance-focused |

## Documentation

- [CONFIGURATION.md](CONFIGURATION.md) - Configuration guide
- [PERFORMANCE_BENCHMARKS.md](PERFORMANCE_BENCHMARKS.md) - Performance characteristics
- [PRODUCTION_SETUP.md](PRODUCTION_SETUP.md) - Production deployment guide
- [DEVELOPER_GUIDE.md](DEVELOPER_GUIDE.md) - Developer onboarding
- [sdk-models/SDK_QUICKSTART.md](../sdk-models/SDK_QUICKSTART.md) - PyPI SDK installation & usage

## Performance

See [PERFORMANCE_BENCHMARKS.md](PERFORMANCE_BENCHMARKS.md) for detailed benchmarks.

Quick summary:
- **lite1**: ~0.12ms (fastest, 3-plane)
- **k1/k2/audit1**: ~0.25ms (7-plane)
- **sim1**: ~1.6ms (includes Monte Carlo)

*Note: Benchmarks use mocked dependencies. Real-world performance includes DB/Qdrant latency.*

