Skip to content

Commit

Permalink
reformat for black
Browse files Browse the repository at this point in the history
reformat for black
  • Loading branch information
dieuska committed Jun 26, 2024
1 parent 930f1c7 commit d5d489b
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 54 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ The figure below shows:
* Loading thematic data ((Multi-)Polygons): as a dict, geojson or Web Feature Service (WFS-url)
* Loading reference data ((Multi-)Polygons): as a dict, geojson or Web Feature Service (WFS-url)
* (Flanders-specific) Download reference data from GRB-Flanders
* Align thematic boundaries to reference boundaries
* Align thematic boundaries to reference boundaries with a specific relevant distance (process_dict_thematic)
* Align thematic boundaries to reference boundaries with a series of specified relevant distances (process_series)
* Make use of a 'predictor'-function that aligns thematic boundaries to reference boundaries for 'predicted' interesting relevant distances (predictor)
* Calculating a descriptive formulation of a thematic boundary based on a reference layer

### Possible application fields
Expand Down
81 changes: 50 additions & 31 deletions brdr/aligner.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@

from brdr.constants import BUFFER_MULTIPLICATION_FACTOR
from brdr.constants import CORR_DISTANCE
from brdr.constants import DOWNLOAD_LIMIT
from brdr.constants import DEFAULT_CRS
from brdr.constants import DOWNLOAD_LIMIT
from brdr.constants import MAX_REFERENCE_BUFFER
from brdr.constants import MITRE_LIMIT
from brdr.constants import QUAD_SEGMENTS
Expand Down Expand Up @@ -130,7 +130,7 @@ def __init__(
)
self.dict_relevant_difference = None # dictionary to save relevant_differences

self.dict_predicted = None #dictionary with the 'predicted' results
self.dict_predicted = None # dictionary with the 'predicted' results
# Coordinate reference system
# thematic geometries and reference geometries are assumed to be in the same CRS
# before loading into the Aligner. No CRS-transformation will be performed.
Expand Down Expand Up @@ -540,7 +540,9 @@ def predictor(
for zs in zero_streaks:
dict_predicted[key][zs[0]] = dict_series[zs[0]]

dict_predicted[key] = filter_resulting_series_by_key(dict_predicted[key],key)
dict_predicted[key] = filter_resulting_series_by_key(
dict_predicted[key], key
)
self.dict_predicted = dict_predicted
return dict_predicted, diffs

Expand Down Expand Up @@ -674,7 +676,7 @@ def get_last_version_date(self, geometry, grb_type=GRBType.ADP):
"https://geo.api.vlaanderen.be/GRB/ogc/features/collections/"
+ grb_type
+ "/items?"
"limit=" + str(limit) + "&crs=" + crs + "&bbox-crs=" + crs +"&bbox=" + bbox
"limit=" + str(limit) + "&crs=" + crs + "&bbox-crs=" + crs + "&bbox=" + bbox
)
update_dates = []
collection = get_collection(actual_url, limit)
Expand All @@ -689,29 +691,39 @@ def get_results_as_dict(self):
"""
get a dict-tuple of the results
"""
return (self.dict_result, self.dict_result_diff, self.dict_result_diff_plus, self.dict_result_diff_min,
self.dict_relevant_intersection, self.dict_relevant_difference)

return (
self.dict_result,
self.dict_result_diff,
self.dict_result_diff_plus,
self.dict_result_diff_min,
self.dict_relevant_intersection,
self.dict_relevant_difference,
)

def get_results_as_geojson(self,formula=False):
def get_results_as_geojson(self, formula=False):
"""
get a geojson-tuple of the results
"""
prop_dictionary ={}
prop_dictionary = {}
p = {}
for key in self.dict_result.keys():
formula = self.get_formula(self.dict_result[key])
p[key] = {'formula': formula}
p[key] = {"formula": formula}
prop_dictionary[self.relevant_distance] = p
return geojson_tuple_from_series({self.relevant_distance: self.get_results_as_dict()}, self.CRS,
self.name_thematic_id, prop_dict=prop_dictionary)
return geojson_tuple_from_series(
{self.relevant_distance: self.get_results_as_dict()},
self.CRS,
self.name_thematic_id,
prop_dict=prop_dictionary,
)

def get_predictions_as_dict(self):
"""
get a dict with results for the predicted relevant distances
"""
return self.dict_predicted
def get_predictions_as_geojson(self,formula=False):

def get_predictions_as_geojson(self, formula=False):
"""
get a geojson-tuple of the resulting geometries, based on the 'predicted' relevant distances.
Optional: The discriptive formula is added as an attribute to the result"""
Expand All @@ -721,41 +733,48 @@ def get_predictions_as_geojson(self,formula=False):
formula = self.get_formula(self.dict_predicted[key][rel_dist][0][key])
p = None
if formula:
p = {key:{'formula': formula}}
p = {key: {"formula": formula}}
prop_dictionary[key] = dict.fromkeys(self.dict_predicted[key].keys(), p)
return geojson_tuple_from_dict_theme(self.dict_predicted, crs=self.CRS, name_id=self.name_thematic_id,
prop_dict=prop_dictionary)
return geojson_tuple_from_dict_theme(
self.dict_predicted,
crs=self.CRS,
name_id=self.name_thematic_id,
prop_dict=prop_dictionary,
)

def get_reference_as_geojson(self):
"""
get a geojson of the reference polygons
"""
return geojson_from_dict(self.dict_reference, self.CRS, self.name_reference_id,geom_attributes=False)
return geojson_from_dict(
self.dict_reference, self.CRS, self.name_reference_id, geom_attributes=False
)

def export_results(self, path, formula=True):
"""
Exports analysis results as GeoJSON files.
This function exports 6 GeoJSON files containing the analysis results to the specified `path`.
Exports analysis results as GeoJSON files.
Args:
path (str): The path to the directory where the GeoJSON files will be saved.
This function exports 6 GeoJSON files containing the analysis results to the specified `path`.
Details of exported files:
- result.geojson: Contains the original thematic data from `self.dict_result`.
- result_diff.geojson: Contains the difference between the original and predicted data from `self.dict_result_diff`.
- result_diff_plus.geojson: Contains results for areas that are added (increased area).
- result_diff_min.geojson: Contains results for areas that are removed (decreased area).
- result_relevant_intersection.geojson: Contains the areas with relevant intersection that has to be included in the result.
- result_relevant_difference.geojson: Contains the areas with relevant difference that has to be excluded from the result.
"""
Args:
path (str): The path to the directory where the GeoJSON files will be saved.
Details of exported files:
- result.geojson: Contains the original thematic data from `self.dict_result`.
- result_diff.geojson: Contains the difference between the original and predicted data from `self.dict_result_diff`.
- result_diff_plus.geojson: Contains results for areas that are added (increased area).
- result_diff_min.geojson: Contains results for areas that are removed (decreased area).
- result_relevant_intersection.geojson: Contains the areas with relevant intersection that has to be included in the result.
- result_relevant_difference.geojson: Contains the areas with relevant difference that has to be excluded from the result.
"""
fcs = self.get_results_as_geojson(formula=formula)
resultnames = [
"result.geojson",
"result_diff.geojson",
"result_diff_plus.geojson",
"result_diff_min.geojson",
"result_relevant_intersection.geojson",
"result_relevant_difference.geojson"
"result_relevant_difference.geojson",
]
for count, fc in enumerate(fcs):
write_geojson(os.path.join(path, resultnames[count]), fcs[count])
Expand Down
2 changes: 1 addition & 1 deletion brdr/enums.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from enum import IntEnum
from enum import Enum
from enum import IntEnum


class OpenbaarDomeinStrategy(IntEnum):
Expand Down
2 changes: 1 addition & 1 deletion brdr/geometry_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
from shapely import buffer
from shapely import difference
from shapely import intersection
from shapely import is_empty
from shapely import symmetric_difference
from shapely import union
from shapely import is_empty
from shapely.geometry.base import BaseGeometry

from brdr.constants import MITRE_LIMIT
Expand Down
69 changes: 49 additions & 20 deletions brdr/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import logging
import os.path

import numpy as np
import requests
import logging
from geojson import Feature
from geojson import FeatureCollection
from geojson import dump
Expand All @@ -10,47 +11,72 @@
from shapely import node
from shapely import polygonize
from shapely.geometry import shape
from brdr.constants import MULTI_SINGLE_ID_SEPARATOR

import brdr.constants
from brdr.constants import MULTI_SINGLE_ID_SEPARATOR


def geojson_tuple_from_tuple(my_tuple, crs, name_id, prop_dict=None, geom_attributes=True):
def geojson_tuple_from_tuple(
my_tuple, crs, name_id, prop_dict=None, geom_attributes=True
):
"""
get a geojson-tuple (6 geojsons) for a tuple of results (results, result_diff, ...)
"""
feature_collections = []
for count, tup in enumerate(my_tuple):
feature_collections.append(geojson_from_dict(tup, crs, name_id, prop_dict=prop_dict,geom_attributes=geom_attributes))
feature_collections.append(
geojson_from_dict(
tup, crs, name_id, prop_dict=prop_dict, geom_attributes=geom_attributes
)
)
return tuple(feature_collections)
def geojson_tuple_from_series(dict_series, crs, name_id, prop_dict=None, geom_attributes=True):


def geojson_tuple_from_series(
dict_series, crs, name_id, prop_dict=None, geom_attributes=True
):
"""
get a geojson-tuple (6 geojsons) for a dictionary of relevant distances() keys and resulting tuples (values)
"""
features = [[], [], [], [], [], []]
for rel_dist in dict_series.keys():
my_tuple = dict_series [rel_dist]
prop_rel_dist = {'relevant_distance': rel_dist}
my_tuple = dict_series[rel_dist]
prop_rel_dist = {"relevant_distance": rel_dist}
prop_dictionary = dict.fromkeys(my_tuple[0].keys(), prop_rel_dist)
if prop_dict is not None and rel_dist in prop_dict:
prop_dictionary = prop_dictionary | prop_dict[rel_dist]
fcs = geojson_tuple_from_tuple(my_tuple, crs, name_id, prop_dict=prop_dictionary, geom_attributes=geom_attributes)
fcs = geojson_tuple_from_tuple(
my_tuple,
crs,
name_id,
prop_dict=prop_dictionary,
geom_attributes=geom_attributes,
)
for count, ft in enumerate(features):
ft.extend(fcs[count].features)
crs_geojson = {"type": "name", "properties": {"name": crs}}
feature_collections =[]
feature_collections = []
for ft in features:
feature_collections.append (FeatureCollection(ft, crs=crs_geojson))
feature_collections.append(FeatureCollection(ft, crs=crs_geojson))
return tuple(feature_collections)
def geojson_tuple_from_dict_theme(dict_theme, crs, name_id, prop_dict=None, geom_attributes=True):


def geojson_tuple_from_dict_theme(
dict_theme, crs, name_id, prop_dict=None, geom_attributes=True
):
"""
get a geojson-tuple (6 geojsons) for a dictionary of theme_ids (keys) and dictionary of relevant distance-results (values)
"""
features = [[], [], [], [], [], []]
for key in dict_theme.keys():
if prop_dict is not None and key in prop_dict:
prop_dictionary = prop_dict[key]
fcs = geojson_tuple_from_series(dict_theme[key], crs, name_id, prop_dict=prop_dictionary, geom_attributes=geom_attributes)
fcs = geojson_tuple_from_series(
dict_theme[key],
crs,
name_id,
prop_dict=prop_dictionary,
geom_attributes=geom_attributes,
)
for count, ft in enumerate(features):
ft.extend(fcs[count].features)
crs_geojson = {"type": "name", "properties": {"name": crs}}
Expand Down Expand Up @@ -99,9 +125,9 @@ def geojson_from_dict(dictionary, crs, name_id, prop_dict=None, geom_attributes=
shape_index = perimeter / area
else:
shape_index = -1
properties['area'] = area
properties['perimeter'] = perimeter
properties['shape_index'] = shape_index
properties["area"] = area
properties["perimeter"] = perimeter
properties["shape_index"] = shape_index
features.append(
Feature(
geometry=geom,
Expand All @@ -112,12 +138,14 @@ def geojson_from_dict(dictionary, crs, name_id, prop_dict=None, geom_attributes=
geojson = FeatureCollection(features, crs=crs_geojson)
return geojson

def write_geojson(path_to_file,geojson):

def write_geojson(path_to_file, geojson):
parent = os.path.dirname(path_to_file)
os.makedirs(parent, exist_ok=True)
with open(path_to_file, "w") as f:
dump(geojson, f)


def multipolygons_to_singles(dict_geoms):
"""
Converts a dictionary of shapely-geometries to a dictionary containing only single polygons.
Expand Down Expand Up @@ -198,7 +226,7 @@ def polygonize_reference_data(dict_ref):
return dict_ref


def get_oe_dict_by_ids(objectids, oetype='aanduidingsobjecten'):
def get_oe_dict_by_ids(objectids, oetype="aanduidingsobjecten"):
"""
Fetches thematic data for a list of objectIDs from the Inventaris Onroerend Erfgoed API.
Expand All @@ -223,12 +251,12 @@ def get_oe_dict_by_ids(objectids, oetype='aanduidingsobjecten'):
for a in objectids:
url = base_url + str(a)
response = requests.get(url, headers=headers).json()
if 'id' in response.keys():
if "id" in response.keys():
key = str(response["id"])
geom = shape(response["locatie"]["contour"])
dict_thematic[key] = geom
else:
logging.warning('object id ' + str(a) +' not available in ' + oetype)
logging.warning("object id " + str(a) + " not available in " + oetype)
return dict_thematic


Expand Down Expand Up @@ -273,6 +301,7 @@ def get_oe_geojson_by_bbox(bbox, limit=1000):
collection = collection | feature_collection
return collection


def get_breakpoints_zerostreak(x, y):
"""
Determine the extremes and zero_streaks of a graph based on the derivative, and return:
Expand Down

0 comments on commit d5d489b

Please sign in to comment.