In this section
- Port CSV to Parquet Impl storage · data-gb-electricity / pipelines/port_csv_to_parquet_impl.py lines 1–200
- Verify Bounded Growth storage · data-gb-electricity / pipelines/verify_bounded_growth.py lines 1–141
- Test Price Daily Browser test · data-gb-electricity / tests/test_price_daily_browser.py lines 1–152
- Test Price Rollup Parts test · data-gb-electricity / tests/test_price_rollup_parts.py lines 1–85
Port CSV to Parquet Impl
A Python command-line tool in the pipelines folder of Data GB Electricity that reads half hourly, years, combined and audit.
storagedata-gb-electricity / pipelines/port_csv_to_parquet_impl.py · lines 1–200 of 200 · Entry point · pattern sources (shared by 6 files)
- What it does
- It loads half hourly, years, combined and audit. Defines 8 functions or classes, including mb, exclude_combined_sources, sources, check_counts, convert. Uses libraries __future__, argparse, glob, json, shutil. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "That wrapper calls `pipelines/port_csv_to_parquet_impl.py`, where the current implementation lives."
- Inputs & outputs
- In: CSV file _half_hourly.csv; CSV file _all_years.csv; CSV file _combined.csv; JSON file latest_parquet_audit.json; DuckDB queries; command-line arguments.
- Downstream impact
- Used directly by 1 file: Port CSV to Parquet (data-gb-electricity). Reached from 1 other entry point, including Backfill History Workflow (data-gb-electricity).
- What it achieves
- It checks counts (`check_counts`) and is built from the exclude combined sources helper (`exclude_combined_sources`) and the sources step (`sources`). The README says: That wrapper calls `pipelines/port_csv_to_parquet_impl.py`, where the current implementation lives. It accepts `--source-root`, `--output-root` and `--apply`.
- Why it matters
- Imported by Port CSV to Parquet.
- Application
- data-gb-electricity · pipelines · Python CLI
- Uses
- __future__, argparse, glob, json, shutil, sys, datetime, pathlib
- Used by
- imported by Port CSV to Parquet (import)
- Produces
- mb, exclude_combined_sources, sources, check_counts, convert, duplicate_key_groups, verify, main
- Defines here
- mb, exclude_combined_sources, sources, check_counts, convert, duplicate_key_groups, verify, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-gb-electricity@e888f35c1a65589b3eb7c78bcc542022bc707298 pipelines/port_csv_to_parquet_impl.py:1-200 · blob 2c6d50843d17134dfb73321ce995c8dbafedc519 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import glob
import json
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path
import duckdb
EXPECTED = {
"fuelinst": 72,
"fuelhh": 125,
"prices": 11,
"parquet_files_min": 300,
"canary_rows": 156_960,
}
COMBINED_SOURCE_MARKERS = (
"_half_hourly.csv",
"_all_years.csv",
"_combined.csv",
)
def mb(path: Path) -> float:
if path.is_file():
return round(path.stat().st_size / 1048576, 3)
if not path.exists():
return 0.0
return round(sum(p.stat().st_size for p in path.rglob("*") if p.is_file()) / 1048576, 3)
def exclude_combined_sources(files: list[str]) -> list[str]:
clean: list[str] = []
for file in files:
name = Path(file).name.lower()
if any(name.endswith(marker) for marker in COMBINED_SOURCE_MARKERS):
continue
clean.append(file)
return sorted(clean)
def sources(root: Path) -> dict[str, list[str]]:
return {
"fuelinst": exclude_combined_sources(sorted(glob.glob(str(root / "data/generation/archive/*/*.csv")))),
"fuelhh": exclude_combined_sources(sorted(glob.glob(str(root / "data/generation/fuelhh_halfhourly/*/*.csv")))),
"prices": exclude_combined_sources(sorted(glob.glob(str(root / "data/electricity/elexon_system_prices_*.csv")))),
}
def check_counts(src: dict[str, list[str]]) -> None:
print(f"found clean source files: {len(src['fuelinst'])} FUELINST, {len(src['fuelhh'])} FUELHH, {len(src['prices'])} price files")
for key in ("fuelinst", "fuelhh", "prices"):
if len(src[key]) < EXPECTED[key]:
raise SystemExit(f"count below clean baseline for {key}: {len(src[key])} < {EXPECTED[key]}")
def convert(src_root: Path, out_root: Path) -> None:
src = sources(src_root)
check_counts(src)
for rel in ("generation", "prices"):
target = out_root / rel
if target.exists():
shutil.rmtree(target)
(out_root / "generation").mkdir(parents=True, exist_ok=True)
(out_root / "prices").mkdir(parents=True, exist_ok=True)
con = duckdb.connect()
out = str(out_root)
fi, fh, pr = src["fuelinst"], src["fuelhh"], src["prices"]
con.execute(f"""COPY (
WITH raw AS (
SELECT *, row_number() OVER (PARTITION BY periodStartUTC, fuelType ORDER BY filename) AS _rn
FROM read_csv_auto({fi!r}, union_by_name=true, filename=true)
)
SELECT * EXCLUDE (filename, _rn), 'fuelinst' AS dataset, year(periodStartUTC) AS year, month(periodStartUTC) AS month
FROM raw
WHERE _rn = 1
)
TO '{out}/generation/dataset=fuelinst' (FORMAT parquet, COMPRESSION zstd, PARTITION_BY (year,month), OVERWRITE_OR_IGNORE);""")
con.execute(f"""COPY (
WITH raw AS (
SELECT *, row_number() OVER (PARTITION BY "time", technology ORDER BY filename) AS _rn
FROM read_csv_auto({fh!r}, union_by_name=true, filename=true)
)
SELECT * EXCLUDE (filename, _rn), 'fuelhh' AS dataset, year("time") AS year, month("time") AS month
FROM raw
WHERE _rn = 1
)
TO '{out}/generation/dataset=fuelhh' (FORMAT parquet, COMPRESSION zstd, PARTITION_BY (year,month), OVERWRITE_OR_IGNORE);""")
con.execute(f"""COPY (
WITH raw AS (
SELECT *, row_number() OVER (PARTITION BY periodStartUTC ORDER BY filename) AS _rn
FROM read_csv_auto({pr!r}, union_by_name=true, filename=true)
)
SELECT * EXCLUDE (filename, _rn), year(periodStartUTC) AS year, month(periodStartUTC) AS month
FROM raw
WHERE _rn = 1
)
TO '{out}/prices' (FORMAT parquet, COMPRESSION zstd, PARTITION_BY (year,month), OVERWRITE_OR_IGNORE);""")
def duplicate_key_groups(con: duckdb.DuckDBPyConnection, query: str) -> int:
return int(con.execute(query).fetchone()[0])
def verify(out_root: Path) -> dict[str, object]:
con = duckdb.connect()
parquet_files = list(out_root.glob("generation/**/*.parquet")) + list(out_root.glob("prices/**/*.parquet"))
total_mb = round(sum(p.stat().st_size for p in parquet_files) / 1048576, 3)
canary = con.execute(
f"SELECT count(*) FROM read_parquet('{out_root}/generation/dataset=fuelinst/year=2023/month=9/*.parquet')"
).fetchone()[0]
duplicates = {
"fuelinst": duplicate_key_groups(con, f"""
SELECT count(*) FROM (
SELECT periodStartUTC, fuelType, count(*) AS c
FROM read_parquet('{out_root}/generation/dataset=fuelinst/year=*/month=*/*.parquet')
GROUP BY 1, 2
HAVING count(*) > 1
)
"""),
"fuelhh": duplicate_key_groups(con, f"""
SELECT count(*) FROM (
SELECT "time", technology, count(*) AS c
FROM read_parquet('{out_root}/generation/dataset=fuelhh/year=*/month=*/*.parquet')
GROUP BY 1, 2
HAVING count(*) > 1
)
"""),
"prices": duplicate_key_groups(con, f"""
SELECT count(*) FROM (
SELECT periodStartUTC, count(*) AS c
FROM read_parquet('{out_root}/prices/year=*/month=*/*.parquet')
GROUP BY 1
HAVING count(*) > 1
)
"""),
}
report = {
"generated_utc": datetime.now(timezone.utc).isoformat(),
"parquet_files": len(parquet_files),
"parquet_files_minimum_baseline": EXPECTED["parquet_files_min"],
"total_mb": total_mb,
"fuelinst_mb": mb(out_root / "generation/dataset=fuelinst"),
"fuelhh_mb": mb(out_root / "generation/dataset=fuelhh"),
"prices_mb": mb(out_root / "prices"),
"fuelinst_2023_09_rows": canary,
"duplicate_key_groups": duplicates,
}
print(json.dumps(report, indent=2))
if len(parquet_files) < EXPECTED["parquet_files_min"]:
raise SystemExit("parquet file count below baseline")
if total_mb < 25.0:
raise SystemExit("parquet size below expected minimum baseline")
if canary != EXPECTED["canary_rows"]:
raise SystemExit("canary row count mismatch")
if any(count != 0 for count in duplicates.values()):
raise SystemExit(f"duplicate key groups found: {duplicates}")
return report
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--source-root", default="../globalgrid2050")
ap.add_argument("--output-root", default=".")
ap.add_argument("--apply", action="store_true")
ap.add_argument("--report", default="reports/latest_parquet_audit.json")
args = ap.parse_args()
src_root = Path(args.source_root).resolve()
out_root = Path(args.output_root).resolve()
src = sources(src_root)
check_counts(src)
print("clean source MB:", {k: round(sum(Path(f).stat().st_size for f in v) / 1048576, 3) for k, v in src.items()})
report = {"generated_utc": datetime.now(timezone.utc).isoformat(), "mode": "apply" if args.apply else "audit"}
if args.apply:
convert(src_root, out_root)
report.update(verify(out_root))
else:
print("audit only - no parquet written")
report_path = out_root / args.report
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(json.dumps(report, indent=2) + "\n")
print(f"report written: {report_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())Verify Bounded Growth
A Python command-line tool in the pipelines folder of Data GB Electricity that reads audit, fetch month and bounded growth gate.
storagedata-gb-electricity / pipelines/verify_bounded_growth.py · lines 1–141 of 141 · Entry point
- What it does
- It loads audit, fetch month and bounded growth gate. Defines git_output, working_tree_changes, evaluate_changes, main. Uses libraries __future__, argparse, json, re, subprocess. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file latest_parquet_audit.json; JSON file fetch_latest_month_latest.json; JSON file bounded_growth_gate_latest.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: Monthly Update Workflow (data-gb-electricity); Test Bounded Monthly Update (data-gb-electricity). Reached from 1 other entry point, including Refresh Price Decade Rollup Workflow (data-gb-electricity).
- What it achieves
- It is built from the git output helper (`git_output`), the working tree changes helper (`working_tree_changes`) and the evaluate changes helper (`evaluate_changes`). Fail CI if a monthly update exceeds its declared repository-growth scope. It accepts `--audit`, `--base` and `--max-new-parquet-files`.
- Why it matters
- Run by Monthly Update Workflow. Checked by Test Bounded Monthly Update.
- Application
- data-gb-electricity · pipelines · Python CLI
- Uses
- __future__, argparse, json, re, subprocess, pathlib, typing
- Used by
- run by Monthly Update Workflow (workflow run), imported by Test Bounded Monthly Update (sys.path import)
- Produces
- git_output, working_tree_changes, evaluate_changes, main
- Defines here
- git_output, working_tree_changes, evaluate_changes, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-gb-electricity@e888f35c1a65589b3eb7c78bcc542022bc707298 pipelines/verify_bounded_growth.py:1-141 · blob 7c29d81d95043f9e15b38c156ea8e5064552e034 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Fail CI if a monthly update exceeds its declared repository-growth scope."""
from __future__ import annotations
import argparse
import json
import re
import subprocess
from pathlib import Path
from typing import Any
DATA_PATH = re.compile(
r"^(?:generation/dataset=(fuelinst|fuelhh)|(?P<prices>prices))/year=(\d{4})/month=(\d{1,2})/([^/]+)$"
)
ALLOWED_REPORTS = {
"reports/latest_parquet_audit.json",
"reports/fetch_latest_month_latest.json",
"reports/bounded_growth_gate_latest.json",
}
def git_output(*args: str) -> str:
result = subprocess.run(["git", *args], check=True, text=True, capture_output=True)
return result.stdout
def working_tree_changes(base: str) -> list[tuple[str, str]]:
changes: dict[str, str] = {}
for line in git_output("diff", "--name-status", "--no-renames", base, "--").splitlines():
if not line.strip():
continue
status, path = line.split("\t", 1)
changes[path.replace("\\", "/")] = status[0]
for path in git_output("ls-files", "--others", "--exclude-standard").splitlines():
if path.strip():
changes[path.replace("\\", "/")] = "A"
return sorted((status, path) for path, status in changes.items())
def evaluate_changes(
audit: dict[str, Any],
changes: list[tuple[str, str]],
root: Path,
*,
max_new_parquet_files: int,
max_new_parquet_bytes: int,
) -> dict[str, Any]:
errors: list[str] = []
mode = audit.get("mode")
apply = audit.get("apply") is True
allowed: dict[str, str] = {}
for item in audit.get("plan", []):
if item.get("action") in {"ADD_MISSING", "REPAIR_EXISTING"}:
allowed[str(item.get("partition", "")).replace("\\", "/").rstrip("/")] = item["action"]
changed_parquet: list[dict[str, Any]] = []
seen_partitions: set[str] = set()
for status, path in changes:
if path in ALLOWED_REPORTS:
if status == "D":
errors.append(f"audit report deleted: {path}")
continue
match = DATA_PATH.match(path)
if match is None:
errors.append(f"monthly updater changed an out-of-scope path: {status} {path}")
continue
if not path.endswith(".parquet"):
errors.append(f"non-Parquet data artifact: {status} {path}")
continue
partition = path.rsplit("/", 1)[0]
action = allowed.get(partition)
if action is None:
errors.append(f"data changed outside the audited plan: {status} {path}")
continue
seen_partitions.add(partition)
if mode == "FILL_MISSING" and (action != "ADD_MISSING" or status != "A"):
errors.append(f"normal run must only add a missing partition: {status} {path}")
if mode == "EXPLICIT_REPAIR" and action != "REPAIR_EXISTING":
errors.append(f"repair run has a non-repair plan action: {status} {path}")
size = 0
physical = root / Path(path)
if status != "D" and physical.exists():
size = physical.stat().st_size
changed_parquet.append({"status": status, "path": path, "bytes": size, "action": action})
if apply and mode == "FILL_MISSING":
missing = sorted(set(allowed) - seen_partitions)
if missing:
errors.append("planned dataset-months produced no Parquet change: " + ", ".join(missing))
additions = [item for item in changed_parquet if item["status"] != "D"]
total_bytes = sum(int(item["bytes"]) for item in additions)
if len(additions) > max_new_parquet_files:
errors.append(f"{len(additions)} written Parquet files exceed limit {max_new_parquet_files}")
if total_bytes > max_new_parquet_bytes:
errors.append(f"{total_bytes} written Parquet bytes exceed limit {max_new_parquet_bytes}")
if mode not in {"FILL_MISSING", "EXPLICIT_REPAIR"}:
errors.append(f"unknown audit mode: {mode!r}")
return {
"schemaVersion": "data-gb-electricity.bounded-growth-gate.v1",
"status": "PASS" if not errors else "FAIL",
"mode": mode,
"limits": {
"maxNewParquetFiles": max_new_parquet_files,
"maxNewParquetBytes": max_new_parquet_bytes,
"actualWrittenParquetFiles": len(additions),
"actualChangedParquetFiles": len(changed_parquet),
"actualWrittenParquetBytes": total_bytes,
},
"changedParquet": changed_parquet,
"errors": errors,
}
def main() -> int:
parser = argparse.ArgumentParser(description="Verify the monthly updater changed only its bounded plan")
parser.add_argument("--audit", default="reports/fetch_latest_month_latest.json")
parser.add_argument("--base", default="HEAD")
parser.add_argument("--max-new-parquet-files", type=int, default=9)
parser.add_argument("--max-new-parquet-bytes", type=int, default=128 * 1024 * 1024)
parser.add_argument("--report", default="reports/bounded_growth_gate_latest.json")
args = parser.parse_args()
audit = json.loads(Path(args.audit).read_text(encoding="utf-8"))
result = evaluate_changes(
audit,
working_tree_changes(args.base),
Path("."),
max_new_parquet_files=args.max_new_parquet_files,
max_new_parquet_bytes=args.max_new_parquet_bytes,
)
if args.report:
Path(args.report).parent.mkdir(parents=True, exist_ok=True)
Path(args.report).write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(json.dumps(result, indent=2))
return 0 if result["status"] == "PASS" else 1
if __name__ == "__main__":
raise SystemExit(main())Test Price Daily Browser
A test in the tests folder of Data GB Electricity that checks Price Daily Browser. It sets up (`setUp`) and adds day (`add_day`).
testdata-gb-electricity / tests/test_price_daily_browser.py · lines 1–152 of 152 · Entry point · pattern result (shared by 8 files)
- What it does
- It tests its inputs. Defines 18 functions or classes, including DailyBrowserTests, setUp, tearDown, add_day, result. Uses libraries datetime, json, pathlib, sys, tempfile. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file index.json; Parquet file data_extra.parquet; JSON file 2026.json; Parquet file replacement.parquet; DuckDB queries.
- Downstream impact
- Used directly by 2 files: Monthly Update Workflow (data-gb-electricity); Refresh Price Decade Rollup Workflow (data-gb-electricity).
- What it achieves
- Synthetic daily `source-grain/DST/coverage` checks, plus actual-source replay. It writes `replacement.parquet`.
- Why it matters
- Run by Monthly Update Workflow and Refresh Price Decade Rollup Workflow.
- Application
- data-gb-electricity · tests · test
- Uses
- Price Daily Browser (sys.path import), datetime, json, pathlib, sys, tempfile, unittest, duckdb
- Used by
- run by Monthly Update Workflow (workflow run), run by Refresh Price Decade Rollup Workflow (workflow run)
- Produces
- DailyBrowserTests
- Defines here
- DailyBrowserTests, setUp, tearDown, add_day, result, test_spring46_and_autumn50_are_complete_source_days, test_every_physical_part_is_combined_without_market_index_prices, test_absent_dates_are_explicit_gaps_with_null_prices, test_missing_and_null_periods_are_partial_not_zero_or_imputed, test_legacy_utc_clock_disagreement_is_retained_and_counted, test_legacy_october_clock_collision_loss_stays_partial_on_oct31, test_unremoved_legacy_clock_key_collision_is_rejected, test_twenty_four_period_floor_never_certifies_a_complete_day, test_no_sell_observations_keep_null_mean_and_zero_price_coverage, test_duplicate_declared_periods_fail_before_replacing_output, test_impossible_spring_period47_is_not_allowed, test_corrupted_product_is_not_accepted_by_shape_only, test_negative_prices_remain_negative_and_full_parquet_readback_passes
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-gb-electricity@e888f35c1a65589b3eb7c78bcc542022bc707298 tests/test_price_daily_browser.py:1-152 · blob 84f55e4e22cc8736ff5d8e0551d9629ce8ffd636 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: supporting_data
"""Synthetic daily source-grain/DST/coverage checks, plus actual-source replay."""
import datetime as dt
import json
from pathlib import Path
import sys
import tempfile
import unittest
import duckdb
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'derived'))
import price_daily_browser as producer
class DailyBrowserTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.repo = Path(self.temp.name)
self.output = self.repo / 'derived/product'
self.db = duckdb.connect()
self.db.execute('CREATE TABLE fixture(settlementDate DATE,settlementPeriod BIGINT,periodStartUTC TIMESTAMPTZ,systemSellPriceGBPperMWh DOUBLE,marketIndexPrice DOUBLE)')
def tearDown(self):
self.db.close()
self.temp.cleanup()
def add_day(self, date, periods, first_utc, missing=(), null_price=(), split=False):
first = dt.datetime.fromisoformat(first_utc.replace('Z', '+00:00'))
for part in range(2 if split else 1):
self.db.execute('DELETE FROM fixture')
rows = [(date, i, (first+dt.timedelta(minutes=(i-1)*30)).isoformat(), None if i in null_price else float(i), 999.0)
for i in range(1, periods+1) if i not in missing and (not split or (i-1)%2 == part)]
self.db.executemany('INSERT INTO fixture VALUES (CAST(? AS DATE),?,CAST(? AS TIMESTAMPTZ),?,?)', rows)
target = self.repo / f'prices/year={date[:4]}/month={int(date[5:7])}/data_{date}_{part}.parquet'
target.parent.mkdir(parents=True, exist_ok=True)
self.db.sql('SELECT * FROM fixture ORDER BY periodStartUTC').write_parquet(str(target), compression='zstd')
def result(self):
index = producer.run(self.repo, self.output)
data = json.loads((self.output / str(index['parts'][0]['year'])).with_suffix('.json').read_bytes())
return index, data['rows']
def test_spring46_and_autumn50_are_complete_source_days(self):
for date, n, first in [('2026-03-29',46,'2026-03-29T00:00:00Z'),('2026-10-25',50,'2026-10-24T23:00:00Z')]:
with self.subTest(date=date):
self.add_day(date,n,first)
index, rows = self.result()
selected = {r['date']:r for r in rows}
self.assertEqual((selected['2026-03-29']['expected_periods'], selected['2026-10-25']['expected_periods']), (46,50))
self.assertEqual(selected['2026-03-29']['coverage_status'], 'COMPLETE_SOURCE_DAY')
self.assertEqual(selected['2026-10-25']['utc_alignment_mismatches'], 0)
self.assertEqual(index['observed_periods'],96)
def test_every_physical_part_is_combined_without_market_index_prices(self):
self.add_day('2026-01-01',48,'2026-01-01T00:00:00Z',split=True)
index, rows = self.result()
self.assertEqual(index['source_periods'],48)
self.assertEqual(rows[0]['mean_available_gbp_per_mwh'],24.5)
self.assertEqual(rows[0]['maximum_observed_gbp_per_mwh'],48.0)
def test_absent_dates_are_explicit_gaps_with_null_prices(self):
self.add_day('2026-01-01',48,'2026-01-01T00:00:00Z')
self.add_day('2026-01-03',48,'2026-01-03T00:00:00Z')
_, rows = self.result()
self.assertEqual(rows[1]['date'],'2026-01-02')
self.assertEqual(rows[1]['coverage_status'],'NO_OBSERVATIONS')
self.assertIsNone(rows[1]['mean_available_gbp_per_mwh'])
def test_missing_and_null_periods_are_partial_not_zero_or_imputed(self):
self.add_day('2026-01-01',48,'2026-01-01T00:00:00Z',missing=(1,2),null_price=(3,))
_, rows = self.result()
self.assertEqual((rows[0]['observed_periods'],rows[0]['priced_periods']),(46,45))
self.assertEqual(rows[0]['coverage_status'],'PARTIAL_SOURCE_DAY')
self.assertEqual(rows[0]['minimum_observed_gbp_per_mwh'],4.0)
def test_legacy_utc_clock_disagreement_is_retained_and_counted(self):
self.add_day('2026-07-01',48,'2026-07-01T00:00:00Z')
index, rows = self.result()
self.assertEqual(rows[0]['utc_alignment_mismatches'],48)
self.assertEqual(index['utc_alignment_mismatches'],48)
self.assertEqual(rows[0]['mean_available_gbp_per_mwh'],24.5)
self.assertIn('Source-declared', index['time_basis'])
def test_legacy_october_clock_collision_loss_stays_partial_on_oct31(self):
self.add_day('2016-10-30',50,'2016-10-30T00:00:00Z')
self.add_day('2016-10-31',48,'2016-10-31T00:00:00Z',missing=(1,2))
_, rows=self.result()
self.assertEqual((rows[0]['expected_periods'],rows[0]['utc_alignment_mismatches']),(50,50))
self.assertEqual((rows[1]['observed_periods'],rows[1]['expected_periods']),(46,48))
self.assertEqual(rows[1]['coverage_status'],'PARTIAL_SOURCE_DAY')
self.assertEqual(rows[1]['price_coverage_pct'],95.833333)
def test_unremoved_legacy_clock_key_collision_is_rejected(self):
self.add_day('2016-10-30',50,'2016-10-30T00:00:00Z')
self.add_day('2016-10-31',48,'2016-10-31T00:00:00Z')
with self.assertRaisesRegex(ValueError,'Price grain failed'):
producer.run(self.repo,self.output)
self.assertFalse(self.output.exists())
def test_twenty_four_period_floor_never_certifies_a_complete_day(self):
self.add_day('2026-01-01',24,'2026-01-01T00:00:00Z')
index, rows=self.result()
self.assertEqual(rows[0]['coverage_status'],'PARTIAL_SOURCE_DAY')
self.assertEqual(rows[0]['price_coverage_pct'],50.0)
self.assertEqual(index['parts'][0]['complete_days'],0)
def test_no_sell_observations_keep_null_mean_and_zero_price_coverage(self):
self.add_day('2026-01-01',48,'2026-01-01T00:00:00Z',null_price=tuple(range(1,49)))
_, rows=self.result()
self.assertIsNone(rows[0]['mean_available_gbp_per_mwh'])
self.assertEqual(rows[0]['price_coverage_pct'],0.0)
self.assertEqual(rows[0]['coverage_status'],'PARTIAL_SOURCE_DAY')
def test_duplicate_declared_periods_fail_before_replacing_output(self):
self.add_day('2026-01-01',48,'2026-01-01T00:00:00Z')
self.result()
saved = (self.output/'index.json').read_bytes()
self.db.execute('DELETE FROM fixture')
self.db.execute("INSERT INTO fixture VALUES ('2026-01-01',1,'2026-01-02T00:00:00Z',1,999)")
self.db.sql('SELECT * FROM fixture').write_parquet(str(self.repo/'prices/year=2026/month=1/data_extra.parquet'))
with self.assertRaisesRegex(ValueError,'duplicate'):
producer.run(self.repo,self.output)
self.assertEqual((self.output/'index.json').read_bytes(),saved)
def test_impossible_spring_period47_is_not_allowed(self):
self.add_day('2026-03-29',47,'2026-03-29T00:00:00Z')
with self.assertRaisesRegex(ValueError,'identity'):
producer.run(self.repo,self.output)
self.assertFalse(self.output.exists())
def test_corrupted_product_is_not_accepted_by_shape_only(self):
self.add_day('2026-01-01',48,'2026-01-01T00:00:00Z')
self.result()
part=self.output/'2026.json';data=json.loads(part.read_bytes());data['rows'][0]['mean_available_gbp_per_mwh']=999
part.write_bytes(producer.encode(data))
with self.assertRaisesRegex(ValueError,'actual source rebuild'):
producer.run(self.repo,self.output,verify=True)
def test_negative_prices_remain_negative_and_full_parquet_readback_passes(self):
self.add_day('2026-01-01',48,'2026-01-01T00:00:00Z')
p=next((self.repo/'prices').glob('**/*.parquet'))
self.db.read_parquet(str(p)).create_view('original')
self.db.sql('SELECT settlementDate,settlementPeriod,periodStartUTC, -systemSellPriceGBPperMWh AS systemSellPriceGBPperMWh,marketIndexPrice FROM original').write_parquet(str(p.with_name('replacement.parquet')))
p.unlink();p.with_name('replacement.parquet').rename(p)
index, rows=self.result()
self.assertEqual(rows[0]['mean_available_gbp_per_mwh'],-24.5)
self.assertEqual(index['parquet']['full_row_readback'],'PASS')
self.assertEqual(producer.run(self.repo,self.output,verify=True)['rows'],1)
if __name__ == '__main__':
unittest.main()Test Price Rollup Parts
A test in the tests folder of Data GB Electricity. It splits price parts tests (`SplitPricePartsTests`), sets up (`setUp`) and runs builder (`run_builder`).
testdata-gb-electricity / tests/test_price_rollup_parts.py · lines 1–85 of 85 · Entry point · pattern run_builder (shared by 2 files)
- What it does
- It tests its inputs. Defines 8 functions or classes, including SplitPricePartsTests, setUp, tearDown, run_builder, test_all_physical_parts_combine_before_daily_inclusion_and_verify. Uses libraries datetime, importlib, json, pathlib, sys. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file price-decade-rollup.json; Parquet file data_0.parquet; Parquet file data_2.parquet; DuckDB queries.
- Downstream impact
- Used directly by 2 files: Monthly Update Workflow (data-gb-electricity); Refresh Price Decade Rollup Workflow (data-gb-electricity).
- What it achieves
- Synthetic split-part regression; no upstream fetch or historical rewrite.
- Why it matters
- Run by Monthly Update Workflow and Refresh Price Decade Rollup Workflow.
- Application
- data-gb-electricity · tests · test
- Uses
- datetime, importlib, json, pathlib, sys, tempfile, unittest, unittest.mock
- Used by
- run by Monthly Update Workflow (workflow run), run by Refresh Price Decade Rollup Workflow (workflow run)
- Produces
- SplitPricePartsTests
- Defines here
- SplitPricePartsTests, setUp, tearDown, run_builder, test_all_physical_parts_combine_before_daily_inclusion_and_verify, test_a_duplicate_in_an_extra_part_fails_before_output_replacement, test_null_period_in_extra_part_is_not_hidden_by_daily_aggregation, test_nonfinite_price_does_not_become_an_aggregate
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-gb-electricity@e888f35c1a65589b3eb7c78bcc542022bc707298 tests/test_price_rollup_parts.py:1-85 · blob 9421b2c980493634d7cd8e664ef59533fde75575 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: supporting_data
"""Synthetic split-part regression; no upstream fetch or historical rewrite."""
import datetime
import importlib
import json
import pathlib
import sys
import tempfile
import unittest
from unittest.mock import patch
import duckdb
ROOT = pathlib.Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'derived'))
builder = importlib.import_module('build_price_decade_rollup')
verifier = importlib.import_module('verify_price_decade_rollup')
class SplitPricePartsTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.repo = pathlib.Path(self.temp.name)
self.derived = self.repo / 'derived'
self.derived.mkdir()
self.db = duckdb.connect(':memory:')
self.db.execute('CREATE TABLE fixture(settlementDate DATE,settlementPeriod BIGINT,periodStartUTC TIMESTAMPTZ,systemSellPriceGBPperMWh DOUBLE)')
for year in range(2016, 2026):
for part in (0, 1):
rows = []
for period in range(part * 12, (part + 1) * 12):
stamp = datetime.datetime(year, 1, 1, tzinfo=datetime.timezone.utc) + datetime.timedelta(minutes=period * 30)
rows.append((stamp.date().isoformat(), period + 1, stamp.isoformat(), float(period - 10)))
self.db.execute('DELETE FROM fixture')
self.db.executemany('INSERT INTO fixture VALUES (CAST(? AS DATE),?,CAST(? AS TIMESTAMPTZ),?)', rows)
target = self.repo / 'prices' / f'year={year}' / 'month=1' / f'data_{part}.parquet'
target.parent.mkdir(parents=True, exist_ok=True)
self.db.sql('SELECT * FROM fixture ORDER BY periodStartUTC').write_parquet(str(target), compression='zstd')
def tearDown(self):
self.db.close()
self.temp.cleanup()
def run_builder(self):
with patch.object(builder, 'REPO', str(self.repo)), patch.object(builder, 'HERE', str(self.derived)):
builder.main()
return json.loads((self.derived / 'price-decade-rollup.json').read_text(encoding='utf-8'))
def test_all_physical_parts_combine_before_daily_inclusion_and_verify(self):
product = self.run_builder()
self.assertEqual(product['derived_from']['settlement_periods'], 240)
self.assertEqual(product['derived_from']['included_days'], 10)
self.assertTrue(all(row['days_included'] == 1 for row in product['price']['by_year']))
self.assertEqual(product['derived_from']['input_grain']['distinct_periods'], 240)
with patch.object(verifier, 'REPO', str(self.repo)), patch.object(verifier, 'PATH', str(self.derived / 'price-decade-rollup.json')):
verifier.main()
def test_a_duplicate_in_an_extra_part_fails_before_output_replacement(self):
target = self.derived / 'price-decade-rollup.json'
target.write_text('accepted previous bytes', encoding='utf-8')
source = self.repo / 'prices/year=2016/month=1/data_0.parquet'
duplicate = source.with_name('data_2.parquet')
duplicate.write_bytes(source.read_bytes())
with self.assertRaisesRegex(ValueError, 'Price grain failed'):
self.run_builder()
self.assertEqual(target.read_text(encoding='utf-8'), 'accepted previous bytes')
def test_null_period_in_extra_part_is_not_hidden_by_daily_aggregation(self):
self.db.execute('DELETE FROM fixture')
self.db.execute("INSERT INTO fixture VALUES ('2016-01-01',49,NULL,12)")
target = self.repo / 'prices/year=2016/month=1/data_2.parquet'
self.db.sql('SELECT * FROM fixture').write_parquet(str(target), compression='zstd')
with self.assertRaisesRegex(ValueError, 'Price grain failed'):
self.run_builder()
def test_nonfinite_price_does_not_become_an_aggregate(self):
self.db.execute('DELETE FROM fixture')
self.db.execute("INSERT INTO fixture VALUES ('2016-01-02',1,'2016-01-02T00:00:00Z','NaN'::DOUBLE)")
target = self.repo / 'prices/year=2016/month=1/data_2.parquet'
self.db.sql('SELECT * FROM fixture').write_parquet(str(target), compression='zstd')
with self.assertRaisesRegex(ValueError, 'Price grain failed'):
self.run_builder()
if __name__ == '__main__':
unittest.main()