Metadata-Version: 2.1
Name: dynos-adaptive-resampling
Version: 0.3.0
Summary: Adaptive resampling extension for DYNOS Sentry surveys
Author: Chris Thierauf
License: Apache-2.0
Project-URL: Homepage, https://dynosplan.com
Project-URL: Source, https://git.whoi.edu/cthierauf/dynos_public
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: dynos-core<0.4,>=0.3.0
Requires-Dist: dynos-client<0.4,>=0.3.0
Requires-Dist: dynos-sentry-domain<0.4,>=0.3.0
Requires-Dist: numpy
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"

# dynos-adaptive-resampling

A worked example: chain an ML-driven resampling step onto a Sentry survey. This
package is scaffolding: it ships a stub `AdaptiveResampler` that you
replace with your model, plus the wiring (`runnable.py`, `mission.py`) that
lets `dynos connect` find it and that lets the planner sequence "survey,
resample, resurvey".

The package contributes one new transition (`resample_zone`) and one new
mission template (`build_resample_mission`). Everything else is for you to
edit.

## Install

From PyPI:

```bash
pip install dynos-adaptive-resampling
```

To modify the source, install editable from a source checkout instead (the
`dynos-adaptive-resampling/` directory of the release tree):
`pip install -e dynos-adaptive-resampling`.

This pulls in `dynos-client`, `dynos-sentry-domain`, and `numpy`.

## What's in this repository

### `domain.py`

Declares `resample_zone` (the transition), `ResampleZoneParams` (its parameter
dataclass) and `resampled(zone)` (the fact it makes true). The transition
needs `full_coverage_of(source_zone)` first, so a goal of `resampled(site)`
makes the planner survey the site and then call your action. Edit if you need
new fluents or parameters.

### `resampler.py`

Provides the `AdaptiveResampler` class with `@Action(transition=resample_zone)`.
Edit `_gather_historic_data` and `_predict_new_zone` (or whatever else you
need) to get your model integrated.

### `mission.py`

`build_resample_mission(zone)` returns a `Mission` that does survey, resample,
resurvey. Pass the `Zone` object (e.g. `Zone(name="site_alpha")`), not its name
string. Edit if you want a different sequence.

### `runnable.py`

Provides `AdaptiveResamplingNode`, the `dynos connect`-compatible entry point.
You probably don't need to edit this. Connecting it also sends this package's
domain module to your session as data (so `resample_zone` becomes plannable
and dispatches back to your node), with no edits to the backend or the Sentry
domain, and nothing installed there. This needs dynos-client 0.3.0 or later;
older clients send the module's name instead, which works only because the
hosted backend has this package installed and allowlisted.

## How the round-trip works

1. You launch the resampler as a servant: `dynos connect
   dynos_adaptive_resampling.runnable:AdaptiveResamplingNode`. The servant
   registers its transition + domain with the backend, then idles, polling for
   assignments.
2. From a second terminal you build the mission and call `execute_blocks`. The
   first plan block surveys the source zone end-to-end.
3. The planner reaches `resample_zone(source_zone=site_alpha)`. It dispatches
   the assignment over HTTP to your servant.
4. Your `AdaptiveResampler` runs `_gather_historic_data`, then
   `_predict_new_zone`, and **creates the new `Zone` on the backend**
   (`resampled_site_alpha`) so the follow-up survey can plan coverage over it.
5. Once the new zone exists, the next plan block surveys it.

The vehicle-lifecycle bookends (takeover, descent, and abort/recovery) are
inserted by the planner and the on-vehicle safety system. The mission you author
is only the three survey/resample/resurvey blocks; you never hand-write a
takeover or an abort.

## Replacing the stub

You will edit `resampler.py`. Two methods shape the proposal:

`_gather_historic_data(zone_name)`: return whatever your model needs. The
shipped stub returns a few synthetic sensor readings (`{"longitude",
"latitude", "value"}`); you replace it with calls to a shared database, ROS
bag, the backend API (`orch.list_objects(type_filter="zone")`), an offline
NetCDF, etc.

`_predict_new_zone(historic_data, new_zone_name, coverage_width, robot_width)`:
return a ready-to-create `Zone` (the domain object), not a side-car type. The
shipped stub is a trivial heuristic (it centers a 30 m x 30 m box on the
highest-`value` reading); replace it with your model:

```python
from dynos_sentry.sentry import Zone

def _predict_new_zone(self, historic_data, new_zone_name, coverage_width, robot_width):
    features = self._extract_features(historic_data["sonar_readings"])
    prediction = self._model.predict(features)
    return Zone(
        name=new_zone_name,
        vertices=self._prediction_to_polygon(prediction),  # (lon, lat) corners
        altitude=70.0,
        speed=0.8,
        coordinate_frame="geographic",
        coverage_width=coverage_width,   # sensor swath; keep > 0 or coverage can't plan
        robot_width=robot_width,
    )
```

`do_resample` then calls `ctx.create_object(new_zone)` for you. The context's
object-management capability targets the same backend this action was dispatched
by, whether it runs in-process or on a servant connected via `dynos connect`,
so you never reconstruct a client from `~/.dynos` (a `from_config()` call could
silently reconnect to a different backend than the one the servant was started
against). It also reads the source zone's `coverage_width`/`robot_width` via
`ctx.list_objects()` and threads them in so the resurvey flies the same sensor
swath (falling back to sane defaults if the source can't be read).

You can add fields to `ResampleZoneParams` (e.g. a confidence threshold), but
don't change the `Zone` parameter: the backend's coverage planner reads
`Zone.vertices`, `Zone.coverage_width`, etc. to draw tracklines, and it expects
the public schema.

## Test offline

Before pointing at the real backend, run the package's own tests from a
source checkout:

```bash
pip install -e "dynos-adaptive-resampling/[dev]"
pytest dynos-adaptive-resampling/tests/ -v
```

These exercise `_gather_historic_data`, `_predict_new_zone`, and `do_resample`
(with a fake backend that records the created zone). No network or session
needed.

## Run it for real

Two terminals.

Terminal 1 is your resampler. This can be your laptop, a lab server, or the
same machine as the backend; the backend dispatches each assignment to
whichever servant is currently registered for `resample_zone`.

```bash
dynos login  # logins persist across terminals and last 30 days by default
dynos session create --robot sentry-mock # Omitting '--robot sentry-mock' is valid but will omit important robot knowledge like coordinates, which is probably not what you want
dynos connect dynos_adaptive_resampling.runnable:AdaptiveResamplingNode
```

Leave it running. It executes `resample_zone` whenever the backend reaches that
step.

Terminal 2 is the mission. Create the source zone and run the adaptive mission:

```bash
dynos call create zone.json
```

```python
from dynos_client import RemoteOrchestrator
from dynos_sentry.sentry import Zone
from dynos_adaptive_resampling.mission import build_resample_mission

orch = RemoteOrchestrator.from_config(timeout_s=3600)
results = orch.execute_blocks(build_resample_mission(Zone(name="site_alpha")))
for r in results:
    print(r)
```

While it runs, monitor from a third terminal:

```bash
dynos call state --scope public      # current symbolic state, pruned only for the symbols you're expecting
dynos call goal                      # current goal
dynos call objects --type zone       # source + resampled zones
```

## What the mission does, step by step

The mission you author is two goals; the planner and the on-vehicle safety
system add everything else.

1. `resampled(site_alpha)`. Only `resample_zone` makes that true, and it needs
   `full_coverage_of(site_alpha)`, so the planner surveys the site (with the
   takeover and descent it needs) and then dispatches
   `resample_zone(source_zone=site_alpha)` to your servant. Your model creates
   `resampled_site_alpha` on the backend. If there is no survey data, the action
   fails and the backend replans.
2. Resurvey (`full_coverage_of(resampled_site_alpha)`).

Recovery (`full_abort`, controlled ascent) is owned by the on-vehicle safety
system, not authored in the mission.

## Public API

| Symbol                              | From                                  | Purpose                                        |
|-------------------------------------|---------------------------------------|------------------------------------------------|
| `resample_zone`                     | `dynos_adaptive_resampling.domain`    | The transition that fires your `@Action`.      |
| `ResampleZoneParams`                | `dynos_adaptive_resampling.domain`    | Its parameter dataclass (`source_zone: Zone`). |
| `resampled`                         | `dynos_adaptive_resampling.domain`    | Fact the transition makes true, per zone.      |
| `resampling_complete`               | `dynos_adaptive_resampling.domain`    | Unparameterized fact the transition also adds. |
| `AdaptiveResampler`                 | `dynos_adaptive_resampling.resampler` | The class you edit.                            |
| `AdaptiveResamplingNode`            | `dynos_adaptive_resampling.runnable`  | The `dynos connect` entry point.               |
| `build_resample_mission(zone)`      | `dynos_adaptive_resampling.mission`   | Survey, resample, resurvey.                    |

## Troubleshooting

Resampler never gets an assignment: The mission hasn't reached `resample_zone`
yet. Check `dynos call state --scope public`.

`No plan found`: The source zone doesn't exist, has no `vertices`, or has
`coverage_width <= 0`. Check `dynos call objects --type zone`.

Resurvey failed: the `resampled_*` zone is missing fields. It needs `vertices`
(3+), `coverage_width > 0`, `robot_width > 0`, and `coordinate_frame`. The
shipped `_predict_new_zone` sets all of these; if you replaced it, make sure
your `Zone` still carries them.

For cross-package issues (login, session, connection), see `user_guide.md` or
`dynos-client`'s README.
