pyearthforge 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 msndma2025
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,233 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyearthforge
3
+ Version: 0.1.0
4
+ Summary: Lazy, memory-efficient raster processing and visualization for GeoTIFFs, with vector support, supervised classification and regression, clustering and PCA.
5
+ Author: msndma2025
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://gitlab.com/muddasir.ndma25/earthforge
8
+ Project-URL: Source, https://gitlab.com/muddasir.ndma25/earthforge
9
+ Project-URL: Issues, https://gitlab.com/muddasir.ndma25/earthforge/-/issues
10
+ Project-URL: Changelog, https://gitlab.com/muddasir.ndma25/earthforge/-/blob/main/CHANGELOG.md
11
+ Keywords: remote sensing,raster,geotiff,gis,rasterio,ndvi,satellite,classification,random forest,xgboost,land cover,clustering,pca,mosaic
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Scientific/Engineering :: GIS
18
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: rasterio>=1.3
23
+ Requires-Dist: numpy>=1.24
24
+ Requires-Dist: matplotlib>=3.7
25
+ Requires-Dist: tqdm>=4.60
26
+ Requires-Dist: psutil>=5.9
27
+ Requires-Dist: pandas>=2.0
28
+ Requires-Dist: geopandas>=0.14
29
+ Requires-Dist: pyogrio>=0.7
30
+ Requires-Dist: shapely>=2.0
31
+ Requires-Dist: pyproj>=3.5
32
+ Requires-Dist: pyarrow>=12
33
+ Requires-Dist: openpyxl>=3.1
34
+ Requires-Dist: scikit-learn>=1.3
35
+ Requires-Dist: threadpoolctl>=3.1
36
+ Provides-Extra: jupyter
37
+ Requires-Dist: ipywidgets>=8; extra == "jupyter"
38
+ Provides-Extra: xgboost
39
+ Requires-Dist: xgboost>=2.0; extra == "xgboost"
40
+ Provides-Extra: all
41
+ Requires-Dist: ipywidgets>=8; extra == "all"
42
+ Requires-Dist: xgboost>=2.0; extra == "all"
43
+ Provides-Extra: docs
44
+ Requires-Dist: mkdocs-material>=9; extra == "docs"
45
+ Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
46
+ Dynamic: license-file
47
+
48
+ # EarthForge
49
+
50
+ A Python library for processing and visualizing GeoTIFF rasters, with vector support, built on [rasterio](https://rasterio.readthedocs.io/), geopandas and matplotlib. It provides band selection (`select()`, `bandNames().size()`), band math, comparisons, `normalizedDifference()`, `expression()`, reclassification with `where()` and `remap()`, picking and merging classes, supervised classification and regression (random forest, XGBoost, gradient boosting, CART, SVM, naive Bayes) with accuracy assessment, clustering and PCA, clipping to vector boundaries, memory-safe mosaicking of many tiles, and `visualize()` with `min`/`max`/`gamma`/`palette`.
51
+
52
+ Images are **lazy**. Operations build a recipe, and pixels are read only when you visualize (as a downsampled preview) or save (streamed in blocks). Memory use stays small even for very large rasters, so it runs well on modest PCs.
53
+
54
+ > **Status:** early development (version 0.1). The API may still change.
55
+
56
+ ## Installation
57
+
58
+ Requires Python 3.10+.
59
+
60
+ ```bash
61
+ pip install git+https://gitlab.com/muddasir.ndma25/earthforge.git # latest version from GitLab
62
+ pip install pyearthforge # from PyPI, once published
63
+ pip install "pyearthforge[jupyter]" # plus progress-bar widgets for Jupyter
64
+ pip install "pyearthforge[xgboost]" # plus XGBoost, for classifier.xgboost()
65
+ ```
66
+
67
+ The package is installed and imported as **`pyearthforge`**:
68
+
69
+ ```python
70
+ from pyearthforge import raster, vector, classifier, cluster, pca
71
+ ```
72
+
73
+ Dependencies (installed automatically): `rasterio`, `numpy`, `matplotlib`, `tqdm`, `psutil`, `geopandas`, `pyogrio`, `shapely`, `pandas`, `pyproj`, `pyarrow`, `openpyxl`, `scikit-learn`, `threadpoolctl`. geopandas and scikit-learn are only imported when you use `vector`, `classifier`, `cluster` or `pca`. `xgboost` is optional (`pip install xgboost`); it is only needed for `classifier.xgboost()`.
74
+
75
+ For development (editable install, docs tools):
76
+
77
+ ```bash
78
+ git clone https://gitlab.com/muddasir.ndma25/earthforge.git
79
+ cd EarthForge
80
+ pip install -e ".[docs]"
81
+ ```
82
+
83
+ ## Quick start
84
+
85
+ ```python
86
+ from pyearthforge import raster, vector
87
+
88
+ img = raster.image("sampleImage1.tif") # reads metadata only
89
+ img.meta() # print metadata, including band names
90
+ img.bandNames().size() # 26
91
+
92
+ # True-color composite
93
+ img.select("B4", "B3", "B2").visualize(gamma=1.2)
94
+
95
+ # NDVI with a built-in palette, saved as GeoTIFF
96
+ ndvi = img.normalizedDifference(["B8", "B4"], save="ndvi.tif").rename("NDVI")
97
+ ndvi.visualize(min=-0.2, max=0.8, palette="ndvi")
98
+
99
+ # Band math and expressions
100
+ ratio = img.select("B8") / img.select("B4")
101
+ evi = img.expression("2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))",
102
+ {"NIR": img.select("B8") * 0.0001, "RED": img.select("B4") * 0.0001,
103
+ "BLUE": img.select("B2") * 0.0001})
104
+
105
+ # Reclassify, shown with a legend
106
+ classes = ndvi.where((ndvi.lt(0.1), 1), (ndvi.gte(0.1).And(ndvi.lt(0.5)), 2),
107
+ (ndvi.gte(0.5), 3), otherwise=0)
108
+ classes.visualize(labels={1: "Water / bare", 2: "Sparse", 3: "Dense"},
109
+ palette=["0000FF", "D2B48C", "006400"])
110
+
111
+ # Pick and merge classes
112
+ dense = classes.eq(3) # 1 where class 3
113
+ veg = classes.selectClasses([2, 3]) # keep classes 2 and 3 only
114
+ merged = classes.mergeClasses([2, 3], into=2)
115
+
116
+ # Vectors: open, inspect, filter, add columns, join, clip
117
+ from pyearthforge.vector import Filter
118
+ stations = vector.Open("sample_data/stations.csv") # 600 sample points
119
+ stations.filter(Filter.eq("district", "North") & Filter.gt("rain_mm", 20)).show()
120
+ stations = stations.map(lambda f: f.set({"rain_cm": f.get("rain_mm") / 10}))
121
+ with_zone = stations.spatialJoin(vector.Open("sample_data/districts.geojson"))
122
+
123
+ aoi = vector.Open("boundary.shp") # also geojson, kml, kmz, gpkg, parquet, csv, xlsx
124
+ aoi.meta()
125
+ aoi.columns()
126
+ ndvi.clip(aoi).visualize(min=-0.2, max=0.8, palette="ndvi")
127
+ img.geometry().save("extent.geojson")
128
+
129
+ # Mosaic many tiles without loading them (streamed in parallel, with a progress bar)
130
+ raster.mosaic("tiles/").save("mosaic.tif")
131
+
132
+ # Supervised classification: labelled points -> samples -> train -> classify -> accuracy
133
+ from pyearthforge import classifier
134
+ bands = ["B2", "B3", "B4", "B8", "B11", "B12"]
135
+ points = vector.Open("sample_data/training_points.geojson") # "landcover": 0 water ... 3 forest
136
+ samples = img.select(bands).sampleRegions(points, properties=["landcover"]).randomColumn()
137
+ train = samples.filter(Filter.lt("random", 0.7))
138
+ test = samples.filter(Filter.gte("random", 0.7))
139
+ trained = classifier.randomForest(100).train(train, "landcover", bands) # or classifier.xgboost(200)
140
+ img.classify(trained).save("landcover.tif")
141
+ test.classify(trained).errorMatrix("landcover", "classification").info()
142
+
143
+ # Regression: map a measured number (here canopy cover of survey plots)
144
+ plots = vector.Open("sample_data/survey.xlsx", layer="2023")
145
+ plot_samples = img.select(bands).sampleRegions(plots, properties=["canopy_cover_pct"])
146
+ regressor = classifier.randomForest(200).setOutputMode("REGRESSION").train(plot_samples, "canopy_cover_pct", bands)
147
+ img.classify(regressor, "canopy_cover").visualize(min=0, max=100, palette="YlGn")
148
+
149
+ # Clustering and PCA
150
+ from pyearthforge import cluster, pca
151
+ trained = cluster.wekaKMeans(5).train(img.select("B2", "B3", "B4", "B8"), numPixels=5000)
152
+ img.cluster(trained).visualize(labels={i: f"Cluster {i}" for i in range(5)})
153
+ pcs = img.pca(pca.PCA(3).train(img.select("B2", "B3", "B4", "B8", "B11", "B12")))
154
+
155
+ # One file per band, and back again
156
+ img.select("B2", "B3", "B4", "B8").split(save="bands/")
157
+ stacked = raster.stack("bands/")
158
+
159
+ raster.showPalettes() # see every available palette
160
+ ```
161
+
162
+ <img src="docs/images/visualize_rgb.png" width="32%"> <img src="docs/images/reclassify.png" width="32%"> <img src="docs/images/clip.png" width="32%">
163
+ <img src="docs/images/classification.png" width="32%"> <img src="docs/images/confusion_matrix.png" width="24%"> <img src="docs/images/canopy_cover.png" width="32%">
164
+
165
+ ## Documentation
166
+
167
+ The documentation is a searchable website built with MkDocs Material. It includes an API reference generated from the docstrings. [documentation.html](documentation.html) is the same documentation as one file with search: download it and open it in a browser, offline.
168
+
169
+ ```bash
170
+ pip install -e ".[docs]"
171
+ mkdocs serve # open http://127.0.0.1:8000
172
+ ```
173
+
174
+ The same pages can also be read directly as Markdown:
175
+
176
+ | Section | Page | Contents |
177
+ |---|---|---|
178
+ | | [Home](docs/index.md) | Features, quick start, cheat sheet |
179
+ | **Images** | [Opening & inspecting](docs/raster.md) | `raster.image()`, lazy evaluation, attributes, `bandNames`, `meta` |
180
+ | | [Bands](docs/bands.md) | `select`, `rename`, `addBands`, `split`, `raster.stack()` |
181
+ | | [Extent, clip & masks](docs/clip.md) | `bounds`, `geometry`, `clip`, `updateMask` |
182
+ | | [Saving](docs/save.md) | `save()`: streamed GeoTIFF export, data types, compression |
183
+ | *Image processing* | [Band math](docs/band-math.md) | Arithmetic, operators, comparisons and logic, `normalizedDifference` |
184
+ | | [Expressions](docs/expressions.md) | `expression()`: text formulas |
185
+ | | [Reclassify & classes](docs/reclassify.md) | `where()`, `remap()`, `eq`, `selectClasses`, `mergeClasses` |
186
+ | | [PCA](docs/pca.md) | Principal component analysis of images and tables |
187
+ | | [Mosaic](docs/mosaic.md) | `raster.mosaic()`: combining tiles without loading them |
188
+ | *Visualization* | [Visualize](docs/visualize.md) | `visualize()`: RGB composites, single bands, class maps |
189
+ | | [Palettes & legends](docs/palettes.md) | Built-in palettes, colormaps, legends, colorbars |
190
+ | **Vectors** | [Opening & inspecting](docs/vector.md) | `vector.Open()`, formats, tables, `meta`, `columnNames`, `show`, `get` |
191
+ | | [Creating geometries](docs/vector-geometries.md) | `Rectangle`, `Polygon`, `Point`, `fromGeometry`, `buffer` |
192
+ | | [Filtering & editing](docs/vector-records.md) | `filter` with `Filter`, `sort`, `limit`, `map` and `Feature` |
193
+ | | [Joining datasets](docs/vector-joins.md) | `merge`, `join`, `spatialJoin` |
194
+ | | [Plotting & exporting](docs/vector-export.md) | `visualize`, vectors on images, `toGeoJSON`, `save` |
195
+ | **Machine learning** | [Sampling pixels](docs/sampling.md) | `sample()`, `sampleRegions()` |
196
+ | *Supervised models* | [Classification](docs/classification.md) | `randomForest`, `xgboost`, `gradientTreeBoost`, `cart`, `svm`, `naiveBayes`, confusion matrix, kappa, probabilities |
197
+ | | [Regression](docs/regression.md) | `setOutputMode("REGRESSION")`: mapping measured values; RMSE, R², predicted-vs-actual chart |
198
+ | *Unsupervised models* | [Clustering](docs/clustering.md) | k-means variants, cascade, X-means, Gaussian mixture |
199
+ | | [Machine learning on tables](docs/vector-ml.md) | Clustering, PCA and classification of table columns |
200
+ | **Reference** | [Memory & performance](docs/performance.md) | How memory is kept low, benchmarks, tips |
201
+ | | [Errors](docs/errors.md) | Exceptions and what causes them |
202
+ | | [Number helpers](docs/math.md) | `add`, `subtract` |
203
+ | | [API reference](docs/api.md) | Generated from the docstrings |
204
+ | | [Changelog](CHANGELOG.md) | What changed in each version |
205
+
206
+ ## Sample data
207
+
208
+ `sample_data/` contains example datasets covering `sampleImage1.tif`: `stations.csv` (600 points), `survey.xlsx` (several sheets, with measured canopy cover), `districts.geojson` (5 polygons) and `training_points.geojson` (480 labelled land-cover points). Recreate them with `python sample_data/make_sample_data.py`.
209
+
210
+ ## Package layout
211
+
212
+ ```
213
+ pyearthforge/
214
+ ├── __init__.py # public API: add, subtract, raster, vector, classifier, cluster, pca, errors, FULL_TRACEBACKS
215
+ ├── add.py
216
+ ├── subtract.py
217
+ ├── raster.py # Image class, raster.image(), palettes, lazy evaluation engine
218
+ ├── vector.py # Vector, Feature, Filter, vector.Open(), vector.layers()
219
+ ├── classifier.py # supervised classification / regression (randomForest, xgboost, ...), ConfusionMatrix
220
+ ├── cluster.py # clustering methods (kMeans, wekaKMeans, ...)
221
+ ├── pca.py # principal component analysis
222
+ └── _errors.py # internal: short, clean error messages
223
+ ```
224
+
225
+ Everything listed in `pyearthforge/__init__.py` (`__all__`), plus the public names in `raster` (`image`, `mosaic`, `stack`, `Image`, `BandList`, `palettes`, `showPalettes`, `PALETTES`) and `vector` (`Open`, `layers`, `Vector`, `Feature`, `Filter`, `ColumnList`, `VectorNotFoundError`, `VectorReadError`), is public API. Names starting with `_` are internal and may change without notice.
226
+
227
+ ## Releasing
228
+
229
+ New versions are published to PyPI automatically when a version tag (e.g. `v0.1.1`) is pushed to GitLab. See [RELEASING.md](RELEASING.md).
230
+
231
+ ## License
232
+
233
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,186 @@
1
+ # EarthForge
2
+
3
+ A Python library for processing and visualizing GeoTIFF rasters, with vector support, built on [rasterio](https://rasterio.readthedocs.io/), geopandas and matplotlib. It provides band selection (`select()`, `bandNames().size()`), band math, comparisons, `normalizedDifference()`, `expression()`, reclassification with `where()` and `remap()`, picking and merging classes, supervised classification and regression (random forest, XGBoost, gradient boosting, CART, SVM, naive Bayes) with accuracy assessment, clustering and PCA, clipping to vector boundaries, memory-safe mosaicking of many tiles, and `visualize()` with `min`/`max`/`gamma`/`palette`.
4
+
5
+ Images are **lazy**. Operations build a recipe, and pixels are read only when you visualize (as a downsampled preview) or save (streamed in blocks). Memory use stays small even for very large rasters, so it runs well on modest PCs.
6
+
7
+ > **Status:** early development (version 0.1). The API may still change.
8
+
9
+ ## Installation
10
+
11
+ Requires Python 3.10+.
12
+
13
+ ```bash
14
+ pip install git+https://gitlab.com/muddasir.ndma25/earthforge.git # latest version from GitLab
15
+ pip install pyearthforge # from PyPI, once published
16
+ pip install "pyearthforge[jupyter]" # plus progress-bar widgets for Jupyter
17
+ pip install "pyearthforge[xgboost]" # plus XGBoost, for classifier.xgboost()
18
+ ```
19
+
20
+ The package is installed and imported as **`pyearthforge`**:
21
+
22
+ ```python
23
+ from pyearthforge import raster, vector, classifier, cluster, pca
24
+ ```
25
+
26
+ Dependencies (installed automatically): `rasterio`, `numpy`, `matplotlib`, `tqdm`, `psutil`, `geopandas`, `pyogrio`, `shapely`, `pandas`, `pyproj`, `pyarrow`, `openpyxl`, `scikit-learn`, `threadpoolctl`. geopandas and scikit-learn are only imported when you use `vector`, `classifier`, `cluster` or `pca`. `xgboost` is optional (`pip install xgboost`); it is only needed for `classifier.xgboost()`.
27
+
28
+ For development (editable install, docs tools):
29
+
30
+ ```bash
31
+ git clone https://gitlab.com/muddasir.ndma25/earthforge.git
32
+ cd EarthForge
33
+ pip install -e ".[docs]"
34
+ ```
35
+
36
+ ## Quick start
37
+
38
+ ```python
39
+ from pyearthforge import raster, vector
40
+
41
+ img = raster.image("sampleImage1.tif") # reads metadata only
42
+ img.meta() # print metadata, including band names
43
+ img.bandNames().size() # 26
44
+
45
+ # True-color composite
46
+ img.select("B4", "B3", "B2").visualize(gamma=1.2)
47
+
48
+ # NDVI with a built-in palette, saved as GeoTIFF
49
+ ndvi = img.normalizedDifference(["B8", "B4"], save="ndvi.tif").rename("NDVI")
50
+ ndvi.visualize(min=-0.2, max=0.8, palette="ndvi")
51
+
52
+ # Band math and expressions
53
+ ratio = img.select("B8") / img.select("B4")
54
+ evi = img.expression("2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))",
55
+ {"NIR": img.select("B8") * 0.0001, "RED": img.select("B4") * 0.0001,
56
+ "BLUE": img.select("B2") * 0.0001})
57
+
58
+ # Reclassify, shown with a legend
59
+ classes = ndvi.where((ndvi.lt(0.1), 1), (ndvi.gte(0.1).And(ndvi.lt(0.5)), 2),
60
+ (ndvi.gte(0.5), 3), otherwise=0)
61
+ classes.visualize(labels={1: "Water / bare", 2: "Sparse", 3: "Dense"},
62
+ palette=["0000FF", "D2B48C", "006400"])
63
+
64
+ # Pick and merge classes
65
+ dense = classes.eq(3) # 1 where class 3
66
+ veg = classes.selectClasses([2, 3]) # keep classes 2 and 3 only
67
+ merged = classes.mergeClasses([2, 3], into=2)
68
+
69
+ # Vectors: open, inspect, filter, add columns, join, clip
70
+ from pyearthforge.vector import Filter
71
+ stations = vector.Open("sample_data/stations.csv") # 600 sample points
72
+ stations.filter(Filter.eq("district", "North") & Filter.gt("rain_mm", 20)).show()
73
+ stations = stations.map(lambda f: f.set({"rain_cm": f.get("rain_mm") / 10}))
74
+ with_zone = stations.spatialJoin(vector.Open("sample_data/districts.geojson"))
75
+
76
+ aoi = vector.Open("boundary.shp") # also geojson, kml, kmz, gpkg, parquet, csv, xlsx
77
+ aoi.meta()
78
+ aoi.columns()
79
+ ndvi.clip(aoi).visualize(min=-0.2, max=0.8, palette="ndvi")
80
+ img.geometry().save("extent.geojson")
81
+
82
+ # Mosaic many tiles without loading them (streamed in parallel, with a progress bar)
83
+ raster.mosaic("tiles/").save("mosaic.tif")
84
+
85
+ # Supervised classification: labelled points -> samples -> train -> classify -> accuracy
86
+ from pyearthforge import classifier
87
+ bands = ["B2", "B3", "B4", "B8", "B11", "B12"]
88
+ points = vector.Open("sample_data/training_points.geojson") # "landcover": 0 water ... 3 forest
89
+ samples = img.select(bands).sampleRegions(points, properties=["landcover"]).randomColumn()
90
+ train = samples.filter(Filter.lt("random", 0.7))
91
+ test = samples.filter(Filter.gte("random", 0.7))
92
+ trained = classifier.randomForest(100).train(train, "landcover", bands) # or classifier.xgboost(200)
93
+ img.classify(trained).save("landcover.tif")
94
+ test.classify(trained).errorMatrix("landcover", "classification").info()
95
+
96
+ # Regression: map a measured number (here canopy cover of survey plots)
97
+ plots = vector.Open("sample_data/survey.xlsx", layer="2023")
98
+ plot_samples = img.select(bands).sampleRegions(plots, properties=["canopy_cover_pct"])
99
+ regressor = classifier.randomForest(200).setOutputMode("REGRESSION").train(plot_samples, "canopy_cover_pct", bands)
100
+ img.classify(regressor, "canopy_cover").visualize(min=0, max=100, palette="YlGn")
101
+
102
+ # Clustering and PCA
103
+ from pyearthforge import cluster, pca
104
+ trained = cluster.wekaKMeans(5).train(img.select("B2", "B3", "B4", "B8"), numPixels=5000)
105
+ img.cluster(trained).visualize(labels={i: f"Cluster {i}" for i in range(5)})
106
+ pcs = img.pca(pca.PCA(3).train(img.select("B2", "B3", "B4", "B8", "B11", "B12")))
107
+
108
+ # One file per band, and back again
109
+ img.select("B2", "B3", "B4", "B8").split(save="bands/")
110
+ stacked = raster.stack("bands/")
111
+
112
+ raster.showPalettes() # see every available palette
113
+ ```
114
+
115
+ <img src="docs/images/visualize_rgb.png" width="32%"> <img src="docs/images/reclassify.png" width="32%"> <img src="docs/images/clip.png" width="32%">
116
+ <img src="docs/images/classification.png" width="32%"> <img src="docs/images/confusion_matrix.png" width="24%"> <img src="docs/images/canopy_cover.png" width="32%">
117
+
118
+ ## Documentation
119
+
120
+ The documentation is a searchable website built with MkDocs Material. It includes an API reference generated from the docstrings. [documentation.html](documentation.html) is the same documentation as one file with search: download it and open it in a browser, offline.
121
+
122
+ ```bash
123
+ pip install -e ".[docs]"
124
+ mkdocs serve # open http://127.0.0.1:8000
125
+ ```
126
+
127
+ The same pages can also be read directly as Markdown:
128
+
129
+ | Section | Page | Contents |
130
+ |---|---|---|
131
+ | | [Home](docs/index.md) | Features, quick start, cheat sheet |
132
+ | **Images** | [Opening & inspecting](docs/raster.md) | `raster.image()`, lazy evaluation, attributes, `bandNames`, `meta` |
133
+ | | [Bands](docs/bands.md) | `select`, `rename`, `addBands`, `split`, `raster.stack()` |
134
+ | | [Extent, clip & masks](docs/clip.md) | `bounds`, `geometry`, `clip`, `updateMask` |
135
+ | | [Saving](docs/save.md) | `save()`: streamed GeoTIFF export, data types, compression |
136
+ | *Image processing* | [Band math](docs/band-math.md) | Arithmetic, operators, comparisons and logic, `normalizedDifference` |
137
+ | | [Expressions](docs/expressions.md) | `expression()`: text formulas |
138
+ | | [Reclassify & classes](docs/reclassify.md) | `where()`, `remap()`, `eq`, `selectClasses`, `mergeClasses` |
139
+ | | [PCA](docs/pca.md) | Principal component analysis of images and tables |
140
+ | | [Mosaic](docs/mosaic.md) | `raster.mosaic()`: combining tiles without loading them |
141
+ | *Visualization* | [Visualize](docs/visualize.md) | `visualize()`: RGB composites, single bands, class maps |
142
+ | | [Palettes & legends](docs/palettes.md) | Built-in palettes, colormaps, legends, colorbars |
143
+ | **Vectors** | [Opening & inspecting](docs/vector.md) | `vector.Open()`, formats, tables, `meta`, `columnNames`, `show`, `get` |
144
+ | | [Creating geometries](docs/vector-geometries.md) | `Rectangle`, `Polygon`, `Point`, `fromGeometry`, `buffer` |
145
+ | | [Filtering & editing](docs/vector-records.md) | `filter` with `Filter`, `sort`, `limit`, `map` and `Feature` |
146
+ | | [Joining datasets](docs/vector-joins.md) | `merge`, `join`, `spatialJoin` |
147
+ | | [Plotting & exporting](docs/vector-export.md) | `visualize`, vectors on images, `toGeoJSON`, `save` |
148
+ | **Machine learning** | [Sampling pixels](docs/sampling.md) | `sample()`, `sampleRegions()` |
149
+ | *Supervised models* | [Classification](docs/classification.md) | `randomForest`, `xgboost`, `gradientTreeBoost`, `cart`, `svm`, `naiveBayes`, confusion matrix, kappa, probabilities |
150
+ | | [Regression](docs/regression.md) | `setOutputMode("REGRESSION")`: mapping measured values; RMSE, R², predicted-vs-actual chart |
151
+ | *Unsupervised models* | [Clustering](docs/clustering.md) | k-means variants, cascade, X-means, Gaussian mixture |
152
+ | | [Machine learning on tables](docs/vector-ml.md) | Clustering, PCA and classification of table columns |
153
+ | **Reference** | [Memory & performance](docs/performance.md) | How memory is kept low, benchmarks, tips |
154
+ | | [Errors](docs/errors.md) | Exceptions and what causes them |
155
+ | | [Number helpers](docs/math.md) | `add`, `subtract` |
156
+ | | [API reference](docs/api.md) | Generated from the docstrings |
157
+ | | [Changelog](CHANGELOG.md) | What changed in each version |
158
+
159
+ ## Sample data
160
+
161
+ `sample_data/` contains example datasets covering `sampleImage1.tif`: `stations.csv` (600 points), `survey.xlsx` (several sheets, with measured canopy cover), `districts.geojson` (5 polygons) and `training_points.geojson` (480 labelled land-cover points). Recreate them with `python sample_data/make_sample_data.py`.
162
+
163
+ ## Package layout
164
+
165
+ ```
166
+ pyearthforge/
167
+ ├── __init__.py # public API: add, subtract, raster, vector, classifier, cluster, pca, errors, FULL_TRACEBACKS
168
+ ├── add.py
169
+ ├── subtract.py
170
+ ├── raster.py # Image class, raster.image(), palettes, lazy evaluation engine
171
+ ├── vector.py # Vector, Feature, Filter, vector.Open(), vector.layers()
172
+ ├── classifier.py # supervised classification / regression (randomForest, xgboost, ...), ConfusionMatrix
173
+ ├── cluster.py # clustering methods (kMeans, wekaKMeans, ...)
174
+ ├── pca.py # principal component analysis
175
+ └── _errors.py # internal: short, clean error messages
176
+ ```
177
+
178
+ Everything listed in `pyearthforge/__init__.py` (`__all__`), plus the public names in `raster` (`image`, `mosaic`, `stack`, `Image`, `BandList`, `palettes`, `showPalettes`, `PALETTES`) and `vector` (`Open`, `layers`, `Vector`, `Feature`, `Filter`, `ColumnList`, `VectorNotFoundError`, `VectorReadError`), is public API. Names starting with `_` are internal and may change without notice.
179
+
180
+ ## Releasing
181
+
182
+ New versions are published to PyPI automatically when a version tag (e.g. `v0.1.1`) is pushed to GitLab. See [RELEASING.md](RELEASING.md).
183
+
184
+ ## License
185
+
186
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,27 @@
1
+ """EarthForge: lazy, memory-efficient raster processing and visualization for GeoTIFFs.
2
+
3
+ from pyearthforge import raster, vector, cluster, classifier, pca
4
+
5
+ img = raster.image("scene.tif")
6
+ ndvi = img.normalizedDifference(["B8", "B4"]).rename("NDVI")
7
+ ndvi.visualize(min=-0.2, max=0.8, palette="ndvi")
8
+ ndvi.save("ndvi.tif")
9
+
10
+ Documentation: https://gitlab.com/muddasir.ndma25/earthforge
11
+ """
12
+
13
+ from .add import add
14
+ from .subtract import subtract
15
+ from . import raster # exposes the whole raster MODULE, so you call raster.image(), raster.meta()
16
+ from .raster import RasterNotFoundError, RasterReadError
17
+
18
+ # `vector`, `cluster`, `classifier` and `pca` are NOT imported here, so `from pyearthforge import raster`
19
+ # stays fast (geopandas / scikit-learn are only loaded when you use them).
20
+ # `from pyearthforge import vector, cluster, classifier, pca` still works: Python imports them on demand.
21
+
22
+ # Set to True to see the library's internal frames in tracebacks (for debugging).
23
+ FULL_TRACEBACKS = False
24
+
25
+ __all__ = ["add", "subtract", "raster", "vector", "cluster", "classifier", "pca",
26
+ "RasterNotFoundError", "RasterReadError"]
27
+ __version__ = "0.1.0"
@@ -0,0 +1,125 @@
1
+ # _errors.py -> short, clean error messages for the whole package (internal module)
2
+ #
3
+ # Errors raised by the library's own code are re-raised without the library's
4
+ # internal frames. In Jupyter / IPython only the user's code line and the
5
+ # message are shown. The errors keep their normal classes (ValueError, ...).
6
+ # Set `pyearthforge.FULL_TRACEBACKS = True` to see the internal frames when debugging.
7
+
8
+ import functools
9
+ import os
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ _PACKAGE_DIR = os.path.normcase(os.path.abspath(os.path.dirname(__file__)))
14
+ _PACKAGE = __name__.rpartition(".")[0]
15
+
16
+
17
+ class LibraryError(Exception):
18
+ """Base class for the library's own error types."""
19
+
20
+
21
+ def _in_package(filename):
22
+ return os.path.normcase(os.path.abspath(os.path.dirname(filename))) == _PACKAGE_DIR
23
+
24
+
25
+ def _full_tracebacks():
26
+ return bool(getattr(sys.modules.get(_PACKAGE), "FULL_TRACEBACKS", False))
27
+
28
+
29
+ def _raised_by_library(error):
30
+ """True if the error was raised by this package's code (not numpy, rasterio, ...)."""
31
+ tb = error.__traceback__
32
+ if tb is None:
33
+ return True
34
+ while tb.tb_next is not None:
35
+ tb = tb.tb_next
36
+ return _in_package(tb.tb_frame.f_code.co_filename)
37
+
38
+
39
+ def _frame_label(filename, lineno):
40
+ """'Cell In[3], line 2' for notebook cells, 'File path, line N' otherwise."""
41
+ try:
42
+ from IPython import get_ipython
43
+ shell = get_ipython()
44
+ count = shell.compile._filename_map.get(filename) if shell is not None else None
45
+ if count is not None:
46
+ return f"Cell In[{count}], line {lineno}"
47
+ except Exception:
48
+ pass
49
+ return f"File {filename}, line {lineno}"
50
+
51
+
52
+ class _ShortTraceback:
53
+ """Mixin for library errors: Jupyter/IPython shows only the user's code and the message.
54
+
55
+ IPython calls `_render_traceback_()` instead of printing the full traceback.
56
+ """
57
+
58
+ def _render_traceback_(self):
59
+ import traceback
60
+ red, reset = "\x1b[31m", "\x1b[39m"
61
+ name = type(self).__name__
62
+ lines = ["-" * 75, f"{red}{name}{reset}" + " " * max(1, 42 - len(name))
63
+ + "Traceback (most recent call last)"]
64
+ for frame in traceback.extract_tb(self.__traceback__):
65
+ if _in_package(frame.filename):
66
+ continue # library internals
67
+ if {"IPython", "ipykernel"} & set(Path(frame.filename).parts):
68
+ continue # notebook machinery
69
+ lines.append(_frame_label(frame.filename, frame.lineno))
70
+ if frame.line:
71
+ lines.append(f"----> {frame.line}")
72
+ lines += ["", f"{red}{name}{reset}: {self}"]
73
+ return lines
74
+
75
+
76
+ _SHORT_TYPES = {}
77
+
78
+
79
+ def _short_type(cls):
80
+ """A subclass of `cls` with the same name that has a short Jupyter traceback."""
81
+ if cls not in _SHORT_TYPES:
82
+ _SHORT_TYPES[cls] = type(cls.__name__, (_ShortTraceback, cls),
83
+ {"__module__": cls.__module__, "__qualname__": cls.__qualname__})
84
+ return _SHORT_TYPES[cls]
85
+
86
+
87
+ _CLEANED = (ValueError, TypeError, FileNotFoundError, LibraryError)
88
+
89
+
90
+ def clean_errors(func):
91
+ """Decorator: errors raised by the library show only the user's line and the message."""
92
+ @functools.wraps(func)
93
+ def wrapper(*args, **kwargs):
94
+ __tracebackhide__ = True # noqa: F841 (read by pytest)
95
+ try:
96
+ return func(*args, **kwargs)
97
+ except _CLEANED as error:
98
+ if _full_tracebacks() or not _raised_by_library(error):
99
+ raise
100
+ if not isinstance(error, _ShortTraceback):
101
+ error = _short_type(type(error))(*error.args)
102
+ raise error.with_traceback(None) from None
103
+ return wrapper
104
+
105
+
106
+ _OPERATOR_METHODS = {
107
+ "__init__", "__bool__", "__neg__", "__abs__", "__invert__", "__len__",
108
+ "__add__", "__radd__", "__sub__", "__rsub__", "__mul__", "__rmul__",
109
+ "__truediv__", "__rtruediv__", "__pow__", "__rpow__",
110
+ "__lt__", "__le__", "__gt__", "__ge__", "__and__", "__rand__", "__or__", "__ror__",
111
+ }
112
+
113
+
114
+ def clean_class(cls):
115
+ """Apply clean_errors to every public method (and operators) of a class."""
116
+ for name, attr in list(vars(cls).items()):
117
+ if name.startswith("_") and name not in _OPERATOR_METHODS:
118
+ continue
119
+ if isinstance(attr, staticmethod): # keep static methods static
120
+ setattr(cls, name, staticmethod(clean_errors(attr.__func__)))
121
+ elif isinstance(attr, classmethod):
122
+ setattr(cls, name, classmethod(clean_errors(attr.__func__)))
123
+ elif callable(attr):
124
+ setattr(cls, name, clean_errors(attr))
125
+ return cls
@@ -0,0 +1,21 @@
1
+ def add(a, b):
2
+ """Returns the sum of a and b.
3
+
4
+ Works with anything that supports ``+``: numbers, NumPy arrays and Images.
5
+
6
+ Parameters
7
+ ----------
8
+ a, b : number, numpy.ndarray or Image
9
+
10
+ Returns
11
+ -------
12
+ The same type as the inputs: a + b.
13
+
14
+ Examples
15
+ --------
16
+ >>> from pyearthforge import add
17
+ >>> add(3, 4)
18
+ 7
19
+ >>> add(img.select("B4").data, 100) # NumPy array + number
20
+ """
21
+ return a + b