65 lines
2.1 KiB
Python
65 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
|
|
"""Create a database from a given GeoJSON input file. Intended to quickly create test databases.
|
|
|
|
It assumes the same structure as the one generated by `geojson.io <https://geojson.io/>`__ and only supports
|
|
polygons.
|
|
"""
|
|
|
|
# Standard library
|
|
from argparse import ArgumentDefaultsHelpFormatter
|
|
from argparse import ArgumentParser
|
|
import json
|
|
|
|
# Database and charts
|
|
from typing import Generator
|
|
|
|
# Math
|
|
from numpy import array
|
|
|
|
# Pyrate
|
|
from pyrate.common.charts import SpatialiteDatabase
|
|
from pyrate.plan.geometry import LocationType
|
|
from pyrate.plan.geometry import PolarPolygon
|
|
|
|
|
|
def read_geojson(
|
|
path: str, location_type: LocationType = LocationType.LAND
|
|
) -> Generator[PolarPolygon, None, None]:
|
|
"""Reads a GeoJSON file (only supports specific constructs, see module documentation).
|
|
|
|
Args:
|
|
path: the input file
|
|
location_type: the location type of all chart objects
|
|
"""
|
|
|
|
with open(path, "r", encoding="utf-8") as input_file:
|
|
json_data = json.load(input_file)
|
|
|
|
assert json_data["type"] == "FeatureCollection"
|
|
for feature in json_data["features"]:
|
|
assert feature["type"] == "Feature"
|
|
geometry = feature["geometry"]
|
|
assert geometry["type"] == "Polygon"
|
|
coordinates = geometry["coordinates"]
|
|
assert len(coordinates) == 1, "the polygon may have exactly one exterior and zero interior rings"
|
|
exterior = coordinates[0]
|
|
yield PolarPolygon.from_numpy(array(exterior), location_type=location_type)
|
|
|
|
|
|
def _main() -> None:
|
|
"""The main function."""
|
|
parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter)
|
|
parser.add_argument(
|
|
"path_to_geojson", type=str, help='The input file, usually ends with ".json", UTF-8 encoding'
|
|
)
|
|
parser.add_argument("path_to_db", type=str, help='The output file, usually ends with ".sqlite"')
|
|
args = parser.parse_args()
|
|
|
|
with SpatialiteDatabase(args.path_to_db) as database:
|
|
database.write_geometries(read_geojson(args.path_to_geojson), update=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
_main()
|