Metadata-Version: 2.5
Name: rigsby-atlas
Version: 0.3.0
Summary: Atlas: a personal, deterministic engine for road familiarity, route memory and familiarity-aware navigation (part of Rigsby)
Project-URL: Homepage, https://github.com/rigsby-copilot
Project-URL: Source, https://github.com/rigsby-copilot/rigsby-atlas
Project-URL: Issues, https://github.com/rigsby-copilot/rigsby-atlas/issues
Author: Rahul Baradol
License-Expression: AGPL-3.0-or-later
License-File: LICENSE
Keywords: familiarity,gps,navigation,openstreetmap,rigsby,routing
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: End Users/Desktop
Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: GIS
Requires-Python: >=3.11
Requires-Dist: cryptography>=42
Requires-Dist: fastapi>=0.115
Requires-Dist: gpxpy<2,>=1.6
Requires-Dist: httpx>=0.27
Requires-Dist: networkx>=3.2
Requires-Dist: numpy>=1.26
Requires-Dist: osmnx<3,>=2.0
Requires-Dist: python-multipart>=0.0.9
Requires-Dist: uvicorn[standard]>=0.30
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# Atlas

A personal, deterministic geospatial engine for Bengaluru. It records where you ride, measures how familiar
you are with each road, learns the routes you repeat, notices when you leave one, and guides you back. It
also plans routes that favour familiar roads, unexplored roads, or neither. No LLM is involved: every fact
and route comes from the road graph and your own GPS history. See [specs.md](specs.md).

```
phone (Rigsby Android's ride recording, or the /collector web page)
        │  GPS fixes, buffered on the phone, each with a UUID
        ▼
atlas serve ──► raw observations (SQLite, never modified)
        │                  └─► map matching ─► traversals ─► road familiarity
        │                                   └─► journeys ─► route memory
        ├─ live: matched road, route recognition, deviation, re-entry ──► WebSocket ──► browser map
        └─ REST API ──► browser map, Rigsby agent, scripts
```

## Setup

From PyPI (published as `rigsby-atlas`; the command is `atlas`):

```bash
pip install rigsby-atlas        # or: uv tool install rigsby-atlas / pipx install rigsby-atlas
atlas download-network          # first run: downloads the OSM graph and builds the index
atlas serve                     # prints the map URL and your API token
```

Or from this checkout: `uv sync`, then the same commands with `uv run atlas …`.

Atlas keeps its data (the road network, your rides in `atlas.db`, the API token) in `ATLAS_HOME`. If
that's not set, it uses `data/` when run from this checkout, or `~/.local/share/atlas` when installed
with pip.

The first `download-network` builds `networks/bengaluru_drive.network.pkl` in that folder (about 15 s;
156k intersections, 395k directed road segments). After that, the server starts in about a second. Use
`--refresh` to re-download from OpenStreetMap.

Open the printed `http://localhost:8000/` link and enter the token once. Every data endpoint needs the
token, which is generated once and stored in `api_token.txt` in the data folder (mode 600), or can be set
with `ATLAS_TOKEN`.

To run it on a server (EC2, behind nginx at `https://server.atlas.rahulbaradol.in`), see
[deploy/README.md](deploy/README.md).

## Recording rides

**With Rigsby Android (recommended).** Ride recording is part of the
[Rigsby Android](https://github.com/rigsby-copilot/rigsby-android) app (it was the separate Atlas
app before). It records GPS in a foreground service (it keeps working with the screen locked), buffers every fix on the phone, and pushes
it straight to this server. A fix is deleted from the phone only after the server has stored it, and
every request is idempotent, so an offline stretch is simply uploaded later with nothing lost or stored
twice. If the phone is offline when you stop, a background job finishes the upload and closes the ride
once a network is back, even if Android has closed the app. Rides are named `phone-<session>`.

Install it from its [releases](https://github.com/rigsby-copilot/rigsby-android/releases), or from a
checkout of rigsby-android with `python3 install.py` (the phone connected over adb).

On the phone, open **Atlas: record rides**: **Allow location**, enter the server URL (e.g. `http://192.168.1.20:8000`, or
`http://10.0.2.2:8000` from the emulator) and the token from `atlas token`, **Save server**,
then **Start recording**. The screen shows the fixes waiting to upload, the last upload and the last
error, with **Upload now** to retry at once.

The phone code's tests live in rigsby-android (`./gradlew :app:testDebugUnitTest`: pure rules and the
upload pass against a fake server). `RIGSBY_ANDROID=../rigsby-android scripts/android-e2e.sh` runs the
same upload code against a real, throwaway `atlas serve` from this repository, including an offline
stretch.

Rides recorded earlier through Rigsby keep their `rigsby-` ids.

**Browser collector.** `atlas serve --https`, then open the printed `/collector` link on the phone
(accept the self-signed certificate warning; phone browsers allow GPS only over HTTPS). It buffers in
IndexedDB and retries, but browsers pause GPS when the screen locks.

**GPX files.** `uv run atlas import-gpx rides/*.gpx`, or use the map's import button. Re-importing
the same file is ignored.

## The map

- Roads coloured by how often you've travelled them in that direction: grey 0, blue 1–2, yellow 3–5,
  orange 6–9, green 10+ (configurable). Unexplored roads appear at zoom 15 and above.
- Click a road for its traversal count (each direction), recent count, last travelled date, and known
  attributes. Unknown surface, width and speed are shown as unknown, never guessed.
- The live ride: position, accuracy, path, and the road you're on.
- Familiar routes: click one to show it, rename it, or navigate it.
- Navigation: pick a destination, choose a mode, **Compare modes** or **Start**. A banner shows the
  deviation state. On a confirmed deviation the re-entry path (pink, dashed) and the rejoin point appear,
  with **Cancel re-entry** and **Keep alternative** buttons.
- Rides: click to see the raw GPS path and the matched roads (dashed = inferred), or delete a ride and all
  its location data.

## How it works

| Stage | What it does | Where |
|---|---|---|
| Ingestion | Observations are stored raw, idempotently by client UUID, and may arrive late or out of order. Late fixes for a finished ride trigger reprocessing. | `ingestion/`, `storage/gps_repository.py` |
| Map matching | Nearest-edge matching weighted by GPS accuracy, direction of travel (device heading or neighbouring fixes, which picks the right side of a two-way street) and continuity. Unmatched fixes stay unmatched. | `core/map_matching.py` |
| Traversals | Consecutive fixes on a road count once; single-fix GPS blips are removed; short gaps between non-adjacent roads are filled with the network path (marked *inferred*). Re-entering a road later counts again. | `core/traversals.py` |
| Familiarity | Lifetime count, recent count (90 days), last travelled, per directed road segment. Rebuilt from traversals, so reprocessing never double-counts. | `storage/road_repository.py` |
| Route memory | Rides are split into journeys at long stops. A route is created only when two journeys match (length-weighted overlap ≥ 80%), and is *familiar* from 3 trips. Direction matters; variants with the same origin and destination share a group; partial trips are recorded as partial. | `core/route_memory.py`, `services/processing.py` |
| Recognition | During a live ride, 4+ consecutive roads (300 m+) that follow a familiar route start familiar-route tracking automatically. | `services/familiar_navigation.py` |
| Deviation | Each fix is ON / NEAR (route road within GPS error in the same direction: inconclusive, which absorbs drift and parallel roads) / OFF / NO_INFO (stationary or poor accuracy). A deviation is confirmed after 3 OFF fixes and 40 m. | `core/route_alignment.py`, `core/deviation_detector.py` |
| Re-entry | One Dijkstra search from the end of your current road scores candidate points *ahead* on the route by `1.3 × time to reach it + remaining route time`. Unreachable points are never chosen. It replans if you ignore the path for 100 m, and resumes tracking once you rejoin. | `core/reentry_planner.py` |
| Routing | `travel time × known-quality factors × familiarity factor`. Modes: `familiar`, `balanced`, `exploration`, `normal`. Preference modes have a detour limit (1.6×, 1.25×, 1.5× the fastest time) and relax their preference to stay within it. | `core/routing.py` |

All thresholds live in [config.py](src/atlas/config.py) and can be overridden with environment
variables, e.g. `ATLAS_ROUTE_FAMILIAR_THRESHOLD=5`.

## API

All endpoints except `/health` and `/auth/*` need `Authorization: Bearer <token>` (the phone app,
Rigsby, scripts) or a browser session cookie. Tokens in URLs are refused, since URLs end up in logs.

Browser sessions: the map and `/collector` pages POST the token to `/auth/login`, which sets an
`HttpOnly`, `SameSite=Strict`, host-only cookie (`__Host-atlas_session`, `Secure`, over HTTPS) valid for
30 days; the pages never store the token. The cookie holds an expiry and an HMAC of it keyed by the
token, so changing the token ends every session. Cookie-authenticated writes must send
`X-Atlas-Request: 1`, and cookie-authenticated WebSockets must come from the same origin (CSRF).
`POST /auth/logout` clears the cookie.

```
POST   /rides/start                {ride_id?, started_at?, name?}  idempotent on ride_id
POST   /rides/{id}/observations    {observations: [{id, latitude, longitude, recorded_at, accuracy?, speed?, heading?, altitude?}]}
POST   /rides/{id}/pause | resume | stop
GET    /rides, /rides/{id}, /rides/{id}/path       DELETE /rides/{id}
POST   /imports/gpx                multipart file

GET    /location/latest            most recent fix (with age_s) and the ride recording now, if any
GET    /roads/familiarity?bbox=    /roads/network?bbox=    /roads/near?lat&lon    /roads/{edge_id}
GET    /stats                      /exploration/area?lat&lon&radius_m
GET    /routes, /routes/{id}       PATCH/DELETE /routes/{id}     POST /routes/rebuild

POST   /routing/plan | /routing/compare      {origin, destination, mode}
POST   /navigation/start           {mode, destination? | route_id?, origin?, ride_id?}
POST   /navigation/stop            {session_id}
POST   /navigation/{id}/cancel-reentry | continue-alternative
GET    /navigation, /navigation/{id}

POST   /auth/login {token}   /auth/logout
WS     /ws/rides/{ride_id}   /ws/live
       events: location, route_recognized, navigation_started, navigation_state, navigation_progress, reentry, ride_status
```

Interactive docs: `http://localhost:8000/docs`.

## Try it without riding

```bash
H=12.9784,77.6408; O=12.9352,77.6245        # Indiranagar → Koramangala
for i in 1 2 3; do uv run atlas synth-gpx --from $H --to $O --seed $i --out /tmp/commute$i.gpx; done
uv run atlas import-gpx /tmp/commute*.gpx          # creates a familiar route
uv run atlas synth-gpx --from $H --to $O --mode exploration --out /tmp/explore.gpx
uv run atlas serve
# In the map: pick the route under "Familiar routes" → "Navigate this route", then:
uv run atlas simulate /tmp/explore.gpx --outage-every 60 --shuffle --resend
```

The simulated ride leaves the familiar route, so the map shows the deviation and re-entry path. It also
drops the network, reorders batches and resends some, and the ride still ends up with each fix stored once.
Synthetic data is labelled `"source": "synthetic"`. Delete those rides (map → ride → delete) before
relying on your statistics.

Other commands: `stats`, `routes`, `reprocess` (rebuild everything from raw GPS, e.g. after changing
matching settings), `token`.

## Tests

```bash
uv run pytest
```

Tests use a synthetic street grid, so they need no network or OSM data.

## Limitations

1. Map matching is nearest-edge with direction and continuity, not a full HMM. Flyovers and service roads
   right next to main roads can still be matched to the wrong one; raw data is kept so `reprocess` can apply
   a better matcher later.
2. OSM in Bengaluru rarely tags surface or width, so quality-aware routing has little to work with; unknown
   attributes are neutral. Travel times come from road-type defaults, not traffic.
3. Exploration percentages use the `drive` network, which excludes footpaths and some service lanes.
4. Navigation sessions live in server memory and end if the server restarts. Rides and routes are persisted.
5. Area summaries use a bounding box around a point; there's no neighbourhood boundary data yet.
6. Single user. The token is the only access control: serve it only over HTTPS (see deploy/), and change
   the token if it leaks (delete `api_token.txt` in the data folder and restart).

The earlier GPX-only prototype is kept in `archive/explorer-v0/`, and its database in `data/explorer.db`
(it stored only counts, not raw GPS, so it isn't migrated).

## Layout

```
src/atlas/
  core/            deterministic engine: network + spatial index, matching, traversals, familiarity,
                   route memory, alignment, deviation, re-entry, routing, navigation session
  storage/         SQLite schema and repositories
  ingestion/       GPX import, live observation validation
  services/        Engine (single entry point), tracking, processing, navigation, routing, exploration
  api/             FastAPI app, REST routers, WebSocket hub
  visualization/   live_map/index.html (Leaflet map), live_map/collector.html (phone page)
  tools/synth.py   synthetic tracks for tests and demos
  intelligence/    reserved for future LLM/RAG consumers of the engine
```

## License

GNU Affero General Public License v3.0 or later ([LICENSE](LICENSE)), like the rest of
[Rigsby](https://github.com/rigsby-copilot). Road networks are downloaded from OpenStreetMap at run time
(© OpenStreetMap contributors, ODbL) and aren't part of this repository.
