Metadata-Version: 2.4
Name: plothero
Version: 0.3.0b1
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Rust
Classifier: Topic :: Scientific/Engineering :: Visualization
Requires-Dist: numpy>=1.24.0
Requires-Dist: maturin>=1.4 ; extra == 'dev'
Requires-Dist: pytest>=8.0.0 ; extra == 'dev'
Requires-Dist: pandas>=2.0.0 ; extra == 'dev'
Requires-Dist: plotly>=5.0.0 ; extra == 'dev'
Requires-Dist: mkdocs>=1.6 ; extra == 'docs'
Requires-Dist: mkdocs-material>=9.5 ; extra == 'docs'
Requires-Dist: mkdocstrings[python]>=0.25 ; extra == 'docs'
Requires-Dist: pandas>=2.0.0 ; extra == 'examples'
Requires-Dist: plotly>=5.0.0 ; extra == 'examples'
Requires-Dist: pandas>=2.0.0 ; extra == 'pandas'
Requires-Dist: plotly>=5.0.0 ; extra == 'plotly'
Provides-Extra: dev
Provides-Extra: docs
Provides-Extra: examples
Provides-Extra: pandas
Provides-Extra: plotly
License-File: LICENSE
Summary: Plotly-compatible plotting for heavy signals, backed by a Rust downsampling core.
Keywords: plotly,plotting,visualization,downsampling,lttb,time-series,signal
Author: Matteo Serafino
License: Apache-2.0
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://plothero.matteoserafino.com
Project-URL: Homepage, https://plothero.matteoserafino.com

<p align="center">
  <img src="https://plothero.matteoserafino.com/assets/logo.png" alt="plothero" width="480">
</p>

Plotly-compatible plotting for heavy signals — Rust core, Python API.

plothero is not a replacement for Plotly. It's a drop-in for the specific
case where your traces are too large for Plotly.js to pan and zoom
smoothly. For everything else, use Plotly directly.

`plothero.graph_objects` mirrors `plotly.graph_objects` closely enough that
most `Figure`/`Scatter` code works after just swapping the import. The
whole public API is also available from the top-level package, so the
examples use `import plothero as ph`. The difference: traces above a size
threshold (default 5 000 points) are automatically decimated with a
Rust-accelerated LTTB, Min/Max, or M4 algorithm before being handed to
Plotly.js, so a 5-million-point signal still pans and zooms smoothly in the
browser.

---

## Requirements

- Python ≥ 3.9

Building from source additionally requires the
[Rust toolchain](https://rustup.rs) (`rustc` + `cargo`) and
[maturin](https://www.maturin.rs) — not needed when installing prebuilt
wheels via `pip install plothero`. Without a compiled extension, the
package still works via pure-Python fallback implementations with
identical output. LTTB is about 60× slower without Rust; MinMax and M4 run
at about the same speed.

Install Rust and Cargo with [rustup](https://rustup.rs):

```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
rustc --version   # sanity check
```

macOS users can alternatively run `brew install rust`. If `maturin develop`
fails with `rustc, the rust compiler, is not installed or not in PATH`,
Rust hasn't been installed yet, or the current shell hasn't picked up
`~/.cargo/env` — install it (or re-run `source "$HOME/.cargo/env"`) and
try again.

**`could not amend shell profile: '~/.bash_profile': ... Permission denied`**
— the rustup installer failed to add the `cargo env` line to
`~/.bash_profile` because that file isn't owned by you (or isn't
writable). Rust itself is still installed correctly; you just need
`cargo env` sourced from a profile file your shell actually reads. If
you use zsh (the macOS default), add it to `~/.zprofile` instead:

```bash
echo '. "$HOME/.cargo/env"' >> ~/.zprofile
```

Open a new terminal (or `source ~/.zprofile`) and `rustc --version`
should work.

---

## Installation

```bash
pip install plothero
```

Prebuilt wheels ship the compiled Rust extension, so no Rust toolchain is
needed on the machine installing the package. Each wheel targets the stable
Python ABI (`abi3`), so one wheel per platform covers Python 3.9 and newer:

| Platform | Architectures |
|---|---|
| Linux (manylinux) | x86_64, aarch64 |
| macOS | x86_64 (Intel), arm64 (Apple Silicon) |
| Windows | x64 |

On any other platform (for example musl-based Linux such as Alpine, or
Windows on ARM), pip falls back to the source distribution and compiles the
extension, which requires a [Rust toolchain](https://rustup.rs). Confirm the
compiled extension is active with:

```bash
python -c "import plothero as ph; print(ph.rust_available())"  # True
```

### Local development

See the [Development](#development) section below for the full setup,
build, and test workflow. Short version:

```bash
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
maturin develop --release
pytest
```

---

## Quick start

```python
import numpy as np
import plothero as ph

t = np.linspace(0, 60, 5_000_000)  # 5M points
y = np.sin(2 * np.pi * 1.2 * t) + 0.1 * np.random.randn(len(t))

fig = ph.Figure()
fig.add_trace(ph.Scatter(x=t, y=y, mode="lines", name="PPG",
                          line=dict(color="#e41a1c", width=1)))
fig.update_layout(title="PPG Signal", xaxis_title="Time (s)", yaxis_title="Amplitude")
fig.show()               # opens in the default browser
html = fig.to_html()     # HTML string, for notebooks / dashboards
```

`x` accepts numeric arrays, `datetime64`, or a pandas `DatetimeIndex` —
datetime handling is automatic, same as real Plotly.

The same figure built with real Plotly uses the same calls, only under
`plotly.graph_objects` instead of `ph`. Rendering 5M raw points client-side
is slow to pan/zoom (or crashes the tab entirely) without plothero's
downsampling:

```python
import numpy as np
import plotly.graph_objects as go   # <- the only line that changes

t = np.linspace(0, 60, 5_000_000)  # 5M points
y = np.sin(2 * np.pi * 1.2 * t) + 0.1 * np.random.randn(len(t))

fig = go.Figure()
fig.add_trace(go.Scatter(x=t, y=y, mode="lines", name="PPG",
                          line=dict(color="#e41a1c", width=1)))
fig.update_layout(title="PPG Signal", xaxis_title="Time (s)", yaxis_title="Amplitude")
fig.show()               # opens in the default browser
html = fig.to_html()     # HTML string, for notebooks / dashboards
```

### Walkthrough

`examples/walkthrough/` in the repository is a series of scripts that
go through every feature on a real signal: the
[UCI household power dataset](https://archive.ics.uci.edu/dataset/235/individual+household+electric+power+consumption),
about 2 million samples per channel with timestamps. It covers building the
Rust extension, the downsampling methods, a Rust vs pure-Python benchmark,
subplots, bar charts, heatmaps, export, and interactive zoom.

```bash
pip install -e ".[dev,examples]"   # adds pandas and plotly
maturin develop --release
python examples/walkthrough/01_check_install.py
python examples/walkthrough/02_overview.py   # and so on, up to 10
```

The dataset (about 20 MB) is downloaded on first run and cached in
`examples/walkthrough/data/`. See `examples/walkthrough/README.md` for the
full list.

---

## API reference

### `plothero.graph_objects.Figure`

Mirrors `plotly.graph_objects.Figure`:

| Method | Description |
|--------|-------------|
| `add_trace(trace, row=, col=)` / `add_traces([...])` | Add one or more `Scatter`/`Bar`/`Heatmap` traces (or plain dicts). `row`/`col` (1-indexed) target a specific subplot panel — see below. Returns `self`. |
| `add_scatter(row=, col=, **kwargs)` | Shortcut for `add_trace(Scatter(**kwargs), row=row, col=col)`. |
| `add_bar(row=, col=, **kwargs)` | Shortcut for `add_trace(Bar(**kwargs), row=row, col=col)`. |
| `add_heatmap(row=, col=, **kwargs)` | Shortcut for `add_trace(Heatmap(**kwargs), row=row, col=col)`. |
| `update_layout(**kwargs)` | Update layout — supports Plotly's magic-underscore kwargs (`xaxis_title=`, `line_color=`, ...). |
| `update_xaxes(row=, col=, **kwargs)` / `update_yaxes(row=, col=, **kwargs)` | Update axis properties — every axis by default, or one subplot panel via `row=`/`col=`. |
| `.data` / `.layout` | Read-only access to traces / layout. |
| `to_dict()` / `to_json()` | Plotly JSON spec. |
| `to_html(full_html, include_plotlyjs)` | HTML string (`"cdn"` / `"inline"` / `False`). |
| `write_html(path)` | Write the figure to an HTML file. |
| `show(*, detached=True)` | Serve the figure from a local HTTP server (`http://127.0.0.1:<port>`) and open it in the default browser. By default the server runs in a separate background process, so your script can exit while the figure stays interactive. Pass `detached=False` to serve from the current process instead. |
| `to_plotly_figure()` | Convert to a real `plotly.graph_objects.Figure` (requires `pip install plotly`). |

`Figure` also implements `_repr_html_`, so it renders inline in Jupyter.

`show()` hands the figure to a separate viewer process and returns
immediately, so a script that processes data and then plots it finishes
normally while the figure stays open, like a MATLAB figure. Zooming into a
decimated trace keeps re-fetching full-resolution data from that viewer
process on every pan/zoom. The viewer exits on its own shortly after you
close the last browser tab showing the figure. See
[Downsampling → dynamic re-downsampling on zoom](https://plothero.matteoserafino.com/guide/downsampling/#dynamic-re-downsampling-on-zoom-figureshow-only).

```python
import numpy as np
import plothero as ph

t = np.linspace(0, 60, 5_000_000)
y = np.sin(2 * np.pi * 1.2 * t) + 0.1 * np.random.randn(len(t))

fig = ph.Figure()
fig.add_trace(ph.Scatter(x=t, y=y, name="signal"))
fig.show()                  # returns right away; the script can exit
# fig.show(detached=False)  # serve from this process; blocks exit until Ctrl+C
```

### `plothero.graph_objects.Scatter`

Accepts the same keywords as `plotly.graph_objects.Scatter` — `x`, `y`,
`mode`, `name`, `line`, `marker`, `opacity`, `text`, `fill`,
`hovertemplate`, magic-underscore shortcuts (`line_color=`, `marker_size=`,
...). Anything not explicitly modeled is passed straight through to the
Plotly.js trace spec.

Two extra keywords control the Rust-accelerated downsampling (not part of
real Plotly, additive only):

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `downsample_threshold` | `int` | `5000` | Downsample when `len(x) > threshold`. |
| `downsample_method` | `DownsampleMethod` | `MINMAX` | `MINMAX` (preserves peaks/troughs — best for biomedical signals), `M4` (like `MINMAX` but also keeps each bucket's first/last sample, at up to 2x the point cost), `LTTB` (best visual fidelity for smooth signals), or `NONE`. |

```python
import plothero as ph

ph.Scatter(x=t, y=y, mode="lines", downsample_method=ph.DownsampleMethod.LTTB,
           downsample_threshold=2_000)
```

### `plothero.graph_objects.Bar` / `plothero.graph_objects.Heatmap`

Accept the same keywords as `plotly.graph_objects.Bar` /
`plotly.graph_objects.Heatmap` — `x`/`y`/`name`/`orientation`/`marker` for
`Bar`, `z`/`x`/`y`/`name`/`colorscale` for `Heatmap` — plus magic-underscore
shortcuts and passthrough of anything not explicitly modeled, same as
`Scatter`. No downsampling (categorical/gridded data, not dense signals).

```python
fig.add_bar(x=["a", "b", "c"], y=[10, 20, 15], marker_color="#377eb8")
fig.add_heatmap(z=[[1, 20, 30], [20, 1, 60], [30, 60, 1]], colorscale="Viridis")
```

### `plothero.subplots.make_subplots`

Mirrors `plotly.subplots.make_subplots` — builds a `Figure` pre-populated
with a grid of axes; `row`/`col` (1-indexed, row 1 = top) route traces and
axis updates to a specific panel:

```python
import plothero as ph

fig = ph.make_subplots(rows=1, cols=2, subplot_titles=("Raw", "Filtered"))
fig.add_trace(ph.Scatter(x=t, y=raw, name="raw"), row=1, col=1)
fig.add_trace(ph.Scatter(x=t, y=filtered, name="filtered"), row=1, col=2)
fig.update_xaxes(title="Time (s)", row=1, col=1)
fig.show()
```

Supports `shared_xaxes`/`shared_yaxes`, `horizontal_spacing`/`vertical_spacing`,
`column_widths`/`row_heights`, and `subplot_titles`, same as real Plotly.

### Standalone downsampling functions

```python
import numpy as np
import plothero as ph

t = np.linspace(0, 10, 1_000_000, dtype=np.float64)
y = np.sin(t)

t_small, y_small = ph.lttb_downsample(t, y, threshold=2_000)
t_small, y_small = ph.minmax_downsample(t, y, n_out=2_000)
t_small, y_small = ph.m4_downsample(t, y, n_out=2_000)
```

### Migrating from `plotly`

```diff
-import plotly.graph_objects as go
+import plothero.graph_objects as go
```

The `go` alias keeps existing Plotly code unchanged. For new code, prefer
`import plothero as ph`, which exposes the same objects (`ph.Figure`,
`ph.Scatter`, `ph.make_subplots`, ...).

Trace/layout construction, `add_trace`, `update_layout`, `to_html`, `show`,
`make_subplots`, and Jupyter rendering all behave the same way. `Scatter`,
`Bar`, and `Heatmap` are implemented so far (`Scatter` covers line/marker
plots and time series — datetime `x` "just works"). Multi-trace figures with
`plot_bgcolor`, `legend`, `margin`, custom `hovertemplate`, etc. are
supported via passthrough kwargs.

---

## Architecture

```
plothero/
├── src/lib.rs              Rust: lttb_downsample, minmax_downsample, m4_downsample (PyO3 + numpy)
├── Cargo.toml               Rust package (pyo3 = "0.21", numpy = "0.21")
├── pyproject.toml           Build: maturin >= 1.4
└── plothero/
    ├── __init__.py          Re-exports the public API
    ├── graph_objects.py     Plotly-compatible Figure / Scatter / Bar / Heatmap / Layout
    ├── subplots.py          Plotly-compatible make_subplots (multi-panel figures)
    └── downsample.py        Rust dispatch + pure-Python fallback + DownsampleMethod
```

The Rust module is compiled as `plothero._core` and used transparently by
`Scatter.downsample()`. If the compiled extension is absent, the
pure-Python fallback in `downsample.py` is used automatically — same
results, slower on large arrays. Check which backend is active with:

```python
import plothero as ph
print(ph.rust_available())
```

---

## Development

Everything below assumes you've cloned the repo and are working from its root.

### 1. Set up a virtual environment

```bash
python3 -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
```

### 2. Install the Rust toolchain (one-time)

```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
rustc --version   # sanity check
```

### 3. Install dev dependencies and build the extension

```bash
pip install -e ".[dev]"     # maturin, pytest, pandas, plotly
maturin develop              # debug build, fast to compile, slower at runtime
# or: maturin develop --release   # optimized build, use this for benchmarking
```

`maturin develop` compiles `src/lib.rs` and installs the resulting extension
as `plothero._core` directly into your active virtual environment — no
`pip install` round-trip needed. Confirm it worked:

```bash
python -c "import plothero as ph; print(ph.rust_available())"  # True
```

If you skip steps 2–3, `plothero` still imports and works correctly — it
silently uses the pure-Python fallback in `downsample.py` instead. That's
fine for working on `graph_objects.py`, but you'll want the Rust extension
built when touching `src/lib.rs` or benchmarking large signals.

### 4. Rebuild after editing Rust code

Re-run `maturin develop` (or `--release`) any time you change `src/lib.rs` —
Python code changes under `plothero/` take effect immediately, no rebuild
needed.

### 5. Run the tests

```bash
pytest              # run the full suite
pytest -v            # verbose, one line per test
pytest tests/test_downsample.py   # just the downsampling algorithms
pytest -k datetime   # only tests matching "datetime"
```

The test suite (`tests/`) covers both layers:

- `tests/test_downsample.py` — LTTB, Min/Max, and M4 downsampling correctness
  (shape preservation, peak/trough retention, edge cases). These tests run
  against whichever backend is active (Rust if built, pure-Python
  otherwise), so run them both before and after `maturin develop` if you
  change `src/lib.rs`.
- `tests/test_graph_objects.py` — the Plotly-compatible API surface:
  `Scatter`/`Bar`/`Heatmap`/`Layout`/`Figure` construction, magic-underscore
  expansion, datetime handling, HTML/JSON output.
- `tests/test_subplots.py` — `make_subplots` grid/domain math and its
  integration with `Figure.add_trace`/`update_xaxes`/`update_yaxes`.

### 6. Releasing

Publishing a GitHub release whose tag is `v` plus the version in
`Cargo.toml` builds and tests the wheels, publishes them to PyPI, and
attaches them to the release. See
[Releasing](https://plothero.matteoserafino.com/development/#7-releasing) in the docs for
the full steps and the one-time PyPI setup.

---

## Roadmap

- More trace types (`Box`, `Pie`, `Histogram`) beyond `Scatter`, `Bar`, `Heatmap`
- Desktop GUI rendering target (Qt/GTK), alongside the current browser/Jupyter target

