traybake 0.1.0__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.
- traybake/__init__.py +7 -0
- traybake/convert.py +408 -0
- traybake/grid.py +206 -0
- traybake/poly.py +464 -0
- traybake/stick.py +207 -0
- traybake-0.1.0.dist-info/METADATA +23 -0
- traybake-0.1.0.dist-info/RECORD +9 -0
- traybake-0.1.0.dist-info/WHEEL +4 -0
- traybake-0.1.0.dist-info/licenses/LICENSE +21 -0
traybake/__init__.py
ADDED
traybake/convert.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
"""Convert the data contained in a grid.
|
|
2
|
+
"""
|
|
3
|
+
# --- Imports ---
|
|
4
|
+
import warnings
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# --- Functions ---
|
|
10
|
+
def convert_df_to_2darray(
|
|
11
|
+
df: pd.DataFrame,
|
|
12
|
+
data_col: str,
|
|
13
|
+
*,
|
|
14
|
+
n_rows: float | int,
|
|
15
|
+
n_cols: float | int,
|
|
16
|
+
empty_value: any = None,
|
|
17
|
+
**kwargs
|
|
18
|
+
) -> np.ma.masked_array:
|
|
19
|
+
"""Convert dataframe of grid info to grid layout.
|
|
20
|
+
|
|
21
|
+
Create a new array to hold the grid data using the input numbers
|
|
22
|
+
of rows and columns and with the data type appropriate for the
|
|
23
|
+
data column in the dataframe. Fill the grid using the cell info
|
|
24
|
+
and data from the dataframe. Default value for empty cells depends
|
|
25
|
+
on data type. The resulting grid is a masked array to flag cells
|
|
26
|
+
that do not contain any shapes.
|
|
27
|
+
|
|
28
|
+
Input dataframe of grid info is output from
|
|
29
|
+
stick.stick_shapes_to_grid().
|
|
30
|
+
|
|
31
|
+
**kwargs allows for calling the function with a dictionary
|
|
32
|
+
that contains unnecessary keys,
|
|
33
|
+
e.g. transform_coords_to_grid(coords, **transform_dict).
|
|
34
|
+
The *identifer makes sure that cell properties are passed
|
|
35
|
+
as keywords and so their order doesn't matter.
|
|
36
|
+
|
|
37
|
+
Inputs
|
|
38
|
+
------
|
|
39
|
+
df - pd.DataFrame. One row per cell that contains a shape.
|
|
40
|
+
Columns include row and column index and the data
|
|
41
|
+
to be placed into the grid.
|
|
42
|
+
data_col - str. Column in df to place in the grid.
|
|
43
|
+
n_cols - float | int. Number of columns in the grid.
|
|
44
|
+
n_rows - float | int. Number of rows in the grid.
|
|
45
|
+
empty_value - any. Optional value for cells that contain no shapes.
|
|
46
|
+
|
|
47
|
+
Returns
|
|
48
|
+
-------
|
|
49
|
+
marr - np.ma.masked_array. data attribute holds the df[data_col]
|
|
50
|
+
values, and mask attribute flags whether cells contain any
|
|
51
|
+
shapes.
|
|
52
|
+
"""
|
|
53
|
+
d = df[data_col].dtype
|
|
54
|
+
if isinstance(d, pd.StringDtype):
|
|
55
|
+
d = object
|
|
56
|
+
elif isinstance(d, pd.Float64Dtype):
|
|
57
|
+
d = float
|
|
58
|
+
else:
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
if empty_value is None:
|
|
62
|
+
empty_value = _generate_empty_value(d)
|
|
63
|
+
else:
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
# Make a 2D array with all pixels, not just valid ones:
|
|
67
|
+
arr = np.full((n_rows, n_cols), empty_value, dtype=d)
|
|
68
|
+
# Update the values of valid pixels:
|
|
69
|
+
arr[df['cell_row'], df['cell_col']] = df[data_col].values
|
|
70
|
+
# Make mask to record invalid cells:
|
|
71
|
+
mask = np.full(arr.shape, 1, dtype=int)
|
|
72
|
+
mask[df['cell_row'], df['cell_col']] = 0
|
|
73
|
+
# Combine arr and mask into masked array:
|
|
74
|
+
marr = np.ma.masked_array(arr, mask=mask)
|
|
75
|
+
return marr
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def convert_grid_values(
|
|
79
|
+
arr_old: np.array | np.ma.masked_array,
|
|
80
|
+
dict_values: dict,
|
|
81
|
+
empty_value: any = None
|
|
82
|
+
) -> np.array | np.ma.masked_array:
|
|
83
|
+
"""Convert grid data using a dictionary.
|
|
84
|
+
|
|
85
|
+
This function checks that the data in the input
|
|
86
|
+
dictionary has consistent data types.
|
|
87
|
+
|
|
88
|
+
TO DO - check if all options in arr_values are present
|
|
89
|
+
in keys of dict_colours.
|
|
90
|
+
|
|
91
|
+
Inputs
|
|
92
|
+
------
|
|
93
|
+
arr_old - np.array | np.ma.masked_array. Existing grid to use
|
|
94
|
+
as base for new grid data.
|
|
95
|
+
dict_values - dict. Map of old grid data to new grid data.
|
|
96
|
+
empty_value - any. Optional value for cells that contain no
|
|
97
|
+
data in the new grid.
|
|
98
|
+
|
|
99
|
+
Returns
|
|
100
|
+
-------
|
|
101
|
+
arr_new - np.array | np.ma.masked_array. Type is same as arr_old.
|
|
102
|
+
New grid of data made by mapping dict_values to the old
|
|
103
|
+
grid. If masked_array then the mask is taken from the
|
|
104
|
+
old grid.
|
|
105
|
+
"""
|
|
106
|
+
# Check: data type of incoming values.
|
|
107
|
+
_check_incoming_dtype(list(dict_values.values()))
|
|
108
|
+
value_type = _get_incoming_dtype(list(dict_values.values()))
|
|
109
|
+
listlike = [tuple, list, np.ndarray]
|
|
110
|
+
values_are_colours = any(
|
|
111
|
+
[np.issubdtype(value_type, t) for t in listlike])
|
|
112
|
+
value_example = list(dict_values.values())[0]
|
|
113
|
+
|
|
114
|
+
if values_are_colours:
|
|
115
|
+
_check_colours_valid(list(dict_values.values()))
|
|
116
|
+
arr_shape = (*arr_old.shape, len(value_example))
|
|
117
|
+
arr_dtype = type(value_example[0])
|
|
118
|
+
else:
|
|
119
|
+
arr_shape = arr_old.shape
|
|
120
|
+
if np.issubdtype(value_type, str):
|
|
121
|
+
# Make sure the array isn't initialised with a
|
|
122
|
+
# string dtype that can't hold as many characters
|
|
123
|
+
# as the length of the incoming strings.
|
|
124
|
+
arr_dtype = object
|
|
125
|
+
else:
|
|
126
|
+
arr_dtype = value_type
|
|
127
|
+
|
|
128
|
+
if empty_value is None:
|
|
129
|
+
if values_are_colours:
|
|
130
|
+
empty_value = _generate_empty_colour(value_example)
|
|
131
|
+
else:
|
|
132
|
+
empty_value = _generate_empty_value(value_type)
|
|
133
|
+
else:
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
# New data:
|
|
137
|
+
arr_new = np.full(arr_shape, empty_value, dtype=arr_dtype)
|
|
138
|
+
for old_value, new_value in dict_values.items():
|
|
139
|
+
inds = (arr_old == old_value)
|
|
140
|
+
arr_new[inds] = new_value
|
|
141
|
+
# New mask:
|
|
142
|
+
if isinstance(arr_old, np.ma.MaskedArray):
|
|
143
|
+
if values_are_colours:
|
|
144
|
+
mask_new = np.stack([arr_old.mask] * len(value_example), axis=2)
|
|
145
|
+
else:
|
|
146
|
+
mask_new = arr_old.mask
|
|
147
|
+
arr_new = np.ma.masked_array(arr_new, mask=mask_new)
|
|
148
|
+
else:
|
|
149
|
+
pass
|
|
150
|
+
return arr_new
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _check_incoming_dtype(values: list | tuple):
|
|
154
|
+
"""Check that all values have same/similar dtype(s).
|
|
155
|
+
|
|
156
|
+
If only one dtype or all values are numeric, check passes.
|
|
157
|
+
Otherwise, raise error to flag mixed data types.
|
|
158
|
+
|
|
159
|
+
Inputs
|
|
160
|
+
------
|
|
161
|
+
values - list | tuple.
|
|
162
|
+
"""
|
|
163
|
+
types_here = list(set([type(v) for v in values]))
|
|
164
|
+
if len(types_here) == 1:
|
|
165
|
+
pass
|
|
166
|
+
else:
|
|
167
|
+
numeric_types = [int, float]
|
|
168
|
+
all_numeric = all([
|
|
169
|
+
any([np.issubdtype(t, n) for n in numeric_types])
|
|
170
|
+
for t in types_here
|
|
171
|
+
])
|
|
172
|
+
if all_numeric:
|
|
173
|
+
pass
|
|
174
|
+
else:
|
|
175
|
+
# If they're mixed dtypes, bad.
|
|
176
|
+
raise TypeError(
|
|
177
|
+
f'New values should be same type. Found {types_here}.')
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _get_incoming_dtype(values: list | tuple) -> any:
|
|
181
|
+
"""Find the dtype of these values.
|
|
182
|
+
|
|
183
|
+
Do a series of checks. If it's string, use object. It it's mixed
|
|
184
|
+
numeric, use float. If objects are present, use object. Otherwise
|
|
185
|
+
use the most common dtype in the list.
|
|
186
|
+
|
|
187
|
+
Inputs
|
|
188
|
+
------
|
|
189
|
+
values - list | tuple.
|
|
190
|
+
|
|
191
|
+
Returns
|
|
192
|
+
-------
|
|
193
|
+
d - any. dtype that best describes the input values.
|
|
194
|
+
"""
|
|
195
|
+
types_here = list(set([type(v) for v in values]))
|
|
196
|
+
if len(types_here) == 1:
|
|
197
|
+
d = types_here[0]
|
|
198
|
+
elif any([isinstance(d, pd.StringDtype) for d in types_here]):
|
|
199
|
+
d = pd.StringDtype
|
|
200
|
+
elif any([isinstance(d, pd.Float64Dtype) for d in types_here]):
|
|
201
|
+
d = float
|
|
202
|
+
else:
|
|
203
|
+
# Check for mix of float and int.
|
|
204
|
+
f = any([np.issubdtype(t, float) for t in types_here])
|
|
205
|
+
i = any([np.issubdtype(t, int) for t in types_here])
|
|
206
|
+
if f & i:
|
|
207
|
+
# Pick out the first float type:
|
|
208
|
+
d = [t for t in types_here if np.issubdtype(t, float)][0]
|
|
209
|
+
else:
|
|
210
|
+
# This isn't ideal. If object present, return it.
|
|
211
|
+
# Otherwise use the most common.
|
|
212
|
+
t_o = [t for t in types_here if np.issubdtype(t, object)]
|
|
213
|
+
if len(t_o) > 0:
|
|
214
|
+
d = t_o[0]
|
|
215
|
+
else:
|
|
216
|
+
# Mode. From https://stackoverflow.com/a/28129716
|
|
217
|
+
d = max(set(t_o), key=t_o.count)
|
|
218
|
+
|
|
219
|
+
if isinstance(d, pd.StringDtype):
|
|
220
|
+
d = object
|
|
221
|
+
return d
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _generate_empty_value(d: any) -> any:
|
|
225
|
+
"""Pick value for empty cells with input data type.
|
|
226
|
+
|
|
227
|
+
For colours, use _generate_empty_colour.
|
|
228
|
+
|
|
229
|
+
Inputs
|
|
230
|
+
------
|
|
231
|
+
d - any. A data type.
|
|
232
|
+
|
|
233
|
+
Returns
|
|
234
|
+
-------
|
|
235
|
+
empty_value - any. Value to use for cells with no shapes in.
|
|
236
|
+
"""
|
|
237
|
+
if isinstance(d, pd.StringDtype):
|
|
238
|
+
empty_value = ''
|
|
239
|
+
elif isinstance(d, pd.Float64Dtype):
|
|
240
|
+
empty_value = np.nan
|
|
241
|
+
elif np.issubdtype(d, object) | np.issubdtype(d, str):
|
|
242
|
+
empty_value = ''
|
|
243
|
+
elif np.issubdtype(d, np.integer):
|
|
244
|
+
empty_value = -99
|
|
245
|
+
else:
|
|
246
|
+
empty_value = np.nan
|
|
247
|
+
return empty_value
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _generate_empty_colour(colour_example: list | tuple) -> list | tuple:
|
|
251
|
+
"""Pick colour tuple for empty cells.
|
|
252
|
+
|
|
253
|
+
For other values, use _generate_empty_value.
|
|
254
|
+
|
|
255
|
+
Inputs
|
|
256
|
+
------
|
|
257
|
+
colour_example - list | tuple. A colour tuple.
|
|
258
|
+
|
|
259
|
+
Returns
|
|
260
|
+
-------
|
|
261
|
+
empty_value - any. Colour tuple to use for empty cells.
|
|
262
|
+
"""
|
|
263
|
+
# Define colour for empty cells in same format as example colour.
|
|
264
|
+
c_len = len(colour_example)
|
|
265
|
+
f = np.issubdtype(type(colour_example[0]), float)
|
|
266
|
+
v = 1.0 if f else 255
|
|
267
|
+
a = 0.0 if f else 0
|
|
268
|
+
if c_len > 3:
|
|
269
|
+
colour_empty = (v, v, v, a) # RGBA transparent
|
|
270
|
+
else:
|
|
271
|
+
colour_empty = (v, v, v) # RGB white
|
|
272
|
+
return colour_empty
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _check_colours_valid(colours: list | tuple):
|
|
276
|
+
"""Check that all colour tuples in list have same format.
|
|
277
|
+
|
|
278
|
+
Check that all inputs colours are tuples, are of same length,
|
|
279
|
+
and are in RGB or RGBA format. If any not, raise error.
|
|
280
|
+
|
|
281
|
+
TO DO - could check whether they're all 0.0-1.0 or 0-255.
|
|
282
|
+
|
|
283
|
+
Inputs
|
|
284
|
+
------
|
|
285
|
+
colours - list | tuple. Many colour tuples.
|
|
286
|
+
"""
|
|
287
|
+
all_c_len = []
|
|
288
|
+
for colour_example in colours:
|
|
289
|
+
listlike = (list, tuple, np.ndarray)
|
|
290
|
+
colour_is_listlike = any([
|
|
291
|
+
np.issubdtype(type(colour_example), t) for t in listlike])
|
|
292
|
+
if colour_is_listlike:
|
|
293
|
+
c_len = len(colour_example)
|
|
294
|
+
if c_len in [3, 4]:
|
|
295
|
+
all_c_len.append(c_len)
|
|
296
|
+
else:
|
|
297
|
+
raise TypeError(('Colour tuples must be of length 3 or 4. '
|
|
298
|
+
f'Found {colour_example}.'))
|
|
299
|
+
else:
|
|
300
|
+
raise TypeError(('Colours must be RGB or RGBA tuples. '
|
|
301
|
+
f'Found {colour_example}.'))
|
|
302
|
+
if len(set(all_c_len)) > 1:
|
|
303
|
+
raise TypeError(('All colour tuples must be of same length.'))
|
|
304
|
+
else:
|
|
305
|
+
pass
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def calculate_scaled_cell_values(
|
|
309
|
+
df_props: pd.DataFrame,
|
|
310
|
+
dict_region_value: dict,
|
|
311
|
+
col_label_props: str = 'label_props',
|
|
312
|
+
col_area_props: str = 'area_props',
|
|
313
|
+
r: int = 3
|
|
314
|
+
) -> pd.Series:
|
|
315
|
+
"""Calculate new cell values from combination of cell contents.
|
|
316
|
+
|
|
317
|
+
Expect index to be cell label.
|
|
318
|
+
Assumes that area props sum to 1.
|
|
319
|
+
|
|
320
|
+
Inputs
|
|
321
|
+
------
|
|
322
|
+
df_props - pd.DataFrame. One row per cell in the grid,
|
|
323
|
+
columns containing lists of regions present,
|
|
324
|
+
and the areas they take up.
|
|
325
|
+
dict_region_value - dict. Value associated with each region.
|
|
326
|
+
These values will be used in the scaled sum.
|
|
327
|
+
col_label_props - str. Name of column containing region names.
|
|
328
|
+
col_area_props - str. Name of column containing area
|
|
329
|
+
proportions.
|
|
330
|
+
r - int. Decimal places to round area proportions.
|
|
331
|
+
|
|
332
|
+
Returns
|
|
333
|
+
-------
|
|
334
|
+
d - pd.Series. One row per cell in the grid. Values are the scaled
|
|
335
|
+
sum of the contents of each cell.
|
|
336
|
+
"""
|
|
337
|
+
df = pd.concat(
|
|
338
|
+
[df_props[[c]].explode(c) for c in [col_label_props, col_area_props]],
|
|
339
|
+
axis='columns'
|
|
340
|
+
)
|
|
341
|
+
# Place all values in the df:
|
|
342
|
+
df['label_value'] = df[col_label_props].map(dict_region_value)
|
|
343
|
+
# Scale all values by their contribution to the cell:
|
|
344
|
+
df['area_value_scaled'] = df['label_value'] * df[col_area_props]
|
|
345
|
+
# Sum scaled values for each cell:
|
|
346
|
+
index_name = df.index.name
|
|
347
|
+
d = df['area_value_scaled'].reset_index().groupby(index_name).sum()
|
|
348
|
+
d = d.round(r)
|
|
349
|
+
# Make sure the dtype is numeric, not object.
|
|
350
|
+
# Not sure why the column is object by default.
|
|
351
|
+
d = d.convert_dtypes()
|
|
352
|
+
return d
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def pick_midpoint(arr: np.array, label: any) -> tuple[int, int]:
|
|
356
|
+
"""Find a representative point for cells that equal "label".
|
|
357
|
+
|
|
358
|
+
Assumes that a region is all of the cells with the value "label".
|
|
359
|
+
The midpoint is the middlemost column of the middlemost row in the
|
|
360
|
+
grid for cells that match "label".
|
|
361
|
+
|
|
362
|
+
Inputs
|
|
363
|
+
------
|
|
364
|
+
arr - np.array. 2D grid of values.
|
|
365
|
+
label - any. Some value contained in the grid.
|
|
366
|
+
|
|
367
|
+
Returns
|
|
368
|
+
-------
|
|
369
|
+
(x_med, y_med) - tuple[int, int]. Coordinates of representative
|
|
370
|
+
middle pixel of the region matching the input
|
|
371
|
+
label.
|
|
372
|
+
"""
|
|
373
|
+
ys, xs = np.where(arr == label)
|
|
374
|
+
if len(ys) == 0:
|
|
375
|
+
# This label isn't in the array.
|
|
376
|
+
warnings.warn('Requested label for region midpoint is not in grid.',
|
|
377
|
+
UserWarning)
|
|
378
|
+
y_med, x_med = (99999, 99999)
|
|
379
|
+
else:
|
|
380
|
+
# Pick the middle row:
|
|
381
|
+
i = int(0.5*len(ys))
|
|
382
|
+
y_med = ys[i]
|
|
383
|
+
# Pick the middle column in that row:
|
|
384
|
+
j = int(0.5*len(xs[ys == y_med]))
|
|
385
|
+
x_med = xs[ys == y_med][j]
|
|
386
|
+
return (x_med, y_med)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def pick_midpoints_for_regions(
|
|
390
|
+
arr: np.ndarray, labels_unique: list | tuple
|
|
391
|
+
) -> np.ndarray:
|
|
392
|
+
"""Wrapper for pick_midpoint().
|
|
393
|
+
|
|
394
|
+
Inputs
|
|
395
|
+
------
|
|
396
|
+
arr - np.ndarray. 2D grid of values.
|
|
397
|
+
labels_unique - list | tuple. Labels of areas to find midpoints
|
|
398
|
+
for.
|
|
399
|
+
|
|
400
|
+
Returns
|
|
401
|
+
-------
|
|
402
|
+
coords - np.ndarray. (x, y) coordinate for the midpoint of the
|
|
403
|
+
region with each input label.
|
|
404
|
+
"""
|
|
405
|
+
coords = np.empty((len(labels_unique), 2), dtype=int)
|
|
406
|
+
for i, label in enumerate(labels_unique):
|
|
407
|
+
coords[i] = pick_midpoint(arr, label)
|
|
408
|
+
return coords
|
traybake/grid.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Define grids in the reference frame of the shapes.
|
|
3
|
+
|
|
4
|
+
TO DO - should transform dict function accept various inputs and
|
|
5
|
+
calculate the missing bits? Currently accepts bounds and cell size
|
|
6
|
+
and calculates numbers of columns/rows, but perhaps offer the
|
|
7
|
+
other way round (calculate cell size given target numbers of rows).
|
|
8
|
+
|
|
9
|
+
TO DO - potentially one day allow for non-rectangular grid cells.
|
|
10
|
+
"""
|
|
11
|
+
# --- Imports ---
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# --- Functions ---
|
|
16
|
+
def make_grid_bounds_containing_bbox(
|
|
17
|
+
bbox_shapes: list[float | int] | tuple[float | int, ...],
|
|
18
|
+
cell_width: float | int,
|
|
19
|
+
cell_height: float | int
|
|
20
|
+
) -> list[float | int]:
|
|
21
|
+
"""Calculate nice grid limits that contain this bbox.
|
|
22
|
+
|
|
23
|
+
Find grid limits that contain the bounding box of some set of
|
|
24
|
+
shapes and that start and end at nice round numbers. For
|
|
25
|
+
example, for a cell size of 1000, the limits will be rounded
|
|
26
|
+
down (for xmin, ymin) or up (xmax, ymax) to the nearest multiple
|
|
27
|
+
of 1000.
|
|
28
|
+
|
|
29
|
+
Inputs
|
|
30
|
+
------
|
|
31
|
+
bbox_shapes - list | tuple. Bounding box (xmin, ymin, xmax, ymax).
|
|
32
|
+
cell_width - float | int. Width of cells for this grid.
|
|
33
|
+
cell_height - float | int. Height of cells for this grid.
|
|
34
|
+
|
|
35
|
+
Returns
|
|
36
|
+
-------
|
|
37
|
+
bbox - list | tuple. Bounding box (xmin, ymin, xmax, ymax) that
|
|
38
|
+
just contains the input bbox and has its limits rounded
|
|
39
|
+
to multiples of cell width and cell height.
|
|
40
|
+
"""
|
|
41
|
+
xmin, ymin, xmax, ymax = bbox_shapes
|
|
42
|
+
bbox = [
|
|
43
|
+
(xmin // cell_width) * cell_width, # xmin
|
|
44
|
+
(ymin // cell_height) * cell_height, # ymin
|
|
45
|
+
((xmax // cell_width) + 1.0) * cell_width, # xmax
|
|
46
|
+
((ymax // cell_height) + 1.0) * cell_height, # ymax
|
|
47
|
+
]
|
|
48
|
+
return bbox
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def make_transform_dict(
|
|
52
|
+
bbox: list[float | int] | tuple[float | int, ...],
|
|
53
|
+
cell_width: float | int,
|
|
54
|
+
cell_height: float | int,
|
|
55
|
+
**kwargs
|
|
56
|
+
) -> dict:
|
|
57
|
+
"""Gather information on grid dimensions into a dictionary.
|
|
58
|
+
|
|
59
|
+
Dict contains grid extent, cell size, and number of rows and
|
|
60
|
+
columns. Any kwargs provided are also stored. Recommended kwargs
|
|
61
|
+
are crs name and EPSG.
|
|
62
|
+
|
|
63
|
+
Inputs
|
|
64
|
+
------
|
|
65
|
+
bbox - list | tuple. Bounding box (xmin, ymin, xmax, ymax)
|
|
66
|
+
for the grid itself, not the shapes it will contain.
|
|
67
|
+
cell_width - float | int. Width of cells for this grid.
|
|
68
|
+
cell_height - float | int. Height of cells for this grid.
|
|
69
|
+
crs_name - str. Optional. Name of the crs projection that this
|
|
70
|
+
grid is intended to work for.
|
|
71
|
+
crs_epsg - str | int. Optional. Name of the ESPG that this
|
|
72
|
+
grid is intended to work for.
|
|
73
|
+
|
|
74
|
+
Returns
|
|
75
|
+
-------
|
|
76
|
+
transform_dict - dict. Dictionary of grid coordinate information.
|
|
77
|
+
"""
|
|
78
|
+
xmin, ymin, xmax, ymax = bbox
|
|
79
|
+
# Calculate numbers of rows and columns that fit in this extent:
|
|
80
|
+
n_cols = int(np.ceil((xmax - xmin) // cell_width))
|
|
81
|
+
n_rows = int(np.ceil((ymax - ymin) // cell_height))
|
|
82
|
+
# Recalculate grid limits to ensure that an integer number of cells
|
|
83
|
+
# fit within the limits.
|
|
84
|
+
xmax = xmin + (cell_width * n_cols)
|
|
85
|
+
ymin = ymax - (cell_height * n_rows)
|
|
86
|
+
|
|
87
|
+
transform_dict = {
|
|
88
|
+
'xmin': xmin,
|
|
89
|
+
'ymax': ymax,
|
|
90
|
+
'cell_width': cell_width,
|
|
91
|
+
'cell_height': cell_height,
|
|
92
|
+
'n_cols': n_cols,
|
|
93
|
+
'n_rows': n_rows,
|
|
94
|
+
'xmax': xmax,
|
|
95
|
+
'ymin': ymin,
|
|
96
|
+
}
|
|
97
|
+
for k, v in kwargs:
|
|
98
|
+
transform_dict[k] = v
|
|
99
|
+
return transform_dict
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def set_up_cell_limits(
|
|
103
|
+
col: int,
|
|
104
|
+
row: int,
|
|
105
|
+
xmin: float | int,
|
|
106
|
+
ymin: float | int,
|
|
107
|
+
cell_width: float | int,
|
|
108
|
+
cell_height: float | int
|
|
109
|
+
) -> tuple[float | int, ...]:
|
|
110
|
+
"""Calculate bounds of rectangular cell in this row and column.
|
|
111
|
+
|
|
112
|
+
Assume that this cell starts and ends an integer number of cell
|
|
113
|
+
widths and heights from the starting point of the grid.
|
|
114
|
+
|
|
115
|
+
Inputs
|
|
116
|
+
------
|
|
117
|
+
col - int. Column index for this cell.
|
|
118
|
+
row - int. Row index for this cell.
|
|
119
|
+
xmin - float | int. x bound of the grid.
|
|
120
|
+
ymin - float | int. y bound of the grid.
|
|
121
|
+
cell_width - float | int. Width of cells for this grid.
|
|
122
|
+
cell_height - float | int. Height of cells for this grid.
|
|
123
|
+
|
|
124
|
+
Returns
|
|
125
|
+
-------
|
|
126
|
+
bbox - tuple. Bounding box for this cell.
|
|
127
|
+
"""
|
|
128
|
+
# Usual bbox is xmin, ymin, xmax, ymax:
|
|
129
|
+
bbox = (
|
|
130
|
+
xmin + cell_width * col, # xmin, left
|
|
131
|
+
ymin + cell_height * row, # ymin, bottom
|
|
132
|
+
xmin + cell_width * (col + 1), # xmax, right
|
|
133
|
+
ymin + cell_height * (row + 1), # ymax, top
|
|
134
|
+
)
|
|
135
|
+
return bbox
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def transform_coords_to_grid(
|
|
139
|
+
coords: np.ndarray,
|
|
140
|
+
*,
|
|
141
|
+
cell_width: float | int,
|
|
142
|
+
cell_height: float | int,
|
|
143
|
+
n_rows: float | int,
|
|
144
|
+
xmin: float | int,
|
|
145
|
+
ymax: float | int,
|
|
146
|
+
**kwargs
|
|
147
|
+
) -> np.ndarray:
|
|
148
|
+
"""Transform coordinates from pixel to projected coordinates.
|
|
149
|
+
|
|
150
|
+
Assumes that the first cell is the 0th row and 0th column.
|
|
151
|
+
|
|
152
|
+
**kwargs allows for calling the function with a dictionary
|
|
153
|
+
that contains unnecessary keys,
|
|
154
|
+
e.g. transform_coords_to_grid(coords, **transform_dict).
|
|
155
|
+
The *identifer makes sure that cell properties are passed
|
|
156
|
+
as keywords and so their order doesn't matter.
|
|
157
|
+
|
|
158
|
+
Inputs
|
|
159
|
+
------
|
|
160
|
+
coords - np.ndarray. Stacked coordinates in pixel units.
|
|
161
|
+
First column is x values, second is y.
|
|
162
|
+
cell_width - float | int. Width of cells for this grid.
|
|
163
|
+
cell_height - float | int. Height of cells for this grid.
|
|
164
|
+
n_rows - float | int. Number of rows in the grid.
|
|
165
|
+
xmin - float | int. x bound of the grid.
|
|
166
|
+
ymax - float | int. y bound of the grid.
|
|
167
|
+
**kwargs - dict. These go unused.
|
|
168
|
+
|
|
169
|
+
Returns
|
|
170
|
+
-------
|
|
171
|
+
new_coords - np.ndarray. Transformed coordinates. First column
|
|
172
|
+
is x values, second is y.
|
|
173
|
+
"""
|
|
174
|
+
# Current coordinates:
|
|
175
|
+
x = coords[:, 0]
|
|
176
|
+
y = coords[:, 1]
|
|
177
|
+
# Transformed coordinates:
|
|
178
|
+
x = xmin + x * cell_width
|
|
179
|
+
y = ymax - (n_rows - y) * cell_height
|
|
180
|
+
# Gather transformed coords:
|
|
181
|
+
new_coords = np.stack((x, y), axis=1)
|
|
182
|
+
return new_coords
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def calculate_cell_centres(
|
|
186
|
+
zmin: float | int,
|
|
187
|
+
zmax: float | int,
|
|
188
|
+
cell_size: float | int
|
|
189
|
+
) -> np.array:
|
|
190
|
+
"""Calculate centres of this line of cells given start and size.
|
|
191
|
+
|
|
192
|
+
Assumes that all cells are the same width and that the required
|
|
193
|
+
centre is halfway between the start and end of a cell.
|
|
194
|
+
|
|
195
|
+
Inputs
|
|
196
|
+
------
|
|
197
|
+
zmin - float | int. Start of the first cell.
|
|
198
|
+
zmax - float | int. End of the final cell.
|
|
199
|
+
cell_size - float | int. Size of each cell.
|
|
200
|
+
|
|
201
|
+
Returns
|
|
202
|
+
-------
|
|
203
|
+
z - np.array. Midpoints of all cells in this line.
|
|
204
|
+
"""
|
|
205
|
+
z = np.arange(zmin, zmax, cell_size) + 0.5 * cell_size
|
|
206
|
+
return z
|
traybake/poly.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
"""
|
|
2
|
+
"""
|
|
3
|
+
# --- Imports ---
|
|
4
|
+
import numpy as np
|
|
5
|
+
import rasterio.features # for converting array to shapes
|
|
6
|
+
import shapely.geometry # make polygons from rasterio shapes
|
|
7
|
+
import geojson # for preparing polygons for saving to file
|
|
8
|
+
from .convert import convert_grid_values
|
|
9
|
+
from .grid import transform_coords_to_grid
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# --- Functions ---
|
|
13
|
+
def convert_grid_to_polys(arr: np.array) -> dict:
|
|
14
|
+
"""Make dict of polygons of discrete regions in grid geometry.
|
|
15
|
+
|
|
16
|
+
The rasterio shape conversion needs the region labels to have
|
|
17
|
+
float32 or int32 dtype. If this isn't the case in the input arr,
|
|
18
|
+
then the labels are temporarily switched to arbitrary float32.
|
|
19
|
+
The output dict uses the same labels as in the input arr.
|
|
20
|
+
|
|
21
|
+
Inputs
|
|
22
|
+
------
|
|
23
|
+
arr - np.array. 2D grid of region labels.
|
|
24
|
+
|
|
25
|
+
Returns
|
|
26
|
+
-------
|
|
27
|
+
dict_polys - dict. One key per unique label in arr. Each value
|
|
28
|
+
is a shapely Polygon or MultiPolygon.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
# rasterio shape conversion needs float32 or int32 dtype.
|
|
32
|
+
try:
|
|
33
|
+
arr_float32 = arr.astype(np.float32)
|
|
34
|
+
converted_vals = False
|
|
35
|
+
except ValueError:
|
|
36
|
+
# If not numeric, convert to float with this lookup:
|
|
37
|
+
converted_vals = True
|
|
38
|
+
# Looking to find a shape for each val in the array:
|
|
39
|
+
try:
|
|
40
|
+
vals = np.unique(arr.compressed()) # masked array
|
|
41
|
+
except AttributeError:
|
|
42
|
+
vals = np.unique(arr) # normal array
|
|
43
|
+
dict_val_floats = dict(
|
|
44
|
+
zip(vals, np.arange(len(vals), dtype=np.float32)))
|
|
45
|
+
arr_float32 = convert_grid_values(arr, dict_val_floats)
|
|
46
|
+
|
|
47
|
+
shapes_generator = _make_shapes_from_arr(arr_float32)
|
|
48
|
+
dict_polys = _convert_shapes_to_poly_dict(shapes_generator)
|
|
49
|
+
|
|
50
|
+
if converted_vals:
|
|
51
|
+
# Convert floats back to original labels.
|
|
52
|
+
dict_polys = dict([(val, dict_polys[f_val])
|
|
53
|
+
for val, f_val in dict_val_floats.items()])
|
|
54
|
+
else:
|
|
55
|
+
pass
|
|
56
|
+
return dict_polys
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _make_shapes_from_arr(arr: np.array, **kwargs) -> Generator:
|
|
60
|
+
"""Convert arr of regions into dict of shapes and labels.
|
|
61
|
+
|
|
62
|
+
Wrapper for rasterio.features.shapes.
|
|
63
|
+
|
|
64
|
+
Inputs
|
|
65
|
+
------
|
|
66
|
+
arr - np.array.
|
|
67
|
+
|
|
68
|
+
Returns
|
|
69
|
+
-------
|
|
70
|
+
shapes - Generator.
|
|
71
|
+
"""
|
|
72
|
+
# Convert the array into shapes. Adjacent areas of the array with the
|
|
73
|
+
# same value (e.g. belong to same region) will be gathered as one
|
|
74
|
+
# shape.
|
|
75
|
+
shapes = rasterio.features.shapes(np.float32(arr), **kwargs)
|
|
76
|
+
return shapes
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _convert_shapes_to_poly_dict(shapes_generator: Generator) -> dict:
|
|
80
|
+
"""Convert shapes dictionary to polygon dict.
|
|
81
|
+
|
|
82
|
+
Create a dict with one key per region in the grid and each
|
|
83
|
+
value being a shapely geometry.
|
|
84
|
+
|
|
85
|
+
Gather the geometry carefully in case of non-contiguous regions.
|
|
86
|
+
shapes only gathers areas that are adjacent in the array.
|
|
87
|
+
For example, ambulance area shapes will have one entry for Devon
|
|
88
|
+
and another for the island of Lundy. Both will have the same value
|
|
89
|
+
(belong to the same region). Take care to retain both entries.
|
|
90
|
+
|
|
91
|
+
Inputs
|
|
92
|
+
------
|
|
93
|
+
shapes_generator - Generator. Each item is a tuple of
|
|
94
|
+
(polygon dict, region label). The output from
|
|
95
|
+
rasterio.features.shapes.
|
|
96
|
+
|
|
97
|
+
Returns
|
|
98
|
+
-------
|
|
99
|
+
dict_polys - dict. One key per region in the grid. Each value
|
|
100
|
+
is a shapely Polygon or MultiPolygon.
|
|
101
|
+
"""
|
|
102
|
+
# Convert generator to list so we can access it more than once:
|
|
103
|
+
shapes = [s for s in shapes_generator]
|
|
104
|
+
# Labels of regions present here:
|
|
105
|
+
region_vals, val_counts = np.unique(
|
|
106
|
+
[s[1] for s in shapes], return_counts=True)
|
|
107
|
+
# Set up a dictionary. Each region has an empty array the length of
|
|
108
|
+
# the number of shapes that belong to it.
|
|
109
|
+
dict_shapes = dict([(r, np.empty(n, dtype=object)) for r, n in
|
|
110
|
+
zip(region_vals, val_counts)])
|
|
111
|
+
fill_counts = dict([(r, 0) for r in region_vals])
|
|
112
|
+
|
|
113
|
+
# Fill the dictionary with polygons, grouping by region.
|
|
114
|
+
# shapes can have multiple entries for one region
|
|
115
|
+
# when the region consists of multiple non-adjacent shapes,
|
|
116
|
+
# so place multiple polys for same region in the list.
|
|
117
|
+
for s in shapes:
|
|
118
|
+
region_val = s[1]
|
|
119
|
+
coord_lists = s[0]['coordinates']
|
|
120
|
+
p = _make_poly_from_coords_lists(coord_lists, offset=0.0)
|
|
121
|
+
# Place this poly in the next empty slot for its region:
|
|
122
|
+
ind = fill_counts[region_val]
|
|
123
|
+
dict_shapes[region_val][ind] = p
|
|
124
|
+
fill_counts[region_val] += 1
|
|
125
|
+
|
|
126
|
+
# Convert dict of lists into a dict of polygons and multipolygons.
|
|
127
|
+
# Lists with only one polygon are released from the list.
|
|
128
|
+
# Combine lists of polygons into a single MultiPolygon.
|
|
129
|
+
dict_polys = dict([(region_val, _convert_poly_list_to_poly(p_list))
|
|
130
|
+
for region_val, p_list in dict_shapes.items()])
|
|
131
|
+
return dict_polys
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _make_poly_from_coords_lists(
|
|
135
|
+
coord_lists: list | tuple,
|
|
136
|
+
offset: float | int = 0.5
|
|
137
|
+
) -> shapely.geometry.Polygon:
|
|
138
|
+
"""Make Polygon from lists of exterior and interior coordinates.
|
|
139
|
+
|
|
140
|
+
Inputs
|
|
141
|
+
------
|
|
142
|
+
coord_lists - list | tuple. Sets of coordinates for one polygon.
|
|
143
|
+
The first list is the exterior coordinates and any
|
|
144
|
+
extra lists are for interior holes.
|
|
145
|
+
offset - float | int. Offset to convert result from the
|
|
146
|
+
centres to the edges of cells. Should be 0.5 when
|
|
147
|
+
coords are in pixel units.
|
|
148
|
+
|
|
149
|
+
Returns
|
|
150
|
+
-------
|
|
151
|
+
p - shapely.geometry.Polygon. Polygon from input coords.
|
|
152
|
+
"""
|
|
153
|
+
# Pick out coordinates for the exterior of the polygon.
|
|
154
|
+
# Apply offset so lines are drawn at edge of pixel,
|
|
155
|
+
# not through middle.
|
|
156
|
+
ext = coord_lists[0]
|
|
157
|
+
if offset == 0.0:
|
|
158
|
+
pass
|
|
159
|
+
else:
|
|
160
|
+
ext = list(np.array(ext) - offset)
|
|
161
|
+
# Pick out any holes in the polygon if applicable:
|
|
162
|
+
n_poly = len(coord_lists)
|
|
163
|
+
if n_poly == 1:
|
|
164
|
+
holes = None
|
|
165
|
+
else:
|
|
166
|
+
holes = coord_lists[1:]
|
|
167
|
+
# Apply same offset as for exterior coords:
|
|
168
|
+
if offset == 0.0:
|
|
169
|
+
pass
|
|
170
|
+
else:
|
|
171
|
+
holes = [list(np.array(h) - offset) for h in holes]
|
|
172
|
+
# Convert list(s) of coordinates to shapely Polygon:
|
|
173
|
+
p = shapely.geometry.Polygon(ext, holes)
|
|
174
|
+
return p
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _convert_poly_list_to_poly(
|
|
178
|
+
p_list: list | tuple
|
|
179
|
+
) -> shapely.geometry.Polygon | shapely.geometry.MultiPolygon:
|
|
180
|
+
"""Make a Polygon or MultiPolygon from this list of polygons.
|
|
181
|
+
|
|
182
|
+
Helper for _convert_shapes_to_poly_dict().
|
|
183
|
+
|
|
184
|
+
Inputs
|
|
185
|
+
------
|
|
186
|
+
p_list - list | tuple. List of polygons. Will be length 1 when
|
|
187
|
+
the region is a single landmass and longer
|
|
188
|
+
when the region is non-contiguous.
|
|
189
|
+
|
|
190
|
+
Returns
|
|
191
|
+
-------
|
|
192
|
+
p - shapely.geometry.Polygon | shapely.geometry.MultiPolygon.
|
|
193
|
+
A single geometry from the input polygon(s).
|
|
194
|
+
"""
|
|
195
|
+
if len(p_list) > 1:
|
|
196
|
+
# Combine list of polygons into MultiPolygon.
|
|
197
|
+
p = shapely.geometry.MultiPolygon(list(p_list))
|
|
198
|
+
elif len(p_list) == 1:
|
|
199
|
+
# Use the single polygon given.
|
|
200
|
+
p = p_list[0]
|
|
201
|
+
else:
|
|
202
|
+
# This shouldn't happen!
|
|
203
|
+
p = None
|
|
204
|
+
return p
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def convert_dict_polys_to_featurecollection(
|
|
208
|
+
dict_polys: dict
|
|
209
|
+
) -> geojson.FeatureCollection:
|
|
210
|
+
"""Convert dict to FeatureCollection for saving to file.
|
|
211
|
+
|
|
212
|
+
Inputs
|
|
213
|
+
------
|
|
214
|
+
dict_polys - dict. One key per region, each value is a shapely
|
|
215
|
+
geometry.
|
|
216
|
+
|
|
217
|
+
Returns
|
|
218
|
+
-------
|
|
219
|
+
fc - geojson.FeatureCollection. A single collection of all the
|
|
220
|
+
input geometries with the region labels carried through.
|
|
221
|
+
"""
|
|
222
|
+
features = np.empty(len(dict_polys), dtype=object)
|
|
223
|
+
ind = 0
|
|
224
|
+
for region, poly in dict_polys.items():
|
|
225
|
+
f = geojson.Feature(geometry=shapely.geometry.mapping(poly),
|
|
226
|
+
properties={'label': region})
|
|
227
|
+
features[ind] = f
|
|
228
|
+
ind += 1
|
|
229
|
+
fc = geojson.FeatureCollection(list(features))
|
|
230
|
+
return fc
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def convert_featurecollection_to_dict_polys(
|
|
234
|
+
fc: geojson.FeatureCollection
|
|
235
|
+
) -> dict:
|
|
236
|
+
"""Convert FeatureCollection to dict for easier use.
|
|
237
|
+
|
|
238
|
+
Easier to load FeatureCollection from file than a dict,
|
|
239
|
+
and easier to use a dict than a FeatureCollection.
|
|
240
|
+
|
|
241
|
+
Inputs
|
|
242
|
+
------
|
|
243
|
+
fc - geojson.FeatureCollection. The "label" property is made in
|
|
244
|
+
the convert_dict_polys_to_featurecollection() function.
|
|
245
|
+
|
|
246
|
+
Returns
|
|
247
|
+
-------
|
|
248
|
+
d - dict. One key per region, one geometry per key.
|
|
249
|
+
"""
|
|
250
|
+
d = {}
|
|
251
|
+
for f in fc['features']:
|
|
252
|
+
poly = shapely.geometry.shape(f['geometry'])
|
|
253
|
+
region = f['properties']['label']
|
|
254
|
+
d[region] = poly
|
|
255
|
+
return d
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def update_poly_coords(
|
|
259
|
+
p: shapely.geometry.Polygon,
|
|
260
|
+
*,
|
|
261
|
+
cell_width: float | int,
|
|
262
|
+
cell_height: float | int,
|
|
263
|
+
n_rows: float | int,
|
|
264
|
+
xmin: float | int,
|
|
265
|
+
ymax: float | int,
|
|
266
|
+
**kwargs
|
|
267
|
+
) -> shapely.geometry.Polygon:
|
|
268
|
+
"""Scale a polygon's coordinates from grid to reference system.
|
|
269
|
+
|
|
270
|
+
Wrapper for transform_coords_to_grid().
|
|
271
|
+
|
|
272
|
+
Convert polygon coordinates in terms of the grid (x are column
|
|
273
|
+
indices, y are row indices) to the coordinate reference system
|
|
274
|
+
(e.g. British National Grid).
|
|
275
|
+
|
|
276
|
+
shapely v2.1.0 (April 2025) has a new interleaved kwarg in
|
|
277
|
+
shapely.transform() which would allow for coordinate
|
|
278
|
+
transformation, but this function uses another method to allow
|
|
279
|
+
compatibility with older versions of shapely.
|
|
280
|
+
|
|
281
|
+
Inputs
|
|
282
|
+
------
|
|
283
|
+
p - shapely.geometry.Polygon.
|
|
284
|
+
cell_width - float | int. Width of cells for this grid.
|
|
285
|
+
cell_height - float | int. Height of cells for this grid.
|
|
286
|
+
n_rows - float | int. Number of rows in the grid.
|
|
287
|
+
xmin - float | int. x bound of the grid.
|
|
288
|
+
ymax - float | int. y bound of the grid.
|
|
289
|
+
**kwargs - dict. These go unused.
|
|
290
|
+
|
|
291
|
+
Returns
|
|
292
|
+
-------
|
|
293
|
+
p - shapely.geometry.Polygon. New version of the input polygon
|
|
294
|
+
with transformed coordinates.
|
|
295
|
+
"""
|
|
296
|
+
ext = np.array([list(c) for c in p.exterior.coords])
|
|
297
|
+
ext = transform_coords_to_grid(
|
|
298
|
+
ext, cell_width=cell_width, cell_height=cell_height,
|
|
299
|
+
n_rows=n_rows, xmin=xmin, ymax=ymax
|
|
300
|
+
)
|
|
301
|
+
holes = [list(r.coords) for r in p.interiors]
|
|
302
|
+
holes_t = np.empty(len(holes), dtype=object)
|
|
303
|
+
for i, h in enumerate(holes):
|
|
304
|
+
coords = np.array([list(c) for c in h])
|
|
305
|
+
coords = transform_coords_to_grid(
|
|
306
|
+
coords, cell_width=cell_width, cell_height=cell_height,
|
|
307
|
+
n_rows=n_rows, xmin=xmin, ymax=ymax
|
|
308
|
+
)
|
|
309
|
+
holes_t[i] = coords
|
|
310
|
+
holes = None if len(holes_t) < 1 else holes_t
|
|
311
|
+
p = shapely.geometry.Polygon(ext, holes)
|
|
312
|
+
return p
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def transform_poly_dict_coords(
|
|
316
|
+
dict_polys: dict,
|
|
317
|
+
*,
|
|
318
|
+
cell_width: float | int,
|
|
319
|
+
cell_height: float | int,
|
|
320
|
+
n_rows: float | int,
|
|
321
|
+
xmin: float | int,
|
|
322
|
+
ymax: float | int,
|
|
323
|
+
**kwargs
|
|
324
|
+
) -> dict:
|
|
325
|
+
"""Transform coordinates of each geometry in this dict.
|
|
326
|
+
|
|
327
|
+
Wrapper for update_poly_coords().
|
|
328
|
+
|
|
329
|
+
Assumes that input dict is has geometry in grid coordinates
|
|
330
|
+
(x is column index, y is row index) and that input parameters
|
|
331
|
+
will transform these to the intended reference system, e.g.
|
|
332
|
+
British National Grid.
|
|
333
|
+
|
|
334
|
+
Inputs
|
|
335
|
+
------
|
|
336
|
+
dict_polys - dict. One key per region label, values are
|
|
337
|
+
shapely geometry.
|
|
338
|
+
cell_width - float | int. Width of cells for this grid.
|
|
339
|
+
cell_height - float | int. Height of cells for this grid.
|
|
340
|
+
n_rows - float | int. Number of rows in the grid.
|
|
341
|
+
xmin - float | int. x bound of the grid.
|
|
342
|
+
ymax - float | int. y bound of the grid.
|
|
343
|
+
**kwargs - dict. These go unused.
|
|
344
|
+
|
|
345
|
+
Returns
|
|
346
|
+
-------
|
|
347
|
+
dict_polys_new - dict. Same keys as input dict_polys, values
|
|
348
|
+
have their geometry transformed to new system.
|
|
349
|
+
"""
|
|
350
|
+
dict_polys_new = {}
|
|
351
|
+
for label, p in dict_polys.items():
|
|
352
|
+
if isinstance(p, shapely.geometry.multipolygon.MultiPolygon):
|
|
353
|
+
new_mp_list = np.empty(len(p.geoms), dtype=object)
|
|
354
|
+
for i, poly in enumerate(p.geoms):
|
|
355
|
+
poly = update_poly_coords(
|
|
356
|
+
poly, cell_width=cell_width, cell_height=cell_height,
|
|
357
|
+
n_rows=n_rows, xmin=xmin, ymax=ymax
|
|
358
|
+
)
|
|
359
|
+
new_mp_list[i] = poly
|
|
360
|
+
new_p = shapely.geometry.MultiPolygon(list(new_mp_list))
|
|
361
|
+
elif isinstance(p, shapely.geometry.polygon.Polygon):
|
|
362
|
+
new_p = update_poly_coords(
|
|
363
|
+
p, cell_width=cell_width, cell_height=cell_height,
|
|
364
|
+
n_rows=n_rows, xmin=xmin, ymax=ymax
|
|
365
|
+
)
|
|
366
|
+
else:
|
|
367
|
+
# This shouldn't happen!
|
|
368
|
+
new_p = None
|
|
369
|
+
dict_polys_new[label] = new_p
|
|
370
|
+
return dict_polys_new
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def convert_poly_to_coords(p: shapely.geometry.Polygon) -> np.array:
|
|
374
|
+
"""Flatten Polygon exterior and hole coords for plotly.
|
|
375
|
+
|
|
376
|
+
Inputs
|
|
377
|
+
------
|
|
378
|
+
p - shapely.geometry.Polygon.
|
|
379
|
+
|
|
380
|
+
Returns
|
|
381
|
+
-------
|
|
382
|
+
coords - np.array. All coordinates of the input polygon, first
|
|
383
|
+
the exterior then any holes, where the sections are
|
|
384
|
+
split using None. First column is x, second is y.
|
|
385
|
+
"""
|
|
386
|
+
ext = np.array([list(c) for c in p.exterior.coords])
|
|
387
|
+
holes = [np.array([list(c) for c in list(r.coords)])
|
|
388
|
+
for r in p.interiors]
|
|
389
|
+
if len(holes) == 0:
|
|
390
|
+
coords = ext
|
|
391
|
+
else:
|
|
392
|
+
# Separate coord lists with this gap:
|
|
393
|
+
gap = np.full(ext.shape[-1], None)
|
|
394
|
+
# Set up array of coords to concat.
|
|
395
|
+
# First item ext coords, then alternate gaps and holes.
|
|
396
|
+
list_concat = np.empty(1 + len(holes)*2, dtype=object)
|
|
397
|
+
g_inds = np.arange(1, len(list_concat), 2)
|
|
398
|
+
h_inds = np.arange(2, len(list_concat), 2)
|
|
399
|
+
list_concat[0] = ext
|
|
400
|
+
list_concat[g_inds] = [gap]
|
|
401
|
+
list_concat[h_inds] = holes
|
|
402
|
+
coords = np.vstack(list_concat)
|
|
403
|
+
return coords
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def convert_multipoly_to_coords(
|
|
407
|
+
mp: shapely.geometry.MultiPolygon
|
|
408
|
+
) -> np.array:
|
|
409
|
+
"""Flatten MultiPolygon exterior and hole coords for plotly.
|
|
410
|
+
|
|
411
|
+
Wrapper for convert_poly_to_coords().
|
|
412
|
+
|
|
413
|
+
Inputs
|
|
414
|
+
------
|
|
415
|
+
mp - shapely.geometry.MultiPolygon.
|
|
416
|
+
|
|
417
|
+
Returns
|
|
418
|
+
-------
|
|
419
|
+
coords - np.array. All coordinates of all input polygons, split
|
|
420
|
+
using None. For each polygon's coordinates order, see
|
|
421
|
+
convert_poly_to_coords(). First column is x, second is y.
|
|
422
|
+
"""
|
|
423
|
+
coords_lists = [convert_poly_to_coords(p) for p in mp.geoms]
|
|
424
|
+
# Separate coord lists with this gap:
|
|
425
|
+
gap = np.full(coords_lists[0].shape[-1], None)
|
|
426
|
+
# Set up array of coords to concat. Alternate polys and gaps.
|
|
427
|
+
list_concat = np.empty((len(mp.geoms) * 2) - 1, dtype=object)
|
|
428
|
+
p_inds = np.arange(0, len(list_concat), 2)
|
|
429
|
+
g_inds = np.arange(1, len(list_concat), 2)
|
|
430
|
+
list_concat[p_inds] = coords_lists
|
|
431
|
+
list_concat[g_inds] = [gap]
|
|
432
|
+
coords = np.vstack(list_concat)
|
|
433
|
+
return coords
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def convert_dict_polys_to_coords(
|
|
437
|
+
dict_polys: dict[any, shapely.Geometry]
|
|
438
|
+
) -> dict[any, np.array]:
|
|
439
|
+
"""Convert each Multi/Polygon in dict to coordinates for plotly.
|
|
440
|
+
|
|
441
|
+
Wrapper for convert_poly_to_coords().
|
|
442
|
+
|
|
443
|
+
Inputs
|
|
444
|
+
------
|
|
445
|
+
dict_polys - dict[any, shapely.Geometry].
|
|
446
|
+
|
|
447
|
+
Returns
|
|
448
|
+
-------
|
|
449
|
+
dict_coords - dict[any, np.array].
|
|
450
|
+
"""
|
|
451
|
+
dict_coords = {}
|
|
452
|
+
for label, shape in dict_polys.items():
|
|
453
|
+
if shape.geom_type == 'Polygon':
|
|
454
|
+
coords = convert_poly_to_coords(shape)
|
|
455
|
+
elif shape.geom_type == 'MultiPolygon':
|
|
456
|
+
coords = convert_multipoly_to_coords(shape)
|
|
457
|
+
elif shape.geom_type == 'GeometryCollection':
|
|
458
|
+
print('Do something')
|
|
459
|
+
coords = None
|
|
460
|
+
else:
|
|
461
|
+
# What are we doing here, a warning or an error? TO DO.
|
|
462
|
+
coords = None
|
|
463
|
+
dict_coords[label] = coords
|
|
464
|
+
return dict_coords
|
traybake/stick.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Assign shapes to grid cells and calculate the cell area covered.
|
|
2
|
+
|
|
3
|
+
TO DO - consider changing main stick function so that cell bounds
|
|
4
|
+
are calculated in advance rather than during the loop.
|
|
5
|
+
More potential in the future for non-rectangular cells or not
|
|
6
|
+
calculating all cells in the grid if some are known to be empty.
|
|
7
|
+
Would also need to store cell area rather than proportion as
|
|
8
|
+
cell area could vary.
|
|
9
|
+
"""
|
|
10
|
+
# --- Imports ---
|
|
11
|
+
import warnings
|
|
12
|
+
import numpy as np
|
|
13
|
+
import pandas as pd
|
|
14
|
+
import geopandas as gpd
|
|
15
|
+
from .grid import set_up_cell_limits
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# --- Functions ---
|
|
19
|
+
def stick_shapes_to_grid(
|
|
20
|
+
gdf: gpd.GeoDataFrame,
|
|
21
|
+
*,
|
|
22
|
+
cell_width: float | int,
|
|
23
|
+
cell_height: float | int,
|
|
24
|
+
n_cols: float | int,
|
|
25
|
+
n_rows: float | int,
|
|
26
|
+
xmin: float | int,
|
|
27
|
+
ymin: float | int,
|
|
28
|
+
print_progress: bool = True,
|
|
29
|
+
_test_grid_layout: bool = False,
|
|
30
|
+
**kwargs
|
|
31
|
+
) -> pd.DataFrame:
|
|
32
|
+
"""Record which shapes are in each grid cell.
|
|
33
|
+
|
|
34
|
+
For each cell in turn, clip the input geometry to the cell bounds.
|
|
35
|
+
Record the shapes in the clipped area and the area that each
|
|
36
|
+
covers.
|
|
37
|
+
|
|
38
|
+
Resulting dataframe only stores data for non-empty cells.
|
|
39
|
+
|
|
40
|
+
**kwargs allows for calling the function with a dictionary
|
|
41
|
+
that contains unnecessary keys,
|
|
42
|
+
e.g. transform_coords_to_grid(coords, **transform_dict).
|
|
43
|
+
The *identifer makes sure that cell properties are passed
|
|
44
|
+
as keywords and so their order doesn't matter.
|
|
45
|
+
|
|
46
|
+
TO DO - make it clear whether col and row are starting in top
|
|
47
|
+
left or wherever.
|
|
48
|
+
TO DO - define cells in advance?
|
|
49
|
+
|
|
50
|
+
Inputs
|
|
51
|
+
------
|
|
52
|
+
gdf - gpd.GeoDataFrame. Contains shapes to be stuck
|
|
53
|
+
to the grid.
|
|
54
|
+
cell_width - float | int. Width of cells for this grid.
|
|
55
|
+
cell_height - float | int. Height of cells for this grid.
|
|
56
|
+
n_cols - float | int. Number of columns in the grid.
|
|
57
|
+
n_rows - float | int. Number of rows in the grid.
|
|
58
|
+
xmin - float | int. x bound of the grid.
|
|
59
|
+
ymin - float | int. y bound of the grid.
|
|
60
|
+
print_progress - bool. Optional. Print how many cells so far
|
|
61
|
+
have been checked.
|
|
62
|
+
_test_grid_layout - bool. Optional. Don't use shapes, just assign
|
|
63
|
+
row and column to each cell.
|
|
64
|
+
|
|
65
|
+
Returns
|
|
66
|
+
-------
|
|
67
|
+
df_props - pd.DataFrame. Contains a row for each cell that contains
|
|
68
|
+
any shape. Columns record cell location (row, column),
|
|
69
|
+
contents (shapes, proportions of filled area taken up
|
|
70
|
+
by each shape), proportion of filled area.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
cell_area = cell_width * cell_height
|
|
74
|
+
cell_props = []
|
|
75
|
+
cell_label = 0
|
|
76
|
+
for col in range(n_cols):
|
|
77
|
+
for row in range(n_rows):
|
|
78
|
+
if print_progress:
|
|
79
|
+
perc_done = 100.0 * (cell_label + 1) / (n_rows * n_cols)
|
|
80
|
+
print(f'{perc_done:5.1f}% of cells checked', end='\r')
|
|
81
|
+
else:
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
if _test_grid_layout:
|
|
85
|
+
cell_props.append((cell_label, row, col))
|
|
86
|
+
else:
|
|
87
|
+
# Limit gdf to this pixel:
|
|
88
|
+
bbox = set_up_cell_limits(
|
|
89
|
+
col, row, xmin, ymin, cell_width, cell_height
|
|
90
|
+
)
|
|
91
|
+
gdf_here = gpd.clip(gdf, bbox)
|
|
92
|
+
|
|
93
|
+
if len(gdf_here) > 0:
|
|
94
|
+
# Sanity check - are there intersecting shapes?
|
|
95
|
+
pairs = find_overlapping_polygons(gdf_here)
|
|
96
|
+
warn_overlap_here = 1 if len(pairs) > 0 else 0
|
|
97
|
+
|
|
98
|
+
prop_cell_covered = round(
|
|
99
|
+
gdf_here.area.sum() / cell_area, 3)
|
|
100
|
+
series_area_props = find_area_props(gdf_here).round(3)
|
|
101
|
+
# If this index is returned as a pandas StringArray
|
|
102
|
+
# (experimental feature at time of writing)
|
|
103
|
+
# then turn it into a standard array:
|
|
104
|
+
r = series_area_props.index.values
|
|
105
|
+
try:
|
|
106
|
+
r = r.to_numpy().tolist()
|
|
107
|
+
except AttributeError:
|
|
108
|
+
pass
|
|
109
|
+
# Majority assumes that series is sorted by
|
|
110
|
+
# descending prop.
|
|
111
|
+
cell_props.append((
|
|
112
|
+
cell_label,
|
|
113
|
+
row,
|
|
114
|
+
col,
|
|
115
|
+
r,
|
|
116
|
+
series_area_props.values,
|
|
117
|
+
prop_cell_covered,
|
|
118
|
+
series_area_props.index.values[0], # majority
|
|
119
|
+
warn_overlap_here,
|
|
120
|
+
))
|
|
121
|
+
else:
|
|
122
|
+
pass
|
|
123
|
+
cell_label += 1
|
|
124
|
+
|
|
125
|
+
# Convert the results to dataframe:
|
|
126
|
+
if _test_grid_layout:
|
|
127
|
+
cols = ('cell_label', 'cell_row', 'cell_col')
|
|
128
|
+
else:
|
|
129
|
+
cols = ('cell_label', 'cell_row', 'cell_col',
|
|
130
|
+
'label_props', 'area_props', 'prop_cell_covered',
|
|
131
|
+
'label_majority', 'overlapping_polys')
|
|
132
|
+
df_props = pd.DataFrame(cell_props, columns=cols).set_index('cell_label')
|
|
133
|
+
|
|
134
|
+
if 'overlapping_polys' in df_props.columns:
|
|
135
|
+
# This isn't stored in the test case.
|
|
136
|
+
n_overlapping = df_props['overlapping_polys'].sum()
|
|
137
|
+
if n_overlapping > 0:
|
|
138
|
+
warnings.warn((
|
|
139
|
+
'Overlapping polygons present '
|
|
140
|
+
f'in {n_overlapping:.0f} cells: '
|
|
141
|
+
'overlap area will be counted twice.'
|
|
142
|
+
), UserWarning)
|
|
143
|
+
else:
|
|
144
|
+
pass
|
|
145
|
+
return df_props
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def find_overlapping_polygons(gdf: gpd.GeoDataFrame) -> np.array:
|
|
149
|
+
"""Find pairs of shapes here that overlap.
|
|
150
|
+
|
|
151
|
+
Use this to check whether any shapes overlap and so whether to
|
|
152
|
+
check results about the areas of the cell covered by the shapes.
|
|
153
|
+
For example, the total area covered could be much greater than
|
|
154
|
+
the area of the cell if lots of regions are double-counted.
|
|
155
|
+
|
|
156
|
+
Assumes that shape labels are in the gdf index.
|
|
157
|
+
|
|
158
|
+
Inputs
|
|
159
|
+
------
|
|
160
|
+
gdf - gpd.GeoDataFrame. Contains shapes that share an area.
|
|
161
|
+
Index is the labels for the shapes.
|
|
162
|
+
|
|
163
|
+
Returns
|
|
164
|
+
-------
|
|
165
|
+
pairs - np.array. Each element is a list of the names of a pair
|
|
166
|
+
of shapes that overlap.
|
|
167
|
+
"""
|
|
168
|
+
# predicate='overlaps' means if two shapes touch boundaries,
|
|
169
|
+
# then it doesn't count as overlapping. They are only flagged
|
|
170
|
+
# if their interiors overlap.
|
|
171
|
+
c = gdf.index.name
|
|
172
|
+
gdf_overlap = gpd.sjoin(gdf, gdf, predicate='overlaps').reset_index()
|
|
173
|
+
mask = gdf_overlap[f'{c}_left'] != gdf_overlap[f'{c}_right']
|
|
174
|
+
gdf_overlap = gdf_overlap[mask]
|
|
175
|
+
|
|
176
|
+
pairs = gdf_overlap[[f'{c}_left', f'{c}_right']].values
|
|
177
|
+
# Remove duplicates in different orders:
|
|
178
|
+
pairs = np.unique(np.sort(pairs))
|
|
179
|
+
return pairs
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def find_area_props(gdf: gpd.GeoDataFrame) -> pd.Series:
|
|
183
|
+
"""Calculate proportion of this gdf covered by each shape.
|
|
184
|
+
|
|
185
|
+
Note that these are proportions of the total shape area in gdf,
|
|
186
|
+
not the total area covered by the bounding box of the gdf.
|
|
187
|
+
Empty space within the bounding box and not covered by a shape
|
|
188
|
+
is not included in these calculations.
|
|
189
|
+
|
|
190
|
+
Results are sorted by decreasing proportion.
|
|
191
|
+
|
|
192
|
+
Inputs
|
|
193
|
+
------
|
|
194
|
+
gdf - gpd.GeoDataFrame. Contains shapes that share an area.
|
|
195
|
+
Index is the labels for the shapes.
|
|
196
|
+
|
|
197
|
+
Returns
|
|
198
|
+
-------
|
|
199
|
+
s_area_props - pd.Series. One row for each shape in the gdf.
|
|
200
|
+
Values are the proportion of the total covered
|
|
201
|
+
area that each shape covers.
|
|
202
|
+
"""
|
|
203
|
+
# Find proportion of the constituent LSOAs by area:
|
|
204
|
+
s_area_props = gdf.area / gdf.area.sum()
|
|
205
|
+
# Sort by decreasing proportion:
|
|
206
|
+
s_area_props = s_area_props.sort_values(ascending=False)
|
|
207
|
+
return s_area_props
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: traybake
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Map shapes to grids with large cells where each cell could contain many shapes.
|
|
5
|
+
Project-URL: Homepage, https://github.com/aselaws/traybake
|
|
6
|
+
Project-URL: Bug Tracker, https://github.com/aselaws/traybake/issues
|
|
7
|
+
Author-email: Anna Laws <a.laws2@exeter.ac.uk>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
13
|
+
Requires-Python: >=3.14
|
|
14
|
+
Requires-Dist: geojson>=3.3
|
|
15
|
+
Requires-Dist: geopandas>=1.1
|
|
16
|
+
Requires-Dist: numpy>=2.5
|
|
17
|
+
Requires-Dist: pandas>=3.0
|
|
18
|
+
Requires-Dist: rasterio>=1.5
|
|
19
|
+
Requires-Dist: shapely>=2.1
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# isopods
|
|
23
|
+
Map shapes to grids with large cells where each cell could contain many shapes.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
traybake/__init__.py,sha256=4Ao_avWtUqRpPEcGjvXnOLpuK7gmYAQVzSd-QMrrQCw,145
|
|
2
|
+
traybake/convert.py,sha256=FWMfyZ9LDGf9yBesy72c2Eob05a7ScLM1tPNkttZFHs,13347
|
|
3
|
+
traybake/grid.py,sha256=CDHWCDELQQzvghltSYiUgaM8_FTtDZEVsi7QPFx-ZJg,6870
|
|
4
|
+
traybake/poly.py,sha256=D4klqQTArgEn_iNjaXpjaZTvmcSSZ5ZD0msLMvEcdfw,15840
|
|
5
|
+
traybake/stick.py,sha256=y-XD_epywfM3u88vZrzvyr0M4dHfBNPFpd3KkLn77Bo,7758
|
|
6
|
+
traybake-0.1.0.dist-info/METADATA,sha256=FKbfGhmi_Pdw_a6hDfYzKm2JIIJ5E4GsWUmizlioHog,834
|
|
7
|
+
traybake-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
traybake-0.1.0.dist-info/licenses/LICENSE,sha256=bpsxyKwOipW12Pv_SgHysZj1SJO1w5-9WQbzlFKTtmg,1066
|
|
9
|
+
traybake-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Anna Laws
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|