# Atomizer Dashboard

Real-time optimization monitoring and control dashboard for the Atomizer optimization engine.

## Features

### ✅ Live Dashboard (Current)
- **Real-time WebSocket streaming** - Instant updates on new trials
- **Interactive charts** - Convergence plots and parameter space visualization
- **Pruning alerts** - Toast notifications for failed trials
- **Data export** - Download trial history as JSON or CSV
- **Study discovery** - Automatically detects all active studies
- **Connection monitoring** - WebSocket status indicator

### 🔮 Future Features
- React + TypeScript frontend
- Study Configurator page
- Results Report Viewer
- LLM chat interface for configuration
- Study control (start/stop/pause)

---

## Quick Start

### 1. Install Backend Dependencies
```bash
cd atomizer-dashboard/backend
pip install -r requirements.txt
```

### 2. Start the Backend
```bash
# From backend directory
python -m uvicorn api.main:app --reload --host 0.0.0.0 --port 8000
```

### 3. Access the Dashboard
Open your browser: **http://localhost:8000**

### 4. Monitor an Optimization
```bash
# In a separate terminal
cd ../..
python studies/circular_plate_frequency_tuning/run_optimization.py
```

The dashboard will automatically detect the running study and stream updates in real-time!

---

## Architecture

### Backend Stack
- **FastAPI** - Modern async Python web framework
- **Uvicorn** - ASGI server
- **Watchdog** - File system event monitoring
- **WebSockets** - Bidirectional real-time communication

### Current Frontend
- **HTML/CSS/JavaScript** - Single-page application
- **Chart.js** - Interactive charts
- **WebSocket API** - Real-time data streaming

### Planned Frontend
- **React 18** + **Vite** + **TypeScript**
- **TailwindCSS** - Utility-first CSS
- **Recharts** - React charting library
- **React Query** - Server state management

---

## File Structure

```
atomizer-dashboard/
├── backend/                          ✅ COMPLETE
│   ├── api/
│   │   ├── main.py                  # FastAPI app entry
│   │   ├── routes/
│   │   │   └── optimization.py      # REST endpoints
│   │   └── websocket/
│   │       └── optimization_stream.py  # WebSocket + file watching
│   ├── requirements.txt
│   └── README.md                    # Backend API docs
│
├── dashboard-test.html               ✅ Basic live dashboard
├── dashboard-enhanced.html           ✅ Enhanced with charts & export
└── README.md (this file)
```

---

## API Documentation

### REST Endpoints
- `GET /api/optimization/studies` - List all studies
- `GET /api/optimization/studies/{id}/status` - Get study status
- `GET /api/optimization/studies/{id}/history` - Get trial history
- `GET /api/optimization/studies/{id}/pruning` - Get pruning diagnostics

### WebSocket Endpoint
- `ws://localhost:8000/api/ws/optimization/{study_id}` - Real-time trial stream

**Message Types**:
- `connected` - Initial connection confirmation
- `trial_completed` - New trial finished
- `new_best` - New best trial found
- `progress` - Progress update (X/Y trials)
- `trial_pruned` - Trial pruned with diagnostics

---

## Dashboard Features

### Convergence Chart
Line chart showing:
- **Objective value** progression over trials
- **Best so far** trajectory
- Real-time updates without animation lag

### Parameter Space Chart
Scatter plot showing:
- 2D visualization of first two design variables
- Points colored by objective value
- Best trial highlighted in green

### Pruning Alerts
- Toast notifications for pruned trials
- Auto-dismiss after 5 seconds
- Warning styling (orange) with pruning cause

### Data Export
- **Export JSON** - Download complete trial history
- **Export CSV** - Export as spreadsheet-compatible format
- Success alerts on export

### Metrics Dashboard
- **Total Trials** - Number of completed trials
- **Best Value** - Best objective value found
- **Avg Objective** - Average objective value
- **Pruned** - Number of failed trials

---

## Testing

### Verify Backend is Running
```bash
curl http://localhost:8000/health
# Should return: {"status":"healthy"}

curl http://localhost:8000/api/optimization/studies
# Should return: {"studies":[...]}
```

### Test WebSocket Connection
```bash
# Using wscat (npm install -g wscat)
wscat -c ws://localhost:8000/api/ws/optimization/circular_plate_frequency_tuning

# Or using Python
python -c "
import asyncio
import websockets
import json

async def test():
    uri = 'ws://localhost:8000/api/ws/optimization/circular_plate_frequency_tuning'
    async with websockets.connect(uri) as ws:
        while True:
            msg = await ws.recv()
            print(json.loads(msg))

asyncio.run(test())
"
```

---

## Documentation

- [Master Plan](../docs/DASHBOARD_MASTER_PLAN.md) - Complete architecture roadmap
- [Implementation Status](../docs/DASHBOARD_IMPLEMENTATION_STATUS.md) - Current progress
- [Session Summary](../docs/DASHBOARD_SESSION_SUMMARY.md) - Implementation notes
- [Backend API](backend/README.md) - Detailed API documentation

---

## Next Steps

### Short Term
1. Build full React + Vite + TypeScript frontend
2. Migrate to Recharts for React-compatible charts
3. Add parameter importance visualization
4. Polish UI/UX with TailwindCSS

### Medium Term
5. Build Study Configurator page
6. Build Results Report Viewer page
7. Add study control (start/stop/pause)
8. Implement authentication

### Long Term
9. Add LLM chat interface for configuration
10. Deploy with Docker
11. Add user management
12. Implement study templates

---

## Troubleshooting

### Dashboard shows "Failed to fetch"
- Ensure backend is running: `http://localhost:8000/health`
- Check CORS settings in `backend/api/main.py`
- Access dashboard via `http://localhost:8000` (not `file://`)

### WebSocket not connecting
- Verify backend is running on port 8000
- Check firewall settings
- Look for errors in browser console (F12)

### No studies appearing
- Ensure studies directory exists: `studies/`
- Check study has `1_setup/optimization_config.json`
- Verify `2_results/optimization_history_incremental.json` exists

### Charts not updating
- Check WebSocket connection status in dashboard
- Verify file watcher is running (check backend console)
- Ensure optimization is actually running and creating trials

---

**Status**: ✅ Live dashboard functional and ready for use!
