terraflow.core¶
The core modules define the configuration schema and the end-to-end pipeline.
Quick Start¶
from terraflow.pipeline import run_pipeline
from terraflow.config import load_config
# Load and validate configuration
config = load_config("config.yml")
# Run the complete pipeline
results_df = run_pipeline("config.yml")
Module Organization
- config: YAML schema validation and Pydantic models
- pipeline: End-to-end orchestration and artifact generation
- model: Suitability scoring algorithms and label assignment
API Reference¶
config
¶
ClimateConfig
¶
Bases: BaseModel
Climate data configuration for spatial matching and interpolation.
Supports two strategies for aligning climate observations to raster cells: - 'spatial': Interpolate climate values using geographic coordinates (lat/lon). - 'index': Match cells to climate records by row index or explicit cell ID.
When strategy is 'spatial', three interpolation methods are available: - 'linear': Delaunay-triangulation linear interpolation (scipy.griddata, default). - 'kriging': Ordinary Kriging — geostatistically optimal with per-cell uncertainty (requires pykrige; ≥5 stations recommended). - 'idw': Inverse Distance Weighting — fast, no uncertainty estimate.
The optional temporal_aggregations and scenarios fields support
the flagship climate-impact assessment workflow (#138): each entry in
temporal_aggregations is computed for each entry in scenarios,
producing scenario-tagged derived columns on the features table. When
both lists are empty (the default), the pipeline behaves exactly as
before — a single-period spatial-interpolation run.
Attributes:
| Name | Type | Description |
|---|---|---|
strategy |
Literal['spatial', 'index']
|
Matching strategy: 'spatial' (interpolation) or 'index' (direct matching). |
interpolation_method |
Literal['linear', 'kriging', 'idw']
|
Interpolation algorithm when strategy='spatial'. Choices: 'linear' (default), 'kriging', 'idw'. |
cell_id_column |
str | None
|
Column name in climate CSV for cell ID (used with 'index' strategy). If None with 'index' strategy, uses row order matching. |
fallback_to_mean |
bool
|
If True, use global mean climate for cells outside interpolation range or when climate data is sparse (default True). |
temporal_aggregations |
list[TemporalAggregation]
|
Optional list of climate aggregation rules computed per cell per scenario. |
scenarios |
list[Scenario]
|
Optional list of named climate scenarios (e.g. historical, ssp245, ssp585). |
validate_config()
¶
Validate consistency of climate configuration.
Source code in terraflow/config.py
validate_interpolation_method(v)
classmethod
¶
Ensure interpolation_method is valid.
Source code in terraflow/config.py
validate_strategy(v)
classmethod
¶
Ensure strategy is valid.
ModelParams
¶
Bases: BaseModel
Parameters for normalization and weighting in the suitability model.
The weights w_v, w_t, w_r should sum to approximately 1.0 for proper normalization, though this is not strictly enforced.
Attributes:
| Name | Type | Description |
|---|---|---|
v_min, v_max |
Min/max vegetation index values for normalization. |
|
t_min, t_max |
Min/max temperature values for normalization (in °C). |
|
r_min, r_max |
Min/max rainfall values for normalization (in mm). |
|
w_v, w_t, w_r |
Weights for vegetation, temperature, and rainfall (should sum to 1.0). |
|
uncertainty_samples |
int
|
Number of Monte Carlo draws per cell for uncertainty propagation.
0 (default) disables Monte Carlo. Requires |
validate_max_values(v, info)
classmethod
¶
Ensure max values are reasonable numbers.
Source code in terraflow/config.py
validate_min_values(v, info)
classmethod
¶
Ensure min values are reasonable numbers.
Source code in terraflow/config.py
validate_ranges()
¶
Validate that min < max for all ranges. Call after initialization.
Source code in terraflow/config.py
validate_uncertainty_samples(v)
classmethod
¶
Ensure uncertainty_samples is non-negative.
PipelineConfig
¶
Bases: BaseModel
Top-level pipeline configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
raster_path |
Path
|
Path to the input raster file (GeoTIFF). |
climate_csv |
Path
|
Path to the climate data CSV file. |
output_dir |
Path
|
Directory for output results. |
roi |
ROI
|
Region of interest specification. |
model_params |
ModelParams
|
Suitability model parameters. |
climate |
ClimateConfig
|
Climate data configuration (strategy, fallback behavior, etc.). |
max_cells |
int
|
Maximum number of cells to sample from the ROI (default 500). |
validate_all()
¶
Validate all constraints. Call after model initialization.
Source code in terraflow/config.py
validate_max_cells(v)
classmethod
¶
Ensure max_cells is a positive integer.
validate_raster_band(v)
classmethod
¶
Ensure raster_band is a positive 1-based rasterio band index.
Existence of the band in the actual file is verified at pipeline runtime, because we cannot know the band count at config-load time without opening the raster (#42).
Source code in terraflow/config.py
ROI
¶
Bases: BaseModel
Region of interest. For now we support only a bounding box.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
Literal['bbox']
|
Type of ROI (currently only 'bbox' is supported). |
xmin, ymin, xmax, ymax |
Bounding box coordinates expressed in roi_crs (default WGS 84 degrees). |
|
roi_crs |
str
|
EPSG code or WKT string for the CRS of the bounding box coordinates.
Defaults to |
validate_bounds()
¶
Validate that bounds are sensible. Call after initialization.
Source code in terraflow/config.py
Scenario
¶
Bases: BaseModel
A named climate scenario over a year range (flagship #138).
name is a free-form label — typically historical, ssp245,
ssp585. period is a closed inclusive [year_min, year_max]
pair (e.g. [1991, 2020] or [2041, 2070]).
SensitivityConfig
¶
Bases: BaseModel
Configuration for sensitivity analysis (per D-04).
TemporalAggregation
¶
Bases: BaseModel
A named climate temporal aggregation rule (flagship #138).
Each entry produces one derived column on the per-cell features table.
The kind field selects the computation; remaining fields are
kind-specific and validated below.
Supported kinds:
- annual_mean: yearly mean of the variable (no extra params).
- seasonal_mean: mean over selected calendar months (1-12).
- growing_degree_days: GDD accumulation above base_temp_c.
- frost_days: count of days at or below threshold_c.
- heat_stress_days: count of days at or above threshold_c.
- precip_percentile: nth percentile of daily precipitation
(percentile in 0-100).
- spei: Standardised Precipitation-Evapotranspiration Index at
timescale_months (e.g. 1, 3, 6, 12).
validate_kind_params()
¶
Each kind requires specific fields and forbids the others.
Source code in terraflow/config.py
ValidationConfig
¶
Bases: BaseModel
Configuration for model validation (Phase 3).
WeightBounds
¶
Bases: BaseModel
Bounds for a single weight parameter in sensitivity analysis.
build_config(data)
¶
Validate a raw config dict into a PipelineConfig.
Source code in terraflow/config.py
load_config(path)
¶
Load YAML config from disk and validate with Pydantic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the YAML configuration file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
PipelineConfig |
PipelineConfig
|
Validated configuration object. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError:
|
If the config file does not exist. |
yaml.YAMLError:
|
If the YAML is malformed. |
ValueError:
|
If the configuration is invalid. |
Source code in terraflow/config.py
load_config_dict(path)
¶
Load YAML config from disk into a raw dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the YAML configuration file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Parsed configuration as a Python dict. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError:
|
If the config file does not exist. |
yaml.YAMLError:
|
If the YAML is malformed. |
Source code in terraflow/config.py
pipeline
¶
Pipeline orchestration for TerraFlow.
All outputs are written atomically to::
output_dir/runs/<run_fingerprint>/
Every run produces exactly three artifacts:
features.parquet— per-cell suitability features (tidy/wide schema v1)manifest.json— config snapshot, run identity, input provenancereport.json— QA summaries, coverage metrics, step timings
A backward-compatible results.csv is also written to the same run
directory so that callers relying on the previous output path can migrate
at their own pace.
resolve_run_dir(config_path)
¶
Return the run directory for a given config without running the pipeline.
Uses the same fingerprint computation as run_pipeline() so that
terraflow validate always targets the correct run, not the most
recently modified one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
Path | str
|
Path to a TerraFlow YAML config file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
|
Source code in terraflow/pipeline.py
run_pipeline(config_path)
¶
Run the end-to-end pipeline and return a DataFrame of results.
Uses spatially-aware climate data matching to apply per-cell climate values based on the configured strategy (spatial interpolation or index-based matching).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str | Path
|
Path to YAML configuration file. |
required |
Returns:
| Type | Description |
|---|---|
pd.DataFrame:
|
Results table with columns: run_id, cell_id, lat, lon, v_index,
mean_temp, total_rain, score, label. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError:
|
If config file, raster file, or climate CSV does not exist. |
ValueError:
|
If configuration is invalid or no valid raster cells found in ROI. |
Notes
All artifacts are written atomically under::
output_dir/runs/<run_fingerprint>/
If that directory already contains all three required artifacts
(features.parquet, manifest.json, report.json) the pipeline
detects the identical run and returns early (no-op rerun).
Source code in terraflow/pipeline.py
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 | |
model
¶
suitability_label(score)
¶
Bucket suitability score into qualitative labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
score
|
float
|
Suitability score in [0, 1] range. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
One of 'low', 'medium', or 'high' based on score thresholds. |
Notes
- 'low': score < 0.33
- 'medium': 0.33 <= score < 0.66
- 'high': score >= 0.66
Source code in terraflow/model.py
suitability_score(v_index, mean_temp, total_rain, params)
¶
Compute a simple suitability score in [0, 1].
Combines normalized vegetation index, temperature, and rainfall using weighted linear combination. All inputs are normalized to [0, 1] range based on the parameter min/max bounds, then combined using the weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v_index
|
float
|
Vegetation index value (typically 0-1, but can be outside range). |
required |
mean_temp
|
float
|
Mean temperature in degrees Celsius. |
required |
total_rain
|
float
|
Total rainfall in millimeters. |
required |
params
|
ModelParams
|
Model parameters containing min/max bounds and weights. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Suitability score in [0, 1] range. |
Notes
- Out-of-range inputs are clipped to [0, 1] during normalization
- Weights should sum to 1.0 for proper combination
- Final result is clipped to [0, 1] range
Source code in terraflow/model.py
suitability_score_array(v_index, mean_temp, total_rain, params)
¶
Vectorized suitability scoring over numpy arrays.
Equivalent to calling :func:suitability_score element-wise but operates
on arbitrary-shape numpy arrays. Used internally for Monte Carlo
uncertainty propagation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v_index
|
ndarray
|
Vegetation index values (any shape). |
required |
mean_temp
|
ndarray
|
Mean temperature values in °C (same shape as v_index). |
required |
total_rain
|
ndarray
|
Total rainfall values in mm (same shape as v_index). |
required |
params
|
ModelParams
|
Model parameters containing min/max bounds and weights. |
required |
Returns:
| Type | Description |
|---|---|
np.ndarray:
|
Suitability scores clipped to [0, 1], same shape as inputs. |