traybake 0.1.0__tar.gz

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.
@@ -0,0 +1,53 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ .Python
8
+ build/
9
+ develop-eggs/
10
+ dist/
11
+ downloads/
12
+ eggs/
13
+ .eggs/
14
+ lib/
15
+ lib64/
16
+ parts/
17
+ sdist/
18
+ var/
19
+ wheels/
20
+ pip-wheel-metadata/
21
+ share/python-wheels/
22
+ *.egg-info/
23
+ .installed.cfg
24
+ *.egg
25
+ MANIFEST
26
+
27
+ # PyInstaller
28
+ # Usually these files are written by a python script from a template
29
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
30
+ *.manifest
31
+ *.spec
32
+
33
+ # Installer logs
34
+ pip-log.txt
35
+ pip-delete-this-directory.txt
36
+ # Jupyter Notebook
37
+ .ipynb_checkpoints
38
+
39
+ # IPython
40
+ profile_default/
41
+ ipython_config.py
42
+
43
+ # pyenv
44
+ .python-version
45
+
46
+ # Environments
47
+ .env
48
+ .venv
49
+ env/
50
+ venv/
51
+ ENV/
52
+ env.bak/
53
+ venv.bak/
traybake-0.1.0/LICENSE ADDED
@@ -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.
@@ -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,2 @@
1
+ # isopods
2
+ Map shapes to grids with large cells where each cell could contain many shapes.
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "traybake"
7
+ dynamic = ["version"]
8
+ description = "Map shapes to grids with large cells where each cell could contain many shapes."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.14"
12
+ authors = [
13
+ { name = "Anna Laws", email = "a.laws2@exeter.ac.uk" },
14
+ ]
15
+ classifiers = [
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3.14",
19
+
20
+ ]
21
+ dependencies = [
22
+ "geojson>=3.3",
23
+ "geopandas>=1.1",
24
+ "numpy>=2.5",
25
+ "pandas>=3.0",
26
+ "rasterio>=1.5",
27
+ "shapely>=2.1",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/aselaws/traybake"
32
+ "Bug Tracker" = "https://github.com/aselaws/traybake/issues"
33
+
34
+ [tool.hatch.version]
35
+ path = "traybake/__init__.py"
36
+
37
+ [tool.hatch.build.targets.sdist]
38
+ include = [
39
+ "/traybake",
40
+ ]
@@ -0,0 +1,7 @@
1
+ """
2
+ traybake
3
+
4
+ Map shapes to grids with large cells where each cell could contain many shapes.
5
+ """
6
+ __version__ = '0.1.0'
7
+ __author__ = 'Anna Laws'
@@ -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