EarthForge
A Python library for processing and visualizing GeoTIFF rasters, with vector support, built on rasterio, 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.
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.
Documentation: https://pyearthforge.readthedocs.io/ · Source: https://gitlab.com/earthforge/earthforge · PyPI: https://pypi.org/project/pyearthforge/
Status: early development (latest release: 0.1.1). The API may still change.
Installation
Requires Python 3.10+.
pip install pyearthforge # from PyPI: installs everything
pip install git+https://gitlab.com/earthforge/earthforge.git # newest, unreleased code from GitLab
The package is installed and imported as pyearthforge:
from pyearthforge import raster, vector, classifier, cluster, pca
Dependencies (installed automatically): rasterio, numpy, matplotlib, tqdm, psutil, geopandas, pyogrio, shapely, pandas, pyproj, pyarrow, openpyxl, scikit-learn, threadpoolctl, ipywidgets (progress bars in Jupyter), and XGBoost in its CPU version (xgboost-cpu on Windows and Linux, xgboost on macOS; no GPU packages). geopandas, scikit-learn and XGBoost are only imported when you use vector, classifier, cluster or pca.
For development (editable install, docs tools):
git clone https://gitlab.com/earthforge/earthforge.git
cd EarthForge
pip install -e ".[docs]"
Quick start
from pyearthforge import raster, vector
img = raster.image("sampleImage1.tif") # reads metadata only
img.meta() # print metadata, including band names
img.bandNames().size() # 26
# True-color composite
img.select("B4", "B3", "B2").visualize(gamma=1.2)
# NDVI with a built-in palette, saved as GeoTIFF
ndvi = img.normalizedDifference(["B8", "B4"], save="ndvi.tif").rename("NDVI")
ndvi.visualize(min=-0.2, max=0.8, palette="ndvi")
# Band math and expressions
ratio = img.select("B8") / img.select("B4")
evi = img.expression("2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))",
{"NIR": img.select("B8") * 0.0001, "RED": img.select("B4") * 0.0001,
"BLUE": img.select("B2") * 0.0001})
# Reclassify, shown with a legend
classes = ndvi.where((ndvi.lt(0.1), 1), (ndvi.gte(0.1).And(ndvi.lt(0.5)), 2),
(ndvi.gte(0.5), 3), otherwise=0)
classes.visualize(labels={1: "Water / bare", 2: "Sparse", 3: "Dense"},
palette=["0000FF", "D2B48C", "006400"])
# Pick and merge classes
dense = classes.eq(3) # 1 where class 3
veg = classes.selectClasses([2, 3]) # keep classes 2 and 3 only
merged = classes.mergeClasses([2, 3], into=2)
# Vectors: open, inspect, filter, add columns, join, clip
from pyearthforge.vector import Filter
stations = vector.Open("sample_data/stations.csv") # 600 sample points
stations.filter(Filter.eq("district", "North") & Filter.gt("rain_mm", 20)).show()
stations = stations.map(lambda f: f.set({"rain_cm": f.get("rain_mm") / 10}))
with_zone = stations.spatialJoin(vector.Open("sample_data/districts.geojson"))
aoi = vector.Open("boundary.shp") # also geojson, kml, kmz, gpkg, parquet, csv, xlsx
aoi.meta()
aoi.columns()
ndvi.clip(aoi).visualize(min=-0.2, max=0.8, palette="ndvi")
img.geometry().save("extent.geojson")
# Mosaic many tiles without loading them (streamed in parallel, with a progress bar)
raster.mosaic("tiles/").save("mosaic.tif")
# Supervised classification: labelled points -> samples -> train -> classify -> accuracy
from pyearthforge import classifier
bands = ["B2", "B3", "B4", "B8", "B11", "B12"]
points = vector.Open("sample_data/training_points.geojson") # "landcover": 0 water ... 3 forest
samples = img.select(bands).sampleRegions(points, properties=["landcover"]).randomColumn()
train = samples.filter(Filter.lt("random", 0.7))
test = samples.filter(Filter.gte("random", 0.7))
trained = classifier.randomForest(100).train(train, "landcover", bands) # or classifier.xgboost(200)
img.classify(trained).save("landcover.tif")
test.classify(trained).errorMatrix("landcover", "classification").info()
# Regression: map a measured number (here canopy cover of survey plots)
plots = vector.Open("sample_data/survey.xlsx", layer="2023")
plot_samples = img.select(bands).sampleRegions(plots, properties=["canopy_cover_pct"])
regressor = classifier.randomForest(200).setOutputMode("REGRESSION").train(plot_samples, "canopy_cover_pct", bands)
img.classify(regressor, "canopy_cover").visualize(min=0, max=100, palette="YlGn")
# Clustering and PCA
from pyearthforge import cluster, pca
trained = cluster.wekaKMeans(5).train(img.select("B2", "B3", "B4", "B8"), numPixels=5000)
img.cluster(trained).visualize(labels={i: f"Cluster {i}" for i in range(5)})
pcs = img.pca(pca.PCA(3).train(img.select("B2", "B3", "B4", "B8", "B11", "B12")))
# One file per band, and back again
img.select("B2", "B3", "B4", "B8").split(save="bands/")
stacked = raster.stack("bands/")
raster.showPalettes() # see every available palette
Documentation
Read it online: https://pyearthforge.readthedocs.io/, with docs for each released version. Updated on every push to main; a mirror is on GitLab Pages: https://earthforge.gitlab.io/earthforge/.
The documentation is a searchable website built with MkDocs Material. It includes an API reference generated from the docstrings. documentation.html is the same documentation as one file with search: download it and open it in a browser, offline.
pip install -e ".[docs]"
mkdocs serve # open http://127.0.0.1:8000
The same pages can also be read directly as Markdown:
| Section | Page | Contents |
|---|---|---|
| Home | Features, quick start, cheat sheet | |
| Images | Opening & inspecting | raster.image(), lazy evaluation, attributes, bandNames, meta |
| Bands | select, rename, addBands, split, raster.stack() |
|
| Extent, clip & masks | bounds, geometry, clip, updateMask |
|
| Saving | save(): streamed GeoTIFF export, data types, compression |
|
| Image processing | Band math | Arithmetic, operators, comparisons and logic, normalizedDifference |
| Expressions | expression(): text formulas |
|
| Reclassify & classes | where(), remap(), eq, selectClasses, mergeClasses |
|
| PCA | Principal component analysis of images and tables | |
| Mosaic | raster.mosaic(): combining tiles without loading them |
|
| Visualization | Visualize | visualize(): RGB composites, single bands, class maps |
| Palettes & legends | Built-in palettes, colormaps, legends, colorbars | |
| Vectors | Opening & inspecting | vector.Open(), formats, tables, meta, columnNames, show, get |
| Creating geometries | Rectangle, Polygon, Point, fromGeometry, buffer |
|
| Filtering & editing | filter with Filter, sort, limit, map and Feature |
|
| Joining datasets | merge, join, spatialJoin |
|
| Plotting & exporting | visualize, vectors on images, toGeoJSON, save |
|
| Machine learning | Sampling pixels | sample(), sampleRegions() |
| Supervised models | Classification | randomForest, xgboost, gradientTreeBoost, cart, svm, naiveBayes, confusion matrix, kappa, probabilities |
| Regression | setOutputMode("REGRESSION"): mapping measured values; RMSE, R², predicted-vs-actual chart |
|
| Unsupervised models | Clustering | k-means variants, cascade, X-means, Gaussian mixture |
| Machine learning on tables | Clustering, PCA and classification of table columns | |
| Reference | Memory & performance | How memory is kept low, benchmarks, tips |
| Errors | Exceptions and what causes them | |
| Number helpers | add, subtract |
|
| API reference | Generated from the docstrings | |
| Changelog | What changed in each version |
Sample data
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.
Package layout
pyearthforge/
├── __init__.py # public API: add, subtract, raster, vector, classifier, cluster, pca, errors, FULL_TRACEBACKS
├── add.py
├── subtract.py
├── raster.py # Image class, raster.image(), palettes, lazy evaluation engine
├── vector.py # Vector, Feature, Filter, vector.Open(), vector.layers()
├── classifier.py # supervised classification / regression (randomForest, xgboost, ...), ConfusionMatrix
├── cluster.py # clustering methods (kMeans, wekaKMeans, ...)
├── pca.py # principal component analysis
└── _errors.py # internal: short, clean error messages
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.
Releasing
New versions are published to PyPI automatically when a version tag (e.g. v0.1.1) is pushed to GitLab. See RELEASING.md.
License
MIT. See LICENSE.
Metadata
Release files for pyearthforge 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pyearthforge-0.1.1.tar.gz | 94.9 kB | Without provenance | Details for pyearthforge-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyearthforge-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for pyearthforge-0.1.1-py3-none-any.whl |
Total release size: 189.4 kB
Release files / pyearthforge-0.1.1.tar.gz
| Download URL | pyearthforge-0.1.1.tar.gz |
|---|---|
| Size | 94.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8c99baab81d68a678f89e9cff9a12effd761bebc714416760e27b2cedeeeaff2
|
|
BLAKE2b-256 checksum How to use checksums |
ec17ca9ddf44ebca50ff4111cd4beab5d8520328656f7a8e401a90e99656344d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Release files / pyearthforge-0.1.1-py3-none-any.whl
| Download URL | pyearthforge-0.1.1-py3-none-any.whl |
|---|---|
| Size | 94.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5448d55cdcaf77484941efa32f0e54dd6f98f272cdcbdb3aaca33a99aa48a5ab
|
|
BLAKE2b-256 checksum How to use checksums |
348975520703e6192a41a0aad18197741b7e53a2a185308e4d9479def638ff49
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Security for pyearthforge 0.1.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.