Skip to content

pyautark pyautark PyPI version

pyautark is the declarative Python API for Autark. You describe data sources, spatial joins, GPU computations, maps, and linked plots with Python objects; pyautark serializes them into an UrbanSpec — the exact JSON specification of autk-grammar — and runs it in a bundled browser runtime inside Jupyter, a standalone HTML file, or a native desktop window.

Key capabilities:

  • One specification, one engine: every ak.Spec serializes to a standard UrbanSpec (spec.to_dict()), runs with AutkGrammar in WebGPU + DuckDB-WASM, and validates against the packaged JSON Schema (spec.validate()).
  • Load urban data from files, URLs, or Python objects: OpenStreetMap (Overpass API or .osm.pbf), GeoJSON, CSV, JSON (lat/lon or WKT), GeoTIFF rasters, plus direct pandas (GeoJSON.from_dataframe()) and GeoPandas (GeoJSON.from_geopandas()) helpers.
  • Spatial operations and GPU compute: SpatialJoin, Heatmap, Compute.gpgpu (WGSL per-feature shaders), and Compute.render (sky exposure and visibility passes).
  • Interactive 2D/3D maps and linked plots: Map, Layer, Camera, Basemap, categorical/sequential/diverging scales, and 8 plot builders (Histogram, Barchart, Scatterplot, Table, ParallelCoordinates, Heatmatrix, EventSeries, Timeseries) wired with Link.
  • Two-way Python reactivity in Jupyter: observe brushed plot selections (w.selections), double-click map picks (w.pick / w.picked), dynamic feature hiding (w.hidden), and hover tooltips (w.feature_tooltip) directly from Python without rebuilding the map.

The source code is on GitHub. If you are new to pyautark, you can also work through the pyautark tutorial notebooks (formats, data, maps, plots, and GPU computing).

Package installation ​

pyautark is published on PyPI. It requires Python 3.10 or later and has no required dependencies:

bash
pip install pyautark
pip install "pyautark[widget]"      # Jupyter widget (anywidget, zero local server)
pip install "pyautark[validation]"  # Validate specs against the UrbanSpec JSON Schema
pip install "pyautark[desktop]"     # Native desktop window (pywebview)

Quick start ​

Build a spec with Python objects, then display it in a Jupyter notebook (spec.widget()), open a native window (spec.window()), or export standalone HTML (spec.save_html()):

python
import pyautark as ak

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

brush = ak.interval("area_brush")

spec = ak.Spec(
    metadata=ak.Metadata(title="Neighborhood area and perimeter"),
    data=[neighborhoods],
    views=[
        ak.Map(
            camera=ak.Camera(zoom=12),
            layers=[
                ak.Layer(neighborhoods, id="neighborhoods_layer").style(
                    color="#3498db",
                    opacity=0.7,
                )
            ],
        ),
        ak.Scatterplot(
            source=neighborhoods,
            x="shape_area",
            y="shape_leng",
            title="Neighborhood area and perimeter",
            width=600,
            selection=brush,
        ),
    ],
    links=[ak.Link(brush, target="neighborhoods_layer")],
    layout=ak.Layout(type="horizontal"),
)

spec.to_dict()              # plain UrbanSpec dict
spec.save_json("spec.json") # write UrbanSpec JSON
spec.save_html("map.html")  # standalone HTML (no Python runtime required)
spec.validate()             # check against packaged UrbanSpec schema
spec.widget()               # display in Jupyter / JupyterLab / VS Code / Colab
# spec.window(height="760px")  # open in a native desktop window

WebGPU required

Maps and GPU computations run on WebGPU inside the browser or webview runtime. We recommend recent versions of Chrome, Edge, or Safari. See the browser support table in the Introduction.

Spec structure ​

An ak.Spec mirrors the sections of an UrbanSpec. Each Python builder serializes into the corresponding UrbanSpec section:

ArgumentPurpose
metadataOptional ak.Metadata(title, description) used by HTML/window hosts (not serialized into the UrbanSpec).
dataList of data sources (GeoJSON, CSV, JSON, OSM, GeoTIFF).
transformsList of spatial operations (SpatialJoin, Heatmap) and compute passes (Compute.gpgpu, Compute.render).
viewsList of maps (Map) and plots (Histogram, Barchart, Scatterplot, Table, ParallelCoordinates, Heatmatrix, EventSeries, Timeseries).
linksList of ak.Link(selection, target) connecting plot selections to map layers.
layoutak.Layout(type, columns, gap) arranging maps and plots ('vertical', 'horizontal', or 'grid').

Exporting and running specs ​

Method / HelperPurpose
spec.to_dict()Returns the serialized UrbanSpec as a JSON-compatible Python dict.
spec.save_json(path)Writes the UrbanSpec JSON to disk.
spec.save_html(path, height=...)Writes a self-contained HTML file with the bundled runtime — no Python server needed.
spec.validate()Validates against the packaged urbanspec.json schema (requires pyautark[validation]).
spec.widget()Renders an anywidget instance in Jupyter, JupyterLab, VS Code, or Colab (requires pyautark[widget]).
spec.window(height=...)Opens the bundled runtime in a native window via pywebview (requires pyautark[desktop]).
ak.cli(spec)Turns a Python script into a CLI supporting --output, --html, --validate, --json, --height, or default window display.

Data ​

Every data source takes a table name (serialized as outputTableName) and an optional workspace name. Pass a URL (url=...) or inline Python objects (values=...).

BuilderMain arguments
ak.GeoJSONname, url or values, coordinate_format (default 'EPSG:4326'), layer_type, workspace. Also GeoJSON.from_dataframe(name, df, latitude=..., longitude=...) and GeoJSON.from_geopandas(name, gdf).
ak.CSVname, url or values, delimiter, geometry=ak.latlng(lat, lon) or ak.wkt(column), workspace.
ak.JSONname, url or values, optional geometry=ak.latlng(...) or ak.wkt(...), workspace.
ak.OSMname, geocode_area + area (or bbox=(west, south, east, north)), layers (surface, parks, water, roads, buildings), optional source="pbf" + pbf_file_url, workspace.
ak.GeoTIFFname, url, coordinate_format, max_raster_cells, resample_method, workspace.

DataFrames and GeoPandas ​

Pass in-memory pandas DataFrames or GeoPandas GeoDataFrames directly without writing intermediate files:

python
import geopandas as gpd
import pyautark as ak

gdf = gpd.read_file("neighborhoods.geojson")
neighborhoods = ak.GeoJSON.from_geopandas("neighborhoods", gdf)  # reprojects to EPSG:4326

trees = ak.GeoJSON.from_dataframe("trees", df, latitude="lat", longitude="lon")

See the GeoPandas Workflow and OSMnx Workflow examples.

Workspaces ​

The first source loaded into a workspace sets its extent; later sources in the same workspace are clipped to that extent. Pass workspace="name" on sources, transforms, maps, and plots to keep independent areas separate — each workspace can even reuse the same table names.

See the OSM Layers in Two Workspaces example.

Joins and heatmaps ​

Spatial operations are passed in transforms=[...] and serialize into the UrbanSpec's data array:

  • ak.SpatialJoin(root, join, near=..., group_by=[...]) aggregates features from join onto root using helpers like ak.count(), ak.sum(col), ak.avg(col), ak.min(col), ak.max(col), and ak.collect(col). Joined fields are stored under properties.sjoin.<fn>.<table>.
  • ak.Heatmap(source, output, grid=(rows, cols), near=..., group_by=[...]) aggregates point or polygon features into a grid raster table.
python
join = ak.SpatialJoin(
    root=neighborhoods,
    join=trees,
    group_by=[ak.count(), ak.collect("species")],
)

See the Spatial Join and Heatmap over GeoJSON examples.

Compute ​

GPU compute passes are passed in transforms=[...] and serialize into the UrbanSpec's compute array:

  • ak.Compute.gpgpu(source, variable_mapping, wgsl_body, result_field, output=...) runs a WGSL function per feature. Without output, it writes properties.compute.<result_field> onto source; with output, it creates a new table.
  • ak.Compute.render(output, layers, viewpoints, aggregation, tile_size=...) runs GPU render-based analyses such as sky exposure or visibility and writes a new table.
python
sky = ak.Compute.render(
    output="sky",
    layers=[{"id": "buildings", "source": "mnt_buildings", "type": "buildings"}],
    viewpoints={"source": "mnt_roads", "sampling": {"directions": 8}},
    aggregation={"type": "classes", "includeBackground": True},
    tile_size=64,
)

See the GPU Compute and Sky Exposure examples.

Map ​

Create a map view with ak.Map(layers=[...], camera=..., basemap=..., name=..., workspace=...).

Each layer is built with ak.Layer(source, id=..., visible=...) and configured fluently:

  • .style(color, opacity, strokeColor, width, size) — fixed color, opacity, polygon outline, line width, or point radius in meters (pointSize).
  • .encode(color=ak.field(path, scale)) — data-driven colormap using ak.Scale(type, scheme, domain, colors, domain_strategy, percentiles).
  • visible=False — loads the layer hidden (isSkip: true) so the user can toggle it in the map's layer list.

Basemaps ​

ak.Map(basemap=...) draws web map tiles beneath the layers using a preset string ("esriWorldImagery", "openStreetMap", "osmLight", "osmDark") or ak.Basemap(source, opacity=..., title=...):

python
ak.Map(
    basemap=ak.Basemap("esriWorldImagery", opacity=0.85, title="Satellite"),
    camera=ak.Camera(zoom=13, pitch=45),
    layers=[ak.Layer(neighborhoods).style(opacity=0.5)],
)

See the Map Layers examples.

Plot ​

pyautark provides dedicated plot builders that serialize to UrbanSpec plot entries:

BuilderMark / Use
ak.BarchartCategorical bar chart
ak.HistogramBinned 1D distribution (bins=...)
ak.Scatterplot2D quantitative scatter plot
ak.TableSortable attribute table
ak.ParallelCoordinatesMulti-axis comparison
ak.Heatmatrix2D binned / categorical matrix
ak.EventSeriesTemporal event binning over collected timestamps
ak.TimeseriesTime-series line chart

Attach an interactive selection (ak.interval("name") for brushing or ak.selection("name") for clicking) to a plot and connect it to a map layer with ak.Link:

python
brush = ak.interval("tree_count_brush")
hist = ak.Histogram(source=neighborhoods, x="sjoin.count.trees", bins=20, selection=brush)
link = ak.Link(brush, target="neighborhoods_layer", action="highlight")

Give plots in a 'grid' layout an explicit width and height in pixels so they fit their cells cleanly.

See the Plots examples.

Jupyter widgets and Python reactivity ​

spec.widget() renders using the runtime bundled inside the Python package — no local server is required, and it works in Jupyter, JupyterLab, VS Code, and Google Colab.

Observing plot brushes ​

Selections sync back to Python on w.selections, keyed by the selection's name:

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

Map picking, hiding, and tooltips from Python ​

Three reactive widget traits update a drawn map immediately without rebuilding it:

  • w.pick and w.picked: set w.pick = ["neighborhoods"] to enable double-click picking; w.picked reports {table: [position, ...]} in row order and can also be set from Python to highlight specific features.
  • w.hidden: set w.hidden = {"neighborhoods": [2, 5]} to hide features immediately while preserving pan and zoom. Hidden features are neither drawn nor picked.
  • w.feature_tooltip: set w.feature_tooltip = {"neighborhoods": {"ntaname": "Neighborhood", "area_label": "Area"}} to show a hover tooltip with formatted text values from inline GeoJSON properties.

Python to UrbanSpec reference ​

Each Python builder maps directly to standard UrbanSpec fields:

PythonUrbanSpec
source nameoutputTableName
source url / valuesgeojsonFileUrl / geojsonObject (csvFileUrl, csvObject, ...)
ak.latlng(lat, lon), ak.wkt(col)geometryColumns
OSM(area=..., layers=[...]), OSM(bbox=...)queryArea, autoLoadLayers
Layer(source, id=..., visible=False)dataRef, title, isSkip
.encode(color=ak.field(path, scale))getFnv, isColorMap, colorMapInterpolator, ...
ak.Scale(type="categorical", domain=[...], colors=[...])colorMapDomain, colorMapCategoryColors
.style(color, opacity, strokeColor, width, size)color, opacity, stroke, width, pointSize
SpatialJoin(root, join)data entry with type: 'join'
Heatmap(source, output)data entry with type: 'heatmap'
Compute.gpgpu(...) / Compute.render(...)compute entries (wgslFunction / type: 'render')
Map(name=..., basemap=..., camera=...)map with id, basemap, camera
Link(selection, target)links[]

Fields without a corresponding UrbanSpec property emit a Python UserWarning and are omitted. Browse the pyautark Examples to see full scripts for each workflow.

Released under the MIT License.