In this section
- GlobalGrid2050 Gridbot App Repo Bootstrap storage · globalgrid2050 / scripts/gridbot_app_repo_bootstrap.py lines 1–421
- GlobalGrid2050 Gridbot Bulk Data Workflow Freeze automation · globalgrid2050 / scripts/gridbot_bulk_data_workflow_freeze.py lines 1–172
- GlobalGrid2050 Gridbot Daily MWh Multi Technology Wiring energy-data · globalgrid2050 / scripts/gridbot_daily_mwh_multi_technology_wiring.py lines 1–85
GlobalGrid2050 Gridbot App Repo Bootstrap
A Python command-line tool in the scripts folder using data from GitHub API. It gets login (`get_login`), creates repo (`create_repo`) and gets content sha (`get_content_sha`).
storageglobalgrid2050 / scripts/gridbot_app_repo_bootstrap.py · lines 1–421 of 421 · Entry point · pattern write_reports (shared by 12 files)
- What it does
- It fetches data. Defines 15 functions or classes, including utc_now, stamp, req, get_login, repo_exists. Uses libraries __future__, argparse, base64, datetime, json. Side effects: reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: data source: GitHub API; command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Gridbot App Repo Bootstrap Workflow (globalgrid2050).
- What it achieves
- Audit mode reports the app repositories that would be created. It accepts `--mode`, `--repo-set` and `--owner`.
- Why it matters
- Run by GlobalGrid2050 Gridbot App Repo Bootstrap Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, argparse, base64, datetime, json, os, urllib.error, urllib.request
- Used by
- run by GlobalGrid2050 Gridbot App Repo Bootstrap Workflow (workflow run)
- Produces
- utc_now, stamp, req, get_login, repo_exists, create_repo, get_content_sha, put_file, readme, architecture_doc, data_contract, files_for
- Defines here
- utc_now, stamp, req, get_login, repo_exists, create_repo, get_content_sha, put_file, readme, architecture_doc, data_contract, files_for, selected_apps, write_reports, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/gridbot_app_repo_bootstrap.py:1-421 · blob 9f8d9da47df703185e6e4ee92ece81fca70bac67 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process, storage · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""GridBot app repository bootstrap.
Audit mode reports the app repositories that would be created.
Apply mode uses GRIDBOT_PAT to create lightweight scaffold repositories and seed
repo-local governance files. It does not migrate app code or data; migration is a
separate audited step per app.
"""
from __future__ import annotations
import argparse
import base64
import datetime as dt
import json
import os
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent.parent
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
STEM = "APP_REPO_BOOTSTRAP"
API = "https://api.github.com"
OWNER_DEFAULT = "Ventusltd"
APPS: dict[str, dict[str, str]] = {
"generation_history": {
"repo": "globalgrid2050-generation-history",
"title": "GlobalGrid2050 Generation History",
"description": "UK generation history app. Compact confirmed facts only; raw telemetry stays outside the app repo.",
"sourcePath": "uk_energy_tracking_v6/generation_history",
},
"uk_energy_tracking": {
"repo": "globalgrid2050-uk-energy-tracking",
"title": "GlobalGrid2050 UK Energy Tracking",
"description": "UK energy tracking dashboard shell and app modules. Small public JSON facts only.",
"sourcePath": "uk_energy_tracking_v6",
},
"renewables_pipeline": {
"repo": "globalgrid2050-uk-renewables-pipeline",
"title": "GlobalGrid2050 UK Renewables Pipeline",
"description": "UK renewables project pipeline app. Clean project facts only; raw GIS bulk stays outside normal repo history.",
"sourcePath": "uk_renewables_pipeline",
},
"estimators": {
"repo": "globalgrid2050-estimators",
"title": "GlobalGrid2050 Estimators",
"description": "Engineering and procurement estimator apps with small reference tables only.",
"sourcePath": "estimators",
},
"data_archive": {
"repo": "globalgrid2050-data-archive",
"title": "GlobalGrid2050 Data Archive Index",
"description": "Index and manifests for cold archives. Do not use as a raw data dumping ground.",
"sourcePath": "external cold archive",
},
}
SETS = {
"generation_history": ["generation_history"],
"core_apps": ["generation_history", "uk_energy_tracking", "renewables_pipeline", "estimators"],
"all": ["generation_history", "uk_energy_tracking", "renewables_pipeline", "estimators", "data_archive"],
}
SIZE_GUARD_PY = """#!/usr/bin/env python3
from __future__ import annotations
import os, sys
from pathlib import Path
WARN_MB=float(os.getenv('REPO_GUARD_WARN_MB','5'))
FAIL_MB=float(os.getenv('REPO_GUARD_FAIL_MB','25'))
BLOCK=('data/raw/','data/transient/','data/tmp/','cold_storage/','external_archives/')
root=Path(__file__).resolve().parent.parent
failed=[]; warned=[]
for p in root.rglob('*'):
if not p.is_file() or '.git' in p.parts: continue
r=p.relative_to(root).as_posix(); mb=p.stat().st_size/1024/1024
if any(r.startswith(x) for x in BLOCK): failed.append((r,mb,'blocked raw/cold path'))
elif mb>=FAIL_MB: failed.append((r,mb,'file exceeds hard budget'))
elif mb>=WARN_MB: warned.append((r,mb,'file exceeds warning budget'))
for r,mb,msg in warned: print(f'WARN {mb:.2f} MB {r}: {msg}')
for r,mb,msg in failed: print(f'FAIL {mb:.2f} MB {r}: {msg}', file=sys.stderr)
sys.exit(1 if failed else 0)
"""
SIZE_GUARD_YML = """name: Repo Size Guard
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
repo-size-guard:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check repository size budget
run: python scripts/repo_size_guard.py
"""
GITIGNORE = """# Python
__pycache__/
*.pyc
.venv/
venv/
# Static site build outputs
_site/
.jekyll-cache/
node_modules/
# Secrets and local env
.env
.env.*
!.env.example
# Raw/transient data must not enter app repos
data/raw/
data/transient/
data/tmp/
data/temp/
tmp/
temp/
cold_storage/
external_archives/
*_raw.json
*_raw.csv
*_raw.parquet
*_dump.json
*_dump.csv
*raw_api*
*raw_elexon*
*raw_pvlive*
*fuelinst_raw*
*fuelhh_raw*
*master_halfhourly*
"""
def utc_now() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def stamp() -> str:
return dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def req(method: str, path: str, token: str, payload: dict[str, Any] | None = None) -> tuple[int, Any]:
body = None if payload is None else json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
API + path,
data=body,
method=method,
headers={
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "GlobalGrid2050-GridBot",
},
)
try:
with urllib.request.urlopen(request, timeout=60) as response:
text = response.read().decode("utf-8")
return response.status, json.loads(text) if text else {}
except urllib.error.HTTPError as exc:
text = exc.read().decode("utf-8", errors="replace")
try:
data = json.loads(text) if text else {}
except Exception:
data = {"message": text}
return exc.code, data
def get_login(token: str) -> str:
status, data = req("GET", "/user", token)
if status >= 400:
raise RuntimeError(f"Could not read authenticated user: {data}")
return str(data.get("login") or "")
def repo_exists(owner: str, repo: str, token: str) -> bool:
status, _ = req("GET", f"/repos/{owner}/{repo}", token)
return status == 200
def create_repo(owner: str, app: dict[str, str], private: bool, token: str, login: str) -> dict[str, Any]:
endpoint = "/user/repos" if owner == login else f"/orgs/{owner}/repos"
payload = {
"name": app["repo"],
"description": app["description"],
"private": private,
"auto_init": True,
"has_issues": True,
"has_projects": False,
"has_wiki": False,
}
status, data = req("POST", endpoint, token, payload)
return {"status": status, "ok": status in (200, 201), "response": data}
def get_content_sha(owner: str, repo: str, path: str, token: str) -> str | None:
status, data = req("GET", f"/repos/{owner}/{repo}/contents/{path}", token)
if status == 200 and isinstance(data, dict):
return data.get("sha")
return None
def put_file(owner: str, repo: str, path: str, content: str, token: str, overwrite: bool = False) -> dict[str, Any]:
sha = get_content_sha(owner, repo, path, token)
if sha and not overwrite:
return {"path": path, "status": "exists_skipped"}
payload: dict[str, Any] = {
"message": f"gridbot: bootstrap {path}",
"content": base64.b64encode(content.encode("utf-8")).decode("ascii"),
}
if sha:
payload["sha"] = sha
status, data = req("PUT", f"/repos/{owner}/{repo}/contents/{path}", token, payload)
return {"path": path, "status": status, "ok": status in (200, 201), "response": data}
def readme(app: dict[str, str]) -> str:
return f"""# {app['title']}
{app['description']}
This repository is part of the GlobalGrid2050 app-repo split.
## Contract
- App code lives here.
- Raw telemetry does not live here.
- Browser-facing data must be compact confirmed facts or tiny recent slices.
- Heavy source inputs are fetched temporarily by GitHub Actions and discarded after compilation.
- Data provenance, schema and audit reports are part of the app contract.
## Source path in original monorepo
```text
{app['sourcePath']}
```
## Migration status
Scaffold only. App files are migrated by a separate audited workflow after inventory review.
"""
def architecture_doc(app: dict[str, str]) -> str:
return f"""# App repository architecture
App: {app['title']}
## Data tier rule
```text
Live -> fetched on demand or tiny cache
Recent -> small rolling slice
Confirmed facts -> compact JSON committed here
Cold archive -> outside normal Git history
```
## Forbidden by default
- raw API dumps
- raw half-hourly or five-minute decade history
- generated bulk archives
- large GIS basemap blobs
- files above 25 MB without explicit approval
## Migration method
This repo should receive a clean-copy migration from the monorepo. Do not import old bloated Git history unless a later maintenance plan explicitly requires it.
"""
def data_contract(app: dict[str, str]) -> str:
return f"""# Data contract
App: {app['title']}
Python may fetch raw data inside GitHub Actions. Raw data is a temporary build input. The committed output should be a compact, source-stamped, schema-versioned artifact.
Minimum fields for public facts:
```text
schemaVersion
generatedUTC
source
sourceStatus
unit
grain
rows
```
MWh is additive. Peaks, lows and extremes are not additive and must remain at their fixed grain.
"""
def files_for(app: dict[str, str]) -> dict[str, str]:
return {
"README.md": readme(app),
"docs/ARCHITECTURE.md": architecture_doc(app),
"docs/DATA_CONTRACT.md": data_contract(app),
".gitignore": GITIGNORE,
"scripts/repo_size_guard.py": SIZE_GUARD_PY,
".github/workflows/repo_size_guard.yml": SIZE_GUARD_YML,
}
def selected_apps(repo_set: str) -> list[dict[str, str]]:
return [APPS[key] for key in SETS[repo_set]]
def write_reports(payload: dict[str, Any]) -> None:
REPORT_DIR.mkdir(parents=True, exist_ok=True)
REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
s = stamp()
lines = [
"# App Repo Bootstrap",
"",
f"Generated UTC: `{payload['generatedUTC']}`",
f"Mode: `{payload['mode']}`",
f"Owner: `{payload['owner']}`",
f"Repo set: `{payload['repoSet']}`",
f"Visibility: `{payload['visibility']}`",
f"Applied: `{payload['applied']}`",
f"Pass: `{payload['pass']}`",
"",
"## Repositories",
"",
"| Repo | Action | Existing before | Result |",
"|---|---|---|---|",
]
for item in payload["repositories"]:
lines.append(f"| `{item['repo']}` | {item['action']} | {item['existsBefore']} | {item['result']} |")
lines.extend(["", "## Human next action", "", payload["nextAction"], ""])
text = "\n".join(lines)
for p in (REPORT_DIR / f"{STEM}_{s}.md", REPORT_DIR / f"{STEM}_LATEST.md"):
p.write_text(text, encoding="utf-8")
js = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
for p in (REPORT_JSON_DIR / f"{STEM}_{s}.json", REPORT_JSON_DIR / f"{STEM}_LATEST.json"):
p.write_text(js, encoding="utf-8")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--mode", choices=["audit", "apply"], default="audit")
ap.add_argument("--repo-set", choices=sorted(SETS), default="generation_history")
ap.add_argument("--owner", default=os.getenv("TARGET_OWNER", OWNER_DEFAULT))
ap.add_argument("--visibility", choices=["public", "private"], default="public")
args = ap.parse_args()
token = os.getenv("GRIDBOT_PAT") or os.getenv("GITHUB_TOKEN") or ""
repos = []
ok = True
login = ""
if token:
try:
login = get_login(token)
except Exception as exc:
ok = False
login = f"unavailable: {exc}"
elif args.mode == "apply":
ok = False
for app in selected_apps(args.repo_set):
exists = repo_exists(args.owner, app["repo"], token) if token else False
item = {"repo": app["repo"], "title": app["title"], "existsBefore": exists, "action": "audit_only", "result": "would_create_or_scaffold"}
if args.mode == "apply":
if not token:
item.update({"action": "failed", "result": "GRIDBOT_PAT missing"})
ok = False
else:
if not exists:
created = create_repo(args.owner, app, args.visibility == "private", token, login)
if not created["ok"]:
item.update({"action": "failed_create", "result": str(created["response"])[:300]})
ok = False
repos.append(item)
continue
item.update({"action": "created", "result": "repository created"})
else:
item.update({"action": "scaffold_existing", "result": "repository already existed; missing scaffold files only"})
file_results = []
for path, content in files_for(app).items():
file_results.append(put_file(args.owner, app["repo"], path, content, token, overwrite=False))
item["fileResults"] = file_results
if any(fr.get("ok") is False for fr in file_results):
ok = False
item["result"] = "one or more scaffold file writes failed"
repos.append(item)
payload = {
"reportTitle": "App Repo Bootstrap",
"schemaVersion": "1.0.0",
"generatedUTC": utc_now(),
"mode": args.mode,
"owner": args.owner,
"authenticatedLogin": login,
"repoSet": args.repo_set,
"visibility": args.visibility,
"repositories": repos,
"applied": args.mode == "apply",
"pass": ok,
"nextAction": "Review audit report, then run apply only for the repo set you want created. After repos exist, migrate one app at a time with a separate audited clean-copy workflow.",
}
write_reports(payload)
print(json.dumps({"pass": payload["pass"], "mode": args.mode, "repos": [r["repo"] for r in repos]}, indent=2))
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())GlobalGrid2050 Gridbot Bulk Data Workflow Freeze
A Python command-line tool in the scripts folder that removes schedule block (`remove_schedule_block`), sets commit default false (`set_commit_default_false`) and builds report (`build_report`).
automationglobalgrid2050 / scripts/gridbot_bulk_data_workflow_freeze.py · lines 1–172 of 172 · Entry point · pattern patch (shared by 11 files)
- What it does
- It loads data. Defines 11 functions or classes, including utc_now, stamp, rel, has_schedule, commit_default. Uses libraries __future__, argparse, datetime, json, pathlib. Side effects: reads or writes files.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Gridbot Bulk Data Workflow Freeze Workflow (globalgrid2050).
- What it achieves
- It is built from the utc now helper (`utc_now`), the stamp step (`stamp`) and the rel step (`rel`). Audit/apply control for stopping raw/bulk data workflows from continuing to schedule commits into the monorepo during app-repo migration. It accepts `--apply`.
- Why it matters
- Run by GlobalGrid2050 Gridbot Bulk Data Workflow Freeze Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, argparse, datetime, json, pathlib, typing
- Used by
- run by GlobalGrid2050 Gridbot Bulk Data Workflow Freeze Workflow (workflow run)
- Produces
- utc_now, stamp, rel, has_schedule, commit_default, remove_schedule_block, set_commit_default_false, patch, build_report, write_reports, main
- Defines here
- utc_now, stamp, rel, has_schedule, commit_default, remove_schedule_block, set_commit_default_false, patch, build_report, write_reports, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/gridbot_bulk_data_workflow_freeze.py:1-172 · blob 0c72201fd693c2cdb782bf19123738f1e7498829 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""GridBot bulk-data workflow freeze.
Audit/apply control for stopping raw/bulk data workflows from continuing to
schedule commits into the monorepo during app-repo migration.
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent.parent
TARGET = ROOT / ".github" / "workflows" / "backfill_generation_fuelhh_halfhourly_v6.yml"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
STEM = "BULK_DATA_WORKFLOW_FREEZE"
def utc_now() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def stamp() -> str:
return dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def rel(p: Path) -> str:
return p.relative_to(ROOT).as_posix()
def has_schedule(text: str) -> bool:
return "\n schedule:\n" in "\n" + text
def commit_default(text: str) -> str:
lines = text.splitlines()
in_commit = False
for line in lines:
if line == " commit:":
in_commit = True
continue
if in_commit and line.startswith(" ") and not line.startswith(" "):
in_commit = False
if in_commit and "default:" in line:
return line.split("default:", 1)[1].strip().strip("'\"")
return "unknown"
def remove_schedule_block(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
i = 0
while i < len(lines):
line = lines[i]
if line == " schedule:":
i += 1
while i < len(lines) and (lines[i].startswith(" ") or lines[i].strip() == ""):
i += 1
continue
out.append(line)
i += 1
return "\n".join(out) + "\n"
def set_commit_default_false(text: str) -> str:
lines = text.splitlines()
out: list[str] = []
in_commit = False
for line in lines:
if line == " commit:":
in_commit = True
out.append(line)
continue
if in_commit and line.startswith(" ") and not line.startswith(" "):
in_commit = False
if in_commit and "default: 'true'" in line:
out.append(line.replace("default: 'true'", "default: 'false'"))
elif in_commit and 'default: "true"' in line:
out.append(line.replace('default: "true"', 'default: "false"'))
else:
out.append(line)
return "\n".join(out) + "\n"
def patch(text: str) -> str:
return set_commit_default_false(remove_schedule_block(text))
def build_report(mode: str, before: str, after: str, applied: bool) -> dict[str, Any]:
checks = {
"target_exists": TARGET.exists(),
"target_is_fuelhh_backfill_workflow": TARGET.name == "backfill_generation_fuelhh_halfhourly_v6.yml",
"schedule_removed_after_patch": not has_schedule(after),
"manual_dispatch_preserved": "workflow_dispatch:" in after,
"commit_input_preserved": " commit:" in after,
"commit_default_false_after_patch": commit_default(after) == "false",
"bulk_git_add_still_visible_for_manual_apply": "git add data/generation/fuelhh_halfhourly" in after,
}
return {
"reportTitle": "Bulk Data Workflow Freeze",
"schemaVersion": "1.0.0",
"generatedUTC": utc_now(),
"mode": mode,
"targetFile": rel(TARGET),
"scheduleBefore": has_schedule(before),
"scheduleAfter": has_schedule(after),
"commitDefaultBefore": commit_default(before),
"commitDefaultAfter": commit_default(after),
"changed": before != after,
"checks": checks,
"applied": applied,
"pass": all(checks.values()),
"executiveSummary": "Disables scheduled FUELHH raw half-hourly backfill churn during repo split, while preserving manual dispatch for deliberate regeneration.",
"rollbackMethod": "Revert the apply commit or restore the schedule block in .github/workflows/backfill_generation_fuelhh_halfhourly_v6.yml.",
}
def write_reports(payload: dict[str, Any]) -> None:
REPORT_DIR.mkdir(parents=True, exist_ok=True)
REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
s = stamp()
lines = [
"# Bulk Data Workflow Freeze",
"",
f"Generated UTC: `{payload['generatedUTC']}`",
f"Mode: `{payload['mode']}`",
f"Target file: `{payload['targetFile']}`",
f"Schedule before: `{payload['scheduleBefore']}`",
f"Schedule after: `{payload['scheduleAfter']}`",
f"Commit default before: `{payload['commitDefaultBefore']}`",
f"Commit default after: `{payload['commitDefaultAfter']}`",
f"Changed: `{payload['changed']}`",
f"Applied: `{payload['applied']}`",
f"Pass: `{payload['pass']}`",
"",
"## Executive summary",
"",
payload["executiveSummary"],
"",
"## Checks",
"",
]
for k, v in payload["checks"].items():
lines.append(f"- `{k}`: `{v}`")
lines.extend(["", "## Rollback", "", payload["rollbackMethod"], ""])
text = "\n".join(lines)
for p in (REPORT_DIR / f"{STEM}_{s}.md", REPORT_DIR / f"{STEM}_LATEST.md"):
p.write_text(text, encoding="utf-8")
js = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
for p in (REPORT_JSON_DIR / f"{STEM}_{s}.json", REPORT_JSON_DIR / f"{STEM}_LATEST.json"):
p.write_text(js, encoding="utf-8")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--apply", action="store_true")
args = ap.parse_args()
before = TARGET.read_text(encoding="utf-8") if TARGET.exists() else ""
after = patch(before)
if args.apply and before != after:
TARGET.write_text(after, encoding="utf-8")
payload = build_report("apply" if args.apply else "audit", before, after, args.apply)
write_reports(payload)
print(json.dumps({"pass": payload["pass"], "changed": payload["changed"], "applied": payload["applied"]}, indent=2))
return 0 if payload["pass"] else 1
if __name__ == "__main__":
raise SystemExit(main())GlobalGrid2050 Gridbot Daily MWh Multi Technology Wiring
A Python command-line tool in the scripts folder that patches control and render and patches index, covering pvlive solar daily browser, generation daily mwh by technology fuelhh and wind.
energy-dataglobalgrid2050 / scripts/gridbot_daily_mwh_multi_technology_wiring.py · lines 1–85 of 85 · Entry point · pattern patch_control (shared by 2 files)
- What it does
- It draws pvlive solar daily browser, generation daily mwh by technology fuelhh and wind. Defines 8 functions or classes, including now, stamp, rel, patch_control, patch_render. Uses libraries __future__, argparse, datetime, json, pathlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain terms in the code: wind.
- Inputs & outputs
- In: JSON file pvlive_solar_daily_browser.json; JSON file generation_daily_mwh_by_technology_fuelhh_2016_2026.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Gridbot Daily MWh Multi Technology Wiring Workflow (globalgrid2050).
- What it achieves
- It patches control (`patch_control`), patches render (`patch_render`) and patches index (`patch_index`). Defines `now`, `stamp`, `rel` and 4 more. It accepts `--apply`.
- Why it matters
- Run by GlobalGrid2050 Gridbot Daily MWh Multi Technology Wiring Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, argparse, datetime, json, pathlib
- Used by
- run by GlobalGrid2050 Gridbot Daily MWh Multi Technology Wiring Workflow (workflow run)
- Produces
- now, stamp, rel, patch_control, patch_render, patch_index, report_write, main
- Defines here
- now, stamp, rel, patch_control, patch_render, patch_index, report_write, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/gridbot_daily_mwh_multi_technology_wiring.py:1-85 · blob d2e92f102177de10af51045910eb7e57ecba1a64 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse, datetime as dt, json
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
IDX=ROOT/'uk_energy_tracking_v6'/'generation_history'/'index.md'
CTL=ROOT/'uk_energy_tracking_v6'/'generation_history'/'control_solar_daily_mwh_chart.js'
RND=ROOT/'uk_energy_tracking_v6'/'generation_history'/'render_solar_daily_mwh_chart.js'
SOL=ROOT/'uk_energy_tracking_v6'/'generation_history'/'pvlive_solar_daily_browser.json'
FUEL=ROOT/'uk_energy_tracking_v6'/'generation_history'/'generation_daily_mwh_by_technology_fuelhh_2016_2026.json'
RD=ROOT/'data_science_protocol'/'audit_reports'; RJD=RD/'json'; STEM='DAILY_MWH_MULTI_TECH_WIRING'
NEW_HEAD="""window.V6ControlSolarDailyMwhChart=(function(){
var cache={};
function cfg(){return window.V6GenerationHistoryConfig||{}}
function get(id){return document.getElementById(id)}
function load(key,url){if(cache[key])return cache[key];cache[key]=fetch(url+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.json():{rows:[]}}).then(function(d){return d.rows||[]}).catch(function(){return[]});return cache[key]}
function loadSolarDaily(){return load('solar',(cfg().solarDaily||'/uk_energy_tracking_v6/generation_history/pvlive_solar_daily_browser.json'))}
function loadFuelDaily(){return load('fuel','/uk_energy_tracking_v6/generation_history/generation_daily_mwh_by_technology_fuelhh_2016_2026.json')}
function periodDays(p){return{'30d':30,'3m':92,'6m':183,'12m':366,'5y':1827,'10y':3653}[p]||366}
function niceDate(v){var d=v instanceof Date?v:new Date(String(v));return isNaN(d.getTime())?'—':d.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}
function years(rows){var out={};rows.forEach(function(r){if(r&&r.date)out[String(r.date).slice(0,4)]=true});return Object.keys(out).sort()}
function srcLabel(t){return t==='Solar'?'PVLive stored energy':'Elexon FUELHH derived energy'}
function srcStatus(t){return t==='Solar'?'SHEFFIELD SOLAR PVLIVE STORED MWH':'ELEXON FUELHH DERIVED DAILY MWH'}
function techOptions(fuelRows){var el=get('solar-daily-mwh-technology');if(!el||el.dataset.multiReady==='1')return;var seen={Solar:true};fuelRows.forEach(function(r){if(r&&r.technology)seen[String(r.technology)]=true});var pref=['Solar','Wind','Gas','Nuclear','Coal','Hydro','Imports & Exports','Biomass','Storage','Pumped Storage','Other'];var vals=[];pref.forEach(function(t){if(seen[t])vals.push … [line shortened here: 656 characters; full line on GitHub]
function rowsFor(t,solar,fuel){var rows=t==='Solar'?solar:fuel.filter(function(r){return r&&String(r.technology)===t});return rows.filter(function(r){return r&&r.mwh!=null&&!isNaN(Number(r.mwh))}).map(function(r){var x=Object.assign({},r);x.technology=t;x.sourceLabel=srcLabel(t);return x})}
function setYears(rows,t){var y=get('solar-daily-mwh-year'),s=get('solar-daily-mwh-start');if(!y||!s)return;var key=t+'-'+rows.length;if(y.dataset.readyKey===key)return;var old=y.value,ys=years(rows);y.innerHTML='';ys.forEach(function(v){var o=document.createElement('option');o.value=v;o.textContent=v;y.appendChild(o)});y.value=ys.indexOf(old)>=0?old:(ys[ys.length-1]||String(new Date().getUTCFul … [line shortened here: 458 characters; full line on GitHub]
function selectedWindow(rows,t){var y=get('solar-daily-mwh-year'),s=get('solar-daily-mwh-start'),p=get('solar-daily-mwh-period');setYears(rows,t);var period=p?p.value:'12m',st=s&&s.value?s.value:((y&&y.value?y.value:String(new Date().getUTCFullYear()))+'-01-01'),start=new Date(st+'T00:00:00Z'),end;if(period==='all'){var v=rows.filter(function(r){return r&&r.date});start=new Date((v[0]?v[0].date: … [line shortened here: 593 characters; full line on GitHub]
function update(){var panel=get('solar-daily-mwh-panel'),canvas=get('solar-daily-mwh-canvas'),status=get('solar-daily-mwh-status'),techEl=get('solar-daily-mwh-technology');if(!panel||!canvas||!status||!window.V6RenderSolarDailyMwhChart)return;panel.style.display='block';Promise.all([loadSolarDaily(),loadFuelDaily()]).then(function(d){var solar=d[0]||[],fuel=d[1]||[];techOptions(fuel);var t=techE … [line shortened here: 864 characters; full line on GitHub]
function boot(){Promise.all([loadSolarDaily(),loadFuelDaily()]).then(function(d){techOptions(d[1]||[]);update()});['solar-daily-mwh-technology','solar-daily-mwh-year','solar-daily-mwh-start','solar-daily-mwh-period'].forEach(function(id){var el=get(id);if(el)el.addEventListener('change',function(){if(id==='solar-daily-mwh-year'){var s=get('solar-daily-mwh-start');if(s&&el.value)s.value=el.value+ … [line shortened here: 550 characters; full line on GitHub]
return{boot:boot,update:update};
})();
document.addEventListener('DOMContentLoaded',function(){if(window.V6ControlSolarDailyMwhChart)window.V6ControlSolarDailyMwhChart.boot()});"""
def now(): return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00','Z')
def stamp(): return dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
def rel(p): return p.relative_to(ROOT).as_posix()
def patch_control(t):
marker='\n\n// Solar daily MWh fullscreen and period interaction bridge'
if marker not in t: return t,['control bridge marker']
return NEW_HEAD+marker+t.split(marker,1)[1],[]
def patch_render(t):
miss=[]
a="ctx.fillText('SOLAR DAILY MWh · PVLive stored energy',18*q,28*q,w-36*q);"
b="var chartTitle=(result.technology||'Solar').toUpperCase()+' DAILY MWh · '+(result.sourceLabel||'PVLive stored energy');ctx.fillText(chartTitle,18*q,28*q,w-36*q);"
if a in t: t=t.replace(a,b,1)
else: miss.append('render title marker')
a="ctx.fillText('Awaiting Solar daily MWh data.',18*q,90*q);return}"
b="ctx.fillText('Awaiting selected daily MWh data.',18*q,90*q);return}"
if a in t: t=t.replace(a,b,1)
else: miss.append('render empty marker')
return t,miss
def patch_index(t):
miss=[]
render_done=False; control_done=False
for a in ['20260611mwhlabels1','20260610solarmwh4']:
old='render_solar_daily_mwh_chart.js?v='+a
if old in t: t=t.replace(old,'render_solar_daily_mwh_chart.js?v=20260611mwhmulti1',1); render_done=True
for a in ['20260611mwhlabels1','20260610solarmwh2']:
old='control_solar_daily_mwh_chart.js?v='+a
if old in t: t=t.replace(old,'control_solar_daily_mwh_chart.js?v=20260611mwhmulti1',1); control_done=True
if not render_done: miss.append('index render cache marker')
if not control_done: miss.append('index control cache marker')
return t,miss
def report_write(r):
RD.mkdir(parents=True,exist_ok=True); RJD.mkdir(parents=True,exist_ok=True); s=stamp()
md='\n'.join(['# Daily MWh Multi Technology Wiring','',f"Generated UTC: `{r['generatedUTC']}`",f"Mode: `{r['mode']}`",f"Changed files: `{', '.join(r['changedFiles'])}`",f"Pass: `{r['pass']}`",'','Wires Solar to PVLive and Elexon technologies to the audited daily MWh file. No data files are modified.'])+'\n'
for p in (RD/f'{STEM}_{s}.md',RD/f'{STEM}_LATEST.md'): p.write_text(md,encoding='utf-8')
js=json.dumps(r,indent=2,ensure_ascii=False)+'\n'
for p in (RJD/f'{STEM}_{s}.json',RJD/f'{STEM}_LATEST.json'): p.write_text(js,encoding='utf-8')
def main():
ap=argparse.ArgumentParser(); ap.add_argument('--apply',action='store_true'); args=ap.parse_args()
ci,ri,ii=CTL.read_text(encoding='utf-8'),RND.read_text(encoding='utf-8'),IDX.read_text(encoding='utf-8')
co,m1=patch_control(ci); ro,m2=patch_render(ri); io,m3=patch_index(ii); missing=m1+m2+m3
checks={'solar_file_exists':SOL.exists(),'elexon_daily_mwh_file_exists':FUEL.exists(),'control_wires_solar_pvlive':'pvlive_solar_daily_browser.json' in co,'control_wires_elexon_daily_mwh':'generation_daily_mwh_by_technology_fuelhh_2016_2026.json' in co,'chart_uses_mwh':'r.mwh!=null' in co,'dropdown_populates_elexon_tech':'techOptions' in co and 'fuelRows.forEach' in co,'source_labels_distingui … [line shortened here: 655 characters; full line on GitHub]
changed=[]
if co!=ci: changed.append(rel(CTL))
if ro!=ri: changed.append(rel(RND))
if io!=ii: changed.append(rel(IDX))
passed=all(checks.values()) and len(changed)==3
if args.apply and passed:
CTL.write_text(co,encoding='utf-8'); RND.write_text(ro,encoding='utf-8'); IDX.write_text(io,encoding='utf-8')
r={'reportTitle':'Daily MWh Multi Technology Wiring','schemaVersion':'1.0.0','generatedUTC':now(),'mode':'apply' if args.apply else 'audit','changedFiles':changed,'missingMarkers':missing,'checks':checks,'pass':passed,'applied':bool(args.apply and passed),'nextAction':'Run apply only after audit and human review.' if not args.apply else 'Open Solar, Wind, Gas and Nuclear chart selections.'}
report_write(r)
if not passed: raise SystemExit('daily MWh multi technology wiring checks failed')
return 0
if __name__=='__main__': raise SystemExit(main())