plaknit 0.3.0__tar.gz → 0.3.2__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.
Files changed (48) hide show
  1. {plaknit-0.3.0/plaknit.egg-info → plaknit-0.3.2}/PKG-INFO +34 -3
  2. {plaknit-0.3.0 → plaknit-0.3.2}/README.md +28 -2
  3. plaknit-0.3.2/plaknit/__init__.py +30 -0
  4. plaknit-0.3.2/plaknit/acquisition/__init__.py +10 -0
  5. {plaknit-0.3.0/plaknit → plaknit-0.3.2/plaknit/acquisition}/geometry.py +83 -0
  6. plaknit-0.3.2/plaknit/classify.py +17 -0
  7. plaknit-0.3.2/plaknit/cli/__init__.py +5 -0
  8. {plaknit-0.3.0/plaknit → plaknit-0.3.2/plaknit/cli}/classify_cli.py +13 -1
  9. plaknit-0.3.2/plaknit/cli/ensemble_cli.py +348 -0
  10. plaknit-0.3.0/plaknit/cli.py → plaknit-0.3.2/plaknit/cli/main.py +7 -4
  11. plaknit-0.3.2/plaknit/data/__init__.py +19 -0
  12. plaknit-0.3.2/plaknit/data/raster.py +340 -0
  13. plaknit-0.3.2/plaknit/data/sampling.py +338 -0
  14. plaknit-0.3.2/plaknit/models/__init__.py +3 -0
  15. plaknit-0.3.2/plaknit/models/brt.py +902 -0
  16. plaknit-0.3.2/plaknit/models/ensemble.py +757 -0
  17. plaknit-0.3.0/plaknit/classify.py → plaknit-0.3.2/plaknit/models/rf.py +83 -776
  18. plaknit-0.3.2/plaknit/processing/__init__.py +23 -0
  19. plaknit-0.3.2/plaknit/processing/evaluation.py +381 -0
  20. {plaknit-0.3.0 → plaknit-0.3.2/plaknit.egg-info}/PKG-INFO +34 -3
  21. plaknit-0.3.2/plaknit.egg-info/SOURCES.txt +39 -0
  22. plaknit-0.3.2/plaknit.egg-info/entry_points.txt +2 -0
  23. {plaknit-0.3.0 → plaknit-0.3.2}/plaknit.egg-info/requires.txt +6 -0
  24. {plaknit-0.3.0 → plaknit-0.3.2}/pyproject.toml +4 -3
  25. {plaknit-0.3.0 → plaknit-0.3.2}/requirements.txt +2 -0
  26. plaknit-0.3.2/tests/test_classify.py +250 -0
  27. plaknit-0.3.2/tests/test_ensemble_cli.py +108 -0
  28. plaknit-0.3.2/tests/test_geometry.py +70 -0
  29. {plaknit-0.3.0 → plaknit-0.3.2}/tests/test_mosaic.py +1 -1
  30. {plaknit-0.3.0 → plaknit-0.3.2}/tests/test_orders.py +1 -1
  31. plaknit-0.3.2/tests/test_plaknit.py +19 -0
  32. {plaknit-0.3.0 → plaknit-0.3.2}/tests/test_planner.py +1 -1
  33. plaknit-0.3.2/tests/test_shared_helpers.py +182 -0
  34. plaknit-0.3.0/plaknit/__init__.py +0 -18
  35. plaknit-0.3.0/plaknit/common.py +0 -6
  36. plaknit-0.3.0/plaknit/plaknit.py +0 -1
  37. plaknit-0.3.0/plaknit.egg-info/SOURCES.txt +0 -26
  38. plaknit-0.3.0/plaknit.egg-info/entry_points.txt +0 -2
  39. plaknit-0.3.0/tests/test_geometry.py +0 -31
  40. plaknit-0.3.0/tests/test_plaknit.py +0 -20
  41. {plaknit-0.3.0 → plaknit-0.3.2}/LICENSE +0 -0
  42. {plaknit-0.3.0 → plaknit-0.3.2}/MANIFEST.in +0 -0
  43. {plaknit-0.3.0/plaknit → plaknit-0.3.2/plaknit/acquisition}/mosaic.py +0 -0
  44. {plaknit-0.3.0/plaknit → plaknit-0.3.2/plaknit/acquisition}/orders.py +0 -0
  45. {plaknit-0.3.0/plaknit → plaknit-0.3.2/plaknit/acquisition}/planner.py +0 -0
  46. {plaknit-0.3.0 → plaknit-0.3.2}/plaknit.egg-info/dependency_links.txt +0 -0
  47. {plaknit-0.3.0 → plaknit-0.3.2}/plaknit.egg-info/top_level.txt +0 -0
  48. {plaknit-0.3.0 → plaknit-0.3.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plaknit
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: Processing Large-Scale PlanetScope Data
5
5
  Author-email: Dryver Finch <dryver2206@gmail.com>
6
6
  License: MIT License
@@ -29,8 +29,13 @@ Requires-Dist: rasterio
29
29
  Requires-Dist: requests
30
30
  Requires-Dist: rich
31
31
  Requires-Dist: scikit-learn
32
+ Requires-Dist: scipy
33
+ Requires-Dist: xgboost
32
34
  Provides-Extra: extra
33
35
  Requires-Dist: pandas; extra == "extra"
36
+ Provides-Extra: gpu
37
+ Requires-Dist: cupy; extra == "gpu"
38
+ Requires-Dist: xgboost[gpu]; extra == "gpu"
34
39
  Provides-Extra: all
35
40
  Requires-Dist: pandas; extra == "all"
36
41
  Dynamic: license-file
@@ -44,7 +49,7 @@ Dynamic: license-file
44
49
 
45
50
  **Processing Large-Scale PlanetScope Data**
46
51
 
47
- > Note: plaknit is in active early-stage development. Expect frequent updates, and please share feedback or ideas through the GitHub Issues tab.
52
+ > Note: plaknit is fully operational as of v0.3.0. Continue to look for updates, and please share feedback or ideas through the GitHub Issues tab.
48
53
 
49
54
  PlanetScope Scene (PSS) data are reveared for its quality and distinct ability to
50
55
  balance spatial and temporal resolution in Earth Observation data. While PSS has
@@ -70,4 +75,30 @@ spend time answering big questions, not making a big mess of your data.
70
75
  - Planning workflow that searches Planet's STAC/Data API and scores scenes, with ordering handled by a separate `plaknit order` workflow.
71
76
  - GDAL-powered parallel masking of Planet strips with their UDM rasters.
72
77
  - Tuned Orfeo Toolbox mosaicking pipeline with RAM hints for large jobs.
73
- - Random Forest training + inference utilities for classifying Planet stacks.
78
+ - Random Forest and Boosted Regression Tree ensemble training + inference utilities for classifying Planet stacks.
79
+
80
+ ## Quick Start
81
+
82
+ ### Train a BRT Ensemble Classifier
83
+
84
+ ```bash
85
+ plaknit brt train \
86
+ --image stack.tif \
87
+ --labels training.gpkg \
88
+ --label-column class_id \
89
+ --output ./brt_ensemble/ \
90
+ --n-models 5 \
91
+ --gpu
92
+ ```
93
+
94
+ ### Apply the Ensemble to New Imagery
95
+
96
+ ```bash
97
+ plaknit brt predict \
98
+ --image new_stack.tif \
99
+ --ensemble-dir ./brt_ensemble/ \
100
+ --output-dir ./probability_outputs/ \
101
+ --feature-importance-out predictor_importance.csv
102
+ ```
103
+
104
+ See [Usage](https://dzfinch.github.io/plaknit/usage.html) for complete examples and all supported options.
@@ -7,7 +7,7 @@
7
7
 
8
8
  **Processing Large-Scale PlanetScope Data**
9
9
 
10
- > Note: plaknit is in active early-stage development. Expect frequent updates, and please share feedback or ideas through the GitHub Issues tab.
10
+ > Note: plaknit is fully operational as of v0.3.0. Continue to look for updates, and please share feedback or ideas through the GitHub Issues tab.
11
11
 
12
12
  PlanetScope Scene (PSS) data are reveared for its quality and distinct ability to
13
13
  balance spatial and temporal resolution in Earth Observation data. While PSS has
@@ -33,4 +33,30 @@ spend time answering big questions, not making a big mess of your data.
33
33
  - Planning workflow that searches Planet's STAC/Data API and scores scenes, with ordering handled by a separate `plaknit order` workflow.
34
34
  - GDAL-powered parallel masking of Planet strips with their UDM rasters.
35
35
  - Tuned Orfeo Toolbox mosaicking pipeline with RAM hints for large jobs.
36
- - Random Forest training + inference utilities for classifying Planet stacks.
36
+ - Random Forest and Boosted Regression Tree ensemble training + inference utilities for classifying Planet stacks.
37
+
38
+ ## Quick Start
39
+
40
+ ### Train a BRT Ensemble Classifier
41
+
42
+ ```bash
43
+ plaknit brt train \
44
+ --image stack.tif \
45
+ --labels training.gpkg \
46
+ --label-column class_id \
47
+ --output ./brt_ensemble/ \
48
+ --n-models 5 \
49
+ --gpu
50
+ ```
51
+
52
+ ### Apply the Ensemble to New Imagery
53
+
54
+ ```bash
55
+ plaknit brt predict \
56
+ --image new_stack.tif \
57
+ --ensemble-dir ./brt_ensemble/ \
58
+ --output-dir ./probability_outputs/ \
59
+ --feature-importance-out predictor_importance.csv
60
+ ```
61
+
62
+ See [Usage](https://dzfinch.github.io/plaknit/usage.html) for complete examples and all supported options.
@@ -0,0 +1,30 @@
1
+ """Top-level package for plaknit."""
2
+
3
+ from .acquisition import geometry, mosaic, orders, planner
4
+ from .acquisition.geometry import distance_to_vector
5
+ from .acquisition.orders import submit_orders_for_plan
6
+ from .acquisition.planner import plan_monthly_composites, write_plan
7
+ from .models.brt import predict_brt, train_brt
8
+ from .models.ensemble import BRTEnsemble
9
+ from .models.rf import predict_rf, smooth_probs, train_rf
10
+
11
+ __author__ = """Dryver Finch"""
12
+ __email__ = "dryver2206@gmail.com"
13
+ __version__ = "0.3.2"
14
+
15
+ __all__ = [
16
+ "BRTEnsemble",
17
+ "distance_to_vector",
18
+ "geometry",
19
+ "mosaic",
20
+ "orders",
21
+ "plan_monthly_composites",
22
+ "planner",
23
+ "predict_brt",
24
+ "predict_rf",
25
+ "smooth_probs",
26
+ "submit_orders_for_plan",
27
+ "train_brt",
28
+ "train_rf",
29
+ "write_plan",
30
+ ]
@@ -0,0 +1,10 @@
1
+ """Acquisition subpackage for plaknit.
2
+
3
+ This package groups geometry, planning, ordering, and mosaic workflow modules under
4
+ one import path so callers can use ``from plaknit.acquisition import ...`` without
5
+ relying on implicit namespace package behavior.
6
+ """
7
+
8
+ from . import geometry, mosaic, orders, planner
9
+
10
+ __all__ = ["geometry", "mosaic", "orders", "planner"]
@@ -2,9 +2,14 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from pathlib import Path
5
6
  from typing import Tuple
6
7
 
7
8
  import geopandas as gpd
9
+ import numpy as np
10
+ import rasterio
11
+ from rasterio.features import rasterize
12
+ from scipy.ndimage import distance_transform_edt
8
13
  from shapely.geometry import base as shapely_geom
9
14
 
10
15
 
@@ -139,9 +144,87 @@ def simplify_geometry_to_vertex_limit(
139
144
  )
140
145
 
141
146
 
147
+ def distance_to_vector(
148
+ template_raster: str | Path,
149
+ vector_path: str | Path,
150
+ output_raster: str | Path,
151
+ *,
152
+ backend: str = "cpu",
153
+ ) -> None:
154
+ """Write distances from every template cell to vector features.
155
+
156
+ The template controls the output extent, resolution, transform, and CRS.
157
+ Distances use the template CRS map units. Vector and raster formats are
158
+ those supported by GeoPandas and Rasterio, respectively.
159
+ """
160
+
161
+ if backend not in {"cpu", "gpu"}:
162
+ raise ValueError("backend must be 'cpu' or 'gpu'")
163
+
164
+ with rasterio.open(template_raster) as source:
165
+ if source.crs is None:
166
+ raise ValueError("Input raster has no CRS.")
167
+ if source.crs.is_geographic:
168
+ raise ValueError(
169
+ "Input raster is geographic. Reproject it to a projected CRS "
170
+ "before calculating Euclidean distances."
171
+ )
172
+ if source.transform.b != 0 or source.transform.d != 0:
173
+ raise ValueError("Rotated or sheared rasters are not supported.")
174
+
175
+ vector = gpd.read_file(vector_path)
176
+ if vector.empty or vector.geometry.dropna().empty:
177
+ raise ValueError(f"No geometries found in '{vector_path}'.")
178
+ if vector.crs is None:
179
+ raise ValueError("Input vector has no CRS.")
180
+ vector = vector.to_crs(source.crs)
181
+ geometries = [
182
+ geometry
183
+ for geometry in vector.geometry
184
+ if geometry is not None and not geometry.is_empty
185
+ ]
186
+ if not geometries:
187
+ raise ValueError(f"No non-empty geometries found in '{vector_path}'.")
188
+
189
+ vector_mask = rasterize(
190
+ ((geometry, 1) for geometry in geometries),
191
+ out_shape=(source.height, source.width),
192
+ transform=source.transform,
193
+ fill=0,
194
+ dtype="uint8",
195
+ )
196
+ non_vector = (vector_mask == 0).astype("uint8")
197
+ sampling = (abs(source.transform.e), abs(source.transform.a))
198
+
199
+ if backend == "gpu":
200
+ try:
201
+ import cupy as cp
202
+ from cupyx.scipy.ndimage import (
203
+ distance_transform_edt as gpu_distance_transform_edt,
204
+ )
205
+ except ImportError as exc:
206
+ raise ImportError(
207
+ "The GPU backend requires CuPy; install a CUDA-matched "
208
+ "cupy package or use backend='cpu'."
209
+ ) from exc
210
+ distances = cp.asnumpy(
211
+ gpu_distance_transform_edt(cp.asarray(non_vector), sampling=sampling)
212
+ )
213
+ else:
214
+ distances = distance_transform_edt(non_vector, sampling=sampling)
215
+
216
+ distances = distances.astype("float32", copy=False)
217
+ distances[vector_mask == 1] = 0.0
218
+ profile = source.profile.copy()
219
+ profile.update(count=1, dtype="float32", nodata=None)
220
+ with rasterio.open(output_raster, "w", **profile) as destination:
221
+ destination.write(distances, 1)
222
+
223
+
142
224
  __all__ = [
143
225
  "load_aoi_geometry",
144
226
  "reproject_geometry",
145
227
  "geometry_vertex_count",
146
228
  "simplify_geometry_to_vertex_limit",
229
+ "distance_to_vector",
147
230
  ]
@@ -0,0 +1,17 @@
1
+ """Public classification API for plaknit.
2
+
3
+ This module is the stable import path for random-forest (RF) and boosted regression tree (BRT)
4
+ training and prediction. The ``plaknit.compat`` path remains only as a deprecated compatibility alias.
5
+ """
6
+
7
+ from .models.brt import predict_brt, train_brt
8
+ from .models.rf import _open_raster_stack, predict_rf, smooth_probs, train_rf
9
+
10
+ __all__ = [
11
+ "_open_raster_stack",
12
+ "predict_brt",
13
+ "predict_rf",
14
+ "smooth_probs",
15
+ "train_brt",
16
+ "train_rf",
17
+ ]
@@ -0,0 +1,5 @@
1
+ """CLI entrypoints for model training and prediction."""
2
+
3
+ from .main import main
4
+
5
+ __all__ = ["main"]
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  import argparse
6
6
  from typing import List, Optional, Sequence
7
7
 
8
- from .classify import predict_rf, smooth_probs, train_rf
8
+ from ..models.rf import predict_rf, smooth_probs, train_rf
9
9
 
10
10
 
11
11
  def _add_common_smoothing_args(parser: argparse.ArgumentParser) -> None:
@@ -146,6 +146,12 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
146
146
  "sample per class per grid cell."
147
147
  ),
148
148
  )
149
+ train_parser.add_argument(
150
+ "--training-buffer-meters",
151
+ type=float,
152
+ default=0.0,
153
+ help="Buffer training geometries by this many meters when extracting pixels.",
154
+ )
149
155
 
150
156
  predict_parser = subparsers.add_parser(
151
157
  "predict", help="Apply a trained model to classify a raster stack."
@@ -174,6 +180,10 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
174
180
  "--probs-out",
175
181
  help="Optional output path for class probability GeoTIFF.",
176
182
  )
183
+ predict_parser.add_argument(
184
+ "--binary-out",
185
+ help="Optional directory for one binary GeoTIFF per class.",
186
+ )
177
187
  predict_parser.add_argument(
178
188
  "--block-shape",
179
189
  nargs=2,
@@ -239,6 +249,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
239
249
  n_jobs=args.jobs,
240
250
  test_fraction=args.test_fraction,
241
251
  grid_size=args.grid_size,
252
+ training_buffer_meters=args.training_buffer_meters,
242
253
  )
243
254
  return 0
244
255
 
@@ -278,6 +289,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
278
289
  bayes_neigh_fraction=args.bayes_neigh_fraction,
279
290
  bayes_smoothness=args.bayes_smoothness,
280
291
  probs_out=args.probs_out,
292
+ binary_out=args.binary_out,
281
293
  block_overlap=args.block_overlap,
282
294
  jobs=args.jobs,
283
295
  )
@@ -0,0 +1,348 @@
1
+ """Command-line interface for Boosted Regression Tree (BRT) ensemble training and prediction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from typing import List, Optional, Sequence
7
+
8
+ from ..models.brt import train_brt
9
+ from ..models.ensemble import BRTEnsemble
10
+
11
+
12
+ def _add_common_smoothing_args(parser: argparse.ArgumentParser) -> None:
13
+ """Add common smoothing arguments to a parser."""
14
+ parser.add_argument(
15
+ "--smooth",
16
+ choices=["none", "mrf", "bayes"],
17
+ default="none",
18
+ help=(
19
+ "Post-process predictions. 'mrf' enables Potts-MRF ICM smoothing; "
20
+ "'bayes' enables empirical Bayes smoothing (SITS)."
21
+ ),
22
+ )
23
+ parser.add_argument(
24
+ "--beta",
25
+ type=float,
26
+ default=1.0,
27
+ help="Smoothness strength for MRF (higher = smoother).",
28
+ )
29
+ parser.add_argument(
30
+ "--neighborhood",
31
+ type=int,
32
+ choices=[4, 8],
33
+ default=4,
34
+ help="Neighborhood system for MRF smoothing.",
35
+ )
36
+ parser.add_argument(
37
+ "--icm-iters",
38
+ type=int,
39
+ default=3,
40
+ help="ICM iterations for MRF smoothing.",
41
+ )
42
+ parser.add_argument(
43
+ "--bayes-window-size",
44
+ type=int,
45
+ default=7,
46
+ help="Window size (odd >=3) for Bayesian smoothing.",
47
+ )
48
+ parser.add_argument(
49
+ "--bayes-neigh-fraction",
50
+ type=float,
51
+ default=0.5,
52
+ help="Fraction of neighbors used for Bayesian smoothing (0-1].",
53
+ )
54
+ parser.add_argument(
55
+ "--bayes-smoothness",
56
+ type=float,
57
+ default=20.0,
58
+ help="Smoothness parameter (sigma^2) for Bayesian smoothing.",
59
+ )
60
+ parser.add_argument(
61
+ "--block-overlap",
62
+ type=int,
63
+ default=0,
64
+ help="Overlap (pixels) to reduce seams between blocks when smoothing.",
65
+ )
66
+
67
+
68
+ def _parse_block_shape(values: Optional[Sequence[int]]) -> Optional[tuple[int, int]]:
69
+ """Parse block shape from command-line arguments."""
70
+ if values is None:
71
+ return None
72
+ if len(values) != 2:
73
+ raise argparse.ArgumentTypeError("block shape must be two integers")
74
+ return int(values[0]), int(values[1])
75
+
76
+
77
+ def _flatten_image_args(image_args: Sequence[Sequence[str]]) -> List[str]:
78
+ """Flatten nested image arguments."""
79
+ images: List[str] = []
80
+ for group in image_args:
81
+ images.extend(group)
82
+ return images
83
+
84
+
85
+ def main(argv: Optional[Sequence[str]] = None) -> int:
86
+ """Dispatch to ensemble train/predict sub-commands."""
87
+ parser = argparse.ArgumentParser(
88
+ prog="plaknit brt",
89
+ description="Train or apply a Boosted Regression Tree (BRT) classifier to raster stacks.",
90
+ )
91
+ subparsers = parser.add_subparsers(dest="command", required=True)
92
+
93
+ # Train sub-command
94
+ train_parser = subparsers.add_parser(
95
+ "train", help="Train one BRT model or an ensemble."
96
+ )
97
+ train_parser.add_argument(
98
+ "--image",
99
+ required=True,
100
+ nargs="+",
101
+ action="append",
102
+ help=(
103
+ "Raster input(s): pass one or more GeoTIFF/VRT paths after --image, "
104
+ "or repeat --image. Directories are expanded to TIFFs."
105
+ ),
106
+ )
107
+ train_parser.add_argument(
108
+ "--band-indices",
109
+ nargs="+",
110
+ type=int,
111
+ help="Optional 1-based band indices to use from the stacked inputs.",
112
+ )
113
+ train_parser.add_argument(
114
+ "--labels", required=True, help="Vector labels (e.g., Shapefile/GeoPackage)."
115
+ )
116
+ train_parser.add_argument(
117
+ "--label-column",
118
+ required=True,
119
+ help="Column in labels containing class names/ids.",
120
+ )
121
+ train_parser.add_argument(
122
+ "--output",
123
+ required=True,
124
+ help="Model file when --n-models=1; ensemble directory when --n-models>1.",
125
+ )
126
+ train_parser.add_argument(
127
+ "--n-models",
128
+ type=int,
129
+ default=1,
130
+ help="Number of BRT models; 1 trains a single model (default: 1).",
131
+ )
132
+ train_parser.add_argument(
133
+ "--n-estimators",
134
+ type=int,
135
+ default=200,
136
+ help="Number of boosting rounds per model (default: 200).",
137
+ )
138
+ train_parser.add_argument(
139
+ "--max-depth",
140
+ type=int,
141
+ default=6,
142
+ help="Max tree depth (default: 6).",
143
+ )
144
+ train_parser.add_argument(
145
+ "--learning-rate",
146
+ type=float,
147
+ default=0.1,
148
+ help="Learning rate for boosting (default: 0.1).",
149
+ )
150
+ train_parser.add_argument(
151
+ "--subsample",
152
+ type=float,
153
+ default=1.0,
154
+ help="Fraction of samples per tree (default: 1.0).",
155
+ )
156
+ train_parser.add_argument(
157
+ "--colsample-bytree",
158
+ type=float,
159
+ default=1.0,
160
+ help="Fraction of features per tree (default: 1.0).",
161
+ )
162
+ train_parser.add_argument(
163
+ "--test-fraction",
164
+ type=float,
165
+ default=0.3,
166
+ help="Fraction of samples held out for evaluation (default: 0.3).",
167
+ )
168
+ train_parser.add_argument(
169
+ "--grid-size",
170
+ type=int,
171
+ default=None,
172
+ help=(
173
+ "Grid size in pixels for spatially diverse sampling; keeps at most one "
174
+ "sample per class per grid cell."
175
+ ),
176
+ )
177
+ train_parser.add_argument(
178
+ "--pseudo-absence-ratio",
179
+ type=float,
180
+ default=1.0,
181
+ help="Pseudo-absence samples per presence sample (default: 1.0).",
182
+ )
183
+ train_parser.add_argument(
184
+ "--training-buffer-meters",
185
+ type=float,
186
+ default=0.0,
187
+ help="Buffer training geometries by this many meters (default: 0).",
188
+ )
189
+ train_parser.add_argument(
190
+ "--random-state",
191
+ type=int,
192
+ default=42,
193
+ help="Base random seed for reproducibility (default: 42).",
194
+ )
195
+ train_parser.add_argument(
196
+ "--gpu",
197
+ action="store_true",
198
+ help="Enable GPU acceleration if available (XGBoost + CUDA).",
199
+ )
200
+ train_parser.add_argument(
201
+ "--jobs",
202
+ type=int,
203
+ default=1,
204
+ help="Concurrent ensemble model fits (default: 1; GPU training remains serial).",
205
+ )
206
+
207
+ # Predict sub-command
208
+ predict_parser = subparsers.add_parser(
209
+ "predict",
210
+ help="Apply a trained BRT ensemble to classify a raster stack.",
211
+ )
212
+ predict_parser.add_argument(
213
+ "--image",
214
+ required=True,
215
+ nargs="+",
216
+ action="append",
217
+ help=(
218
+ "Raster input(s): pass one or more GeoTIFF/VRT paths after --image, "
219
+ "or repeat --image. Directories are expanded to TIFFs."
220
+ ),
221
+ )
222
+ predict_parser.add_argument(
223
+ "--band-indices",
224
+ nargs="+",
225
+ type=int,
226
+ help="Optional 1-based band indices to use from the stacked inputs.",
227
+ )
228
+ predict_parser.add_argument(
229
+ "--ensemble-dir",
230
+ required=True,
231
+ help="Directory containing the trained ensemble models and metadata.",
232
+ )
233
+ predict_parser.add_argument(
234
+ "--output-dir",
235
+ required=True,
236
+ help=(
237
+ "Directory for mean_probabilities.tif and, for ensembles with at least "
238
+ "two models, lower_probabilities.tif and upper_probabilities.tif."
239
+ ),
240
+ )
241
+ predict_parser.add_argument(
242
+ "--ci-level",
243
+ type=float,
244
+ default=0.95,
245
+ help="Confidence level for lower and upper probability bounds (default: 0.95).",
246
+ )
247
+ predict_parser.add_argument(
248
+ "--model-summary-out",
249
+ help="Optional CSV path summarizing each ensemble member's seed and ROC AUC.",
250
+ )
251
+ predict_parser.add_argument(
252
+ "--feature-importance-out",
253
+ help="Optional CSV path for unweighted ensemble predictor importance.",
254
+ )
255
+ predict_parser.add_argument(
256
+ "--block-shape",
257
+ nargs=2,
258
+ type=int,
259
+ metavar=("HEIGHT", "WIDTH"),
260
+ help="Override block/window shape for reading (height width).",
261
+ )
262
+ predict_parser.add_argument(
263
+ "--jobs",
264
+ type=int,
265
+ default=1,
266
+ help="Parallel workers for block prediction (default: 1). Use -1 for all cores.",
267
+ )
268
+ predict_parser.add_argument(
269
+ "--block-overlap",
270
+ type=int,
271
+ default=0,
272
+ help="Overlap in pixels used while processing raster blocks (default: 0).",
273
+ )
274
+
275
+ args = parser.parse_args(list(argv) if argv is not None else None)
276
+
277
+ if args.command == "train":
278
+ image_paths = _flatten_image_args(args.image)
279
+ if args.n_models == 1:
280
+ train_brt(
281
+ image_path=image_paths,
282
+ shapefile_path=args.labels,
283
+ label_column=args.label_column,
284
+ model_out=args.output,
285
+ band_indices=args.band_indices,
286
+ n_estimators=args.n_estimators,
287
+ max_depth=args.max_depth,
288
+ learning_rate=args.learning_rate,
289
+ subsample=args.subsample,
290
+ colsample_bytree=args.colsample_bytree,
291
+ random_state=args.random_state,
292
+ test_fraction=args.test_fraction,
293
+ grid_size=args.grid_size,
294
+ pseudo_absence_ratio=args.pseudo_absence_ratio,
295
+ training_buffer_meters=args.training_buffer_meters,
296
+ gpu=args.gpu,
297
+ n_jobs=args.jobs,
298
+ )
299
+ elif args.n_models > 1:
300
+ ensemble = BRTEnsemble(
301
+ n_models=args.n_models,
302
+ n_estimators=args.n_estimators,
303
+ max_depth=args.max_depth,
304
+ learning_rate=args.learning_rate,
305
+ subsample=args.subsample,
306
+ colsample_bytree=args.colsample_bytree,
307
+ random_state=args.random_state,
308
+ pseudo_absence_ratio=args.pseudo_absence_ratio,
309
+ training_buffer_meters=args.training_buffer_meters,
310
+ test_fraction=args.test_fraction,
311
+ gpu=args.gpu,
312
+ )
313
+ ensemble.fit(
314
+ image_path=image_paths,
315
+ shapefile_path=args.labels,
316
+ label_column=args.label_column,
317
+ ensemble_dir=args.output,
318
+ band_indices=args.band_indices,
319
+ grid_size=args.grid_size,
320
+ jobs=args.jobs,
321
+ )
322
+ else:
323
+ raise ValueError("n_models must be at least 1.")
324
+ return 0
325
+
326
+ if args.command == "predict":
327
+ image_paths = _flatten_image_args(args.image)
328
+ block_shape = _parse_block_shape(args.block_shape)
329
+ ensemble = BRTEnsemble() # Dummy instance to call predict classmethod
330
+ ensemble.predict(
331
+ image_path=image_paths,
332
+ ensemble_dir=args.ensemble_dir,
333
+ output_dir=args.output_dir,
334
+ band_indices=args.band_indices,
335
+ block_shape=block_shape,
336
+ ci_level=args.ci_level,
337
+ model_summary_out=args.model_summary_out,
338
+ feature_importance_out=args.feature_importance_out,
339
+ block_overlap=args.block_overlap,
340
+ jobs=args.jobs,
341
+ )
342
+ return 0
343
+
344
+ return 2
345
+
346
+
347
+ if __name__ == "__main__": # pragma: no cover
348
+ raise SystemExit(main())