Last active
January 31, 2026 16:42
-
-
Save hotzeplotz/630d9688e462610e2a31a8286f5afec6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # /// script | |
| # dependencies = [ | |
| # "shapely>=2.0.0", | |
| # ] | |
| # /// | |
| """ | |
| Convert Marxan planning units grid export to GeoJSON. | |
| Usage: | |
| uv run convert_planning_units_to_geojson.py planning-units-grid output.geojson | |
| License: | |
| GNU GPL v3 | |
| Author: | |
| Andrea Rota <a@mey.vn>, with Claude Sonnet 4.5 | |
| """ | |
| import json | |
| import sys | |
| from pathlib import Path | |
| from shapely import wkb | |
| from shapely.geometry import mapping | |
| def convert_to_geojson(input_file: str, output_file: str): | |
| """Convert planning units grid file (puid, ewkt) to GeoJSON.""" | |
| features = [] | |
| with open(input_file, 'r') as f: | |
| for line_num, line in enumerate(f, 1): | |
| try: | |
| # Parse line: puid,[byte,array,...] | |
| puid_str, geom_bytes_str = line.strip().split(',', 1) | |
| puid = int(puid_str) | |
| # Parse JSON array of bytes | |
| geom_bytes_array = json.loads(geom_bytes_str) | |
| # Convert to bytes | |
| ewkb_bytes = bytes(geom_bytes_array) | |
| # Parse EWKB to Shapely geometry | |
| geom = wkb.loads(ewkb_bytes) | |
| # Create GeoJSON feature | |
| feature = { | |
| 'type': 'Feature', | |
| 'properties': {'puid': puid}, | |
| 'geometry': mapping(geom) | |
| } | |
| features.append(feature) | |
| except Exception as e: | |
| print(f"Warning: Error processing line {line_num}: {e}", file=sys.stderr) | |
| continue | |
| # Write GeoJSON FeatureCollection | |
| geojson = { | |
| 'type': 'FeatureCollection', | |
| 'features': features | |
| } | |
| with open(output_file, 'w') as f: | |
| json.dump(geojson, f) | |
| print(f"Converted {len(features)} planning units to {output_file}") | |
| if __name__ == '__main__': | |
| if len(sys.argv) != 3: | |
| print(__doc__) | |
| sys.exit(1) | |
| input_file, output_file = sys.argv[1], sys.argv[2] | |
| convert_to_geojson(input_file, output_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment