Metadata-Version: 2.1
Name: pymoos2
Version: 1.0.0
Summary: MOOS-IvP applications in Python: wire protocol, AppCasting, mission files, geometry and PROJ-based geodesy
Author-email: Raymond Turrisi <rturrisi@mit.edu>
License: MIT
Project-URL: Homepage, https://github.com/raymondturrisi/pymoos2
Project-URL: Repository, https://github.com/raymondturrisi/pymoos2
Keywords: moos,moos-ivp,robotics,auv,marine,middleware
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Topic :: Scientific/Engineering
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.8
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: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS :: MacOS X
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyproj>=3.4
Provides-Extra: web
Requires-Dist: fastapi; extra == "web"
Requires-Dist: uvicorn; extra == "web"
Requires-Dist: websockets; extra == "web"
Requires-Dist: pillow; extra == "web"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"

<p align="center">
  <img src="https://raw.githubusercontent.com/raymondturrisi/pymoos2/main/pymoos2/assets/pymoos2-horizontal-dark.png" alt="pymoos2" width="560">
</p>

# pymoos2

Write [MOOS-IvP](https://oceanai.mit.edu/moos-ivp) applications in Python.
pymoos2 speaks the native MOOSDB wire protocol, so a Python app sits beside
C++ apps under pAntler, shows up in uMAC and pMarineViewer with a full
AppCast, and reads its configuration from the same `.moos` mission file.
It also parses what other apps publish (VIEW_* geometry, NODE_REPORT,
APPCAST, REALMCAST) and converts positions with PROJ.

pymoos2 itself is pure Python. Its one dependency is
[pyproj](https://pyproj4.github.io/pyproj/), which ships binary wheels for
Linux (x86_64, aarch64), macOS and Windows.

```bash
pip install pymoos2
```

Python 3.8 or newer. A MOOSDB (from moos-ivp) to connect to.

## A first app

```python
from pymoos2 import AppCastingMOOSApp, ACTable, run


class Doubler(AppCastingMOOSApp):

    def on_startup(self):
        self.gain = self.config("gain", default=2.0, type=float)
        self.nav_x = 0.0

    def register_variables(self):          # runs on connect and on every reconnect
        self.register("NAV_X")

    def on_new_mail(self, mail):
        for msg in mail:
            if msg.name == "NAV_X":
                self.nav_x = msg.double()

    def iterate(self):
        self.notify("NAV_X_SCALED", self.nav_x * self.gain)

    def build_report(self):                # the AppCast uMAC shows
        table = ACTable(["Variable", "Value"])
        table.add("NAV_X", f"{self.nav_x:.2f}")
        self.report(table)
        return True


if __name__ == "__main__":
    import sys
    run(Doubler, "pDoubler", sys.argv[1])
```

```
ProcessConfig = pDoubler
{
  AppTick   = 4
  CommsTick = 4
  gain      = 3
}
```

`config()` returns the last value of a key in the app's block;
`config_lines()` returns every `(key, value)` in file order, for repeated keys
such as `button = ...`. `global_config()` reads top-level keys like
`LatOrigin`. `notify()` posts a `str` as a string, `bytes` as binary, `bool`
as `"true"`/`"false"`, and any real number (numpy scalars included) as a
double; anything else is a `TypeError`. An exception in `iterate()` or
`on_new_mail()` is printed and shown as an AppCast run warning; the app keeps
running.

## Apps in a moos-ivp extend tree

A pymoos2 app lives in `src/` beside the C++ apps and builds with the same
`./build.sh`. The tree's top-level `CMakeLists.txt` finds pymoos2 once, next
to `find_package(MOOS ...)` and before `ADD_SUBDIRECTORY(src)`; after that,
an app's `CMakeLists.txt` is one call, like a C++ app's `ADD_EXECUTABLE`.

**Once per tree**, paste this into the top-level `CMakeLists.txt`
(`python3 -m pymoos2 --cmake-block` prints it):

```cmake
#=======================================================================
# Find pymoos2 (Python MOOS apps)
#   Interpreter: -DPYMOOS2_PYTHON=<python>, else the active venv, else a
#   venv beside this tree (../venv), else python3 on PATH. Without
#   pymoos2 the Python apps are skipped and everything else still builds.
#=======================================================================
find_program(PYMOOS2_PYTHON NAMES python3 python
             HINTS ENV VIRTUAL_ENV "${CMAKE_SOURCE_DIR}/../venv" PATH_SUFFIXES bin)
execute_process(COMMAND "${PYMOOS2_PYTHON}" -m pymoos2 --cmake-dir
                OUTPUT_VARIABLE PyMOOS2_DIR OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
find_package(PyMOOS2 QUIET)
if(NOT PyMOOS2_FOUND)
  message(WARNING "pymoos2 is not importable with ${PYMOOS2_PYTHON} - Python apps will not be built. "
                  "pip install pymoos2 there, or configure with -DPYMOOS2_PYTHON=<python>.")
  unset(PYMOOS2_PYTHON CACHE)
  function(pymoos2_add_script_app)
  endfunction()
  function(pymoos2_add_package_app)
  endfunction()
endif()
```

**Per app**, generate it in `src/` and list it in `src/CMakeLists.txt`:

```bash
cd moos-ivp-myproject/src
python3 -m pymoos2 --GenAppCastingMOOSApp Foo p "Your Name"   # script app
python3 -m pymoos2 --GenPackageApp Bar p "Your Name" [--web]   # package app
```

```cmake
ADD_SUBDIRECTORY(pMyCppApp)      # C++
ADD_SUBDIRECTORY(pFoo)           # Python, script app
ADD_SUBDIRECTORY(pBar)           # Python, package app
```

The generated `src/pBar/CMakeLists.txt`:

```cmake
#--------------------------------------------------------
# The CMakeLists.txt for:                       pBar
# Author(s):                              Your Name
#--------------------------------------------------------

pymoos2_add_package_app(NAME pBar PACKAGE pbar)
```

- **Script app** (`pymoos2_add_script_app(NAME pFoo ENTRY pFoo.py MODULES Foo.py)`):
  the build copies the files into `bin/` with the entry script's `#!` line
  set to the configured interpreter.
- **Package app** (`pymoos2_add_package_app(NAME pBar PACKAGE pbar)`):
  `pBar/pbar/` is a Python package with as many modules, subpackages and
  data files as it needs. The build puts `bin/pBar`, a launcher that runs the
  package in place, so edits take effect without rebuilding. When stderr is
  not a terminal, as under pAntler, the launcher appends it to
  `~/.pBar/launch.log`.
- **`REQUIRES mod ...`** on either call names modules the app imports beyond
  pymoos2. Every build first parses each `.py` and imports pymoos2 and each
  `REQUIRES` module with the configured interpreter, so a missing module
  fails the build instead of an app that pAntler starts and that dies unseen.
- **Without pymoos2** the configure warns once, the two calls do nothing, and
  the C++ apps build as usual. The tree needs no `IF` around the
  `ADD_SUBDIRECTORY` lines.

`cmake --install build --prefix <dir>` installs script apps to `<dir>/bin`
and package apps to `<dir>/lib/pymoos2-apps/<app>/` with a launcher in
`<dir>/bin` that finds the package relative to itself, so an installed prefix
can be moved. C++ apps need their own `install(TARGETS ...)` line to join them.

All generated apps accept `pFoo file.moos [alias]`, `--alias=<name>`, and
`-h`, `-e` (example config), `-i` (interface), `-v`.

### Examples

```bash
cd moos-ivp-myproject                 # the tree root, with src/ and missions/
python3 -m pymoos2 --example
```

adds three apps to `src/` and a mission to `missions/`. None needs anything
beyond pymoos2. Add the three `ADD_SUBDIRECTORY` lines it prints (and the
block above, if the tree does not have it yet), then `./build.sh`, then
`cd missions/alpha_pymoos2 && ./launch.sh 10`.

| App | Layout | What it does |
|---|---|---|
| `pWptPulse` | script | vehicle: a VIEW_RANGE_PULSE at each waypoint |
| `pNodeWatch` | script | shoreside: a web page of NODE_REPORT traffic on port 8081 |
| `pFrameMonitor` | package with subpackages, packaged data, its own tests | vehicle: local frame distortion at the vehicle, with warnings |

`pFrameMonitor` is the reference for a larger app: its data file is found
through `__file__`, so it works in place and after `cmake --install`, and
`python -m pytest tests` in its directory runs its own unit tests.

## Geodesy

Most behaviors in the IvP helm work in local SI coordinates: meters east (x)
and north (y) of the mission origin (`LatOrigin`, `LongOrigin`).
`pymoos2.geodesy` converts between those and lat/lon, and does the geodesy
around it, with PROJ.

```python
from pymoos2.geodesy import LocalFrame, geodesic, distortion

frame = LocalFrame(42.358456, -71.087589)      # UTM in the origin's zone
x, y = frame.to_xy(42.3601, -71.0942)
lat, lon = frame.to_latlon(x, y)               # exact to well under a micrometer

geodesic.distance(42.36, -71.09, 51.48, 0.0)   # meters on the WGS84 ellipsoid
geodesic.forward(42.36, -71.09, 45.0, 10_000)  # (lat, lon) 10 km out at bearing 45

d = distortion(frame, lat, lon)                # how far the flat frame is off here
d.scale_ppm, d.convergence_deg, d.range_error_m, d.bearing_error_deg
```

- **`LocalFrame(lat, lon, projection="utm", epoch=0)`**. With `utm` (the
  default) x/y are the UTM easting/northing in the origin's zone minus the
  origin's, the same x/y the C++ MOOS-IvP apps compute, so posts between them
  agree. The zone is fixed by the origin, so x/y stay continuous when a vehicle
  crosses a zone line. With `aeqd` (azimuthal equidistant) distances and
  bearings from the origin are exact, distortion grows more slowly, and it
  works at any latitude including the poles; UTM origins must lie between 80°S
  and 84°N. Frames are immutable and thread-safe. `to_xy_many` and
  `to_latlon_many` convert batches in one call. `to_spec()` / `from_spec()`
  publish a frame as one line. `moved_to(lat, lon)` makes the next frame of a
  mission with `epoch + 1`.
- **`geodesic`**: `inverse`, `distance`, `bearing`, `forward`, `path` on
  WGS84, exact to nanometers at any range, across the antimeridian and over
  the poles. Use these, not x/y, for long-range work.
- **`distortion(frame, lat, lon)`**: any flat x/y frame stretches and rotates
  away from its origin. This reports, exactly, the worst-direction scale error
  in ppm, the grid convergence (a true heading H runs along grid bearing
  H + convergence), and the range and bearing error of x/y from the origin
  against the geodesic. `leg_deviation()` gives how far a straight x/y leg
  strays from the true path between its ends. At the MIT origin a UTM frame is
  off by 0.03% in scale 100 km out and 0.8% 1,000 km out.
- **`reframe_xy`, `reframe_many`, `reframe_heading`, `reframe_object`**:
  carry points, headings and geometry objects from one frame to another
  through lat/lon, for missions that move their origin.
- **`geodesy.info`**: pMarineViewer `.info` files for georeferenced images,
  and image lookup along `IVP_IMAGE_DIRS`.

## Parsing what other apps publish

- `pymoos2.dtos.geometry`: every VIEW_* type (point, seglist, seglr, polygon
  with all `format=` constructors, circle, marker, vector, range and comms
  pulses, arrow, wedge, oval, textbox) with `parse_view(var, spec)`,
  `get_spec()`, `to_dict()`, and MOOS color parsing.
- `pymoos2.dtos.NodeRecord`: NODE_REPORT with every field alias, presence
  tracking (`has("depth")`), and serialization in MOOS-IvP's field order.
- `pymoos2.casts`: APPCAST, REALMCAST, REALMCAST_CHANNELS and WATCHCAST
  parsers, request builders, and repositories that order and count them the
  way uMAC and pMarineViewer do.
- `pymoos2.core.strutil`: the string helpers mission files and specs rely on
  (`parse_string_q`, `double_to_string_x`, `macro_expand`, ...).

## Brand assets

`pymoos2.assets` ships the favicon, the mark, the wordmark and the combined
lockup for web pages and docs built on pymoos2. `assets.path("favicon.ico")`
returns a file's path and `assets.names()` lists them. The `--web` package
app template and the `pNodeWatch` example use the favicon and the mark.

## Behavior worth knowing

- **Reconnects**: registrations, including wildcards, are replayed after a
  reconnect, `register_variables()` runs again on the app thread, and mail
  queued while the link was down is sent once it is back. A reply that does not
  decode is treated as a broken link: the client reconnects instead of dying.
- **Text**: MOOS strings are bytes. pymoos2 decodes them as UTF-8 with
  `surrogateescape`, so any byte sequence a C++ app posts survives a round trip
  unchanged.
- **Fail fast**: a missing mission file raises `FileNotFoundError`; an
  invalid `MOOSTimeWarp` is reported and replaced with 1.
- **Time warp** is process wide, as in C++ MOOS: one app per process.

## Tests

The tests live in `tests/` in the repository; the wheel does not include them.

```bash
git clone https://github.com/raymondturrisi/pymoos2 && cd pymoos2
pip install -e .[test]
./test.sh              # every test, one line each: PASSED / FAILED / SKIPPED
./test.sh --wheel      # build the wheel, install it in a fresh venv, test that
./test.sh -k geodesy   # other arguments go to pytest
```

Tests that need a live `MOOSDB` (on `PATH` or in `~/dev/moos/moos-ivp/bin`),
`cmake` or a C++ compiler skip themselves when those are missing, and the
summary at the end says why. The CMake tests build a small extend tree with a
C++ app beside generated apps and the shipped examples, then install it and
move the prefix.

## License

MIT. See `LICENSE`.
