| Conditions | 3 |
| Total Lines | 57 |
| Code Lines | 30 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | """ |
||
| 132 | def voronoi( |
||
| 133 | points: gpd.GeoDataFrame, |
||
| 134 | boundary: gpd.GeoDataFrame, |
||
| 135 | ): |
||
| 136 | """Building a Voronoi Field from points and a boundary.""" |
||
| 137 | logger.info("Building Voronoi Field.") |
||
| 138 | |||
| 139 | sources = DATASET_CFG["original_data"]["sources"] |
||
| 140 | relevant_columns = sources["BAST"]["relevant_columns"] |
||
| 141 | truck_col = relevant_columns[0] |
||
| 142 | srid = DATASET_CFG["tables"]["srid"] |
||
| 143 | |||
| 144 | # convert the boundary geometry into a union of the polygon |
||
| 145 | # convert the Geopandas GeoSeries of Point objects to NumPy array of coordinates. |
||
| 146 | boundary_shape = cascaded_union(boundary.geometry) |
||
| 147 | coords = points_to_coords(points.geometry) |
||
| 148 | |||
| 149 | # calculate Voronoi regions |
||
| 150 | poly_shapes, pts, unassigned_pts = voronoi_regions_from_coords( |
||
| 151 | coords, boundary_shape, return_unassigned_points=True |
||
| 152 | ) |
||
| 153 | |||
| 154 | multipoly_shapes = {} |
||
| 155 | |||
| 156 | for key, shape in poly_shapes.items(): |
||
| 157 | if isinstance(shape, Polygon): |
||
| 158 | shape = wkt.loads(str(shape)) |
||
| 159 | shape = MultiPolygon([shape]) |
||
| 160 | |||
| 161 | multipoly_shapes[key] = [shape] |
||
| 162 | |||
| 163 | poly_gdf = gpd.GeoDataFrame.from_dict( |
||
| 164 | multipoly_shapes, orient="index", columns=["geometry"] |
||
| 165 | ) |
||
| 166 | |||
| 167 | # match points to old index |
||
| 168 | # FIXME: This seems overcomplicated |
||
| 169 | poly_gdf.index = [v[0] for v in pts.values()] |
||
| 170 | |||
| 171 | poly_gdf = poly_gdf.sort_index() |
||
| 172 | |||
| 173 | unmatched = [points.index[idx] for idx in unassigned_pts] |
||
| 174 | |||
| 175 | points_matched = points.drop(unmatched) |
||
| 176 | |||
| 177 | poly_gdf.index = points_matched.index |
||
| 178 | |||
| 179 | # match truck traffic to new polys |
||
| 180 | poly_gdf = poly_gdf.assign( |
||
| 181 | truck_traffic=points.loc[poly_gdf.index][truck_col] |
||
| 182 | ) |
||
| 183 | |||
| 184 | poly_gdf = poly_gdf.set_crs(epsg=srid, inplace=True) |
||
| 185 | |||
| 186 | logger.info("Done.") |
||
| 187 | |||
| 188 | return poly_gdf |
||
| 189 |