Metadata-Version: 2.5
Name: integrate-ui
Version: 0.1.0
Summary: A project-centric workbench UI for the INTEGRATE probabilistic inversion library
Author: Thomas Mejer Hansen
License-Expression: MIT
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: fastapi
Requires-Dist: h5py>=3.8
Requires-Dist: integrate-module>=1.0.0
Requires-Dist: matplotlib>=3.8
Requires-Dist: numpy>=2.0
Requires-Dist: pydantic>=2
Requires-Dist: pyvista>=0.49
Requires-Dist: shapely>=2.2
Requires-Dist: swagger-ui-bundle<2,>=1.1
Requires-Dist: uvicorn[standard]
Requires-Dist: vtk>=9.7
Description-Content-Type: text/markdown

# integrate-ui

A project-centric workbench UI for [`integrate_module`](https://github.com/AUProbGeo/integrate_module),
the Python library for localized probabilistic data integration (electromagnetic inversion with
prior information).

Open a project folder, see the lineage of its data and results (DATA, PRIOR, PRIOR+forward,
POSTERIOR), explore results through linked views, run the pipeline from schema-driven forms, and
turn posterior probabilities into decisions. Everything the UI does is also available through an
API, a CLI and exported Python.

Status: **pre-alpha**. Nothing here is usable yet.

Local development needs a sibling checkout of `integrate_module` at `../integrate_module`, at the commit
pinned in [`docs/parity/UPSTREAM.md`](docs/parity/UPSTREAM.md) (`UPSTREAM_SHA`):

```bash
git clone https://github.com/AUProbGeo/integrate_module.git ../integrate_module
git -C ../integrate_module checkout 0b5e6bffa73bc6198938852d5c6cbf816fcc2a28
```

The pin file is authoritative: when it changes, check out the new SHA there. Without this checkout `uv sync` fails.

### Working in a git worktree

`pyproject.toml` points at the library with the path source `../integrate_module`, which `uv` resolves from the
project root. A git worktree of this repository must therefore sit next to `integrate_module`, as a sibling of
this checkout; anywhere else `uv sync` fails with "Distribution not found". Create one with:

```bash
git worktree add ../integrate_ui-<topic> -b agent/<role>/<topic>
```

## Running the UI

You need [uv](https://docs.astral.sh/uv/). Node.js 22 with npm is needed only to build or change the web UI
(see "What npm is for" below), never to run a released version.

### From a source checkout (contributors)

First time only:

```bash
uv sync                          # Python environment
npm --prefix src/web ci          # web UI dependencies (downloads once into src/web/node_modules)
npm --prefix src/web run build   # compiles the UI into src/web/dist (repeat after changing the UI)
```

Then one command serves the UI and the API together:

```bash
uv run integrate-ui serve                  # UI and API on http://127.0.0.1:8000
uv run integrate-ui serve ./my-survey      # the same, with that folder already open as the project
```

Open `http://127.0.0.1:8000` in a browser. `--port 0` picks a free port and prints it
(`integrate-ui serving on http://127.0.0.1:<port>`). Without a built `src/web/dist`, `serve` runs the API
only. The optional `PROJECT_DIR` is resolved against the current directory; if it is not an existing folder,
`serve` exits with status 2 and binds nothing.

**Using the UI.** Open a folder by starting `serve` with it, or type its absolute path in the UI. Any existing folder
opens: there is nothing to create and nothing is written to your folder when you open it. The UI scans the folder (and
its subfolders) once for HDF5 files and lists them under PRIOR, DATA, POSTERIOR, FORWARD and "Unknown / unreadable"
(a group with no files is not shown), each with its folder, size and date; **Rescan** scans again and the filter box
narrows the list by name. The whole file list folds into a slim strip (it folds by itself when you pick a file, unless "Keep files open" is ticked, so the viewer gets the full width, and "Show files" opens it again), and each type group folds from its heading or with the type buttons above the list (for example only POSTERIOR); the choice is remembered in this browser. Click a file to see the INTEGRATE library's own figure for it (PRIOR, DATA and POSTERIOR files; rendered by the
library in a separate process, a few seconds the first time, with the exact library call as the caption) and, under
"File details", its type, size, attributes, datasets with shape and type, and the PRIOR model parameters. **Explore (POSTERIOR files).** Click a POSTERIOR file that holds posterior statistics and an interactive map appears above the
library figure: one dot per sounding, coloured by a statistic of a model at a depth layer ("Colour by", Model, Statistic and the
Depth layer slider) or by a scalar such as EV, CHI2 or T. Click a dot to choose its line and focus that sounding; the section
beside the map shows the line (depth against distance, same colours) with the focus marked, and a click in the section or the
Left and Right keys move the focus. Drag and wheel pan and zoom the map. Colours and limits come from the library through the
server. A file without statistics says so and shows only the scalar map; a file without coordinates shows only the library
figure, which for every POSTERIOR file sits below the map under "Library figure" and is drawn only when you open it. Below them, the **Sounding** panel shows the focused sounding itself: the observed data
with a band of two standard deviations and the predicted data of 100 accepted realizations (data number on the x axis, as in
the library's own `plot_data_prior_post`), and the accepted models as step profiles over depth with the posterior median and
a band of one standard deviation. Arrow keys on the section step through soundings (one request for the one you stop on). If
the DATA or PRIOR file named in the posterior is not in the project, the panel says so. **Discrete models** (for example a lithology with named classes) are explored too: pick the model, then "Mode (most
probable class)" (one colour per class, with a legend), "Entropy" (0 to 1) or "Probability of class" (choose the class); the
focus text names the class ("class 3 (Till)") and the sounding panel shows the realizations as class ids, the posterior mode and
the class probabilities per layer. If the PRIOR file naming the classes is not in the project, the class names and colours are
assumed and the panel says so. **Region selection.** Above the map, the tools Pan, Lasso and Box select soundings: drag a free shape (Lasso) or a rectangle (Box);
a new drag replaces the region, Shift adds to it, Alt removes from it, Delete or "Clear selection" clears it. The soundings outside
the region are dimmed. Under the map and section, the region panel counts the selected soundings and their lines, gives the extent
and the minimum, median, maximum and mean of the coloured quantity, and draws a histogram of the selected soundings against all of
them (the bins are in a table; a discrete model shows soundings per class). "Select by value range" selects every sounding whose
value lies in a range. The section marks the soundings of its line that are in the region. The region stays while you change
the depth layer or the statistic, and is dropped when you open another file. Not in this slice: QC and a draggable layout.

**Decision.** A POSTERIOR file has two tabs, Explore and Decision. In Decision you ask a geological question: for example "the
probability that Till is more than 5 m thick between 0 and 40 m" (one to three conditions combined with AND; for a discrete model you
tick classes by name, for a continuous model you give a value comparison and a threshold; thickness is cumulative or the first
continuous occurrence, with a depth window and an optional "not"). The question is written out in words above the Run button. The
UI first asks the server for a cost estimate and starts by itself when the upper bound is within 10 s, else you confirm with "Run
anyway". The run is a job with a progress bar ("N of M soundings") and a Cancel button; the result is a probability map. Click a
sounding on it, choose a cut-off (and an optional maximum area) and "Find the coherent area" grows a connected region of high
probability around the seed (drawn as an outline), or use your own lasso or box region. "Run volume" gives the volume of the target
material in the region as the 5th, 50th and 95th percentile of the posterior realizations, with the mean thickness. "Save to
comparison" keeps the answer in a table of this session (in this browser tab only, nothing is written into your project or on the
server) and every record can be exported as JSON or Markdown with the question, the numbers, the exact library calls and the
file names (no folder paths). Everything is computed by the INTEGRATE library in worker processes; if the server was started with
`--allow-network` on a non-loopback address, jobs are switched off and the tab says so. Not in this slice: questions in natural
language, hypothesis probabilities, saving results into the project, comparing several regions on one map.
This is all the UI does so far: no editing, no plot options, no jobs. No Node.js is needed to use it, only to
build it from a source checkout.

**No login.** The UI is a local, single-user tool: the API has no authentication, and the protection is that the
server only listens on loopback and only answers to loopback `Host` names (below). Any program running as you on this
machine can call the API, exactly as it can read your files. To use the API directly:

```bash
curl http://127.0.0.1:8000/api/health
```

The server answers only to loopback host names (`127.0.0.1`, `localhost`, `[::1]`); a request with any other
`Host` header gets `400`. Behind a proxy or on a lab machine, name the host you expect with
`--allowed-host NAME` (repeatable; a bare host name or IP, no port). A `--host` that is not loopback
(`127.0.0.0/8`, `::1`, `localhost`) is refused (exit status 2, nothing is bound) unless you also pass
`--allow-network`: it exposes the UI and API to the network, and the API has no authentication and plain HTTP is not
encrypted, so this is unsupported and at risk (use an SSH tunnel or a TLS proxy and keep the server on loopback). With the flag, `serve` prints a warning. A specific IP address or a host
name typed to `--host` is allowed as a `Host` automatically, so the printed URL works (a typed name is trusted as a
`Host`: keep the name under your own DNS); `--host 0.0.0.0` (or
`::`) is reached locally at `http://127.0.0.1:<port>`, and other machines need `--allowed-host` for the name or
IP they use. An invalid `--host` (a port, a path, spaces, a trailing dot) is a usage error. A reverse proxy in front of the server exposes the
API to its network just as a non-loopback `--host` does, and no warning is printed in that
case; serving under a path prefix (`root_path`) is not supported. The API documentation is
at http://127.0.0.1:8000/api/docs; it works offline (the Swagger UI files come from the `swagger-ui-bundle`
package and are served by the app itself; there is no ReDoc page). Open it in a NEW tab or window, not in the tab that
holds the web app: the bundled Swagger UI is an old release (4.15.5) and shares the web app's origin (see ADR-0009).

### Working on the UI (two terminals)

For live reload while you change the UI, run the backend and the Vite dev server separately:

```bash
uv run integrate-ui serve        # terminal 1: backend API on http://127.0.0.1:8000
npm --prefix src/web run dev     # terminal 2: web UI, prints its address (normally http://localhost:5173)
```

Open the address printed by terminal 2. The dev server forwards `/api` requests to the backend, so both
terminals must be running. The dev server's own CORS handling is switched off (`server.cors: false`), so a page on
another local origin cannot read responses through the proxy or send JSON mutations from the browser.

### End users

Released wheels will include the compiled UI, so end users will need neither Node nor npm: install the
package and run `integrate-ui serve`. No release has been published yet, so this applies once a release
is published.

### Building a wheel with the UI

```bash
npm --prefix src/web ci && npm --prefix src/web run build && INTEGRATE_UI_REQUIRE_WEB_DIST=1 uv build --wheel
```

Do not run a plain `uv build`: it builds the wheel from an sdist, and the sdist does not contain the
git-ignored `src/web/dist`, so you would get a wheel without the UI that looks fine. With
`INTEGRATE_UI_REQUIRE_WEB_DIST=1` the wheel build fails loudly when `src/web/dist/index.html` is missing.
CI runs exactly this build and checks that the wheel contains `integrate_ui/web_dist/index.html`.

### What npm is for

npm is the package and build tool of Node.js. The web UI is written in TypeScript and React; npm
downloads its dependencies and compiles that source into plain HTML, JavaScript and CSS files that any
browser runs. The compiled UI does not need Node or npm at run time, so npm is a **developer** tool:
a contributor builds the UI once, and a release ships the compiled files inside the Python package.
The desktop shell will start `integrate-ui serve --port 0`, see [ADR-0004](docs/decisions/ADR-0004-desktop-shell.md).

### Running the tests

```bash
uv run pytest -n auto -m "not slow" -q   # the fast loop while developing (a few seconds to about a minute)
uv run pytest -n auto -W error -q        # everything, as CI runs it (about 70 s on 16 threads)
npm --prefix src/web test                # web tests (about 20 s)
```

The backend tests run in parallel (`pytest-xdist`); tests that start a library run or a worker process carry the `slow`
marker, so the fast loop leaves them out. Run the full command before pushing.

## Projects

Any existing folder can be opened as the project: no manifest is needed and nothing is written to the folder on open.
The server has one project open at a time; opening another replaces it. If the folder has an `integrate_project.json`
and it is valid, it is read (it will hold the role of files later); a missing, unreadable, invalid or too-new manifest
does not block browsing, the project just has none (`has_manifest: false`). Opening a folder is the only call that
takes an absolute path; every other path is relative to the project, and no response contains an absolute path (the
summary has the folder's base name only).

```bash
URL=http://127.0.0.1:8000
curl -X POST -H "Content-Type: application/json" -d '{"path": "/home/me/my-survey"}' $URL/api/project/open
curl $URL/api/project                   # {"name", "folder_name", "has_manifest"} of the open project
curl $URL/api/project/h5-files          # every HDF5 file of the project, classified (see below)
curl -X POST -H "Content-Type: application/json" -d '{}' $URL/api/project/close
```

`GET /api/project/h5-files` scans the open folder for HDF5 files and classifies each one, so nothing has to be
browsed by hand. It lists only files ending in `.h5` or `.hdf5` (any case), looking at most 8 folder levels down; it
never follows symbolic links, skips names that start with a dot, and takes no parameter. Each entry has the
project-relative `path` (with `/`), `name`, `size`, `modified`, the library's `file_type` (`PRIOR`, `DATA`, `POST`,
`FORWARD` or `UNKNOWN`) and an `error`. A file that cannot be read is `UNKNOWN` with `error` set to
`not an HDF5 file` or `unreadable HDF5 file`; the library's own message is never returned. The list is sorted by type
(PRIOR, DATA, POST, FORWARD, UNKNOWN), then path. It stops at 1000 files, 20000 folder entries or about 10 seconds
(`truncated: true`; which files are kept is then up to the file system's order). The first call imports the
library and takes seconds; classification only reads the file's metadata. Errors have fixed texts, for example
`404 {"detail": "no project is open"}`.

`GET /api/fs/dirs?path=<absolute folder>&hidden=false` lists the sub-folders (names only, at most 2000) of a local folder, or of your home folder when `path` is empty, so the UI can offer a folder chooser instead of a typed path; it is the one route that returns an absolute path (the folder being browsed). It exists only when the server is bound to loopback: `--allow-network` on a non-loopback host turns it off (`404`).

## Inspecting HDF5 files

With a project open, `GET /api/project/h5?path=<project-relative file>` returns the metadata of an HDF5 file: its type
as the library classifies it (`DATA`, `PRIOR`, `POST`, `FORWARD` or `UNKNOWN`), the root attributes, every dataset with
its shape, dtype and attributes, and, for a `PRIOR` file, the model parameters (name, discrete or not, depth range,
number of layers, class names). It reads metadata only, never data values, and no data statistics are computed. The file
type, attributes and names come from the library's `hdf5_info` and `get_prior_model_info`; shape, dtype and per-dataset
attributes come from a small `h5py` walk because the library does not return them (the response's `source` field says which is which;
see `docs/parity/upstream-requests.md`). There is no web UI for this yet.

```bash
curl "$URL/api/project/h5?path=prior/DAUGAARD_CMP_PRIOR_N1000.h5"
```

Limits: at most 2000 datasets (then `truncated: true`), at most 100 attributes per object, attribute values are reduced
to JSON-safe forms (long arrays are summarised by shape and dtype), files that contain HDF5 external links are refused,
and the HDF5 signature must be at offset 0 of the file. Symbolic links on the path are refused. The first call is slow
(seconds) because it imports the library. Errors have fixed texts: `400 invalid path`, `403 permission denied`,
`404 not found` or `no project is open`, `409 unreadable HDF5 file` (valid signature, but it could not be read, or it has
external links), `415 not an HDF5 file`, `422 invalid request` (no `path` given), `503 library unavailable`.

## Figures of HDF5 files

`GET /api/project/figure?path=<project-relative file>` answers `image/png`: the figure the library itself draws for the
file (PRIOR `plot_prior_stats`, DATA `plot_data`, POST `plot_T_EV`; only the first figure of the call). It is drawn in a
separate worker process (60 s limit, at most 2 at a time, PNG at most 20 MB, nothing is written into the project) and the
last 8 figures are cached. The response header `X-Library-Call` names the exact library call. Errors are constant:
the codes of the inspector plus `409 figure could not be rendered`, `415 no figure for this file type` (FORWARD,
unknown) and `504 figure timed out`. A POST file needs its DATA file, named relative to the POST file, inside the project.

## More

- Working agreement for contributors and AI agents: [AGENT.md](AGENT.md)
- Plan and architecture: [docs/PLAN.md](docs/PLAN.md)
- Architecture decisions: [docs/decisions/](docs/decisions/)

License: MIT. See [LICENSE](LICENSE).
