# Swiss Private Housing Discovery & Spatial Density Pipeline (`ch-housing-finder`)

A reproducible, offline-first geospatial data pipeline in Python built on **DuckDB (with the `spatial` extension)** to locate physical private residential houses across Switzerland matching configurable criteria (standalone houses, dual-family houses, row houses with private gardens, within a 10-minute walk of public transit AND a restaurant), and aggregate them into an interactive spatial density map.

**Strict Privacy & Open Data Guarantee:** This project **never** scrapes commercial real estate portals. It relies exclusively on official Swiss Open Government Data (OGD) bulk downloads from [`geo.admin.ch`](https://data.geo.admin.ch), [`bfs.admin.ch`](https://www.bfs.admin.ch), and [`housing-stat.ch`](https://www.housing-stat.ch) / [`madd.bfs.admin.ch`](https://public.madd.bfs.admin.ch). Once downloaded, all spatial joins, filtering, and garden proxy calculations execute **100% offline** in DuckDB.

---

## Architecture & Data Flow

```mermaid
flowchart TD
    subgraph OGD["Swiss Federal Open Government Data (Bulk Downloads)"]
        GWR["Federal Register of Buildings (GWR/MADD)<br/>public.madd.bfs.admin.ch"]
        OV["ARE ÖV-Güteklassen (Transit Quality)<br/>data.geo.admin.ch (ch.are.gueteklassen_oev)"]
        STOPS["BAV Haltestellen des öffentlichen Verkehrs<br/>data.geo.admin.ch (ch.bav.haltestellen-oev)"]
        REST["GWR Gastronomie & Hotelgewerbe<br/>GKLAS 1211 in gebaeude.csv"]
        POP["BFS STATPOP 100m Population Grid<br/>data.geo.admin.ch (ch.bfs.statistik-bevoelkerung_haushalte)"]
        BZ["ARE Bauzonen Schweiz (Building Zones)<br/>data.geo.admin.ch / kgk-cgc.ch"]
        LC["Land Cover (swissTLM3D / Arealstatistik)<br/>data.geo.admin.ch"]
        CAD["(Optional) Cantonal Cadastre (Amtliche Vermessung)<br/>data/raw/cantons/*.gpkg"]
    end

    subgraph INGEST["Ingestion & DuckDB Storage (EPSG:2056)"]
        FETCH["download.py<br/>(Resumable, STAC API discovery, Cache check)"]
        DB[("data/processed/switzerland.duckdb<br/>DuckDB + Spatial Extension")]
    end

    subgraph PIPELINE["Offline Geospatial Pipeline (pipeline.py)"]
        F1["1. Filter Building Status<br/>GSTAT = 1004 (Existing Only)"]
        F2["2. Residential Categorization<br/>GKAT = 1020 (Pure) or 1030 (Mixed)<br/>Exclude 1040, 1060, 1080"]
        F3["3. House Types Classification<br/>Standalone (1110), Dual-family (1121, ≤2 units), Row houses"]
        F4["4. ARE Residential Zoning<br/>ST_Intersects with Wohnzonen (11) & Mischzonen (12)"]
        F5["5. Hybrid Garden Scoring Proxy<br/>Buffer (20m) - Footprint ∩ Vegetated Polygons<br/>OR Exact Cadastral Override (min 100m², green ratio ≥ 0.35)"]
        F6["6. Public Transit Distance & Walk Time<br/>Nearest Stop & ARE Güteklassen A,B,C<br/>ST_Distance ≤ 800m (≤ 10 min walk)"]
        F7["7. Restaurant Distance & Walk Time<br/>Nearest Gastronomy Venue<br/>ST_Distance ≤ 800m (≤ 10 min walk)"]
        F8["8. Urban Density Join<br/>100m STATPOP Grid Snap & Radius Sum"]
    end

    subgraph OUTPUT["Outputs & Interactive Visualization"]
        PQ["output/matching_houses.parquet"]
        GJ["output/matching_houses.geojson"]
        HEX["output/density_hex.geojson<br/>(H3 Res 7 & 8 Polygons)"]
        MAP["output/density_map.html<br/>(Standalone Interactive Folium Map)"]
    end

    OGD --> FETCH --> DB
    CAD -.-> DB
    DB --> F1 --> F2 --> F3 --> F4 --> F5 --> F6 --> F7 --> F8
    F8 --> PQ
    F8 --> GJ
    GJ --> HEX
    GJ --> MAP
```

---

## Features

- **DuckDB Spatial Engine:** Executes fast spatial joins (`ST_Within`, `ST_Intersects`, `ST_Buffer`, `ST_Area`, `ST_Distance`, `ST_Transform`) entirely in local memory/file storage in native Swiss metric projection **EPSG:2056 (LV95)**.
- **Default Criteria (Houses with Garden, 10 min from Transit AND Restaurant):**
  - **Housing Types:** Defaults to `house` covering standalone single-family houses (`GKLAS=1110`, 1 dwelling), dual-family houses (`GKLAS=1121`, up to 2 dwellings), and attached row houses (`GKLAS=1110`, 1 dwelling, row classification).
  - **Existing Private Residential Buildings:** Strictly `GSTAT = 1004` (existing) and pure residential `GKAT = 1020` (or `1030` via flag). Excludes commercial (`1060`), mixed commercial (`1040`), and special structures (`1080`).
  - **Private Garden Determination:** Buffer net of footprint intersected with green land cover (`min_garden_m2 >= 100 m²` and `min_green_ratio >= 0.35`), within recognized residential/mixed building zones (`ch.are.bauzonen`).
  - **10-Minute Walk to Public Transport:** Distance to nearest transit stop (`ch.bav.haltestellen-oev`) $\le$ 800 meters ($\le$ 10.0 minutes at standard 4.8 km/h pedestrian velocity) and ARE Transit Quality Class A, B, or C.
  - **10-Minute Walk to a Restaurant:** Distance to nearest gastronomy / restaurant location (`GKLAS=1211`) $\le$ 800 meters ($\le$ 10.0 minutes walking time).
- **Optional Cantonal Cadastre Plugin Hook:**
  - If official cadastral parcels (Amtliche Vermessung `Bodenbedeckung` or `Liegenschaften`) are placed into `data/raw/cantons/`, the exact parcel `Gartenanlage` polygon area automatically overrides the buffer proxy.
- **BFS STATPOP Urban Density:**
  - Fast 100m grid coordinate snap (`FLOOR(x / 100) * 100`, `FLOOR(y / 100) * 100`) providing local hectare population and neighborhood density filters.
- **H3 Density Aggregation & Interactive HTML Map:**
  - Bins matching houses into Uber H3 hexagons (resolutions 7 & 8) with counts, median garden size, median green ratio, median walk time to transit, median walk time to restaurant, dominant transit class, and dominant house type.
  - Generates a standalone, zero-dependency interactive HTML map (`output/density_map.html`) viewable in any modern web browser offline.
  - **Tile Usage Policy Compliance:** Uses the official Swiss Federal Geoportal **swisstopo WMTS raster basemap** (`wmts.geo.admin.ch`) as the primary default layer, eliminating unauthorized bulk or automated tile traffic against donation-funded OpenStreetMap servers (`tile.openstreetmap.org`) in strict accordance with the [OpenStreetMap Tile Usage Policy](https://operations.osmfoundation.org/policies/tiles/). Includes full copyright attributions for all optional layers (swisstopo, CartoDB, OpenStreetMap).

---

## Repository Structure

```text
ch-housing-finder/
├── pyproject.toml               # Modern Python dependencies and package definition
├── README.md                    # Documentation, architecture, and usage
├── config.default.yaml          # Default filter thresholds, dataset URLs & STAC endpoints
├── data/
│   ├── raw/                     # Downloaded official archives (gitignored)
│   │   └── cantons/             # (Optional) Drop cantonal cadastral .gpkg here
│   └── processed/               # Intermediate switzerland.duckdb (gitignored)
├── output/                      # Final GeoParquet, GeoJSON, and density map HTML
│   ├── matching_houses.parquet  # Filtered inventory with all attributes
│   ├── matching_houses.geojson  # GeoJSON Point FeatureCollection (EPSG:4326)
│   ├── density_hex.geojson      # H3 hexagon density polygons (EPSG:4326)
│   └── density_map.html         # Self-contained interactive heatmap
├── src/
│   └── ch_housing/
│       ├── __init__.py
│       ├── cli.py               # Typer CLI entrypoint (fetch, build, query, map, run, seed)
│       ├── download.py          # Resumable OGD fetcher with STAC API auto-discovery
│       ├── ingest.py            # Loads CSV/GPKG/Parquet into DuckDB Spatial
│       ├── pipeline.py          # Offline filtering, spatial joins, and garden scoring
│       ├── density.py           # H3 hex binning & interactive Folium map export
│       └── seed.py              # Realistic Swiss sample database generator for testing
└── tests/
    └── test_pipeline.py         # Comprehensive unit tests with synthetic LV95 records
```

---

## Installation & Setup

Requires Python **3.11+** or **3.12+**. Using [`uv`](https://github.com/astral-sh/uv) is recommended for fast installation:

```bash
# Clone the repository
git clone https://github.com/your-org/housing-map-ch.git
cd housing-map-ch

# Create virtual environment with Python 3.12
uv venv --python 3.12
source .venv/bin/activate

# Install dependencies and package in editable mode
uv pip install -e .
```

*Alternatively, using standard `pip`:*
```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -e .
```

---

## Quickstart (Instant Demo)

To test the entire pipeline immediately without downloading large federal archives:

```bash
# 1. Seed sample database with representative Swiss houses across multiple cantons
ch-housing seed

# 2. Run query filtering and interactive map export
ch-housing run --cantons BE,ZH,LU,VD,GE --building-type house --min-garden-m2 100

# 3. Open the resulting interactive map in your browser
xdg-open output/density_map.html   # On Linux
# open output/density_map.html     # On macOS
```

---

## Official Bulk Pipeline Workflow

### Step 1: Fetch Official Bulk Datasets (`fetch`)
Downloads nationwide bulk releases into `data/raw/` with resumable downloads, cache checks, and automatic STAC API discovery:

```bash
# Fetch all federal datasets
ch-housing fetch

# Or fetch a single dataset (e.g. GWR building register)
ch-housing fetch --dataset gwr

# Force redownload
ch-housing fetch --force
```

Datasets fetched:
- **GWR / MADD:** Federal Register of Buildings and Dwellings (`https://public.madd.bfs.admin.ch/ch.zip`).
- **ÖV-Güteklassen:** ARE Public Transport Quality Classes (`ch.are.gueteklassen_oev` GeoPackage).
- **STATPOP:** BFS Population & Households Statistics 100m grid (`ch.bfs.statistik-bevoelkerung_haushalte` Parquet/CSV).
- **Bauzonen Schweiz:** ARE Harmonized Building Zones (`ch.are.bauzonen` / KGK-CGC GeoPackage).
- **Land Cover:** BFS Arealstatistik / swisstopo swissTLM3D Bodenbedeckung.

### Step 2: Build DuckDB Spatial Database (`build`)
Ingests raw CSVs, GeoPackages, and Parquet files into `data/processed/switzerland.duckdb` and establishes spatial indexes:

```bash
ch-housing build
```

*(Optional Cantonal Cadastre Hook)*: Drop cantonal cadastral GeoPackages (Amtliche Vermessung `Bodenbedeckung` or `Liegenschaften`) into `data/raw/cantons/` prior to running `build` or `query` to enable exact parcel garden polygons.

### Step 3: Offline Filtering & Garden Scoring (`query`)
Executes offline filtering and exports matching houses to Parquet and GeoJSON:

```bash
# Default query: Standalone, dual-family & row houses with garden, ≤10min walk to transit AND restaurant
ch-housing query

# Query specific cantons with at least 150m² garden
ch-housing query --cantons ZH,BE --min-garden-m2 150.0

# Dual-family houses with strict 5-minute walk to transit and restaurant
ch-housing query --building-type dual-family --max-transit-walk-min 5.0 --max-restaurant-walk-min 5.0

# Small multi-family houses (max 3 units) in high-transit zones (A or B)
ch-housing query --building-type small-mfh --max-units 3 --transit-classes A,B

# Low-density rural/suburban houses (max 40 residents/hectare)
ch-housing query --max-density 40.0 --min-green-ratio 0.40
```

#### Available CLI Options:
| Flag | Default | Description |
|---|---|---|
| `--cantons` | `ALL` | Comma-separated canton codes (e.g. `ZH,BE,AG,VD`) |
| `--building-type` | `house` | Classification: `house` (default: standalone, dual-family, row), `standalone`, `dual-family`, `row`, `small-mfh`, or `any` |
| `--max-units` | `2` | Maximum dwelling units per building (`GANZWHG`), default 2 to include dual-family |
| `--include-mixed-use` | `False` | When passed, includes secondary residential (`GKAT=1030`) |
| `--pure-residential-only` | `True` | Restricts strictly to pure residential (`GKAT=1020`) |
| `--transit-classes` | `A,B,C` | Permitted ARE ÖV-Güteklassen (comma-separated e.g. `A,B,C`) |
| `--max-transit-walk-min` | `10.0` | Maximum walking time to public transit in minutes |
| `--max-transit-dist-m` | `800.0` | Maximum walking distance to public transit in meters |
| `--max-restaurant-walk-min` | `10.0` | Maximum walking time to nearest restaurant in minutes |
| `--max-restaurant-dist-m` | `800.0` | Maximum walking distance to nearest restaurant in meters |
| `--min-density` | `0.0` | Minimum residents per hectare |
| `--max-density` | `None` | Maximum residents per hectare |
| `--min-garden-m2` | `100.0` | Minimum estimated private garden area in square meters |
| `--min-green-ratio` | `0.35` | Minimum ratio of vegetated surface in 20m buffer (0.0 to 1.0) |
| `--garden-buffer-m` | `20.0` | Building parcel proxy buffer radius in meters |
| `--basemap` | `swisstopo-gray` | Default basemap layer: `swisstopo-gray` (OGD), `swisstopo-color`, `swisstopo-imagery`, `cartodb-positron`, `openstreetmap` |
| `--config` | `config.default.yaml` | Path to configuration file |

### Step 4: Spatial Density Map Export (`map`)
Aggregates matching houses into H3 hexagons and generates an interactive map:

```bash
ch-housing map --h3-res 7 --output output/density_map.html
```

---

## Output Schema

### 1. `output/matching_houses.parquet` & `output/matching_houses.geojson`
Every matching house record contains:

| Column | Type | Description |
|---|---|---|
| `egid` | BIGINT | Federal Building Identifier (Eidgenössischer Gebäudeidentifikator) |
| `canton` | VARCHAR | Canton 2-letter abbreviation (e.g. `BE`, `ZH`) |
| `municipality` | VARCHAR | Municipality name (Gemeindename) |
| `street` | VARCHAR | Street name (Strassenname) |
| `house_number` | VARCHAR | House / entrance number (Hausnummer) |
| `postal_code` | INTEGER | 4-digit postal code (PLZ4) |
| `city` | VARCHAR | Postal locality name |
| `gkode` | DOUBLE | Swiss Easting coordinate in EPSG:2056 / LV95 (meters) |
| `gkodn` | DOUBLE | Swiss Northing coordinate in EPSG:2056 / LV95 (meters) |
| `lat` | DOUBLE | Latitude in WGS84 (EPSG:4326) |
| `lon` | DOUBLE | Longitude in WGS84 (EPSG:4326) |
| `gkat` | INTEGER | Building Category (1020: pure residential; 1030: other residential) |
| `gklas` | INTEGER | Building Class (1110: 1-dwelling; 1121: 2-dwelling; 1122: 3+ dwelling MFH) |
| `house_type` | VARCHAR | Detailed classification (`standalone`, `dual-family`, `row`, `small-mfh`) |
| `num_dwellings` | INTEGER | Total dwellings count in building (`GANZWHG`) |
| `building_area_m2` | DOUBLE | Official building footprint area (`GAREA` in m²) |
| `ov_class` | VARCHAR | ARE Public Transport Quality Class (`A`, `B`, `C`, `D`, or `None`) |
| `dist_to_transit_m` | DOUBLE | Metric distance to nearest public transport stop (meters) |
| `walk_time_transit_min` | DOUBLE | Estimated walking time to public transit (minutes at 4.8 km/h) |
| `dist_to_restaurant_m` | DOUBLE | Metric distance to nearest gastronomy / restaurant location (meters) |
| `walk_time_restaurant_min` | DOUBLE | Estimated walking time to nearest restaurant (minutes at 4.8 km/h) |
| `local_pop_density` | DOUBLE | BFS STATPOP resident count in local 100m × 100m hectare cell |
| `estimated_garden_m2`| DOUBLE | Estimated private garden surface in m² (hybrid proxy or cadastral override) |
| `green_ratio` | DOUBLE | Ratio of vegetated ground in surrounding building buffer (0.0 to 1.0) |

### 2. `output/density_hex.geojson`
H3 hexagon polygons with aggregate attributes:
- `cell_id`: H3 hexagon index string.
- `resolution`: H3 resolution level (7 or 8).
- `count`: Number of matching houses in the cell.
- `median_garden_m2`: Median garden area across all houses in the cell.
- `median_green_ratio`: Median green surface ratio.
- `median_pop_density`: Median local population density (residents/ha).
- `dominant_ov_class`: Predominant ÖV-Güteklasse in the hex.
- `median_walk_transit_min`: Median walk time to public transport in minutes.
- `median_walk_restaurant_min`: Median walk time to a restaurant in minutes.
- `dominant_house_type`: Predominant house type in the hex cell (`standalone`, `dual-family`, `row`).

### 3. `output/density_map.html`
A self-contained HTML file featuring:
- Interactive zoomable Swiss map with H3 density heatmap tiles.
- Dynamic color-coding from light green (low density) to dark blue (high density).
- Clickable and hover tooltips showing cell ID, house counts, median walk times, dominant house type, and median statistics.
- Interactive toggleable individual house markers with address, EGID, walk times to transit & restaurant, and garden specs.
- Fixed legend and data provenance panel adhering to official swisstopo OGD & OpenStreetMap tile attribution policies.

---

## Testing & Verification

Unit tests use synthetic Swiss LV95 records to test edge cases:
- Standalone, dual-family, and row houses matching default criteria.
- Commercial building exclusion (`GKAT=1060`).
- Planned and demolished building exclusion (`GSTAT!=1004`).
- Multi-family apartment complexes exceeding unit thresholds.
- Houses without a restaurant within a 10-minute walk (>800m).
- Houses without public transit within a 10-minute walk (>800m).
- Dense urban buildings with zero garden / sealed surfaces.
- Houses situated in industrial zones (`Arbeitszonen`).
- Walking time and metric distance computation accuracy (transit and restaurant).
- Mixed-use residential toggle (`GKAT=1030` vs `GKAT=1020`).
- H3 hexagon density aggregation and map export.
- Tile Usage Policy compliance (swisstopo WMTS, CartoDB, OSM attributions).
- CLI runner and argument validation.
- YAML configuration loading and defaults.

To run the unit test suite:

```bash
PYTHONPATH=src pytest tests/ -v
```

Expected output:
```text
tests/test_pipeline.py::test_default_criteria_matches_standalone_dual_family_and_row PASSED
tests/test_pipeline.py::test_commercial_building_exclusion PASSED
tests/test_pipeline.py::test_planned_and_demolished_buildings_exclusion PASSED
tests/test_pipeline.py::test_dense_apartment_blocks_exclusion PASSED
tests/test_pipeline.py::test_house_without_restaurant_within_10min_exclusion PASSED
tests/test_pipeline.py::test_house_without_transit_within_10min_exclusion PASSED
tests/test_pipeline.py::test_zero_garden_urban_flat_exclusion PASSED
tests/test_pipeline.py::test_industrial_zone_exclusion PASSED
tests/test_pipeline.py::test_walk_times_and_distances_computed PASSED
tests/test_pipeline.py::test_mixed_use_toggle PASSED
tests/test_pipeline.py::test_density_map_export PASSED
tests/test_pipeline.py::test_tile_usage_policy_compliance PASSED
tests/test_pipeline.py::test_cli_runner PASSED
tests/test_pipeline.py::test_config_loader PASSED
============================== 14 passed ==============================
```

---

## License

MIT License. Open data sources are governed by their respective Swiss federal OGD terms of use (Federal Statistical Office BFS, Federal Office for Spatial Development ARE, and Federal Office of Topography swisstopo).
