Metadata-Version: 2.4
Name: mskit-simu
Version: 0.7.0
Summary: Mini Simulation Kit — terrain + traffic simulations powered by Simu AI, OpenCTV, JAXA AW3D30
Author: MegaBites AI Team
License: MIT
Project-URL: Homepage, https://github.com/MegaBites-AI/MSKit
Project-URL: Repository, https://github.com/MegaBites-AI/MSKit
Project-URL: Dataset, https://huggingface.co/datasets/MegaBites-AI/AW3D30-DEM-Tiles
Project-URL: Bug Tracker, https://github.com/MegaBites-AI/MSKit/issues
Project-URL: Simu Model, https://huggingface.co/HuggingFaceTB/SmolLM2-360M-Instruct
Keywords: simulation,terrain,dem,elevation,ai,gis,jaxa,aw3d30,traffic,opentraffic,utd19,openctv,cameras,smollm2,llm,natural language,vehicles,visualisation,spectate,animation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Visualization
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: requests>=2.28
Requires-Dist: huggingface_hub>=0.20
Provides-Extra: llm
Requires-Dist: transformers>=4.40; extra == "llm"
Requires-Dist: torch>=2.0; extra == "llm"
Requires-Dist: accelerate>=0.27; extra == "llm"
Requires-Dist: sentencepiece>=0.1.99; extra == "llm"
Provides-Extra: gguf
Requires-Dist: llama-cpp-python>=0.2; extra == "gguf"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.7; extra == "viz"
Requires-Dist: Pillow>=9.0; extra == "viz"
Provides-Extra: tiff
Requires-Dist: tifffile>=2023.1; extra == "tiff"
Provides-Extra: all
Requires-Dist: mskit-simu[gguf,llm,tiff,viz]; extra == "all"
Dynamic: license-file

# MSKit-Simu — Mini Simulation Kit

[![PyPI](https://img.shields.io/pypi/v/mskit-simu?color=blue&label=PyPI)](https://pypi.org/project/mskit-simu/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/mskit-simu)](https://pypi.org/project/mskit-simu/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![HuggingFace Dataset](https://img.shields.io/badge/🤗%20Dataset-AW3D30--DEM--Tiles-yellow)](https://huggingface.co/datasets/MegaBites-AI/AW3D30-DEM-Tiles)
[![HuggingFace Model](https://img.shields.io/badge/🤗%20Model-SmolLM2--360M-orange)](https://huggingface.co/HuggingFaceTB/SmolLM2-360M-Instruct)

A lightweight Python library for **terrain-based simulations** powered by real-world elevation data, live traffic feeds, open camera streams, **Simu** (an embedded AI assistant you talk to in plain English), and a 3-D vehicle visualiser with a live spectator mode.

---

## ✨ What's Inside

| Module | Description |
|---|---|
| **DEMLoader** | Streams JAXA AW3D30 30 m elevation tiles lazily from HuggingFace — no manual download needed |
| **TrafficRouter** | Auto-selects OpenTraffic → UTD19 → synthetic fallback, globally |
| **OpenCTVLayer** | Aggregates free public traffic camera feeds (Singapore, London, NYC) |
| **Simu** | Embedded AI assistant — understands plain English, picks and runs the right simulation |
| **VehicleScene** | 3-D vehicle models (car=rectangle, bike=cube, bus=hexagon) + map legend |
| **SpectateSession** | Live animated top-down traffic view — vehicles drive around in real time |
| **CLI** (`mskit`) | **One command** — boots an interactive hub that loads every feature at once |

---

## 🚀 Installation

```bash
# Core only — terrain, traffic, cameras, rule-based Simu
pip install mskit-simu

# + AI brain (SmolLM2-360M, ~700 MB download once)
pip install mskit-simu[llm]

# + 3-D visualisation + spectate + GIF export
pip install mskit-simu[viz]

# + GGUF / quantised model support
pip install mskit-simu[gguf]

# Everything
pip install mskit-simu[all]
```

---

## 🖥️ One Command — Everything Loaded

```bash
mskit
```

That's it. One command boots the **interactive hub** and pre-warms every module:

```
  Loading modules…
  ✅ Loading DEMLoader (JAXA AW3D30)… done
  ✅ Loading TrafficRouter… done
  ✅ Loading OpenCTVLayer… done
  ✅ All systems ready — DEM · Traffic · Cameras · Vehicles · Simu

  mskit [Tokyo] >
```

Then drive everything from one prompt:

| Command | What it does |
|---|---|
| `traffic london` | Live speed, flow, congestion + nearby cameras |
| `cameras singapore` | OpenCTV live camera feed near Singapore |
| `vehicles` | 3-D vehicle model scene + map legend |
| `spec session` | **Live animated top-down traffic view** |
| `spec session save out.gif` | Export spectate animation as GIF |
| `elevation fuji` | JAXA elevation lookup at Mount Fuji |
| `goto paris` | Switch active location to Paris |
| `random walk in Tokyo 500 steps` | → Simu AI runs it |
| `water flow near Zurich` | → Simu AI runs it |
| `run everything in London` | → Simu runs all 6 sims |
| `demo` | Full feature walkthrough |
| `info` | Version + data source summary |
| `help` | Full command list |
| `exit` | Quit |

### Start at a specific location

```bash
mskit --city tokyo
mskit --city singapore
mskit --lat 51.5074 --lon -0.1278      # London
```

---

## 🎥 Spectate Session

Watch vehicles drive around a live animated arena — cars, bikes, and buses all rendered as their correct 3-D shapes in a top-down view.

```bash
# In the hub:
mskit [Tokyo] > spec session                     # live window (close to exit)
mskit [Tokyo] > spec session save traffic.gif    # export as animated GIF
```

```python
from mskit.viz import SpectateSession

# Live window
SpectateSession().run()

# More vehicles, longer
SpectateSession(n_vehicles=20, fps=15).run()

# Export animated GIF (requires Pillow)
SpectateSession(duration_s=5).run(save_gif="spectate.gif")
```

**Vehicle shapes:**

| Shape | Type | Colour | Size |
|---|---|---|---|
| Flat **rectangle** | 🚗 Car | Blue | 4.5 × 2.0 m |
| Tall thin **cube** | 🏍️ Two-wheeler | Amber | 2.0 × 0.6 m |
| **Hexagon** prism | 🚌 Bus | Green | r = 1.5 m |

---

## 🚗 3-D Vehicle Scene + Map Legend

```bash
mskit [Tokyo] > vehicles                         # interactive 3-D window
mskit [Tokyo] > vehicles save my_scene.png       # save to PNG
```

```python
from mskit.viz import VehicleScene, Vehicle, VehicleType, draw_vehicle_scene

# Quick demo — 2 of each type
draw_vehicle_scene()
draw_vehicle_scene(save="scene.png", show=False)

# Build your own scene
scene = VehicleScene(title="Tokyo Intersection")
scene.add(Vehicle(VehicleType.CAR,         x=0,   y=0,   heading=0,   label="Taxi"))
scene.add(Vehicle(VehicleType.TWO_WHEELER, x=6,   y=2,   heading=45,  label="Bike"))
scene.add(Vehicle(VehicleType.BUS,         x=-8,  y=5,   heading=90,  label="Bus 12"))
scene.show()
scene.save("intersection.png")
```

---

## 🖥️ Legacy CLI Subcommands

The following subcommands still work alongside the hub:

```bash
mskit simu                                   # full interactive Simu session
mskit run "water flow simulation in Zurich"  # one-shot from terminal
mskit cameras --city singapore               # cameras near Singapore
mskit cameras --city london --radius 3
mskit traffic --city london                  # traffic report
mskit traffic --lat 35.6762 --lon 139.6503   # by coordinates
mskit demo                                   # full feature walkthrough
mskit info                                   # version + data sources
```

---

## 🐍 Python API

### Talk to Simu (plain English)
```python
from mskit import Simu

simu = Simu(auto_select="untrained", auto_simmode="custom")
result = simu.chat("random walk in Tokyo for 300 steps")
print(result["output"])     # sim results dict
print(result["intent"])     # what Simu understood
```

### Load elevation data
```python
from mskit import DEMLoader

dem = DEMLoader()
elev = dem.elevation_at(35.6762, 139.6503)           # Tokyo → metres
patch = dem.patch(lat=51.5074, lon=-0.1278, radius_km=5)  # numpy array
```

### Run simulations directly
```python
from mskit import DEMLoader, RandomWalk, Projectile, WaterFlow, TerrainAgent

dem = DEMLoader()

rw   = RandomWalk(dem, lat=35.6762, lon=139.6503, slope_bias=0.6)
path = rw.run(steps=500)
print(f"Distance: {path['total_distance_km']:.2f} km")

proj = Projectile(dem, lat=35.3606, lon=138.7274,
                  elevation_deg=45, azimuth_deg=90, speed_ms=80)
traj = proj.run()
print(f"Range: {traj['range_km']:.2f} km")

wf   = WaterFlow(dem, patch_km=10)
flow = wf.run(lat=47.3769, lon=8.5417)          # Zurich

agent   = TerrainAgent(dem, 35.6762, 139.6503, 35.73, 139.74)
episode = agent.generate_episode(max_steps=300)
```

### Query live traffic
```python
from mskit import TrafficRouter, DEMLoader

router = TrafficRouter(DEMLoader())
info   = router.traffic_at(51.5074, -0.1278)   # London
print(f"{info.speed_kmh:.1f} km/h — {info.congestion_level} ({info.source})")
```

### OpenCTV traffic cameras
```python
from mskit import OpenCTVLayer

ctv    = OpenCTVLayer()
report = ctv.traffic_report(lat=1.3521, lon=103.8198, radius_km=3)
print(f"{report.camera_count} cameras near Singapore")
if report.nearest:
    print(report.nearest.image_url)
```

---

## 📷 OpenCTV Camera Sources

| Source | Region | Cameras | Refresh | Key needed |
|---|---|---|---|---|
| Singapore LTA | Singapore | 87 | 20 s | ❌ |
| TfL JamCam | London | 900+ | ~30 s | ❌ (optional) |
| NYC DOT | New York City | ~900 | ~60 s | ❌ |
| Synthetic | Everywhere else | ∞ | — | ❌ |

---

## 🚦 Traffic Source Priority

| Priority | Source | Coverage |
|---|---|---|
| 1 | OpenTraffic / OSRM | Global road network |
| 2 | UTD19 (ETH Zurich) | 40 cities, 23,541 loop detectors |
| 3 | Synthetic | Everywhere — slope + time-of-day |

---

## 🤖 Simu Brain Options

| Option | Activate | Download |
|---|---|---|
| `untrained` | `auto_select="untrained"` | None — instant |
| `huggingface` | `auto_select="huggingface"` | ~700 MB once |
| `custom` (HF repo) | `auto_select="custom"`, `custom_model="org/repo"` | varies |
| `custom` (local) | `auto_select="custom"`, `custom_model="/path"` | None |
| `custom` (GGUF) | `auto_select="custom"`, `custom_model="file.gguf"` | None |

---

## 🗂 Project Structure

```
mskit-simu/
├── mskit/
│   ├── __init__.py          ← top-level exports (all public API)
│   ├── cli.py               ← unified hub CLI  (mskit command)
│   ├── dem.py               ← DEMTile + DEMLoader (JAXA AW3D30)
│   ├── sims/
│   │   ├── random_walk.py   ← slope-biased terrain walk
│   │   ├── projectile.py    ← ballistic trajectory
│   │   ├── flow.py          ← D8 water runoff routing
│   │   └── agent.py         ← RL terrain navigator
│   ├── traffic/
│   │   ├── opentraffic.py   ← OpenTraffic / OSRM layer
│   │   ├── utd19.py         ← UTD19 loop detector layer
│   │   ├── openctv.py       ← OpenCTV camera aggregator
│   │   └── router.py        ← TrafficRouter (auto source selection)
│   ├── simu/
│   │   ├── simu.py          ← Simu AI assistant
│   │   └── intent.py        ← NLU intent parser
│   └── viz/
│       └── vehicles.py      ← VehicleScene + SpectateSession
└── pyproject.toml
```

---

## 📋 Changelog

### v0.7.0
- **Single `mskit` command** boots the all-in-one interactive hub
- **`spec session`** — live animated top-down spectator view with direction arrows, live stats, and map legend
- **GIF export** — `spec session save out.gif` (requires Pillow)
- `SpectateSession` class added to `mskit.viz`
- Hub pre-warms all modules (DEM, Traffic, Cameras, Simu, Viz) on startup
- Hub commands: `traffic`, `cameras`, `vehicles`, `spec session`, `elevation`, `goto`, `info`, `demo`, `help`
- `Pillow` added to `[viz]` extra dependency
- Status bumped to **Beta**

### v0.6.x
- 3-D vehicle models + map legend (`VehicleScene`, `draw_vehicle_scene`)
- Car → rectangle · Two-wheeler → cube · Bus → hexagon prism
- `mskit.viz` module introduced

### v0.5.x – v0.6.x
- OpenCTV layer (Singapore LTA, TfL, NYC DOT)
- TrafficRouter multi-source auto-selection
- Unified CLI with `simu`, `run`, `cameras`, `traffic`, `demo`, `info` subcommands
- Simu two-tier startup (brain selection + sim mode selection)

### v0.4.x and earlier
- Core DEM streaming, RandomWalk, Projectile, WaterFlow, TerrainAgent
- UTD19 integration
- OpenTraffic / OSRM integration

---

## 📄 License

MIT — see [LICENSE](LICENSE).

| Resource | Link |
|---|---|
| PyPI | https://pypi.org/project/mskit-simu/ |
| GitHub | https://github.com/MegaBites-AI/MSKit |
| Dataset | https://huggingface.co/datasets/MegaBites-AI/AW3D30-DEM-Tiles |
| Simu model | https://huggingface.co/HuggingFaceTB/SmolLM2-360M-Instruct |
