Metadata-Version: 2.4
Name: soil-etl
Version: 0.3.8
Summary: YAML-driven ETL mappers for ForSITE soil database imports.
License: MIT
License-File: LICENSE
Keywords: soil,etl,yaml,postgis,forestry,forsite
Author: Olivier Forgues-Nhan
Author-email: olivier.forgues-nhan@agr.gc.ca
Requires-Python: >=3.11,<4.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Provides-Extra: excel
Requires-Dist: certifi (>=2025.8.3,<2026.0.0)
Requires-Dist: duckdb (>=2)
Requires-Dist: geoalchemy2 (>=0.17.1)
Requires-Dist: geopandas (>=1.0.1)
Requires-Dist: hydra-colorlog (>=1.2.0)
Requires-Dist: hydra-core (>=1.3.2)
Requires-Dist: nrcan-etl-toolbox (>=0.2.1)
Requires-Dist: openpyxl (>=3.1.0) ; extra == "excel"
Requires-Dist: pandas (>=2.2.3)
Requires-Dist: psycopg2-binary (>=2.9.10)
Requires-Dist: pyarrow (>=18)
Requires-Dist: pydantic (>=2.0)
Requires-Dist: pyproj (>=3.0)
Requires-Dist: pyyaml (>=6.0)
Requires-Dist: shapely (>=2.1.0)
Requires-Dist: sqlalchemy (>=2.0.40)
Requires-Dist: sqlmodel (>=0.0.25)
Requires-Dist: xlrd (>=2.0.2) ; extra == "excel"
Project-URL: Changelog, https://gitlab.com/nrcan-rncan-cfs-scf/lfc-cfl/soil-etl/-/blob/main/CHANGELOG.md
Project-URL: Documentation, https://gitlab.com/nrcan-rncan-cfs-scf/lfc-cfl/soil-etl/-/blob/main/docs/README_yaml_format_en.md
Project-URL: Homepage, https://gitlab.com/nrcan-rncan-cfs-scf/lfc-cfl/soil-etl
Project-URL: Issues, https://gitlab.com/nrcan-rncan-cfs-scf/lfc-cfl/soil-etl/issues
Project-URL: Repository, https://gitlab.com/nrcan-rncan-cfs-scf/lfc-cfl/soil-etl
Description-Content-Type: text/markdown

# SOIL - Structured Observation Ingestion Library

> **Version**: 0.3.0 · **Python**: ≥ 3.10 · **PyPI**: `soil-etl`

SQL-first ETL package for importing Canadian forestry soil datasets into the ForSITE PostGIS database model,
built on the OGC Observations, Measurements & Samples specification. DuckDB performs reproducible
preprocessing in saved SQL; Parquet carries validated relational data to the importer.
Existing flat-table/YAML pipelines remain supported.

## Acknowledgements

| Project Partners                                                                                               |
|:---------------------------------------------------------------------------------------------------------------|
| <img src="docs/logo/gc-logo.svg" width="310" style="background-color: white ; padding: 10px; padding-right: 55px" > |
| <img src="docs/logo/nrcan-logo.svg" width="310" style="background-color: white ; padding: 10px">                    |
| <img src="docs/logo/aafc_logo.svg" width="310" style="background-color: white ; padding: 10px">                     |

This project was developed through joint funding provided by Agriculture and Agri-Food Canada (`AAFC`) under
the [CSBO](https://sis.agr.gc.ca/cansis/biome/index.html) program and Natural Resources Canada (`NRCan`) for
the ForSITE-Soil degradation project.

The code developed as part of this project includes contributions from:

- [Olivier Forgues-Nhan](olivier.forgues-nhan@agr.gc.ca)
- [Xavier Malet](xavier.malet@nrcan-rncan.gc.ca)
- [Catlan Dallaire](catlan.dallaire@nrcan-rncan.gc.ca)
- [David Gagné](david.gagne@agr.gc.ca)

---

## Installation

```bash
pip install soil-etl
```

DuckDB reads CSV/Parquet directly, XLSX through its `excel` extension and GPKG/SHP through
`spatial`. Extensions must be provisioned explicitly; legacy XLS needs an optional adapter.
The pandas Excel adapter is available with `pip install "soil-etl[excel]"`.
Excel is never an export unless explicitly requested. Error reports and enabled diagnostic exports default
to Parquet, including for Excel inputs. See [standardization and migration](docs/STANDARDIZATION.md).
The current `nrcan-etl-toolbox` dependency still installs `openpyxl` transitively.

The [SQL-first prepared pipeline](docs/PREPARED_PIPELINE.md) loads sources natively in
DuckDB and prepares relational Parquet entities with executable geometry, enum, unit and
lineage contracts before staging. Generated project agents follow this preprocessing workflow;
existing flat-Parquet/YAML imports remain supported.
`import_prepared_bundle` reuses the YAML path's metadata/association resolution and transactional
tmp-table persistence, with an offline dry-run default and no external tmp-to-final transfer.

Or with Poetry:

```bash
poetry add soil-etl
```

---

## Quick Start

### SQL-first pipeline (recommended)

Create a project with `soil-etl start-project my-soil-imports`, install its dependencies and
run the following agent prompts one at a time:

| Stage | Prompt | Output |
|---|---|---|
| 1 | `/1-create-data-dictionary` | Evidence-based source dictionary |
| 2 | `/2-interpret-soil-source` | Scientific interpretation and human-reviewed decisions |
| 3 | `/3-load-sources` | Raw DuckDB loading SQL, checks and checkpoint |
| 4 | `/4-standardize-source` | Approved standardization SQL, checks and checkpoint |
| 5 | `/5-prepare-data` | Relational preparation SQL and validated Parquet bundle |
| 6 | `/6-build-import-runner` | Reviewed metadata, import runner and offline dry run |

```text
Sources -> DuckDB raw -> standardized -> prepared -> Parquet bundle
                                                        |
                                  import_prepared_bundle(dry_run=True)
                                                        |
                                  Explicitly authorized real import
                                                        |
                            ForSITE metadata + staging -> tmp_data_import
```

Each stage stops at its review gate. Version the SQL and orchestrator, not source data or
generated artifacts. Loading/standardization checkpoints are project-local prefix-run records;
stage 5 replays the full sequence with `run_prepared_pipeline` before publishing a new bundle
directory and `manifest.json`. The full-pipeline API does not support incomplete phase schemas.

The saved sequence is `01_load_raw.sql`, `02_standardize.sql`, `03_prepare_locations.sql`,
`04_prepare_features.sql`, `05_prepare_relationships.sql`, `06_prepare_observations.sql`,
`07_prepare_results.sql` and `08_validate.sql`, plus phase-specific checks.
Preparation enforces POINTZ/EPSG:3979 with documented Z/vertical reference, enum keys,
property/unit/method contracts, lineage and exactly one result per observation.
Missing scientific evidence blocks the relevant gate; agents never approve their own decisions.

Adapt `pipelines/prepare_example_dataset.py` and `pipelines/import_prepared_example.py`
in the generated project. The importer accepts the same `ProjectDataMeta` graph as the YAML
path: projects/subprojects, partners, datasets, stewards and associations.
Its default dry run is offline; real imports are atomic and stop at `tmp_data_import`.
External tmp-to-final transfer functions are never invoked.

See the [workflow and review gates](project-template/.github/knowledge/soil-etl-workflow.md),
[prepared pipeline API](docs/PREPARED_PIPELINE.md) and
[project template](project-template/README.md).

### Flat-table/YAML pipeline (compatibility)

```python
from pathlib import Path
from soil_etl.yaml_mapper import YamlDatasetMapper

mapper = YamlDatasetMapper(
    config_path=Path("my_config.yaml"),
    data_file_path=Path("data.parquet"),
)
metrics = mapper.import_data(
    dry_run=True,
    database_connection_string="postgresql+psycopg2://user:password@host:5432/database",
)
print(metrics)
```

Flat-table pipelines use `YamlDatasetMapper`; relational bundles use `import_prepared_bundle`
without a YAML mapping. Do not pass a bundle directory to the YAML mapper or repeat DuckDB
transformations in bindings. The generated project provides `/build-yaml-runner-compatibility`
for an existing validated flat Parquet table.

### Canonical imports

```python
from soil_etl.yaml_mapper import YamlDatasetMapper
from soil_etl.bindings import Binding, FromColumn
from soil_etl.db import ImportationInterface
```

---

## Boilerplate - Scaffolding for the new project

The fastest way to start a new import project is to **create a ready-to-use project** from the
packaged template. It creates a complete, self-contained project: 
- saved DuckDB loading, standardization, preparation and validation SQL;
- preparation/import runners and flat-table/YAML compatibility examples;
- Hydra DB configuration and an `.env.example` for later authorized writes;
- agents, six ordered prompts, skills and embedded knowledge under `.github/`,
  with entrypoints for Copilot, OpenCode and Claude Code.

### From the command line

```bash
# Scaffold into a new subfolder
soil-etl start-project my-soil-imports

# ...or into the current directory
soil-etl start-project

# Options
soil-etl start-project my-soil-imports --dest ./projects --overwrite
```

Equivalent module invocation:

```bash
python -m soil_etl start-project my-soil-imports
```

### From Python

```python
import soil_etl

soil_etl.start_project("my-soil-imports")     # into a new subfolder
soil_etl.start_project()                       # into the current directory
soil_etl.start_project(name="my-soil-imports", overwrite=True)
```

### Generated project layout

```
my-soil-imports/
+-- pyproject.toml                    # depends on soil-etl
+-- .env.example                      # env vars (DB_CONN, etc.)
+-- .gitignore
+-- AGENTS.md                         # agent rules for any tool (Copilot, OpenCode, Claude Code)
+-- CLAUDE.md                         # Claude Code entry point (imports AGENTS.md)
+-- opencode.json, .opencode/         # OpenCode adapter
+-- configs/
|   +-- configs.yaml                  # Hydra root (selects db: local)
|   +-- db/
|   |   +-- base_con.yaml
|   |   +-- local.yaml
+-- data/
|   +-- <project>/                    # sources, phase checkpoints, Parquet bundles - not tracked
+-- pipelines/
|   +-- <project>/                    # dataset dictionary, interpretation and adapted runners/SQL
|   +-- prepare_example_dataset.py    # full saved-SQL preparation scaffold
|   +-- import_prepared_example.py    # metadata graph and offline prepared import
|   +-- sql/prepared_example/         # ordered 01-08 SQL scaffold
|   +-- import_example_dataset.py     # flat-table/YAML compatibility runner
|   +-- example_dataset.yaml          # compatibility YAML config
+-- .github/                          # Copilot agent + embedded knowledge
    +-- agents/                       # soil-etl-pipeline agent, specialists, read-only reviewers
    +-- prompts/                      # ordered stages /1- to /6-, compatibility and review utilities
    +-- instructions/                 # file-scoped workflow and safety rules
    +-- knowledge/                    # workflow, prepared contracts, DB model, enums, YAML reference
    +-- skills/                       # workflow skills (dictionary, interpretation, standardization)
```

Next steps after boilerplate exec.:

```powershell
cd my-soil-imports
poetry install                       # installs soil-etl
poetry run python pipelines\prepare_example_dataset.py --help
```

Start with `/1-create-data-dictionary`; adapt the example's scientific assumptions only
from reviewed evidence. Preprocessing and offline dry runs need no ForSITE credentials.
Configure `.env` only for a later explicitly authorized real import.

> **Maintainers:** the editable source of the template lives in `project-template/` at the repo root
> and is synced into the packaged copy (`src/soil_etl/_project_template/`) with
> `python scripts/sync_template.py` (use `--check` in CI to detect drift).

---

## Database Connection

Connection resolution priority (first non-null wins):

1. Explicit `database_connection_string` argument to `import_data()`
2. `DB_CONN` environment variable
3. Hydra config directory (`database_config_path` / `CONFIG_PATH` env var)

```python
# Option 1 - direct connection string
mapper.import_data(
    database_connection_string="postgresql+psycopg2://user:password@host:5432/database",
    database_engine_kwargs={"pool_size": 10, "pool_pre_ping": True},
)

# Option 2 - Hydra config files
mapper.import_data(
    database_config_path="configs",
    database_config_name="configs.yaml",
)

# Option 3 - environment variables
import os
os.environ["DB_CONN"] = "postgresql+psycopg2://user:password@host:5432/database"
mapper.import_data()
```

**Environment variables recognized:**

| Variable                     | Description                                                          |
|------------------------------|----------------------------------------------------------------------|
| `DB_CONN`                    | Full SQLAlchemy connection string                                    |
| `DB_USER`                    | Database username (used alongside Hydra config)                      |
| `DB_PASSWORD`                | Database password (used alongside Hydra config)                      |
| `CONFIG_PATH`                | Hydra config directory path                                          |
| `IMPORT_BATCH_SIZE`          | Override batch size for this run (positive integer)                  |
| `EXPORT_RETREATED_DATAFRAME` | Export transformed DataFrame to `*_retreated.parquet` (`1`/`true`/`yes`) |

---

## `import_data()` Signature

```python
mapper.import_data(
    error_file_path=Path("errors.parquet"),         # defaults to <dataset_title>_ERROR.parquet
    dry_run=False,                                   # True: extract + validate only, no DB writes
    database_connection_string="postgresql+...",
    database_config_path="configs",
    database_config_name="configs.yaml",
    database_engine_kwargs={"pool_size": 10},
) -> ImportRunMetrics
```

Returns an `ImportRunMetrics` dataclass:

```python
@dataclass(frozen=True)
class ImportRunMetrics:
    rows_processed: int
    error_rows: int
    generic_results: int
    feature_relationships: int
    sample_information: int
    batches: int
    batch_size: int
    dry_run: bool
    extract_seconds: float
    persist_seconds: float
    total_seconds: float
```

---

## YAML Configuration

For flat-table compatibility imports, YAML defines standardized-table reading parameters,
project metadata, feature of interest hierarchy, observations and results.
SQL-first relational bundles do not require this mapping.

Reference files (packaged):

| File                                               | Purpose                                            |
|----------------------------------------------------|----------------------------------------------------|
| `src/soil_etl/yaml_mapper/dummy_config_file.yaml`  | Fully-documented boilerplate with all options      |
| `src/soil_etl/yaml_mapper/template.yaml`           | Real-world example with YAML anchors               |
| `src/soil_etl/yaml_mapper/examples/on_master.yaml` | Province-specific example                          |
| `examples/configs/example_config.yaml`             | Additional annotated example                       |

For full documentation of the YAML format, see [docs/README_yaml_format_en.md](docs/README_yaml_format_en.md).

### Top-level sections

```yaml
source:                        # standardized-table reading parameters
  format: parquet
export_retreated_dataframe: false
import_batch_size: 1000        # Rows per DB batch (default: 5000)
project:                       # Project metadata (strategy, name, abbrev, province, type...)
partners:                      # Partner organizations
stewards:                      # Data steward contacts
feature_relationships:         # Optional parent-child FOI hierarchies (e.g. ProfileElement -> Sample)
sample_information:            # Optional sample metadata (type and dimensions)
profile_elements:              # Soil horizons/layers: depth bounds + designation on a PROFILE feature
observations:                  # v2: each observation carries one nested result (1:1)
```

> **v2 data model:** the pipeline targets `om_observation_v2` / `om_result_v2` / `profile_element`. Declare an
> `observations:` list where each observation carries exactly **one** nested `result:` (1:1). The observed property
> (`element_name`) lives on the observation. The observation `type` field is deprecated/ignored. Depth bounds live on
> `profile_elements` (a `PROFILE` feature of interest), not on the sample; a profile element can own an observation or
> be the parent of a `SAMPLE`. Soil horizons/layers are modeled with `profile_elements` (a `PROFILE` FOI carrying depth
> bounds + designation) with observations attached, following the chain `FOI > Profile > Observation(v2) > Result(v2)`
> (or `FOI > Profile > Sample > [FOI/Profile/Sample relations] > Observation(v2) > Result(v2)`). The
> former root keys `results:` / `horizon_results:` have been **removed** (rejected at load time). See
> [docs/README_yaml_format_en.md](docs/README_yaml_format_en.md).

---

## Python Subclass (advanced)

When YAML alone cannot express the required logic, subclass `YamlDatasetMapper` and override properties:

```python
from pathlib import Path
from soil_etl.yaml_mapper import YamlDatasetMapper
from soil_etl.model_bindings import FeatureOfInterestBinding

class MyMapper(YamlDatasetMapper):
    @property
    def _feature_of_interest(self) -> FeatureOfInterestBinding:
        # custom logic here
        ...

mapper = MyMapper(
    config_path=Path("my_config.yaml"),
    data_file_path=Path("data.parquet"),
)
mapper.import_data(database_connection_string="postgresql+psycopg2://...")
```

See `examples/subclass_runner.py` for a complete example.

---

## Development

```bash
pip install poetry
poetry install --with dev,test
poetry run pytest tests
```

Tests use **testcontainers** with `postgis/postgis:17-3.4` - Docker must be running.

### Linting & formatting

```bash
poetry run black src tests
poetry run ruff check src tests
poetry run isort src tests
```

---

## Build & Publish

```bash
python -m build
twine check dist/*
twine upload dist/*
```

---

## Links

- **Repository**: [gitlab.com/nrcan-rncan-cfs-scf/lfc-cfl/soil-etl](https://gitlab.com/nrcan-rncan-cfs-scf/lfc-cfl/soil-etl)
- **Issues**: [soil-etl/issues](https://gitlab.com/nrcan-rncan-cfs-scf/lfc-cfl/soil-etl/issues)
- **YAML format reference**: [docs/README_yaml_format_en.md](docs/README_yaml_format_en.md)
- **Testing guide**: [docs/testing.md](docs/testing.md)
- **Project template**: [project-template/README.md](project-template/README.md)
- **SQL-first workflow**: [six stages and review gates](project-template/.github/knowledge/soil-etl-workflow.md)
- **Prepared pipeline API**: [docs/PREPARED_PIPELINE.md](docs/PREPARED_PIPELINE.md)

