Skip to main content

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.

Status: early development (version 0.1). The API may still change.

Installation

Requires Python 3.10+.

pip install git+https://gitlab.com/muddasir.ndma25/earthforge.git     # latest version from GitLab
pip install pyearthforge                                          # from PyPI, once published
pip install "pyearthforge[jupyter]"                               # plus progress-bar widgets for Jupyter
pip install "pyearthforge[xgboost]"                               # plus XGBoost, for classifier.xgboost()

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. 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().

For development (editable install, docs tools):

git clone https://gitlab.com/muddasir.ndma25/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

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.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyearthforge 0.1.0
File Size Uploaded Provenance Actions
pyearthforge-0.1.0.tar.gz 94.3 kB Without provenance Details for pyearthforge-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyearthforge 0.1.0
File Interpreter ABI Platform Actions
pyearthforge-0.1.0-py3-none-any.whl Python 3 none any Details for pyearthforge-0.1.0-py3-none-any.whl

Total release size: 188.6 kB

Release files / pyearthforge-0.1.0.tar.gz

Download URL pyearthforge-0.1.0.tar.gz
Size 94.3 kB
Tags Source
SHA-256 checksum
How to use checksums
fccb968f14d148ec38e60408bcd4586685c12a7918da50f35a25290821c66b3c
BLAKE2b-256 checksum
How to use checksums
b19d612be1c7f6cbf85c742af69b2700de95e04e37b9e12c956a995f82bce9f9
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.0-py3-none-any.whl

Download URL pyearthforge-0.1.0-py3-none-any.whl
Size 94.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
64f9f7f45446c9b8f9a1d1e1724737fbac6b62e753128a008ad98819a31b44d4
BLAKE2b-256 checksum
How to use checksums
5830e9fc37f8455f300cd472671688e465f670b4a826f3fcbb27bd7fb1f55c79
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.0

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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page