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.
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). |
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). |
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
SensitivityConfig
¶
Bases: BaseModel
Configuration for sensitivity analysis (per D-04).
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
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 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 | |
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. |