Metadata-Version: 2.4
Name: nexusflow-sdk
Version: 1.2.0
Summary: Python SDK for NexusFlow model editing and simulation workflows
Author: NexusFlow Team
License-Expression: LicenseRef-Proprietary
Keywords: nexusflow,pipeline-simulation,oil-gas,sdk,digital-twin
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.31.0
Requires-Dist: websocket-client>=1.8.0
Provides-Extra: dev
Requires-Dist: build>=1.2.2; extra == "dev"
Requires-Dist: twine>=5.1.1; extra == "dev"

# nexusflow-sdk

nexusflow-sdk is a Python SDK for NexusFlow model editing, simulation execution, streaming result retrieval, and runtime command control.

## Features

- Token-based authentication against the NexusFlow backend
- Create models for supported workspace types and open existing models
- Add, remove, connect, and configure components in the model graph
- Create and edit two-port linear components represented as component edges
- Create and manage multiple drawing sheets in one model
- Save model snapshots and start simulation jobs
- Poll or stream logs, plots, tables, inspect data, and container messages
- Send runtime commands to components during online or transient execution
- Run a local algorithm through NexusFlow Bridge with the `BridgeRuntime` JSON Lines API
- Bind scalar external-compute input/output channels to existing control ports

## Requirements

- Python 3.10 or later
- A reachable NexusFlow service endpoint
- A NexusFlow account that can obtain access tokens

## Install

Install from a built wheel or from PyPI after publication:

```bash
pip install nexusflow-sdk
```

For local development in this repository:

```bash
pip install -e .
```

## Quick Start

```python
from nexusflow_sdk import NexusFlowClient

client = NexusFlowClient(
    base_url="http://localhost:8000",
    username="admin",
    password="your-password",
)

model = client.create_model(
    name="sdk-demo-model",
    workspace_type="lps_online",
    description="Created by nexusflow-sdk",
)

source = model.add_component("Source", position=(0, 0))
pipe = model.add_component("Pipe", position=(240, 0), mode="node")
load = model.add_component("Load", position=(480, 0))

model.connect(source, "0", pipe, "0")
model.connect(pipe, "1", load, "0")

model.save()
# run() validates the current snapshot through the backend by default.
job = model.run(timeout=120, image="nexusflow")

for message in job.stream_results(timeout=2):
    print(message.get("type"), message.get("key"))
```

New node components use the icon SVG's `viewBox` width and height by default,
matching WorkBench. Definitions with `graphMetaData.width` and `height` can
override these defaults.
Missing or invalid dimensions fall back individually to width 120 and height 80.
An explicit `view_status` takes precedence; loading existing models preserves
their saved layout.

Parsed log results expose `LogMessage.format` as `"text"` or `"html"`;
missing and unknown values safely normalize to `"text"`. Table results retain
`html` columns through update and append merging. The SDK exposes
`LogFormat`, `TableColumnType`, and `TableColumnData` for type annotations, but
does not render or execute HTML.

`model.run(validate=True)` is the default and creates no job when shared backend
validation reports errors. For trusted large batch workloads,
`model.run(validate=False)` skips only that explicit pre-run business-validation
request. The job API still performs required structural, authorization, and
runtime-safety checks. The SDK force-refreshes the workspace definition before
every run so the submitted runtime definition does not come from a stale local
cache.

## Local algorithms and external software

NexusFlow Bridge launches a locally saved command, provides formal INPUT and
context files, and forwards standard messages to the platform. An algorithm
does not receive platform credentials and does not connect to Redis.

```python
from nexusflow_sdk import BridgeRuntime

runtime = BridgeRuntime()
case = runtime.read_input()
context = runtime.read_context()
runtime.log("Local algorithm received INPUT")
runtime.send_status("running", 0)
# Send the same {key,type,verb,data} result objects used by a Docker kernel.
runtime.send_message({"key": "my-table", "type": "table", "verb": "update",
                      "data": {"columns": [], "data": []}})
runtime.finish("success")
```

Existing scripts can continue to import `Runtime` as an alias of `BridgeRuntime`.

Configure the executable and arguments only in the desktop client; use `-u`
for Python. `examples/local_runtime.py` demonstrates a complete controllable
process. Reserve stdout for protocol messages and write diagnostics to stderr.

For a runnable calculation, configure Bridge to run `python -u /path/to/bridge_sum_constants.py`
using [the biptGps example](examples/bridge_sum_constants.py). Add `ConstInput`
components to the model and select the command as the full kernel. The script
reads each component's `ConstantValue` from formal INPUT, then publishes a
container and chart that the platform result viewer displays.
Read `runtime.commands()` in a control thread to support existing `JOB_CONTROL`
pause/resume/stop commands. Closing stdin means the controlling client has gone
away; stop the process rather than continuing unobserved computation.

`BridgeRuntime.send_message()` rejects nonstandard envelopes, producer-supplied
archive IDs and non-finite JSON numbers. `send_com()` also checks operation
payloads; `nexusflow_sdk.protocol.validate_com_message()` can be called in
development tools without sending. The client and coordinator additionally
check assignment ownership, schema hashes and exact signal sets/shapes. Ordinary
plot/table/inspect contents remain opaque in the platform upload hot path.

Drain all result/log producers, then call `finish()` once. It sends terminal
status followed by `terminate`; stopped/fault outcomes retain their prior
progress. Sending after finish is an error. Acknowledged upload is accepted
ingress, not a guarantee that the archive writer has finished persisting.

To select a client as the full kernel through the model SDK:

```python
model.set_global("kernelSource", "client")
model.set_global("clientId", "your-bound-client-id")
model.set_global("computeConfigId", "your-local-configuration-id")
model.set_global("computeConfigVersion", "1")
job = model.run()
```

The backend supplies built-in execution parameters and workspace meta defaults.
An explicit nonempty task/model image wins over
`meta.config.executionDefaults.image`, then the legacy definition default, then
the server fallback. Client mode keeps the saved image for switching back to
Docker. Omitting `kernelSource` preserves Docker behavior.

For external participants, add `ExternalComputeInterface` to biptGps and set
`ClientId`, `ComputeConfigId` and `ComputeConfigVersion`. Its two ordinary table
parameters, `InputChannels` and `OutputChannels`, contain rows in the exact order
`[name, portReference, unit, initialValue]`. Input means platform-to-external;
output means external-to-platform. Each row exchanges one finite scalar.

```python
source = model.add_component("ConstInput", params={"ConstantValue": 3})
scope = model.add_component("Oscilloscope")
bridge = model.add_component("ExternalComputeInterface", params={
    "ClientId": "your-bound-client-id",
    "ComputeConfigId": "your-participant-configuration-id",
    "ComputeConfigVersion": "1",
    "InputChannels": [["u", source.port("0").reference, "", 0]],
    "OutputChannels": [["y", scope.port("0").reference, "", 0]],
})
```

Port references serialize `[sheetId, componentId, portKey]`; model-internal
cross-sheet bindings are supported. The source must be an enabled CONTROL OUT
port, such as the output of a SignalMeasurementAdapter. The destination must
be an enabled CONTROL IN port, such as the input of a SignalActuationAdapter.
Port directions come from the component definition. Binding an output
into an already driven signal network is rejected. Input fanout is supported.
Units are annotations only, and initial values do not replace invalid bindings.

The bridge has no visible ports: table references are the connection, so there
is no additional wire to draw. Table order does not determine channel identity.
`nexusflow_sdk.compute.external_signals_from_channels()` derives the internal
scalar wire interface using stable UUIDv5 IDs and deterministic ordering.
Renaming a channel changes its external interface identity; replacing its
platform port binding alone keeps the external interface intact. Copying a sheet
remaps bindings to components copied with that sheet and preserves other refs.

The platform groups matching client/config/revision participants and freezes
their interface manifest. The desktop client increments configuration revisions
when execution settings change; reselect the updated configuration in the model.
This does not hash or freeze local files modified in place. Run/stop controls and
result consumption are unchanged. The former `Signals`/`instancePorts` model
definition is explicitly rejected and must be reconfigured in the two tables.

## Multiple Sheets

Every new model contains `sheet_0`. Sheet IDs are allocated as `sheet_1`,
`sheet_2`, and so on for the lifetime of the model object.

```python
process = model.default_sheet
control = model.add_sheet("Control")

source = process.add_component("Source", position=(0, 0))
controller = control.add_component("Controller", position=(0, 0))

# Physical edges stay inside one sheet. Matching trimmed, case-sensitive pin
# labels create a logical connection across sheets.
source.set_pin_label("0", "pressure_signal")
controller.set_pin_label("0", "pressure_signal")

copied = model.copy_sheet(control)
print(copied.id)  # sheet_2
```

Legacy snapshots with top-level `nodes` and `edges` are loaded as `sheet_0`.
New saves always use snapshot schema version 2 with a top-level `sheets` array.

## Wire Junctions

An existing wire can terminate on another wire in the same sheet. Inspect
`connection.source` or `connection.target` for the full endpoint. For example,
`{"cell": "edge_0", "anchor": {"name": "ratio", "args": {"ratio": 0.5}}}`
describes a junction halfway along `edge_0`. The corresponding `source_port` or
`target_port` is `None`; `source_component` or `target_component` holds the
referenced wire ID. For a node port, those fields still hold the node ID and port
key.

The SDK preserves these endpoints when saving or submitting a model. Copying a
sheet remaps junctions to the copied wires, and removing a wire also removes
branches that depend on it. `model.connect(...)` creates node-to-node wires.

## Linear Components

A component definition with exactly two physical ports can use `mode="edge"`.
If its definition sets `linearization.defaultMode` to `edge`, the SDK uses the
linear form by default; pass `mode="node"` to override it.

```python
source = model.add_component("Source", position=(0, 0))
sink = model.add_component("Sink", position=(480, 0))
pipe = model.add_component("Pipe", position=(240, 40), mode="edge")

# portsDefinition[0] is the source end and portsDefinition[1] is the target end.
pipe.attach("source", source, "0")
pipe.attach("target", sink, "0")

# Either end may be detached at an explicit free canvas point.
pipe.detach("source", point=(120, 40))

# Conversion keeps the component id, label, parameters, and pin labels.
node_pipe = pipe.delinearize()
linear_pipe = node_pipe.linearize()
```

Attach a `LinearComponent` source or target endpoint directly to a node port as
shown above. `model.connect(...)` does not enforce this as a local business rule;
use backend validation to reject an unsupported graph shape.
Linear components remain available through `model.components`; annotation
edges are kept separately in `model.annotations` and are excluded from physical
connections and simulation topology.

## Public API

The package currently exports these main entry points:

- `NexusFlowClient`
- `Model`
- `Component`
- `LinearComponent`
- `Connection`
- `AnnotationEdge`
- `Sheet`
- `Job`
- `MetaService`
- `ResultStream`
- `LogMessage`
- `LogFormat`
- `PlotMessage`
- `TableMessage`
- `TableColumnData`
- `TableColumnType`
- `InspectMessage`
- `ContainerMessage`
- `NexusFlowError`
- `AuthError`
- `APIError`
- `NotFoundError`
- `ValidationError`
- `ValidationIssue`
- `ValidationResult`

## Examples

- `examples/quickstart.py`: create, save, run, and fetch results
- `examples/transient_streaming.py`: stream transient online results and send commands during execution
- `examples/run_existing_model.py`: open an existing model by ID and run it

## Release Validation

Build and metadata check:

```bash
python -m build
python -m twine check dist/*
```

Minimal install smoke test with the built wheel:

```bash
python -m venv .smoke-venv
.smoke-venv\Scripts\python -m pip install dist\nexusflow_sdk-0.6.0-py3-none-any.whl
.smoke-venv\Scripts\python -c "from nexusflow_sdk import NexusFlowClient, Model, Job, ResultStream; print('smoke ok')"
```

## Release Workflow

If you want to publish a new version yourself, the repository now includes a reusable PowerShell script:

```powershell
.\scripts\release.ps1 -Repository pypi -Token "pypi-..."
```

Recommended process:

1. Update `version` in `pyproject.toml`.
2. Run the release script from the `nexusflow-sdk` directory.
3. Wait for PyPI index propagation if the published install smoke test fails on the first try.

The script performs these steps automatically:

- clean `dist/`
- `python -m build`
- `python -m twine check dist/*`
- `python -m unittest tests.test_public_api`
- install the built wheel into a temporary virtual environment for a local smoke test
- upload to PyPI or TestPyPI
- create a fresh temporary virtual environment and install the published package for a post-publish smoke test

Examples:

```powershell
# Full publish to PyPI
.\scripts\release.ps1 -Repository pypi -Token "pypi-..."

# Full publish to TestPyPI
.\scripts\release.ps1 -Repository testpypi -Token "pypi-..."

# Local validation only, without upload
.\scripts\release.ps1 -SkipUpload -SkipSmokeTest
```

You can also avoid passing tokens on the command line by using environment variables:

```powershell
$env:PYPI_TOKEN = "pypi-..."
.\scripts\release.ps1 -Repository pypi
```

## License

This package is currently distributed as proprietary software.
