Metadata-Version: 2.4
Name: pyearthforge
Version: 0.1.0
Summary: Lazy, memory-efficient raster processing and visualization for GeoTIFFs, with vector support, supervised classification and regression, clustering and PCA.
Author: msndma2025
License-Expression: MIT
Project-URL: Homepage, https://gitlab.com/muddasir.ndma25/earthforge
Project-URL: Source, https://gitlab.com/muddasir.ndma25/earthforge
Project-URL: Issues, https://gitlab.com/muddasir.ndma25/earthforge/-/issues
Project-URL: Changelog, https://gitlab.com/muddasir.ndma25/earthforge/-/blob/main/CHANGELOG.md
Keywords: remote sensing,raster,geotiff,gis,rasterio,ndvi,satellite,classification,random forest,xgboost,land cover,clustering,pca,mosaic
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Scientific/Engineering :: Image Processing
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: rasterio>=1.3
Requires-Dist: numpy>=1.24
Requires-Dist: matplotlib>=3.7
Requires-Dist: tqdm>=4.60
Requires-Dist: psutil>=5.9
Requires-Dist: pandas>=2.0
Requires-Dist: geopandas>=0.14
Requires-Dist: pyogrio>=0.7
Requires-Dist: shapely>=2.0
Requires-Dist: pyproj>=3.5
Requires-Dist: pyarrow>=12
Requires-Dist: openpyxl>=3.1
Requires-Dist: scikit-learn>=1.3
Requires-Dist: threadpoolctl>=3.1
Provides-Extra: jupyter
Requires-Dist: ipywidgets>=8; extra == "jupyter"
Provides-Extra: xgboost
Requires-Dist: xgboost>=2.0; extra == "xgboost"
Provides-Extra: all
Requires-Dist: ipywidgets>=8; extra == "all"
Requires-Dist: xgboost>=2.0; extra == "all"
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
Dynamic: license-file

# EarthForge

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

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

```bash
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`**:

```python
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):

```bash
git clone https://gitlab.com/muddasir.ndma25/earthforge.git
cd EarthForge
pip install -e ".[docs]"
```

## Quick start

```python
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
```

<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%">
<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%">

## Documentation

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.

```bash
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](docs/index.md) | Features, quick start, cheat sheet |
| **Images** | [Opening & inspecting](docs/raster.md) | `raster.image()`, lazy evaluation, attributes, `bandNames`, `meta` |
| | [Bands](docs/bands.md) | `select`, `rename`, `addBands`, `split`, `raster.stack()` |
| | [Extent, clip & masks](docs/clip.md) | `bounds`, `geometry`, `clip`, `updateMask` |
| | [Saving](docs/save.md) | `save()`: streamed GeoTIFF export, data types, compression |
| *Image processing* | [Band math](docs/band-math.md) | Arithmetic, operators, comparisons and logic, `normalizedDifference` |
| | [Expressions](docs/expressions.md) | `expression()`: text formulas |
| | [Reclassify & classes](docs/reclassify.md) | `where()`, `remap()`, `eq`, `selectClasses`, `mergeClasses` |
| | [PCA](docs/pca.md) | Principal component analysis of images and tables |
| | [Mosaic](docs/mosaic.md) | `raster.mosaic()`: combining tiles without loading them |
| *Visualization* | [Visualize](docs/visualize.md) | `visualize()`: RGB composites, single bands, class maps |
| | [Palettes & legends](docs/palettes.md) | Built-in palettes, colormaps, legends, colorbars |
| **Vectors** | [Opening & inspecting](docs/vector.md) | `vector.Open()`, formats, tables, `meta`, `columnNames`, `show`, `get` |
| | [Creating geometries](docs/vector-geometries.md) | `Rectangle`, `Polygon`, `Point`, `fromGeometry`, `buffer` |
| | [Filtering & editing](docs/vector-records.md) | `filter` with `Filter`, `sort`, `limit`, `map` and `Feature` |
| | [Joining datasets](docs/vector-joins.md) | `merge`, `join`, `spatialJoin` |
| | [Plotting & exporting](docs/vector-export.md) | `visualize`, vectors on images, `toGeoJSON`, `save` |
| **Machine learning** | [Sampling pixels](docs/sampling.md) | `sample()`, `sampleRegions()` |
| *Supervised models* | [Classification](docs/classification.md) | `randomForest`, `xgboost`, `gradientTreeBoost`, `cart`, `svm`, `naiveBayes`, confusion matrix, kappa, probabilities |
| | [Regression](docs/regression.md) | `setOutputMode("REGRESSION")`: mapping measured values; RMSE, R², predicted-vs-actual chart |
| *Unsupervised models* | [Clustering](docs/clustering.md) | k-means variants, cascade, X-means, Gaussian mixture |
| | [Machine learning on tables](docs/vector-ml.md) | Clustering, PCA and classification of table columns |
| **Reference** | [Memory & performance](docs/performance.md) | How memory is kept low, benchmarks, tips |
| | [Errors](docs/errors.md) | Exceptions and what causes them |
| | [Number helpers](docs/math.md) | `add`, `subtract` |
| | [API reference](docs/api.md) | Generated from the docstrings |
| | [Changelog](CHANGELOG.md) | 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](RELEASING.md).

## License

MIT. See [LICENSE](LICENSE).
