pyautark 0.1.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyautark/__init__.py +98 -0
- pyautark/_cli.py +64 -0
- pyautark/_serialise.py +64 -0
- pyautark/data.py +376 -0
- pyautark/display.py +287 -0
- pyautark/encodings.py +100 -0
- pyautark/links.py +19 -0
- pyautark/selections.py +25 -0
- pyautark/spec.py +214 -0
- pyautark/static/autark-widget.js +47907 -0
- pyautark/static/duckdb-browser-eh.worker.js +14 -0
- pyautark/static/duckdb-browser-mvp.worker.js +14 -0
- pyautark/static/duckdb-eh.wasm +4 -0
- pyautark/static/duckdb-mvp.wasm +4 -0
- pyautark/transforms.py +281 -0
- pyautark/views.py +421 -0
- pyautark/widget.py +104 -0
- pyautark-0.1.0a1.dist-info/METADATA +269 -0
- pyautark-0.1.0a1.dist-info/RECORD +20 -0
- pyautark-0.1.0a1.dist-info/WHEEL +4 -0
pyautark/__init__.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Python builders for Autark declarative specifications."""
|
|
2
|
+
|
|
3
|
+
from ._cli import cli
|
|
4
|
+
from .data import CSV, OSM, GeoJSON, GeoTIFF, JSON, latlng, wkt
|
|
5
|
+
from .display import open_window, to_embedded_html
|
|
6
|
+
from .encodings import Encoding, Field, Scale, Value, field, value
|
|
7
|
+
from .widget import create_widget
|
|
8
|
+
from .links import Link
|
|
9
|
+
from .selections import Selection, interval, multi, point
|
|
10
|
+
from .spec import AutarkSpec, Metadata, Spec
|
|
11
|
+
from .transforms import (
|
|
12
|
+
Aggregation,
|
|
13
|
+
Compute,
|
|
14
|
+
Heatmap,
|
|
15
|
+
HeatmapGrid,
|
|
16
|
+
Near,
|
|
17
|
+
SpatialJoin,
|
|
18
|
+
avg,
|
|
19
|
+
collect,
|
|
20
|
+
count,
|
|
21
|
+
maximum,
|
|
22
|
+
max,
|
|
23
|
+
minimum,
|
|
24
|
+
min,
|
|
25
|
+
sum,
|
|
26
|
+
total,
|
|
27
|
+
weighted,
|
|
28
|
+
)
|
|
29
|
+
from .views import (
|
|
30
|
+
Barchart,
|
|
31
|
+
Camera,
|
|
32
|
+
EventSeries,
|
|
33
|
+
Heatmatrix,
|
|
34
|
+
Histogram,
|
|
35
|
+
Layer,
|
|
36
|
+
Layout,
|
|
37
|
+
Map,
|
|
38
|
+
ParallelCoordinates,
|
|
39
|
+
Scatterplot,
|
|
40
|
+
Table,
|
|
41
|
+
Timeseries,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"Barchart",
|
|
46
|
+
"EventSeries",
|
|
47
|
+
"Heatmatrix",
|
|
48
|
+
"ParallelCoordinates",
|
|
49
|
+
"Timeseries",
|
|
50
|
+
"Aggregation",
|
|
51
|
+
"AutarkSpec",
|
|
52
|
+
"CSV",
|
|
53
|
+
"Camera",
|
|
54
|
+
"Compute",
|
|
55
|
+
"Encoding",
|
|
56
|
+
"Field",
|
|
57
|
+
"GeoJSON",
|
|
58
|
+
"GeoTIFF",
|
|
59
|
+
"Heatmap",
|
|
60
|
+
"HeatmapGrid",
|
|
61
|
+
"Histogram",
|
|
62
|
+
"JSON",
|
|
63
|
+
"Layer",
|
|
64
|
+
"Layout",
|
|
65
|
+
"Link",
|
|
66
|
+
"Map",
|
|
67
|
+
"Metadata",
|
|
68
|
+
"Near",
|
|
69
|
+
"OSM",
|
|
70
|
+
"Scale",
|
|
71
|
+
"Scatterplot",
|
|
72
|
+
"Selection",
|
|
73
|
+
"Spec",
|
|
74
|
+
"SpatialJoin",
|
|
75
|
+
"Table",
|
|
76
|
+
"Value",
|
|
77
|
+
"avg",
|
|
78
|
+
"cli",
|
|
79
|
+
"collect",
|
|
80
|
+
"count",
|
|
81
|
+
"create_widget",
|
|
82
|
+
"field",
|
|
83
|
+
"interval",
|
|
84
|
+
"latlng",
|
|
85
|
+
"maximum",
|
|
86
|
+
"max",
|
|
87
|
+
"minimum",
|
|
88
|
+
"min",
|
|
89
|
+
"multi",
|
|
90
|
+
"open_window",
|
|
91
|
+
"point",
|
|
92
|
+
"sum",
|
|
93
|
+
"to_embedded_html",
|
|
94
|
+
"total",
|
|
95
|
+
"value",
|
|
96
|
+
"weighted",
|
|
97
|
+
"wkt",
|
|
98
|
+
]
|
pyautark/_cli.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import TYPE_CHECKING, Sequence
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from .spec import AutarkSpec
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def cli(
|
|
13
|
+
spec: "AutarkSpec",
|
|
14
|
+
*,
|
|
15
|
+
argv: Sequence[str] | None = None,
|
|
16
|
+
description: str | None = None,
|
|
17
|
+
) -> None:
|
|
18
|
+
"""Dispatch a small CLI for a built spec.
|
|
19
|
+
|
|
20
|
+
Without flags, opens the spec in a native window (requires the ``desktop``
|
|
21
|
+
extra). Action flags suppress the window and perform the requested action.
|
|
22
|
+
|
|
23
|
+
Flags:
|
|
24
|
+
``--output PATH`` Write the spec as JSON.
|
|
25
|
+
``--html PATH`` Write a standalone HTML file (embedded runtime by default).
|
|
26
|
+
``--validate`` Validate against the bundled JSON schema.
|
|
27
|
+
``--json`` Print the spec as JSON to stdout.
|
|
28
|
+
``--height H`` Override the window/HTML height (default ``760px``).
|
|
29
|
+
``--schema PATH`` Override the schema path used by ``--validate``.
|
|
30
|
+
|
|
31
|
+
@example
|
|
32
|
+
if __name__ == "__main__":
|
|
33
|
+
ak.cli(spec)
|
|
34
|
+
"""
|
|
35
|
+
parser = argparse.ArgumentParser(description=description)
|
|
36
|
+
parser.add_argument("--output", type=Path, help="Write the spec as JSON to this path.")
|
|
37
|
+
parser.add_argument("--html", type=Path, help="Write a standalone HTML file to this path.")
|
|
38
|
+
parser.add_argument("--validate", action="store_true", help="Validate the spec against the JSON schema.")
|
|
39
|
+
parser.add_argument("--json", action="store_true", help="Print the spec as JSON to stdout.")
|
|
40
|
+
parser.add_argument("--height", default="760px", help="Window/HTML height (default: 760px).")
|
|
41
|
+
parser.add_argument("--schema", type=Path, help="Override the schema path for --validate.")
|
|
42
|
+
args = parser.parse_args(argv)
|
|
43
|
+
|
|
44
|
+
if args.validate:
|
|
45
|
+
try:
|
|
46
|
+
spec.validate(args.schema)
|
|
47
|
+
except Exception as exc:
|
|
48
|
+
print(f"Validation failed: {exc}", file=sys.stderr)
|
|
49
|
+
sys.exit(1)
|
|
50
|
+
print("Validation passed.")
|
|
51
|
+
|
|
52
|
+
if args.output:
|
|
53
|
+
spec.save_json(args.output)
|
|
54
|
+
print(f"JSON spec saved to: {args.output}")
|
|
55
|
+
|
|
56
|
+
if args.html:
|
|
57
|
+
spec.save_html(args.html, height=args.height)
|
|
58
|
+
print(f"HTML saved to: {args.html}")
|
|
59
|
+
|
|
60
|
+
if args.json:
|
|
61
|
+
print(spec.to_json())
|
|
62
|
+
|
|
63
|
+
if not (args.validate or args.output or args.html or args.json):
|
|
64
|
+
spec.window(height=args.height)
|
pyautark/_serialise.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import fields, is_dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Mapping
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Serializable:
|
|
9
|
+
"""Mixin for objects that serialize into an Autark JSON spec fragment."""
|
|
10
|
+
|
|
11
|
+
def to_dict(self) -> dict[str, Any]:
|
|
12
|
+
plain = to_plain(self)
|
|
13
|
+
assert isinstance(plain, dict)
|
|
14
|
+
return plain
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def to_plain(value: Any) -> Any:
|
|
18
|
+
if isinstance(value, Serializable) and type(value).to_dict is not Serializable.to_dict:
|
|
19
|
+
return value.to_dict()
|
|
20
|
+
if is_dataclass(value) and not isinstance(value, type):
|
|
21
|
+
out: dict[str, Any] = {}
|
|
22
|
+
for item in fields(value):
|
|
23
|
+
key = item.metadata.get("json", item.name)
|
|
24
|
+
raw = getattr(value, item.name)
|
|
25
|
+
if raw is None:
|
|
26
|
+
continue
|
|
27
|
+
plain = to_plain(raw)
|
|
28
|
+
if plain == {} or plain == []:
|
|
29
|
+
continue
|
|
30
|
+
out[key] = plain
|
|
31
|
+
return out
|
|
32
|
+
if isinstance(value, Serializable):
|
|
33
|
+
return value.to_dict()
|
|
34
|
+
if isinstance(value, Mapping):
|
|
35
|
+
mapped: dict[str, Any] = {}
|
|
36
|
+
for key, item in value.items():
|
|
37
|
+
if item is None:
|
|
38
|
+
continue
|
|
39
|
+
plain = to_plain(item)
|
|
40
|
+
if plain == {} or plain == []:
|
|
41
|
+
continue
|
|
42
|
+
mapped[str(key)] = plain
|
|
43
|
+
return mapped
|
|
44
|
+
if isinstance(value, (list, tuple)):
|
|
45
|
+
return [to_plain(item) for item in value if item is not None]
|
|
46
|
+
if isinstance(value, Path):
|
|
47
|
+
return str(value)
|
|
48
|
+
return value
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def ref_name(value: Any) -> str:
|
|
52
|
+
if isinstance(value, str):
|
|
53
|
+
return value
|
|
54
|
+
name = getattr(value, "name", None)
|
|
55
|
+
if isinstance(name, str):
|
|
56
|
+
return name
|
|
57
|
+
raise TypeError(f"Expected a string name or object with a name, got {type(value).__name__}")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def exactly_one(label: str, first: Any, second: Any, first_name: str, second_name: str) -> None:
|
|
61
|
+
has_first = first is not None
|
|
62
|
+
has_second = second is not None
|
|
63
|
+
if has_first == has_second:
|
|
64
|
+
raise ValueError(f"{label} requires exactly one of {first_name} or {second_name}")
|
pyautark/data.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any, Literal, Mapping, Sequence
|
|
6
|
+
|
|
7
|
+
from ._serialise import Serializable, exactly_one
|
|
8
|
+
|
|
9
|
+
OsmLayer = Literal["buildings", "roads", "parks", "water", "surface"]
|
|
10
|
+
|
|
11
|
+
LayerType = Literal[
|
|
12
|
+
"surface",
|
|
13
|
+
"parks",
|
|
14
|
+
"water",
|
|
15
|
+
"roads",
|
|
16
|
+
"buildings",
|
|
17
|
+
"points",
|
|
18
|
+
"polygons",
|
|
19
|
+
"polylines",
|
|
20
|
+
"raster",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
_GEOMETRY_LAYER_TYPES: dict[str, LayerType] = {
|
|
24
|
+
"Polygon": "polygons",
|
|
25
|
+
"MultiPolygon": "polygons",
|
|
26
|
+
"LineString": "polylines",
|
|
27
|
+
"MultiLineString": "polylines",
|
|
28
|
+
"Point": "points",
|
|
29
|
+
"MultiPoint": "points",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _jsonable(value: Any) -> Any:
|
|
34
|
+
"""Convert pandas/numpy-laden structures into plain JSON-safe values.
|
|
35
|
+
|
|
36
|
+
numpy scalars are unwrapped, non-finite floats become null (JSON.parse in
|
|
37
|
+
browsers rejects NaN/Infinity), tuples become lists, and unknown objects
|
|
38
|
+
fall back to their string representation.
|
|
39
|
+
"""
|
|
40
|
+
if value is None or isinstance(value, (str, bool, int)):
|
|
41
|
+
return value
|
|
42
|
+
if isinstance(value, float):
|
|
43
|
+
return value if math.isfinite(value) else None
|
|
44
|
+
if isinstance(value, Mapping):
|
|
45
|
+
return {str(key): _jsonable(item) for key, item in value.items()}
|
|
46
|
+
if isinstance(value, (list, tuple)):
|
|
47
|
+
return [_jsonable(item) for item in value]
|
|
48
|
+
item_getter = getattr(value, "item", None)
|
|
49
|
+
if callable(item_getter):
|
|
50
|
+
# numpy scalar (e.g. int64/float64/bool_)
|
|
51
|
+
return _jsonable(item_getter())
|
|
52
|
+
return str(value)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _infer_layer_type(features: Sequence[Mapping[str, Any]]) -> LayerType:
|
|
56
|
+
geometry_types = {
|
|
57
|
+
str((feature.get("geometry") or {}).get("type")) for feature in features
|
|
58
|
+
}
|
|
59
|
+
layer_types = {_GEOMETRY_LAYER_TYPES.get(g) for g in geometry_types}
|
|
60
|
+
layer_types.discard(None)
|
|
61
|
+
if len(layer_types) != 1:
|
|
62
|
+
raise ValueError(
|
|
63
|
+
f"Cannot infer layer_type from geometry types {sorted(geometry_types)}; "
|
|
64
|
+
"pass layer_type explicitly"
|
|
65
|
+
)
|
|
66
|
+
(layer_type,) = layer_types
|
|
67
|
+
assert layer_type is not None
|
|
68
|
+
return layer_type
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class LatLngGeometry(Serializable):
|
|
73
|
+
"""Point geometry from two columns, written as UrbanSpec's ``geometryColumns``."""
|
|
74
|
+
|
|
75
|
+
latitude: str
|
|
76
|
+
longitude: str
|
|
77
|
+
coordinate_format: str | None = None
|
|
78
|
+
|
|
79
|
+
def to_dict(self) -> dict[str, Any]:
|
|
80
|
+
out: dict[str, Any] = {"latColumnName": self.latitude, "longColumnName": self.longitude}
|
|
81
|
+
if self.coordinate_format is not None:
|
|
82
|
+
out["coordinateFormat"] = self.coordinate_format
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class WktGeometry(Serializable):
|
|
88
|
+
"""Geometry from one WKT column, written as UrbanSpec's ``geometryColumns``."""
|
|
89
|
+
|
|
90
|
+
column: str
|
|
91
|
+
coordinate_format: str | None = None
|
|
92
|
+
|
|
93
|
+
def to_dict(self) -> dict[str, Any]:
|
|
94
|
+
out: dict[str, Any] = {"wktColumnName": self.column}
|
|
95
|
+
if self.coordinate_format is not None:
|
|
96
|
+
out["coordinateFormat"] = self.coordinate_format
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def latlng(latitude: str, longitude: str, coordinate_format: str | None = None) -> LatLngGeometry:
|
|
101
|
+
return LatLngGeometry(latitude=latitude, longitude=longitude, coordinate_format=coordinate_format)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def wkt(column: str, coordinate_format: str | None = None) -> WktGeometry:
|
|
105
|
+
return WktGeometry(column=column, coordinate_format=coordinate_format)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True)
|
|
109
|
+
class OSM(Serializable):
|
|
110
|
+
"""OpenStreetMap layers for a named area or a box, from Overpass or from a PBF extract.
|
|
111
|
+
|
|
112
|
+
Give ``area`` (a place name, geocoded) or ``bbox`` (``(west, south, east, north)`` in degrees). The tables are
|
|
113
|
+
named ``<name>_<layer>``.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
name: str
|
|
117
|
+
layers: list[OsmLayer]
|
|
118
|
+
area: str | None = None
|
|
119
|
+
bbox: tuple[float, float, float, float] | None = None
|
|
120
|
+
geocode_area: str | None = None
|
|
121
|
+
areas: list[str] | None = None
|
|
122
|
+
source: Literal["overpass", "pbf"] | None = None
|
|
123
|
+
pbf_file_url: str | None = None
|
|
124
|
+
workspace: str | None = None
|
|
125
|
+
|
|
126
|
+
def __post_init__(self) -> None:
|
|
127
|
+
if not self.layers:
|
|
128
|
+
raise ValueError("OSM requires at least one layer")
|
|
129
|
+
if self.bbox is not None:
|
|
130
|
+
if self.area is not None or self.geocode_area is not None or self.areas is not None:
|
|
131
|
+
raise ValueError("OSM takes either bbox or area, not both")
|
|
132
|
+
if len(self.bbox) != 4:
|
|
133
|
+
raise ValueError("OSM bbox must be (west, south, east, north)")
|
|
134
|
+
elif self.area is None:
|
|
135
|
+
raise ValueError("OSM requires area or bbox")
|
|
136
|
+
if self.areas is not None and not self.areas:
|
|
137
|
+
raise ValueError("OSM areas must not be empty")
|
|
138
|
+
if self.source == "pbf" and not self.pbf_file_url:
|
|
139
|
+
raise ValueError("OSM with source='pbf' requires pbf_file_url")
|
|
140
|
+
|
|
141
|
+
def layer_source(self, layer: OsmLayer) -> str:
|
|
142
|
+
return f"{self.name}_{layer}"
|
|
143
|
+
|
|
144
|
+
def to_dict(self) -> dict[str, Any]:
|
|
145
|
+
if self.bbox is not None:
|
|
146
|
+
query_area: dict[str, Any] = {"bbox": list(self.bbox)}
|
|
147
|
+
else:
|
|
148
|
+
query_area = {
|
|
149
|
+
"geocodeArea": self.geocode_area or self.area,
|
|
150
|
+
"areas": list(self.areas) if self.areas is not None else [self.area],
|
|
151
|
+
}
|
|
152
|
+
out: dict[str, Any] = {
|
|
153
|
+
"type": "osm",
|
|
154
|
+
"outputTableName": self.name,
|
|
155
|
+
"queryArea": query_area,
|
|
156
|
+
"autoLoadLayers": {"layers": list(self.layers)},
|
|
157
|
+
}
|
|
158
|
+
if self.pbf_file_url:
|
|
159
|
+
out["pbfFileUrl"] = self.pbf_file_url
|
|
160
|
+
if self.workspace is not None:
|
|
161
|
+
out["workspace"] = self.workspace
|
|
162
|
+
return out
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@dataclass(frozen=True)
|
|
166
|
+
class GeoJSON(Serializable):
|
|
167
|
+
name: str
|
|
168
|
+
url: str | None = None
|
|
169
|
+
values: dict[str, Any] | None = None
|
|
170
|
+
layer_type: LayerType | None = None
|
|
171
|
+
coordinate_format: str | None = None
|
|
172
|
+
workspace: str | None = None
|
|
173
|
+
|
|
174
|
+
def __post_init__(self) -> None:
|
|
175
|
+
exactly_one("GeoJSON", self.url, self.values, "url", "values")
|
|
176
|
+
|
|
177
|
+
def to_dict(self) -> dict[str, Any]:
|
|
178
|
+
out: dict[str, Any] = {"type": "geojson", "outputTableName": self.name}
|
|
179
|
+
if self.url is not None:
|
|
180
|
+
out["geojsonFileUrl"] = self.url
|
|
181
|
+
if self.values is not None:
|
|
182
|
+
out["geojsonObject"] = self.values
|
|
183
|
+
if self.layer_type is not None:
|
|
184
|
+
out["layerType"] = self.layer_type
|
|
185
|
+
if self.coordinate_format is not None:
|
|
186
|
+
out["coordinateFormat"] = self.coordinate_format
|
|
187
|
+
if self.workspace is not None:
|
|
188
|
+
out["workspace"] = self.workspace
|
|
189
|
+
return out
|
|
190
|
+
|
|
191
|
+
@classmethod
|
|
192
|
+
def from_geopandas(
|
|
193
|
+
cls,
|
|
194
|
+
name: str,
|
|
195
|
+
gdf: Any,
|
|
196
|
+
*,
|
|
197
|
+
layer_type: LayerType | None = None,
|
|
198
|
+
coordinate_format: str | None = None,
|
|
199
|
+
workspace: str | None = None,
|
|
200
|
+
) -> "GeoJSON":
|
|
201
|
+
"""Create an inline GeoJSON source from a GeoDataFrame.
|
|
202
|
+
|
|
203
|
+
The GeoDataFrame is reprojected to EPSG:4326 when its CRS is known and
|
|
204
|
+
differs, and serialized through ``__geo_interface__``, so this works
|
|
205
|
+
with geopandas without autark depending on it.
|
|
206
|
+
|
|
207
|
+
@param name: Data source name referenced by views/transforms.
|
|
208
|
+
@param gdf: A geopandas GeoDataFrame (or anything exposing
|
|
209
|
+
``__geo_interface__``; ``crs``/``to_crs`` are used when present).
|
|
210
|
+
@param layer_type: Layer type; inferred from the geometries if omitted.
|
|
211
|
+
@param coordinate_format: Coordinate format; defaults to EPSG:4326 when
|
|
212
|
+
the CRS is known (after reprojection).
|
|
213
|
+
@returns A GeoJSON data source with inline values.
|
|
214
|
+
@example
|
|
215
|
+
gdf = geopandas.read_file("neighborhoods.shp")
|
|
216
|
+
source = ak.GeoJSON.from_geopandas("neighborhoods", gdf)
|
|
217
|
+
"""
|
|
218
|
+
crs = getattr(gdf, "crs", None)
|
|
219
|
+
if crs is not None:
|
|
220
|
+
epsg = crs.to_epsg() if hasattr(crs, "to_epsg") else None
|
|
221
|
+
if epsg != 4326 and callable(getattr(gdf, "to_crs", None)):
|
|
222
|
+
gdf = gdf.to_crs(epsg=4326)
|
|
223
|
+
if coordinate_format is None:
|
|
224
|
+
coordinate_format = "EPSG:4326"
|
|
225
|
+
|
|
226
|
+
geo = getattr(gdf, "__geo_interface__", None)
|
|
227
|
+
if not isinstance(geo, Mapping):
|
|
228
|
+
raise TypeError(
|
|
229
|
+
f"from_geopandas expects an object with __geo_interface__, got {type(gdf).__name__}"
|
|
230
|
+
)
|
|
231
|
+
collection = _jsonable(geo)
|
|
232
|
+
features = collection.get("features", [])
|
|
233
|
+
if layer_type is None:
|
|
234
|
+
layer_type = _infer_layer_type(features)
|
|
235
|
+
return cls(
|
|
236
|
+
name,
|
|
237
|
+
values={"type": "FeatureCollection", "features": features},
|
|
238
|
+
layer_type=layer_type,
|
|
239
|
+
coordinate_format=coordinate_format,
|
|
240
|
+
workspace=workspace,
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
@classmethod
|
|
244
|
+
def from_dataframe(
|
|
245
|
+
cls,
|
|
246
|
+
name: str,
|
|
247
|
+
df: Any,
|
|
248
|
+
*,
|
|
249
|
+
latitude: str,
|
|
250
|
+
longitude: str,
|
|
251
|
+
properties: Sequence[str] | None = None,
|
|
252
|
+
coordinate_format: str = "EPSG:4326",
|
|
253
|
+
workspace: str | None = None,
|
|
254
|
+
) -> "GeoJSON":
|
|
255
|
+
"""Create an inline points source from a DataFrame with lat/lng columns.
|
|
256
|
+
|
|
257
|
+
Rows are converted into GeoJSON Point features (the runtime supports
|
|
258
|
+
inline GeoJSON, unlike inline CSV). Works with pandas without autark
|
|
259
|
+
depending on it.
|
|
260
|
+
|
|
261
|
+
@param name: Data source name referenced by views/transforms.
|
|
262
|
+
@param df: A pandas DataFrame (or anything with ``to_dict("records")``).
|
|
263
|
+
@param latitude: Column holding latitudes.
|
|
264
|
+
@param longitude: Column holding longitudes.
|
|
265
|
+
@param properties: Columns to keep as feature properties; defaults to
|
|
266
|
+
every column except the coordinate columns.
|
|
267
|
+
@param coordinate_format: Coordinate format of the lat/lng values.
|
|
268
|
+
@returns A GeoJSON data source with inline point features.
|
|
269
|
+
@example
|
|
270
|
+
df = pandas.read_csv("trees.csv")
|
|
271
|
+
source = ak.GeoJSON.from_dataframe("trees", df, latitude="lat", longitude="lon")
|
|
272
|
+
"""
|
|
273
|
+
to_dict = getattr(df, "to_dict", None)
|
|
274
|
+
if not callable(to_dict):
|
|
275
|
+
raise TypeError(
|
|
276
|
+
f"from_dataframe expects an object with to_dict('records'), got {type(df).__name__}"
|
|
277
|
+
)
|
|
278
|
+
records = to_dict("records")
|
|
279
|
+
|
|
280
|
+
features = []
|
|
281
|
+
for row in records:
|
|
282
|
+
if latitude not in row or longitude not in row:
|
|
283
|
+
raise KeyError(
|
|
284
|
+
f"Row is missing coordinate column {latitude!r} or {longitude!r}"
|
|
285
|
+
)
|
|
286
|
+
keys = properties if properties is not None else [k for k in row if k not in (latitude, longitude)]
|
|
287
|
+
features.append(
|
|
288
|
+
{
|
|
289
|
+
"type": "Feature",
|
|
290
|
+
"properties": {str(key): _jsonable(row[key]) for key in keys},
|
|
291
|
+
"geometry": {
|
|
292
|
+
"type": "Point",
|
|
293
|
+
"coordinates": [_jsonable(row[longitude]), _jsonable(row[latitude])],
|
|
294
|
+
},
|
|
295
|
+
}
|
|
296
|
+
)
|
|
297
|
+
return cls(
|
|
298
|
+
name,
|
|
299
|
+
values={"type": "FeatureCollection", "features": features},
|
|
300
|
+
layer_type="points",
|
|
301
|
+
coordinate_format=coordinate_format,
|
|
302
|
+
workspace=workspace,
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
@dataclass(frozen=True)
|
|
307
|
+
class CSV(Serializable):
|
|
308
|
+
name: str
|
|
309
|
+
url: str | None = None
|
|
310
|
+
values: list[list[Any]] | None = None
|
|
311
|
+
delimiter: str | None = None
|
|
312
|
+
geometry: LatLngGeometry | WktGeometry | None = None
|
|
313
|
+
workspace: str | None = None
|
|
314
|
+
|
|
315
|
+
def __post_init__(self) -> None:
|
|
316
|
+
exactly_one("CSV", self.url, self.values, "url", "values")
|
|
317
|
+
|
|
318
|
+
def to_dict(self) -> dict[str, Any]:
|
|
319
|
+
out: dict[str, Any] = {"type": "csv", "outputTableName": self.name}
|
|
320
|
+
if self.url is not None:
|
|
321
|
+
out["csvFileUrl"] = self.url
|
|
322
|
+
if self.values is not None:
|
|
323
|
+
out["csvObject"] = self.values
|
|
324
|
+
if self.delimiter is not None:
|
|
325
|
+
out["delimiter"] = self.delimiter
|
|
326
|
+
if self.geometry is not None:
|
|
327
|
+
out["geometryColumns"] = self.geometry.to_dict()
|
|
328
|
+
if self.workspace is not None:
|
|
329
|
+
out["workspace"] = self.workspace
|
|
330
|
+
return out
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
@dataclass(frozen=True)
|
|
334
|
+
class JSON(Serializable):
|
|
335
|
+
name: str
|
|
336
|
+
url: str | None = None
|
|
337
|
+
values: list[Any] | dict[str, Any] | None = None
|
|
338
|
+
geometry: LatLngGeometry | WktGeometry | None = None
|
|
339
|
+
workspace: str | None = None
|
|
340
|
+
|
|
341
|
+
def __post_init__(self) -> None:
|
|
342
|
+
exactly_one("JSON", self.url, self.values, "url", "values")
|
|
343
|
+
|
|
344
|
+
def to_dict(self) -> dict[str, Any]:
|
|
345
|
+
out: dict[str, Any] = {"type": "json", "outputTableName": self.name}
|
|
346
|
+
if self.url is not None:
|
|
347
|
+
out["jsonFileUrl"] = self.url
|
|
348
|
+
if self.values is not None:
|
|
349
|
+
out["jsonObject"] = self.values if isinstance(self.values, list) else [self.values]
|
|
350
|
+
if self.geometry is not None:
|
|
351
|
+
out["geometryColumns"] = self.geometry.to_dict()
|
|
352
|
+
if self.workspace is not None:
|
|
353
|
+
out["workspace"] = self.workspace
|
|
354
|
+
return out
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
@dataclass(frozen=True)
|
|
358
|
+
class GeoTIFF(Serializable):
|
|
359
|
+
name: str
|
|
360
|
+
url: str
|
|
361
|
+
coordinate_format: str | None = None
|
|
362
|
+
max_pixels: int | None = None
|
|
363
|
+
resample_method: Literal["nearest", "bilinear"] | None = None
|
|
364
|
+
workspace: str | None = None
|
|
365
|
+
|
|
366
|
+
def to_dict(self) -> dict[str, Any]:
|
|
367
|
+
out: dict[str, Any] = {"type": "geotiff", "outputTableName": self.name, "geotiffFileUrl": self.url}
|
|
368
|
+
if self.coordinate_format is not None:
|
|
369
|
+
out["coordinateFormat"] = self.coordinate_format
|
|
370
|
+
if self.max_pixels is not None:
|
|
371
|
+
out["maxRasterCells"] = self.max_pixels
|
|
372
|
+
if self.resample_method is not None:
|
|
373
|
+
out["resampleMethod"] = self.resample_method
|
|
374
|
+
if self.workspace is not None:
|
|
375
|
+
out["workspace"] = self.workspace
|
|
376
|
+
return out
|