Metadata-Version: 2.5
Name: pyautark
Version: 0.1.0a1
Summary: Declarative Python API for urban visual analytics (maps, plots, spatial joins) rendered with WebGPU and DuckDB-WASM
Project-URL: Homepage, https://github.com/urban-toolkit/pyautark
Project-URL: Repository, https://github.com/urban-toolkit/pyautark
Project-URL: Issues, https://github.com/urban-toolkit/pyautark/issues
Author: Urban Toolkit
License: MIT
Keywords: declarative,duckdb,gis,jupyter,maps,urban,visualization,webgpu
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Jupyter
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
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 :: GIS
Classifier: Topic :: Scientific/Engineering :: Visualization
Requires-Python: >=3.10
Provides-Extra: desktop
Requires-Dist: pywebview>=5.0; extra == 'desktop'
Provides-Extra: dev
Requires-Dist: anywidget>=0.9; extra == 'dev'
Requires-Dist: jsonschema>=4.0; extra == 'dev'
Requires-Dist: mypy>=1.8; extra == 'dev'
Requires-Dist: nbclient>=0.7; extra == 'dev'
Requires-Dist: nbformat>=5.0; extra == 'dev'
Requires-Dist: pywebview>=5.0; extra == 'dev'
Provides-Extra: test
Requires-Dist: jsonschema>=4.0; extra == 'test'
Provides-Extra: validation
Requires-Dist: jsonschema>=4.0; extra == 'validation'
Provides-Extra: widget
Requires-Dist: anywidget>=0.9; extra == 'widget'
Description-Content-Type: text/markdown

# Autark Python API

Declarative Python API for creating urban visual analytics views. You describe the data, the tables derived from it, the maps and the plots with Python objects. Each object writes its part of an **UrbanSpec**, the JSON specification of [autk-grammar](https://github.com/urban-toolkit/autk-grammar), and a bundled browser runtime runs that spec with the Autark modules.

## Quick Example

```python
import pyautark as ak

# Load GeoJSON data
neighborhoods = ak.GeoJSON(
    "neighborhoods",
    url="/data/neighborhoods.geojson",
    coordinate_format="EPSG:4326",
)

# Create a map with styled layers
spec = ak.Spec(
    metadata=ak.Metadata(title="Neighborhood Map"),
    data=[neighborhoods],
    views=[
        ak.Map(
            camera=ak.Camera(zoom=12),
            layers=[
                ak.Layer(neighborhoods)
                    .style(color="#3498db", opacity=0.7)
            ]
        )
    ]
)

# The UrbanSpec, as plain Python
spec.to_dict()

# Export
spec.save_json("spec.json")
spec.save_html("map.html")

# Validate against schema/urbanspec.json (requires pyautark[validation])
spec.validate()

# Display in Jupyter without any local server (requires pyautark[widget])
spec.widget()

# Open the same bundled runtime in a native window from a Python script
# (requires: pip install -e ".[desktop]")
spec.window(height="760px")
```

## Features

- **Declarative specs** - Python objects that serialize as an UrbanSpec, which the browser bundle runs as it is
- **Data sources** - `GeoJSON`, `CSV` and `JSON` (latitude/longitude or WKT geometry), `OSM` (a place or a `bbox`, from Overpass or a PBF extract) and `GeoTIFF`
- **Spatial operations** - `SpatialJoin` and `Heatmap`
- **Compute transforms** - `Compute.gpgpu` (a WGSL function per feature) and `Compute.render` (render-based analysis such as sky exposure)
- **Interactive visualizations** - `Map`; plots (`Histogram`, `Barchart`, `Scatterplot`, `Table`, `ParallelCoordinates`, `Heatmatrix`, `EventSeries`, `Timeseries`); and linked selections
- **Jupyter integration** - bundled anywidget rendering
- **Script window display** - Open the bundled runtime in a native window via pywebview
- **Selections back in Python** - observe `widget.selections` for brushes
- **pandas/GeoPandas input** - `GeoJSON.from_dataframe()` / `from_geopandas()`
- **Standalone HTML export** - No Python runtime required

## Installation

**Note:** Not yet published to PyPI. Install from source:

```bash
cd autark/python
pip install -e .
pip install -e ".[validation]"  # Optional: JSON Schema validation
pip install -e ".[widget]"      # Optional: zero-server Jupyter widget (anywidget)
```

Package builds use Hatch and `hatch-jupyter-builder` to run
`npm run build:widget` in `autk-runtime` and include
`autark/static/autark-widget.js` automatically.

### Displaying specs in Jupyter

`spec.widget()` renders with the runtime bundled inside the Python package. No local server needed; works in Jupyter, JupyterLab, VS Code, and Colab. DuckDB sidecar assets are packaged next to the widget bundle and used when the host exposes sibling files. Data sources must use absolute URLs or inline `values` (in JupyterLab started from a folder, `/files/<path>` URLs also work).

Plot selections sync back to the kernel, keyed by plot id (the name of the plot's selection):

```python
brush = ak.interval("latitude_brush")
w = spec.widget()
w  # display; brush the plot, then:
w.selections  # {'latitude_brush': [0, 2]}
w.observe(lambda change: print(change["new"]), names="selections")
```

DataFrames can be passed directly as inline data:

```python
trees = ak.GeoJSON.from_dataframe("trees", df, latitude="lat", longitude="lon")
neighborhoods = ak.GeoJSON.from_geopandas("neighborhoods", gdf)  # reprojects to EPSG:4326
```

A notebook kernel keeps the widget bundle it loaded. After rebuilding the bundle, restart the kernel and reload the page.

## Names and rules

Python keeps its own words, and each builder writes the UrbanSpec fields:

| Python | UrbanSpec |
|---|---|
| a source's `name` | `outputTableName` |
| a source's `url` / `values` | `geojsonFileUrl` / `geojsonObject` (`csvFileUrl`, `csvObject`, `jsonFileUrl`, ...) |
| `ak.latlng(lat, lon)`, `ak.wkt(col)` | `geometryColumns` |
| `OSM(area=..., layers=[...])`, `OSM(bbox=...)` | `queryArea`, `autoLoadLayers` |
| a layer's source (name or object) | `dataRef` |
| `Layer(id=...)` | `title` |
| `.encode(color=ak.field(path, scale))` | `getFnv`, `isColorMap`, `colorMapInterpolator`, ... |
| `.style(color, opacity, strokeColor, width, size)` | `color`, `opacity`, `stroke`, `width`, `pointSize` |
| `SpatialJoin(root, join)` | a `join` entry of `data`: `dataRef`, `joinDataRef` |
| `Heatmap(source, output)` | a `heatmap` entry of `data`: `joinDataRef`, `outputTableName` |
| `Compute.gpgpu(source, variable_mapping, wgsl_body, result_field)` | an entry of `compute`: `dataRef`, `attributes`, `wgslFunction`, `outputColumnName` |
| `Compute.render(output, ...)` | a `compute` entry with `type: 'render'` |
| `Map(name=...)`, `Camera` | `map` with `id`, `camera` |
| `Histogram`, `Barchart`, `Scatterplot`, `Table`, `ParallelCoordinates`, `Heatmatrix`, `EventSeries`, `Timeseries` | `plot` with `mark` `bar`, `scatter`, `table`, `parallel-coordinates`, `heatmatrix`, `linechart` and the matching `transform` |
| `Link(selection, target)` | `links[]`: the plot that owns the selection, the map and layer that draw `target` |

Rules worth knowing:

- **The first source sets the workspace.** Autark cuts every later source to the extent of the first one, so a table that lies outside it comes out empty. Put the source that covers the area of interest first.
- **Workspaces keep areas apart.** `workspace="name"` on a source, a join, a heatmap, a compute pass, a map or a plot puts it in a named workspace, with its own extent; the entries without one share the default workspace. Two areas that must not clip each other go in two workspaces, and each workspace may hold a table of the same name (see `examples/python/osm_layers_workspaces.py`).
- **A table is drawn from its geometry** (points, lines or polygons); a layer does not say. A collection that mixes types goes in as one source per type.
- **A plot with a selection takes the selection's name as its id**, which is also the key of `widget.selections`. A link points to a layer by its `id`, and an unnamed map gets `map1`, `map2`, ... when a link needs it.
- **Joins and heatmaps run before compute passes.** A `SpatialJoin` or `Heatmap` that reads a table a compute pass wrote is refused.
- **`Compute.gpgpu` without `output` adds its result to the source table** (`properties.compute.<name>`); with `output`, it makes a new table and leaves the source as it was. `Compute.render` always makes a new table.
- **Links highlight.** Other actions are refused.
- **Give plots in a grid a `width` and `height`** (pixels) so they fit their cells.
- **What the grammar has no field for is reported with a `UserWarning` and left out**, for example `strokeWidth`, or sizing or opacity driven by a field.
- `metadata` (title, ...) is for the page that shows the spec and is not serialized.

## Example styles

Examples come in two flavors. Both build the same `Spec`; they differ in what
the script does when run from the command line.

**Style A (default) — terse `spec.window()`.** The spec is built at module
scope and `spec.window()` opens a native window when the script is run. Best
for small didactic examples; the spec is also importable from a REPL or
notebook.

```python
import pyautark as ak

spec = ak.Spec(
    data=[ak.OSM("osm", geocode_area="New York", area="Financial District",
                 layers=["roads", "buildings"])],
    views=[ak.Map(layers=[ak.Layer("osm_roads"),
                          ak.Layer("osm_buildings")])],
)

if __name__ == "__main__":
    spec.window(height="760px")
```

**Style B — CLI flags via `ak.cli(spec)`.** Use this when the example should
also be runnable from CI to regenerate JSON, validate against the schema, or
emit standalone HTML without needing the `desktop` extra installed.

```python
import pyautark as ak

spec = ak.Spec(...)  # same builder

if __name__ == "__main__":
    ak.cli(spec)
```

Resulting CLI:

```bash
python ex.py                       # opens a window (same as Style A)
python ex.py --output spec.json    # write the UrbanSpec as JSON
python ex.py --html out.html       # write standalone HTML
python ex.py --validate            # validate against schema/urbanspec.json
python ex.py --json                # print JSON to stdout
python ex.py --height 800px        # override window/HTML height
```

Action flags suppress the window. `--validate` can be combined with `--output`
or `--html`.

## Documentation

- **[examples/](../examples/)** - Working examples
  - [simple_geojson_map.py](../examples/python/simple_geojson_map.py) - Basic map
  - [csv_points_map.py](../examples/python/csv_points_map.py) - CSV points + histogram
  - [spatial_join.py](../examples/python/spatial_join.py) - Spatial join workflow
  - [geopandas_workflow.py](../examples/python/geopandas_workflow.py) - GeoPandas workflow
  - [specs/](../examples/specs/) - the same kind of views as UrbanSpec JSON files
- The **pyautark tutorial** (https://github.com/ctsilva/pyautark-tutorial): six notebooks, from data formats to GPU computing
- The UrbanSpec itself: [autk-grammar](https://github.com/urban-toolkit/autk-grammar)

## Design

The Autark Python API follows the Vega-Lite/Altair pattern:

1. Python authors **structured specifications**
2. Specifications **serialize to an UrbanSpec** (JSON)
3. The browser bundle **runs the UrbanSpec with `AutkGrammar`** (autk-db, autk-compute, autk-map, autk-plot)
4. All rendering/compute happens in **WebGPU/DuckDB-WASM**

Benefits:
- Shareable as JSON or HTML
- Jupyter-friendly
- LLM/agent-friendly
- No Python runtime needed for visualization
- One specification and one engine: the UrbanSpec runs in any autk-grammar host

## Testing

```bash
# Run Python tests
python -m unittest discover -s tests

# Type check (pip install -e ".[dev]")
python -m mypy

# Validate examples
python ../examples/python/simple_geojson_map.py --validate
python ../examples/python/csv_points_map.py --validate
python ../examples/python/spatial_join.py --validate
```

## License

MIT License
