# WEPP Soil Files Package
> WEPP soil input file format specification, manipulation utilities, and pre-built soil library

> **See also:** [AGENTS.md](../../../AGENTS.md) for coding conventions and [wepppy.soils](../../soils/README.md) for SSURGO data acquisition.
>
> **User documentation:** [Soil Input File Specification](../../../weppcloud/routes/usersum/input-file-specifications/soil-file.spec.md) (line-by-line file format reference) and [Soil File Parameters](../../../weppcloud/routes/usersum/db/soil_file.parameters.md) (parameter dictionary with extended descriptions).

## Overview

The `wepppy.wepp.soils` package provides tools and data for working with WEPP soil input files (`.sol`). This package handles the **model integration** side of soils - parsing WEPP file formats, transforming parameters, version migration, and providing pre-built reference soils. For **data acquisition** from SSURGO/STATSGO2 databases, see the [`wepppy.soils`](../../soils/README.md) package.

**Key Capabilities:**
- Parse and generate WEPP soil files across 8 format versions (97.5 - 9005)
- Transform soil parameters for disturbance scenarios (wildfire, logging, land use change)
- Migrate between WEPP file format versions with parameter estimation
- Access pre-built soil library (50+ states, standardized forest/rangeland soils)
- Calculate erodibility and hydraulic parameters from soil texture

**Primary Users:**
- NoDb controllers building WEPP model input files
- Researchers transforming soils for scenario modeling
- Wildfire analysts applying burn severity adjustments
- Model developers extending WEPP soil capabilities

**Package Organization:**
```
wepppy/wepp/soils/
├── __init__.py              # Package exports
├── README.md                # This file
├── builder/                 # Soil file builders
├── horizon_mixin.py         # Erodibility and conductivity calculations
├── soilsdb/                 # Pre-built soil library
│   ├── README.md            # Library documentation
│   ├── __init__.py          # Library API
│   └── data/                # Soil files (Database/, Forest/, Forest2006/)
└── utils/                   # Parsing and transformation utilities
    ├── README.md            # WeppSoilUtil documentation
    ├── wepp_soil_util.py    # Primary soil file parser/transformer
    ├── multi_ofe.py         # Multi-OFE composition
    └── utils.py             # Helper functions
```

## Quick Start

### Parse a WEPP Soil File

```python
from wepppy.wepp.soils.utils import WeppSoilUtil

# Load soil file
soil = WeppSoilUtil('/path/to/soil.sol')

# Access properties
print(f"Texture: {soil.simple_texture}")
print(f"Clay: {soil.clay}%, Sand: {soil.sand}%")
print(f"Depth: {soil.soil_depth} mm")
print(f"Conductivity: {soil.avke} mm/h")
print(f"Version: {soil.datver}")
```

### Transform Soil Parameters

```python
# Modify initial saturation
soil.modify_initial_sat(0.75)

# Adjust restrictive layer conductivity
soil.modify_kslast(0.5)

# Write modified soil
soil.write('/path/to/modified_soil.sol')
```

### Migrate to Modern Format

```python
# Upgrade legacy soil to version 7778
modern = soil.to7778(hostname='analysis.server.edu')
modern.write('/path/to/upgraded_soil.sol')
```

### Access Pre-Built Soils

```python
from wepppy.wepp.soils.soilsdb import load_db, get_soil

# Browse library
available_soils = load_db()
print(f"Library contains {len(available_soils)} soils")

# Load reference soil
forest_loam = WeppSoilUtil(get_soil('Forest/Forest loam.sol'))
```

### Apply Wildfire Adjustments

```python
from wepppy.wepp.soils.soilsdb import read_disturbed_wepp_soil_fire_pars

# Get high severity burn parameters for loam
fire_pars = read_disturbed_wepp_soil_fire_pars(
    simple_texture='loam',
    fire_severity='high'
)

# Access adjusted erodibility
print(f"Burned ki: {fire_pars['ki']}")
print(f"Burned kr: {fire_pars['kr']}")
```

## WEPP Soil File Format Versions

WEPP soil files have evolved through multiple versions, each adding capabilities for improved hydrologic and erosion modeling.

### Version Evolution Timeline

| Version | Year | Key Features | Use Case |
|---------|------|--------------|----------|
| 97.5 | 1997 | Basic texture, erodibility | Legacy compatibility |
| 2006.2 | 2006 | Restrictive layer parameters | Bedrock/hardpan modeling |
| 7777 | 2010 | Bulk density, field capacity, wilting point | Hydrologic refinement |
| 7778 | 2010 | Anisotropy for lateral flow | Hillslope hydrology |
| 9001 | 2014 | Exponential keff recovery | Post-fire infiltration recovery |
| 9002 | 2014 | Saxton & Rawls keff calculation | Improved conductivity estimates |
| 9003 | 2018 | Burn severity codes, lower keff limit | Wildfire erosion modeling |
| 9005 | 2022 | Revegetation, upper keff limit | Post-fire recovery trajectories |

### Version 97.5 (Basic Soils)

**Introduced:** WEPP 97.5 (1997)

**Horizon Parameters:** solthk, sand, clay, orgmat, cec, rfg

**Limitations:** 
- No hydraulic conductivity specification
- Missing bulk density, field capacity, wilting point
- WEPP internally estimates missing parameters

**Use Case:** Legacy model runs, educational demonstrations

### Version 2006.2 (Restrictive Layer)

**Introduced:** WEPP 2006.2 (2006)

**New Features:**
- Restrictive layer parameters (bedrock depth, conductivity)
- Enables modeling shallow soils over bedrock or hardpan

**Horizon Parameters:** Same as 97.5

**Restrictive Layer:**
- `slflag` - Presence flag
- `ui_bdrkth` - Bedrock depth (mm)
- `kslast` - Restrictive layer conductivity (mm/h)

**Use Case:** Mountainous terrain, shallow soils, perched water tables

### Version 7777 (Hydrologic Enhancement)

**Introduced:** WEPP 2010

**New Features:**
- Bulk density specification
- Field capacity (water retention at -33 kPa)
- Wilting point (water retention at -1500 kPa)
- Hydraulic conductivity per horizon

**Horizon Parameters:** solthk, bd, ksat, fc, wp, sand, clay, orgmat, cec, rfg

**Improvements:**
- More accurate water balance
- Better baseflow predictions
- Reduced reliance on internal parameter estimation

**Use Case:** Hydrologic studies, watershed modeling, calibration against stream gauges

### Version 7778 (Anisotropy)

**Introduced:** WEPP 2010

**New Features:**
- Anisotropy ratio (lateral vs. vertical conductivity)

**Horizon Parameters:** solthk, bd, ksat, anisotropy, fc, wp, sand, clay, orgmat, cec, rfg

**Anisotropy Ratio:**
- `1.0` - Isotropic (equal horizontal/vertical flow)
- `> 1.0` - Preferential lateral flow (common in forest soils)
- Typical values: 1.0 (deep layers) to 10.0 (shallow organic layers)

**Use Case:** Hillslope hydrology, subsurface lateral flow, forested watersheds

### Version 9001 (Disturbed Lands - Exponential Recovery)

**Introduced:** Disturbed WEPP (2014)

**New OFE Parameters:**
- `ksatadj` - Enable keff adjustment flag
- `luse` - Disturbed land use class (forest, shrub, grass)
- `stext` - Simple texture classification
- `ksatfac` - Lower bound for keff (multiplier)
- `ksatrec` - Exponential recovery rate

**Effective Conductivity (keff):**
```
keff(t) = ksat * (ksatfac + (1 - ksatfac) * (1 - exp(-ksatrec * t)))
```
where `t` is cumulative precipitation since disturbance.

**Use Case:** Post-fire infiltration recovery, fire severity modeling, temporal hydrophobicity

### Version 9002 (Saxton & Rawls)

**Introduced:** Disturbed WEPP (2014)

**New Features:**
- keff calculated from Saxton & Rawls (2006) pedotransfer functions
- van Genuchten parameters estimated from texture via Rosetta

**OFE Parameters:** ksatadj, luse, stext (ksatfac, ksatrec retained for compatibility but not used)

**Improvements:**
- Physically-based conductivity reduction
- Better alignment with soil physics literature
- Consistent with SSURGO parameter estimation

**Use Case:** Research applications requiring defensible parameter sources

### Version 9003 (Burn Severity Codes)

**Introduced:** WEPPcloud (2018)

**New OFE Parameters:**
- `burn_code` - Burn severity classification (unburned, low, moderate, high)
- `texid_enum` - Integer texture code (1-4)
- `lkeff` - Lower limit on keff (mm/h) to simulate hydrophobicity

**Lower keff Limit:**
- Prevents keff from falling below `lkeff` even as soil wets
- Simulates persistent water repellency in burned soils
- Typical values: 1.0 (high severity) to 10.0 (low severity)

**Use Case:** Wildfire erosion prediction, BAER (Burned Area Emergency Response), burn severity mapping

### Version 9005 (Revegetation)

**Introduced:** WEPPcloud (2022, Beta)

**New OFE Parameters:**
- `uksat` - Upper limit on keff (mm/h) for revegetation recovery
- Enhanced texture enum for finer classification

**keff Bounds:**
- `lkeff` ≤ keff ≤ `uksat`
- Enables modeling of vegetation-driven infiltration improvement
- Supports multi-year post-fire recovery trajectories

**Use Case:** Long-term post-fire monitoring, revegetation effectiveness, treatment evaluation

## Module Documentation

### [WeppSoilUtil](utils/README.md)
Primary interface for parsing, transforming, and exporting WEPP soil files. Comprehensive documentation includes:
- Class methods and properties
- Version migration workflows
- Parameter replacement patterns
- Advanced transformation examples
- Integration with NoDb controllers

**Highlights:**
- Parse all WEPP versions (97.5 - 9005)
- Modify saturation, conductivity, erodibility
- Migrate between versions with automatic parameter estimation
- Export to WEPP, YAML, or BSON formats

### [Soil Library (soilsdb)](soilsdb/README.md)
Pre-built WEPP soil files for standardized modeling. Comprehensive documentation includes:
- API reference (`load_db()`, `get_soil()`, `read_disturbed_wepp_soil_fire_pars()`)
- Library collections (Database, Forest, Forest2006)
- 32 forest/rangeland/disturbed soils by texture and land cover
- State-specific NRCS soil series
- Usage examples and integration patterns

**Highlights:**
- 50+ state directories with NRCS soil series
- Standardized forest, shrub, grass, skid trail, and burned soils
- Legacy 2006.2 format collection for backward compatibility
- Wildfire parameter lookup by texture and burn severity


### Parameter descriptions

#### Soil
 - datver: dataversion (e.g. 2006, 7777, 7778, 9001, 9002, 9003)
 - solcom: User comment line - character*80 
 - ntemp: number of overland flow elements(OFE’s) or channels integer
 - ksflag: flag to use internal hydraulic conductivity adjustments
   - 0: do not use adjustments (conductivity will be held constant)
   - 1: use internal adjustments

#### OFE
 - slid: soil name for current OFE or channel
 - texid: soil texture for current OFE or channel
 - nsl: number of soil layers for current OFE or channel
 - salb: albedo of the bare dry surface soil on the current OFE or channel
 - sat: initial saturation level of the soil profile porosity (m/m)
 - ki: baseline interrill erodibility parameter (kg*s/m^4)
 - kr: baseline rill erodibility parameter (s/m)
 - shcrit: baseline critical shear parameter (N/m2) 
 - avke: effective hydraulic conductivity of surface soil (mm/h) _> 94.1 and < 2006.2_
 - luse: disturbed class (forest, shrub, grass, ...)
 - stext: simple soil texture (clay, clay loam, silt, sand)
 - ksatadj: flag to specify using soil saturation (`keff`) adjustment for forests
   - 0: do not adjust
   - 1: do internal adjustment
 - ksatfac: specifies lower bound for `keff` adjustment _9001_
 - ksatrec: exponential recovery parameter for `keff` adjustment _9001_

#### Horizon
 - solthk: horizon depth (mm)
 - bd: bulk density
 - ksat: hydraulic conductivity _< 94.1 or ≥ 7777_
 - anisotropy: _≥ 7778_
 - fc: field capacity _≥ 7778_
 - wp: wilting point _≥ 7778_
 - sand: percentage of sand content (%)
 - clay: percentage of  clay content (%)
 - orgmat: percentage of organic matter (%)
 - cec: cation exchange capacity in the layer (meq/100 g of soil)
 - rfg: percentage of rock fragments by volume in the layer (%)


#### Restrictive Layer
 - slflag: flag to specify restrictive layer
   - 0: no restrictive layer
   - 1: restritive layer present
 - ui_bdrkth: bed rock depth (mm)
 - kslast: hydraulic conductivity of restrictive layer
