cell-terrain 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.
- cell_terrain-0.1.0/LICENSE +202 -0
- cell_terrain-0.1.0/PKG-INFO +96 -0
- cell_terrain-0.1.0/README.md +68 -0
- cell_terrain-0.1.0/pyproject.toml +117 -0
- cell_terrain-0.1.0/pyproject.toml.orig +83 -0
- cell_terrain-0.1.0/src/cell_terrain/__init__.py +31 -0
- cell_terrain-0.1.0/src/cell_terrain/_reproject.py +28 -0
- cell_terrain-0.1.0/src/cell_terrain/derivatives.py +62 -0
- cell_terrain-0.1.0/src/cell_terrain/elevation.py +110 -0
- cell_terrain-0.1.0/src/cell_terrain/geology.py +118 -0
- cell_terrain-0.1.0/src/cell_terrain/landcover.py +84 -0
- cell_terrain-0.1.0/src/cell_terrain/py.typed +0 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cell-terrain
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Terrain, land cover and geology per cell of a grid: slope, aspect and curvature from a DEM, the dominant CORINE class, the lithology and the distance from faults
|
|
5
|
+
Keywords: dem,slope,corine,land cover,lithology,zonal statistics,italy
|
|
6
|
+
Author: Giuseppe Zileni
|
|
7
|
+
Author-email: Giuseppe Zileni <giuseppe.zileni@gmail.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Dist: numpy>=2.0
|
|
19
|
+
Requires-Dist: pyproj>=3.6
|
|
20
|
+
Requires-Dist: rasterio>=1.4
|
|
21
|
+
Requires-Dist: shapely>=2.0
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Project-URL: Homepage, https://github.com/agent-engineering-studio/cell-terrain
|
|
24
|
+
Project-URL: Issues, https://github.com/agent-engineering-studio/cell-terrain/issues
|
|
25
|
+
Project-URL: Documentation, https://agentengineering.it/cell-terrain/
|
|
26
|
+
Project-URL: Changelog, https://github.com/agent-engineering-studio/cell-terrain/blob/main/CHANGELOG.md
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# cell-terrain
|
|
30
|
+
|
|
31
|
+
[Documentation](https://agentengineering.it/cell-terrain/) · [Changelog](CHANGELOG.md)
|
|
32
|
+
|
|
33
|
+
**cell-terrain** describes the ground under each cell of a grid: how high and
|
|
34
|
+
steep it is, which way it faces, what covers it and what rock it is made of,
|
|
35
|
+
from public rasters and maps.
|
|
36
|
+
|
|
37
|
+
| Function | From | What each cell gets |
|
|
38
|
+
|---|---|---|
|
|
39
|
+
| `cell_elevation` | a DEM raster in a metric CRS (TINITALY, Copernicus DEM) | mean elevation, mean slope, median aspect of the non-flat pixels, mean curvature, valid pixels |
|
|
40
|
+
| `cell_landcover` | a categorical raster (CORINE Land Cover) | the most frequent class, valid pixels |
|
|
41
|
+
| `cell_geology` | lithology polygons and fault lines (the Carta geolitologica d'Italia 1:500,000) | the lithology covering most of the cell, its weight if you give one, the distance from the nearest fault |
|
|
42
|
+
| `derivatives` | a 2-D elevation array | slope, aspect and curvature per pixel |
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install cell-terrain
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from shapely.geometry import box
|
|
50
|
+
|
|
51
|
+
from cell_terrain import cell_elevation, cell_landcover
|
|
52
|
+
|
|
53
|
+
cells = {"c-1": box(16.80, 41.10, 16.81, 41.11)} # lon/lat, EPSG:4326
|
|
54
|
+
terrain = cell_elevation("tinitaly_w50070.tif", cells)
|
|
55
|
+
cover = cell_landcover("U2018_CLC2018_V2020_20u1.tif", cells)
|
|
56
|
+
print(terrain[0].slope_deg, cover[0].code)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## What it gets right
|
|
60
|
+
|
|
61
|
+
- **Not measured is not a number.** A cell outside the raster, or with only
|
|
62
|
+
nodata under it, gets `None` and `pixel_count` 0, never a NaN that a model
|
|
63
|
+
would read as a value.
|
|
64
|
+
- **One reprojection per loop.** Building a pyproj transformer from a rasterio
|
|
65
|
+
CRS costs about 67 ms; applying it, 0.07 ms. Over 312,550 cells that is 5.9
|
|
66
|
+
hours against 5 minutes, for the same numbers.
|
|
67
|
+
- **Aspect is a direction.** It does not average: a cell gets the median
|
|
68
|
+
bearing of its non-flat pixels.
|
|
69
|
+
- **Calibration stays with you.** How prone a rock is to slide is a parameter of
|
|
70
|
+
the landslide model, not of the map: `cell_geology` takes a `weight`
|
|
71
|
+
function and ships no table.
|
|
72
|
+
- **Deterministic.** Ties in land cover go to the smallest code, in lithology to
|
|
73
|
+
the first label.
|
|
74
|
+
|
|
75
|
+
## The rules
|
|
76
|
+
|
|
77
|
+
- **Standalone.** It imports none of the project's other libraries, and a test
|
|
78
|
+
checks it. [limen-core](https://github.com/agent-engineering-studio/limen-core)
|
|
79
|
+
joins it with the others.
|
|
80
|
+
- **From Limen, with its tests.** The code was Limen's static bootstrap, and its
|
|
81
|
+
tests came with it.
|
|
82
|
+
- **It reads files you have.** No download: the rasters and maps are large and
|
|
83
|
+
each has its own licence and terms.
|
|
84
|
+
|
|
85
|
+
## Develop
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
make help # the targets
|
|
89
|
+
make check # ruff, mypy --strict, pytest: the gate CI runs
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Licence
|
|
93
|
+
|
|
94
|
+
Code: Apache-2.0. The data keep the licence of their source: TINITALY CC BY
|
|
95
|
+
4.0 (INGV), CORINE Land Cover the Copernicus licence, the Carta geolitologica
|
|
96
|
+
the terms of ISPRA.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# cell-terrain
|
|
2
|
+
|
|
3
|
+
[Documentation](https://agentengineering.it/cell-terrain/) · [Changelog](CHANGELOG.md)
|
|
4
|
+
|
|
5
|
+
**cell-terrain** describes the ground under each cell of a grid: how high and
|
|
6
|
+
steep it is, which way it faces, what covers it and what rock it is made of,
|
|
7
|
+
from public rasters and maps.
|
|
8
|
+
|
|
9
|
+
| Function | From | What each cell gets |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| `cell_elevation` | a DEM raster in a metric CRS (TINITALY, Copernicus DEM) | mean elevation, mean slope, median aspect of the non-flat pixels, mean curvature, valid pixels |
|
|
12
|
+
| `cell_landcover` | a categorical raster (CORINE Land Cover) | the most frequent class, valid pixels |
|
|
13
|
+
| `cell_geology` | lithology polygons and fault lines (the Carta geolitologica d'Italia 1:500,000) | the lithology covering most of the cell, its weight if you give one, the distance from the nearest fault |
|
|
14
|
+
| `derivatives` | a 2-D elevation array | slope, aspect and curvature per pixel |
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install cell-terrain
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from shapely.geometry import box
|
|
22
|
+
|
|
23
|
+
from cell_terrain import cell_elevation, cell_landcover
|
|
24
|
+
|
|
25
|
+
cells = {"c-1": box(16.80, 41.10, 16.81, 41.11)} # lon/lat, EPSG:4326
|
|
26
|
+
terrain = cell_elevation("tinitaly_w50070.tif", cells)
|
|
27
|
+
cover = cell_landcover("U2018_CLC2018_V2020_20u1.tif", cells)
|
|
28
|
+
print(terrain[0].slope_deg, cover[0].code)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## What it gets right
|
|
32
|
+
|
|
33
|
+
- **Not measured is not a number.** A cell outside the raster, or with only
|
|
34
|
+
nodata under it, gets `None` and `pixel_count` 0, never a NaN that a model
|
|
35
|
+
would read as a value.
|
|
36
|
+
- **One reprojection per loop.** Building a pyproj transformer from a rasterio
|
|
37
|
+
CRS costs about 67 ms; applying it, 0.07 ms. Over 312,550 cells that is 5.9
|
|
38
|
+
hours against 5 minutes, for the same numbers.
|
|
39
|
+
- **Aspect is a direction.** It does not average: a cell gets the median
|
|
40
|
+
bearing of its non-flat pixels.
|
|
41
|
+
- **Calibration stays with you.** How prone a rock is to slide is a parameter of
|
|
42
|
+
the landslide model, not of the map: `cell_geology` takes a `weight`
|
|
43
|
+
function and ships no table.
|
|
44
|
+
- **Deterministic.** Ties in land cover go to the smallest code, in lithology to
|
|
45
|
+
the first label.
|
|
46
|
+
|
|
47
|
+
## The rules
|
|
48
|
+
|
|
49
|
+
- **Standalone.** It imports none of the project's other libraries, and a test
|
|
50
|
+
checks it. [limen-core](https://github.com/agent-engineering-studio/limen-core)
|
|
51
|
+
joins it with the others.
|
|
52
|
+
- **From Limen, with its tests.** The code was Limen's static bootstrap, and its
|
|
53
|
+
tests came with it.
|
|
54
|
+
- **It reads files you have.** No download: the rasters and maps are large and
|
|
55
|
+
each has its own licence and terms.
|
|
56
|
+
|
|
57
|
+
## Develop
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
make help # the targets
|
|
61
|
+
make check # ruff, mypy --strict, pytest: the gate CI runs
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Licence
|
|
65
|
+
|
|
66
|
+
Code: Apache-2.0. The data keep the licence of their source: TINITALY CC BY
|
|
67
|
+
4.0 (INGV), CORINE Land Cover the Copernicus licence, the Carta geolitologica
|
|
68
|
+
the terms of ISPRA.
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "cell-terrain"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Terrain, land cover and geology per cell of a grid: slope, aspect and curvature from a DEM, the dominant CORINE class, the lithology and the distance from faults"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
keywords = [
|
|
10
|
+
"dem",
|
|
11
|
+
"slope",
|
|
12
|
+
"corine",
|
|
13
|
+
"land cover",
|
|
14
|
+
"lithology",
|
|
15
|
+
"zonal statistics",
|
|
16
|
+
"italy",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 3 - Alpha",
|
|
20
|
+
"Intended Audience :: Science/Research",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Topic :: Scientific/Engineering :: GIS",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"numpy>=2.0",
|
|
30
|
+
"pyproj>=3.6",
|
|
31
|
+
"rasterio>=1.4",
|
|
32
|
+
"shapely>=2.0",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[[project.authors]]
|
|
36
|
+
name = "Giuseppe Zileni"
|
|
37
|
+
email = "giuseppe.zileni@gmail.com"
|
|
38
|
+
|
|
39
|
+
[project.urls]
|
|
40
|
+
Homepage = "https://github.com/agent-engineering-studio/cell-terrain"
|
|
41
|
+
Issues = "https://github.com/agent-engineering-studio/cell-terrain/issues"
|
|
42
|
+
Documentation = "https://agentengineering.it/cell-terrain/"
|
|
43
|
+
Changelog = "https://github.com/agent-engineering-studio/cell-terrain/blob/main/CHANGELOG.md"
|
|
44
|
+
|
|
45
|
+
[build-system]
|
|
46
|
+
requires = ["uv_build>=0.13.6,<0.14"]
|
|
47
|
+
build-backend = "uv_build"
|
|
48
|
+
|
|
49
|
+
[dependency-groups]
|
|
50
|
+
dev = [
|
|
51
|
+
"mypy>=1.13",
|
|
52
|
+
"pytest>=8.3",
|
|
53
|
+
"pytest-cov>=6.0",
|
|
54
|
+
"ruff>=0.8",
|
|
55
|
+
]
|
|
56
|
+
docs = [
|
|
57
|
+
"zensical>=0.1.0",
|
|
58
|
+
"mkdocstrings[python]>=0.26",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
[tool.ruff]
|
|
62
|
+
line-length = 100
|
|
63
|
+
target-version = "py312"
|
|
64
|
+
|
|
65
|
+
[tool.ruff.lint]
|
|
66
|
+
select = [
|
|
67
|
+
"E",
|
|
68
|
+
"F",
|
|
69
|
+
"W",
|
|
70
|
+
"I",
|
|
71
|
+
"N",
|
|
72
|
+
"UP",
|
|
73
|
+
"B",
|
|
74
|
+
"C4",
|
|
75
|
+
"SIM",
|
|
76
|
+
"ARG",
|
|
77
|
+
"PTH",
|
|
78
|
+
"RUF",
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
[tool.ruff.lint.per-file-ignores]
|
|
82
|
+
"tests/**" = [
|
|
83
|
+
"ARG",
|
|
84
|
+
"B018",
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
[tool.mypy]
|
|
88
|
+
strict = true
|
|
89
|
+
python_version = "3.12"
|
|
90
|
+
files = [
|
|
91
|
+
"src",
|
|
92
|
+
"tests",
|
|
93
|
+
]
|
|
94
|
+
warn_unused_ignores = true
|
|
95
|
+
warn_redundant_casts = true
|
|
96
|
+
|
|
97
|
+
[[tool.mypy.overrides]]
|
|
98
|
+
module = [
|
|
99
|
+
"rasterio",
|
|
100
|
+
"rasterio.*",
|
|
101
|
+
"shapely",
|
|
102
|
+
"shapely.*",
|
|
103
|
+
"pyproj",
|
|
104
|
+
"pyproj.*",
|
|
105
|
+
]
|
|
106
|
+
ignore_missing_imports = true
|
|
107
|
+
|
|
108
|
+
[tool.pytest.ini_options]
|
|
109
|
+
testpaths = ["tests"]
|
|
110
|
+
addopts = "--strict-markers"
|
|
111
|
+
|
|
112
|
+
[tool.coverage.run]
|
|
113
|
+
source = ["cell_terrain"]
|
|
114
|
+
|
|
115
|
+
[tool.coverage.report]
|
|
116
|
+
fail_under = 90
|
|
117
|
+
show_missing = true
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "cell-terrain"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Terrain, land cover and geology per cell of a grid: slope, aspect and curvature from a DEM, the dominant CORINE class, the lithology and the distance from faults"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [
|
|
10
|
+
{ name = "Giuseppe Zileni", email = "giuseppe.zileni@gmail.com" },
|
|
11
|
+
]
|
|
12
|
+
keywords = ["dem", "slope", "corine", "land cover", "lithology", "zonal statistics", "italy"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Intended Audience :: Science/Research",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Topic :: Scientific/Engineering :: GIS",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
dependencies = [
|
|
24
|
+
"numpy>=2.0",
|
|
25
|
+
"pyproj>=3.6",
|
|
26
|
+
"rasterio>=1.4",
|
|
27
|
+
"shapely>=2.0",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/agent-engineering-studio/cell-terrain"
|
|
32
|
+
Issues = "https://github.com/agent-engineering-studio/cell-terrain/issues"
|
|
33
|
+
Documentation = "https://agentengineering.it/cell-terrain/"
|
|
34
|
+
Changelog = "https://github.com/agent-engineering-studio/cell-terrain/blob/main/CHANGELOG.md"
|
|
35
|
+
|
|
36
|
+
[build-system]
|
|
37
|
+
requires = ["uv_build>=0.13.6,<0.14"]
|
|
38
|
+
build-backend = "uv_build"
|
|
39
|
+
|
|
40
|
+
[dependency-groups]
|
|
41
|
+
dev = [
|
|
42
|
+
"mypy>=1.13",
|
|
43
|
+
"pytest>=8.3",
|
|
44
|
+
"pytest-cov>=6.0",
|
|
45
|
+
"ruff>=0.8",
|
|
46
|
+
]
|
|
47
|
+
docs = [
|
|
48
|
+
"zensical>=0.1.0",
|
|
49
|
+
"mkdocstrings[python]>=0.26",
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
[tool.ruff]
|
|
53
|
+
line-length = 100
|
|
54
|
+
target-version = "py312"
|
|
55
|
+
|
|
56
|
+
[tool.ruff.lint]
|
|
57
|
+
select = ["E", "F", "W", "I", "N", "UP", "B", "C4", "SIM", "ARG", "PTH", "RUF"]
|
|
58
|
+
|
|
59
|
+
[tool.ruff.lint.per-file-ignores]
|
|
60
|
+
"tests/**" = ["ARG", "B018"]
|
|
61
|
+
|
|
62
|
+
[tool.mypy]
|
|
63
|
+
strict = true
|
|
64
|
+
python_version = "3.12"
|
|
65
|
+
files = ["src", "tests"]
|
|
66
|
+
warn_unused_ignores = true
|
|
67
|
+
warn_redundant_casts = true
|
|
68
|
+
|
|
69
|
+
# rasterio, shapely and pyproj ship incomplete annotations.
|
|
70
|
+
[[tool.mypy.overrides]]
|
|
71
|
+
module = ["rasterio", "rasterio.*", "shapely", "shapely.*", "pyproj", "pyproj.*"]
|
|
72
|
+
ignore_missing_imports = true
|
|
73
|
+
|
|
74
|
+
[tool.pytest.ini_options]
|
|
75
|
+
testpaths = ["tests"]
|
|
76
|
+
addopts = "--strict-markers"
|
|
77
|
+
|
|
78
|
+
[tool.coverage.run]
|
|
79
|
+
source = ["cell_terrain"]
|
|
80
|
+
|
|
81
|
+
[tool.coverage.report]
|
|
82
|
+
fail_under = 90
|
|
83
|
+
show_missing = true
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Terrain, land cover and geology per cell of a grid, from public rasters and maps.
|
|
2
|
+
|
|
3
|
+
- :mod:`cell_terrain.derivatives`: slope, aspect and curvature of a DEM array;
|
|
4
|
+
- :mod:`cell_terrain.elevation`: those, averaged per cell, from a DEM raster
|
|
5
|
+
(TINITALY, Copernicus DEM);
|
|
6
|
+
- :mod:`cell_terrain.landcover`: the dominant class per cell of a categorical
|
|
7
|
+
raster (CORINE Land Cover);
|
|
8
|
+
- :mod:`cell_terrain.geology`: the dominant lithology per cell and the distance
|
|
9
|
+
from the nearest fault, from vector maps (the Carta geolitologica d'Italia).
|
|
10
|
+
|
|
11
|
+
Not measured stays not measured: a cell outside the data gets ``None``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from importlib.metadata import version
|
|
15
|
+
|
|
16
|
+
from cell_terrain.elevation import CellElevation, cell_elevation
|
|
17
|
+
from cell_terrain.geology import CellGeology, LithologyPolygon, cell_geology
|
|
18
|
+
from cell_terrain.landcover import CellLandCover, cell_landcover
|
|
19
|
+
|
|
20
|
+
__version__ = version("cell-terrain")
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"CellElevation",
|
|
24
|
+
"CellGeology",
|
|
25
|
+
"CellLandCover",
|
|
26
|
+
"LithologyPolygon",
|
|
27
|
+
"__version__",
|
|
28
|
+
"cell_elevation",
|
|
29
|
+
"cell_geology",
|
|
30
|
+
"cell_landcover",
|
|
31
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""One reprojection for a whole loop of cells."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from shapely.geometry.base import BaseGeometry
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def reprojector(*, src_crs: Any, dst_crs: Any) -> Callable[[BaseGeometry], BaseGeometry]:
|
|
12
|
+
"""A function that reprojects a geometry from ``src_crs`` to ``dst_crs``.
|
|
13
|
+
|
|
14
|
+
Built once, not per geometry: building a pyproj ``Transformer`` from a
|
|
15
|
+
rasterio CRS costs about 67 ms, against 0.07 ms to apply it; over 312,550
|
|
16
|
+
cells that is 5.9 hours instead of 5 minutes. The transformer is the same
|
|
17
|
+
for every cell, so the numbers are identical.
|
|
18
|
+
"""
|
|
19
|
+
if src_crs == dst_crs:
|
|
20
|
+
return lambda geom: geom
|
|
21
|
+
import shapely
|
|
22
|
+
from pyproj import Transformer
|
|
23
|
+
|
|
24
|
+
transformer = Transformer.from_crs(src_crs, dst_crs, always_xy=True)
|
|
25
|
+
return lambda geom: shapely.transform(geom, transformer.transform, interleaved=False)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
__all__ = ["reprojector"]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Slope, aspect and curvature of a DEM array, in numpy alone.
|
|
2
|
+
|
|
3
|
+
Each function takes a 2-D elevation array (rows are y, north at row 0,
|
|
4
|
+
columns are x) and a ``cellsize`` in metres, and returns an array of the same
|
|
5
|
+
shape. A NaN in the input stays NaN in the output near it, so that nodata never
|
|
6
|
+
becomes a number.
|
|
7
|
+
|
|
8
|
+
- **slope**: ``atan(sqrt((dz/dx)^2 + (dz/dy)^2))``, in degrees;
|
|
9
|
+
- **aspect**: the compass bearing of the steepest ascent (0 north,
|
|
10
|
+
clockwise), ``-1`` on flat pixels;
|
|
11
|
+
- **curvature**: the Laplacian ``d2z/dx2 + d2z/dy2``, positive on ridges and
|
|
12
|
+
negative in valleys.
|
|
13
|
+
|
|
14
|
+
First-order central differences (``numpy.gradient``): accurate enough at the
|
|
15
|
+
10 to 30 m pixels of TINITALY for landslide susceptibility, with no scipy.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
from numpy.typing import NDArray
|
|
24
|
+
|
|
25
|
+
type Grid = NDArray[np.floating[Any]]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _gradients(dem: Grid, cellsize: float) -> tuple[Grid, Grid]:
|
|
29
|
+
"""``(dz/dx, dz/dy)`` in metres per metre, with +y pointing north."""
|
|
30
|
+
if cellsize <= 0:
|
|
31
|
+
raise ValueError(f"cellsize must be > 0, got {cellsize}")
|
|
32
|
+
dz_dy_pixels, dz_dx_pixels = np.gradient(dem)
|
|
33
|
+
# Raster row 0 is north, geographic +y points up.
|
|
34
|
+
dz_dx: Grid = np.asarray(dz_dx_pixels) / cellsize
|
|
35
|
+
dz_dy: Grid = -np.asarray(dz_dy_pixels) / cellsize
|
|
36
|
+
return dz_dx, dz_dy
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def slope_deg(dem: Grid, *, cellsize: float) -> Grid:
|
|
40
|
+
"""Slope in degrees."""
|
|
41
|
+
dz_dx, dz_dy = _gradients(dem, cellsize)
|
|
42
|
+
out: Grid = np.degrees(np.arctan(np.sqrt(dz_dx**2 + dz_dy**2)))
|
|
43
|
+
return out
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def aspect_deg(dem: Grid, *, cellsize: float) -> Grid:
|
|
47
|
+
"""Aspect as a compass bearing of the uphill direction; ``-1`` where flat."""
|
|
48
|
+
dz_dx, dz_dy = _gradients(dem, cellsize)
|
|
49
|
+
aspect = (np.degrees(np.arctan2(dz_dx, dz_dy)) + 360.0) % 360.0
|
|
50
|
+
flat = (np.abs(dz_dx) < 1e-9) & (np.abs(dz_dy) < 1e-9)
|
|
51
|
+
out: Grid = np.where(flat, -1.0, aspect)
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def curvature(dem: Grid, *, cellsize: float) -> Grid:
|
|
56
|
+
"""Total (Laplacian) curvature: positive on ridges, negative in valleys."""
|
|
57
|
+
dz_dx, dz_dy = _gradients(dem, cellsize)
|
|
58
|
+
out: Grid = np.gradient(dz_dx, axis=1) / cellsize - np.gradient(dz_dy, axis=0) / cellsize
|
|
59
|
+
return out
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
__all__ = ["Grid", "aspect_deg", "curvature", "slope_deg"]
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Elevation, slope, aspect and curvature per cell of a grid, from a DEM raster.
|
|
2
|
+
|
|
3
|
+
Each cell polygon (EPSG:4326 by default) is reprojected into the raster's CRS,
|
|
4
|
+
the raster is masked to it, and the derivatives are computed on the masked
|
|
5
|
+
window. The DEM must be in a metric CRS (TINITALY is ETRS89 / UTM 32N), or the
|
|
6
|
+
cell size must be given.
|
|
7
|
+
|
|
8
|
+
Aspect does not average linearly, so a cell gets the **median** aspect of its
|
|
9
|
+
non-flat pixels. A cell with no valid pixel gets ``None`` everywhere and
|
|
10
|
+
``pixel_count`` 0: not measured, never a number.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import math
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
from shapely.geometry.base import BaseGeometry
|
|
24
|
+
|
|
25
|
+
from cell_terrain._reproject import reprojector
|
|
26
|
+
from cell_terrain.derivatives import aspect_deg, curvature, slope_deg
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class CellElevation:
|
|
33
|
+
"""The terrain of one cell."""
|
|
34
|
+
|
|
35
|
+
cell_id: str
|
|
36
|
+
elevation_m: float | None
|
|
37
|
+
slope_deg: float | None
|
|
38
|
+
aspect_deg: float | None
|
|
39
|
+
curvature: float | None
|
|
40
|
+
pixel_count: int
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _mean(arr: Any) -> float | None:
|
|
44
|
+
"""The mean of the finite values; ``None`` when there are none."""
|
|
45
|
+
if not np.any(~np.isnan(arr)):
|
|
46
|
+
return None
|
|
47
|
+
value = float(np.nanmean(arr))
|
|
48
|
+
return value if math.isfinite(value) else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _empty(cell_id: str) -> CellElevation:
|
|
52
|
+
return CellElevation(cell_id, None, None, None, None, 0)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def cell_elevation(
|
|
56
|
+
raster: Path | str,
|
|
57
|
+
cells: Mapping[str, BaseGeometry],
|
|
58
|
+
*,
|
|
59
|
+
cells_crs: Any = 4326,
|
|
60
|
+
cellsize_m: float | None = None,
|
|
61
|
+
) -> list[CellElevation]:
|
|
62
|
+
"""The terrain of each cell of ``cells`` (id to polygon) from the DEM at ``raster``.
|
|
63
|
+
|
|
64
|
+
``cellsize_m`` overrides the pixel size read from the raster's transform.
|
|
65
|
+
Raises ``FileNotFoundError`` when the raster does not exist.
|
|
66
|
+
"""
|
|
67
|
+
import rasterio
|
|
68
|
+
from rasterio.crs import CRS
|
|
69
|
+
from rasterio.errors import RasterioError
|
|
70
|
+
from rasterio.mask import mask
|
|
71
|
+
|
|
72
|
+
path = Path(raster)
|
|
73
|
+
if not path.exists():
|
|
74
|
+
raise FileNotFoundError(f"DEM raster not found: {path}")
|
|
75
|
+
out: list[CellElevation] = []
|
|
76
|
+
with rasterio.open(path) as src:
|
|
77
|
+
size = cellsize_m or float(abs(src.transform.a))
|
|
78
|
+
if size <= 0:
|
|
79
|
+
raise ValueError(f"non-positive cell size: {size}")
|
|
80
|
+
reproject = reprojector(src_crs=CRS.from_user_input(cells_crs), dst_crs=src.crs)
|
|
81
|
+
for cell_id, geom in cells.items():
|
|
82
|
+
try:
|
|
83
|
+
data, _ = mask(src, [reproject(geom)], crop=True, filled=False)
|
|
84
|
+
except (ValueError, RasterioError):
|
|
85
|
+
# Outside the raster: not measured.
|
|
86
|
+
out.append(_empty(cell_id))
|
|
87
|
+
continue
|
|
88
|
+
band = data[0].astype(np.float32, copy=False)
|
|
89
|
+
arr = np.where(np.ma.getmaskarray(band), np.nan, np.ma.getdata(band))
|
|
90
|
+
valid = int(np.count_nonzero(~np.isnan(arr)))
|
|
91
|
+
if valid == 0:
|
|
92
|
+
out.append(_empty(cell_id))
|
|
93
|
+
continue
|
|
94
|
+
aspect = aspect_deg(arr, cellsize=size)
|
|
95
|
+
not_flat = aspect[(aspect >= 0.0) & ~np.isnan(aspect)]
|
|
96
|
+
out.append(
|
|
97
|
+
CellElevation(
|
|
98
|
+
cell_id=cell_id,
|
|
99
|
+
elevation_m=_mean(arr),
|
|
100
|
+
slope_deg=_mean(slope_deg(arr, cellsize=size)),
|
|
101
|
+
aspect_deg=float(np.median(not_flat)) if not_flat.size else None,
|
|
102
|
+
curvature=_mean(curvature(arr, cellsize=size)),
|
|
103
|
+
pixel_count=valid,
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
log.info("%d cells, %d with data", len(out), sum(1 for c in out if c.pixel_count))
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
__all__ = ["CellElevation", "cell_elevation"]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Lithology and distance from faults per cell, from vector maps.
|
|
2
|
+
|
|
3
|
+
- **lithology**: the label of the polygon that covers the largest area of the
|
|
4
|
+
cell (ties to the first label in lexical order);
|
|
5
|
+
- **weight**: whatever ``weight`` makes of that label. The susceptibility of a
|
|
6
|
+
rock is a calibration of the landslide model, not a property of the map, so
|
|
7
|
+
it is a parameter: no table ships here;
|
|
8
|
+
- **distance from faults**: geodesic metres from the cell centroid to the
|
|
9
|
+
nearest fault line, capped at ``cap_m`` (50 km by default): beyond it a cell
|
|
10
|
+
is "far from any mapped fault".
|
|
11
|
+
|
|
12
|
+
Every geometry is in EPSG:4326. Pure shapely: no raster.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import math
|
|
18
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
|
|
21
|
+
from shapely.geometry.base import BaseGeometry
|
|
22
|
+
from shapely.strtree import STRtree
|
|
23
|
+
|
|
24
|
+
#: Beyond this distance a cell is "far from any mapped fault".
|
|
25
|
+
DISTANCE_CAP_M = 50_000.0
|
|
26
|
+
EARTH_RADIUS_M = 6_371_008.8
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True, slots=True)
|
|
30
|
+
class LithologyPolygon:
|
|
31
|
+
geom: BaseGeometry
|
|
32
|
+
label: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class CellGeology:
|
|
37
|
+
cell_id: str
|
|
38
|
+
lithology: str | None
|
|
39
|
+
weight: float | None
|
|
40
|
+
distance_to_fault_m: float | None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def haversine_m(lon_a: float, lat_a: float, lon_b: float, lat_b: float) -> float:
|
|
44
|
+
"""Great-circle distance in metres on the mean Earth sphere."""
|
|
45
|
+
pa, pb = math.radians(lat_a), math.radians(lat_b)
|
|
46
|
+
dlat, dlon = math.radians(lat_b - lat_a), math.radians(lon_b - lon_a)
|
|
47
|
+
h = math.sin(dlat / 2) ** 2 + math.cos(pa) * math.cos(pb) * math.sin(dlon / 2) ** 2
|
|
48
|
+
return float(2 * EARTH_RADIUS_M * math.asin(math.sqrt(h)))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _dominant(
|
|
52
|
+
cell: BaseGeometry, tree: STRtree, polygons: Sequence[LithologyPolygon]
|
|
53
|
+
) -> str | None:
|
|
54
|
+
best: str | None = None
|
|
55
|
+
best_area = 0.0
|
|
56
|
+
for idx in tree.query(cell):
|
|
57
|
+
poly = polygons[int(idx)]
|
|
58
|
+
area = float(cell.intersection(poly.geom).area)
|
|
59
|
+
if area <= 0:
|
|
60
|
+
continue
|
|
61
|
+
if area > best_area or (area == best_area and best is not None and poly.label < best):
|
|
62
|
+
best_area, best = area, poly.label
|
|
63
|
+
return best
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _fault_distance(
|
|
67
|
+
cell: BaseGeometry, tree: STRtree, faults: Sequence[BaseGeometry], cap_m: float
|
|
68
|
+
) -> float:
|
|
69
|
+
centroid = cell.centroid
|
|
70
|
+
# A box of half a degree around the centroid: about 50 km at Italian latitudes.
|
|
71
|
+
candidates = [faults[int(i)] for i in tree.query(centroid.buffer(0.5))]
|
|
72
|
+
best = cap_m
|
|
73
|
+
for fault in candidates:
|
|
74
|
+
nearest = fault.interpolate(fault.project(centroid))
|
|
75
|
+
best = min(best, haversine_m(centroid.x, centroid.y, nearest.x, nearest.y))
|
|
76
|
+
return float(best)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def cell_geology(
|
|
80
|
+
cells: Mapping[str, BaseGeometry],
|
|
81
|
+
lithology: Sequence[LithologyPolygon],
|
|
82
|
+
faults: Sequence[BaseGeometry] | None = None,
|
|
83
|
+
*,
|
|
84
|
+
weight: Callable[[str], float | None] | None = None,
|
|
85
|
+
cap_m: float = DISTANCE_CAP_M,
|
|
86
|
+
) -> list[CellGeology]:
|
|
87
|
+
"""The lithology, its weight and the distance from the nearest fault of each cell.
|
|
88
|
+
|
|
89
|
+
No lithology polygon over a cell gives ``None`` (and no weight); no fault
|
|
90
|
+
map gives ``None`` distance; a fault map with nothing near gives ``cap_m``.
|
|
91
|
+
"""
|
|
92
|
+
polygons = [p for p in lithology if not p.geom.is_empty]
|
|
93
|
+
litho_tree = STRtree([p.geom for p in polygons]) if polygons else None
|
|
94
|
+
lines = [f for f in (faults or []) if not f.is_empty]
|
|
95
|
+
fault_tree = STRtree(lines) if lines else None
|
|
96
|
+
out: list[CellGeology] = []
|
|
97
|
+
for cell_id, geom in cells.items():
|
|
98
|
+
label = _dominant(geom, litho_tree, polygons) if litho_tree is not None else None
|
|
99
|
+
out.append(
|
|
100
|
+
CellGeology(
|
|
101
|
+
cell_id=cell_id,
|
|
102
|
+
lithology=label,
|
|
103
|
+
weight=None if label is None or weight is None else weight(label),
|
|
104
|
+
distance_to_fault_m=_fault_distance(geom, fault_tree, lines, cap_m)
|
|
105
|
+
if fault_tree is not None
|
|
106
|
+
else None,
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
__all__ = [
|
|
113
|
+
"DISTANCE_CAP_M",
|
|
114
|
+
"CellGeology",
|
|
115
|
+
"LithologyPolygon",
|
|
116
|
+
"cell_geology",
|
|
117
|
+
"haversine_m",
|
|
118
|
+
]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""The dominant land-cover class per cell, from a categorical raster (CORINE).
|
|
2
|
+
|
|
3
|
+
Each cell gets the most frequent valid code of the pixels inside it; ties go
|
|
4
|
+
to the smallest code, so the answer is deterministic. ``pixel_count`` tells "no
|
|
5
|
+
coverage" (0) from "sparse coverage".
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from shapely.geometry.base import BaseGeometry
|
|
17
|
+
|
|
18
|
+
from cell_terrain._reproject import reprojector
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class CellLandCover:
|
|
23
|
+
cell_id: str
|
|
24
|
+
#: The dominant class code as text (``"112"``), ``None`` with no valid pixel.
|
|
25
|
+
code: str | None
|
|
26
|
+
pixel_count: int
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def majority_class(values: Any, *, nodata: float | None) -> tuple[str | None, int]:
|
|
30
|
+
"""``(most frequent code, valid pixels)``; nodata and NaN are left out.
|
|
31
|
+
|
|
32
|
+
Ties resolve to the smallest code.
|
|
33
|
+
"""
|
|
34
|
+
arr = np.asarray(values).ravel()
|
|
35
|
+
if arr.dtype.kind == "f":
|
|
36
|
+
kept = arr[np.isfinite(arr)]
|
|
37
|
+
if nodata is not None:
|
|
38
|
+
kept = kept[kept != nodata]
|
|
39
|
+
else:
|
|
40
|
+
kept = arr if nodata is None else arr[arr != nodata]
|
|
41
|
+
if kept.size == 0:
|
|
42
|
+
return None, 0
|
|
43
|
+
classes, counts = np.unique(kept, return_counts=True)
|
|
44
|
+
best = int(np.lexsort((classes, -counts))[0])
|
|
45
|
+
return str(int(classes[best])), int(kept.size)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def cell_landcover(
|
|
49
|
+
raster: Path | str,
|
|
50
|
+
cells: Mapping[str, BaseGeometry],
|
|
51
|
+
*,
|
|
52
|
+
cells_crs: Any = 4326,
|
|
53
|
+
) -> list[CellLandCover]:
|
|
54
|
+
"""The dominant class of each cell of ``cells`` (id to polygon) in the raster at ``raster``.
|
|
55
|
+
|
|
56
|
+
Raises ``FileNotFoundError`` when the raster does not exist.
|
|
57
|
+
"""
|
|
58
|
+
import rasterio
|
|
59
|
+
from rasterio.crs import CRS
|
|
60
|
+
from rasterio.errors import RasterioError
|
|
61
|
+
from rasterio.mask import mask
|
|
62
|
+
|
|
63
|
+
path = Path(raster)
|
|
64
|
+
if not path.exists():
|
|
65
|
+
raise FileNotFoundError(f"land-cover raster not found: {path}")
|
|
66
|
+
out: list[CellLandCover] = []
|
|
67
|
+
with rasterio.open(path) as src:
|
|
68
|
+
nodata = src.nodata
|
|
69
|
+
reproject = reprojector(src_crs=CRS.from_user_input(cells_crs), dst_crs=src.crs)
|
|
70
|
+
for cell_id, geom in cells.items():
|
|
71
|
+
try:
|
|
72
|
+
data, _ = mask(src, [reproject(geom)], crop=True, filled=False)
|
|
73
|
+
except (ValueError, RasterioError):
|
|
74
|
+
out.append(CellLandCover(cell_id, None, 0))
|
|
75
|
+
continue
|
|
76
|
+
band = data[0]
|
|
77
|
+
if isinstance(band, np.ma.MaskedArray):
|
|
78
|
+
band = band.compressed()
|
|
79
|
+
code, n = majority_class(band, nodata=nodata)
|
|
80
|
+
out.append(CellLandCover(cell_id, code, n))
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
__all__ = ["CellLandCover", "cell_landcover", "majority_class"]
|
|
File without changes
|