In this section
- GlobalGrid2050 Gridbot Solar Historic Backfill energy-data · globalgrid2050 / scripts/gridbot_solar_historic_backfill.py lines 1–181
- GlobalGrid2050 Gridbot Solar Immediate Data energy-data · globalgrid2050 / scripts/gridbot_solar_immediate_data.py lines 1–142
- GlobalGrid2050 Gridbot Solar Monthly Backfill energy-data · globalgrid2050 / scripts/gridbot_solar_monthly_backfill.py lines 1–119
GlobalGrid2050 Gridbot Solar Historic Backfill
A Python command-line tool in the scripts folder that fetches pvlive solar daily candidate and pvlive solar daily browser, using SHA-256. It parses float (`parse_float`) and parses MW (`parse_mw`).
energy-dataglobalgrid2050 / scripts/gridbot_solar_historic_backfill.py · lines 1–181 of 181 · Entry point · pattern fetch_day (shared by 3 files)
- What it does
- It fetches pvlive solar daily candidate and pvlive solar daily browser. Defines 9 functions or classes, including utc_now, fetch_json, rows_from, parse_float, parse_mw. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file pvlive_solar_daily_candidate.json; JSON file pvlive_solar_daily_browser.json; JSON file SOLAR_HISTORIC_BACKFILL_LATEST.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: GlobalGrid2050 Gridbot Solar 10 Year Backfill Workflow (globalgrid2050); GlobalGrid2050 Gridbot Solar Historic Backfill Workflow (globalgrid2050).
- What it achieves
- Defines `utc_now`, `fetch_json`, `rows_from` and 5 more. It accepts `--start-date`, `--end-date` and `--max-days`.
- Why it matters
- Run by GlobalGrid2050 Gridbot Solar 10 Year Backfill Workflow and GlobalGrid2050 Gridbot Solar Historic Backfill Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, argparse, datetime, hashlib, json, urllib.parse, urllib.request, pathlib
- Used by
- run by GlobalGrid2050 Gridbot Solar 10 Year Backfill Workflow (workflow run), run by GlobalGrid2050 Gridbot Solar Historic Backfill Workflow (workflow run)
- Produces
- utc_now, fetch_json, rows_from, parse_float, parse_mw, fetch_day, load_existing, write_report, main
- Defines here
- utc_now, fetch_json, rows_from, parse_float, parse_mw, fetch_day, load_existing, write_report, 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_solar_historic_backfill.py:1-181 · blob 5ef6d98ad76a4c90c25e4a1808c386fae6a5895c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import json
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CANDIDATE = ROOT / 'data' / 'confirmed' / 'pvlive_solar_daily_candidate.json'
BROWSER = ROOT / 'uk_energy_tracking_v6' / 'generation_history' / 'pvlive_solar_daily_browser.json'
REPORT = ROOT / 'data_science_protocol' / 'audit_reports' / 'SOLAR_HISTORIC_BACKFILL_LATEST.md'
REPORT_JSON = ROOT / 'data_science_protocol' / 'audit_reports' / 'json' / 'SOLAR_HISTORIC_BACKFILL_LATEST.json'
API = 'https://api.solar.sheffield.ac.uk/pvlive/api/v4/gsp/0'
SOURCE = 'Sheffield Solar PVLive'
ATTRIBUTION = 'Sheffield Solar PVLive, solar.sheffield.ac.uk'
def utc_now() -> str:
return dt.datetime.now(dt.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
def fetch_json(url: str):
req = urllib.request.Request(url, headers={'User-Agent': 'GlobalGrid2050 GridBot'})
with urllib.request.urlopen(req, timeout=60) as response:
return json.loads(response.read().decode('utf-8'))
def rows_from(payload):
if isinstance(payload, list):
return payload
if isinstance(payload, dict):
for key in ('data', 'results', 'items'):
if isinstance(payload.get(key), list):
return payload[key]
return []
def parse_float(value):
try:
return float(value)
except Exception:
return None
def parse_mw(row):
if isinstance(row, list) and len(row) >= 3:
return parse_float(row[2])
if isinstance(row, dict):
return parse_float(row.get('generation_mw') or row.get('generationMW') or row.get('generation') or row.get('power'))
return None
def fetch_day(day: dt.date):
start = dt.datetime.combine(day, dt.time(0, 0), tzinfo=dt.timezone.utc)
end = dt.datetime.combine(day, dt.time(23, 59), tzinfo=dt.timezone.utc)
url = API + '?' + urllib.parse.urlencode({'start': start.isoformat().replace('+00:00', 'Z'), 'end': end.isoformat().replace('+00:00', 'Z')})
values = []
for raw in rows_from(fetch_json(url)):
mw = parse_mw(raw)
if mw is not None:
values.append(mw)
return values, url
def load_existing(path: Path):
if not path.exists():
return {}
try:
payload = json.loads(path.read_text(encoding='utf-8'))
return {row['date']: row for row in payload.get('rows', []) if isinstance(row, dict) and row.get('date')}
except Exception:
return {}
def write_report(payload):
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT_JSON.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text('# Solar Historic Backfill Report\n\n```json\n' + json.dumps(payload, indent=2) + '\n```\n', encoding='utf-8')
REPORT_JSON.write_text(json.dumps(payload, indent=2) + '\n', encoding='utf-8')
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('--start-date', default='2016-01-01')
parser.add_argument('--end-date', default='')
parser.add_argument('--max-days', type=int, default=31)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
start = dt.date.fromisoformat(args.start_date)
end = dt.date.fromisoformat(args.end_date) if args.end_date else dt.datetime.now(dt.timezone.utc).date() - dt.timedelta(days=1)
if end < start:
end = start
days = []
d = start
while d <= end and len(days) < args.max_days:
days.append(d)
d += dt.timedelta(days=1)
existing = load_existing(CANDIDATE)
fetched = 0
failures = []
last_url = ''
for day in days:
try:
values, url = fetch_day(day)
last_url = url
if values:
fetched += 1
existing[day.isoformat()] = {
'date': day.isoformat(),
'technology': 'Solar',
'averageMW': round(sum(values) / len(values), 3),
'highMW': round(max(values), 3),
'lowMW': round(min(values), 3),
'sampleCount': len(values),
'source': SOURCE,
'sourceAttribution': ATTRIBUTION,
'methodState': 'PVLIVE EMBEDDED ESTIMATE',
'status': 'candidate'
}
else:
failures.append({'date': day.isoformat(), 'error': 'no values'})
except Exception as exc:
failures.append({'date': day.isoformat(), 'error': str(exc)[:200]})
rows = [existing[k] for k in sorted(existing)]
candidate_payload = {
'schemaVersion': '0.2.0-pvlive-solar-daily-candidate',
'generatedUTC': utc_now(),
'title': 'PVLive solar daily MW candidate',
'timezone': 'UTC',
'source': SOURCE,
'sourceAttribution': ATTRIBUTION,
'sourceNote': 'Solar generation is estimated from Sheffield Solar PVLive. It is not Elexon FUELHH transmission metered solar.',
'methodState': 'PVLIVE EMBEDDED ESTIMATE',
'rows': rows
}
browser_rows = [{k: row[k] for k in ('date', 'technology', 'averageMW', 'highMW', 'lowMW', 'sampleCount', 'source', 'sourceAttribution', 'methodState', 'status') if k in row} for row in rows]
browser_payload = {
'schemaVersion': '0.2.0-pvlive-solar-daily-browser',
'generatedUTC': utc_now(),
'title': 'PVLive solar daily browser file',
'timezone': 'UTC',
'source': SOURCE,
'sourceAttribution': ATTRIBUTION,
'sourceNote': 'Solar generation is estimated from Sheffield Solar PVLive. It is not Elexon FUELHH transmission metered solar.',
'methodState': 'PVLIVE EMBEDDED ESTIMATE',
'rows': browser_rows
}
ctext = json.dumps(candidate_payload, separators=(',', ':'), ensure_ascii=False)
btext = json.dumps(browser_payload, separators=(',', ':'), ensure_ascii=False)
passed = fetched > 0 and len(failures) == 0 and len(btext.encode('utf-8')) < 3000000
if args.apply and passed:
CANDIDATE.write_text(ctext, encoding='utf-8')
BROWSER.write_text(btext, encoding='utf-8')
report = {
'mode': 'apply' if args.apply else 'audit',
'startDate': start.isoformat(),
'requestedEndDate': end.isoformat(),
'daysAttempted': len(days),
'daysFetched': fetched,
'candidateRowsAfterMerge': len(rows),
'browserRowsAfterMerge': len(browser_rows),
'candidateBytes': len(ctext.encode('utf-8')),
'browserBytes': len(btext.encode('utf-8')),
'candidateSha256': hashlib.sha256(ctext.encode('utf-8')).hexdigest(),
'browserSha256': hashlib.sha256(btext.encode('utf-8')).hexdigest(),
'lastUrl': last_url,
'failures': failures[:20],
'applied': bool(args.apply and passed),
'pass': passed
}
write_report(report)
print(json.dumps(report, indent=2))
return 0 if passed else 1
if __name__ == '__main__':
raise SystemExit(main())GlobalGrid2050 Gridbot Solar Immediate Data
A Python command-line tool in the scripts folder that fetches pvlive solar recent 30d 30min browser, using SHA-256. It parses row (`parse_row`) and writes report (`write_report`).
energy-dataglobalgrid2050 / scripts/gridbot_solar_immediate_data.py · lines 1–142 of 142 · Entry point · pattern parse_row (shared by 3 files)
- What it does
- It fetches pvlive solar recent 30d 30min browser. Defines 8 functions or classes, including now_utc, fetch_json, rows_from, iso_z, parse_row. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file pvlive_solar_recent_30d_30min_browser.json; JSON file SOLAR_IMMEDIATE_DATA_LATEST.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Gridbot Solar Immediate Data Workflow (globalgrid2050).
- What it achieves
- Defines `now_utc`, `fetch_json`, `rows_from` and 4 more. It accepts `--days` and `--apply`.
- Why it matters
- Run by GlobalGrid2050 Gridbot Solar Immediate Data Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, argparse, datetime, hashlib, json, urllib.parse, urllib.request, pathlib
- Used by
- run by GlobalGrid2050 Gridbot Solar Immediate Data Workflow (workflow run)
- Produces
- now_utc, fetch_json, rows_from, iso_z, parse_row, build, write_report, main
- Defines here
- now_utc, fetch_json, rows_from, iso_z, parse_row, build, write_report, 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_solar_immediate_data.py:1-142 · blob d6c017fab239a3e396b96dc3fcbc35858303ef11 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import json
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / 'uk_energy_tracking_v6' / 'generation_history' / 'pvlive_solar_recent_30d_30min_browser.json'
REPORT = ROOT / 'data_science_protocol' / 'audit_reports' / 'SOLAR_IMMEDIATE_DATA_LATEST.md'
REPORT_JSON = ROOT / 'data_science_protocol' / 'audit_reports' / 'json' / 'SOLAR_IMMEDIATE_DATA_LATEST.json'
API = 'https://api.solar.sheffield.ac.uk/pvlive/api/v4/gsp/0'
SOURCE = 'Sheffield Solar PVLive'
ATTRIBUTION = 'Sheffield Solar PVLive, solar.sheffield.ac.uk'
def now_utc() -> dt.datetime:
return dt.datetime.now(dt.timezone.utc)
def fetch_json(url: str):
req = urllib.request.Request(url, headers={'User-Agent': 'GlobalGrid2050 GridBot'})
with urllib.request.urlopen(req, timeout=60) as response:
return json.loads(response.read().decode('utf-8'))
def rows_from(payload):
if isinstance(payload, list):
return payload
if isinstance(payload, dict):
for key in ('data', 'results', 'items'):
if isinstance(payload.get(key), list):
return payload[key]
return []
def iso_z(value) -> str:
try:
parsed = dt.datetime.fromisoformat(str(value).replace('Z', '+00:00'))
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=dt.timezone.utc)
return parsed.astimezone(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
except Exception:
return ''
def parse_row(row):
if isinstance(row, list) and len(row) >= 3:
timestamp = row[1]
generation = row[2]
elif isinstance(row, dict):
timestamp = row.get('datetime_gmt') or row.get('datetime') or row.get('time') or row.get('timestamp') or row.get('periodStartUTC')
generation = row.get('generation_mw') or row.get('generationMW') or row.get('generation') or row.get('power')
else:
return None
try:
mw = round(float(generation), 3)
except Exception:
return None
timestamp_utc = iso_z(timestamp)
if not timestamp_utc:
return None
return {
'time': timestamp_utc,
'technology': 'Solar',
'generationMW': mw,
'source': SOURCE,
'sourceAttribution': ATTRIBUTION,
'methodState': 'PVLIVE EMBEDDED ESTIMATE',
'status': 'candidate'
}
def build(days: int):
end = now_utc()
start = dt.datetime.combine(end.date() - dt.timedelta(days=days - 1), dt.time(0, 0), tzinfo=dt.timezone.utc)
url = API + '?' + urllib.parse.urlencode({'start': start.isoformat().replace('+00:00', 'Z'), 'end': end.isoformat().replace('+00:00', 'Z')})
parsed = [row for row in (parse_row(raw) for raw in rows_from(fetch_json(url))) if row]
by_key = {(row['time'], row['technology']): row for row in parsed}
rows = [by_key[key] for key in sorted(by_key)]
return rows, url, start, end
def write_report(payload):
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT_JSON.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text('# Solar Immediate Data Report\n\n```json\n' + json.dumps(payload, indent=2) + '\n```\n', encoding='utf-8')
REPORT_JSON.write_text(json.dumps(payload, indent=2) + '\n', encoding='utf-8')
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('--days', type=int, default=30)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
rows, url, start, end = build(args.days)
today = end.date().isoformat()
today_rows = [row for row in rows if row['time'].startswith(today)]
payload = {
'schemaVersion': '0.3.0-pvlive-solar-recent-30min-browser',
'title': 'PVLive solar recent 30 minute browser file',
'generatedUTC': now_utc().strftime('%Y-%m-%dT%H:%M:%SZ'),
'timezone': 'UTC',
'source': SOURCE,
'sourceAttribution': ATTRIBUTION,
'sourceNote': 'Solar generation is estimated from Sheffield Solar PVLive. It is not Elexon FUELHH transmission metered solar.',
'methodState': 'PVLIVE EMBEDDED ESTIMATE',
'rows': rows
}
text = json.dumps(payload, separators=(',', ':'), ensure_ascii=False)
byte_count = len(text.encode('utf-8'))
passed = len(rows) > 0 and len(today_rows) > 0 and byte_count < 900000
if args.apply and passed:
OUT.write_text(text, encoding='utf-8')
report = {
'mode': 'apply' if args.apply else 'audit',
'outputPath': str(OUT.relative_to(ROOT)),
'source': SOURCE,
'sourceAttribution': ATTRIBUTION,
'rangeStart': start.isoformat().replace('+00:00', 'Z'),
'rangeEnd': end.isoformat().replace('+00:00', 'Z'),
'rows': len(rows),
'todayRows': len(today_rows),
'firstTime': rows[0]['time'] if rows else None,
'lastTime': rows[-1]['time'] if rows else None,
'estimatedBytes': byte_count,
'sha256': hashlib.sha256(text.encode('utf-8')).hexdigest(),
'workingUrl': url,
'applied': bool(args.apply and passed),
'pass': passed
}
write_report(report)
print(json.dumps(report, indent=2))
return 0 if passed else 1
if __name__ == '__main__':
raise SystemExit(main())GlobalGrid2050 Gridbot Solar Monthly Backfill
A Python command-line tool in the scripts folder that fetches pvlive solar daily candidate, pvlive solar daily browser and pvlive solar daily backfill progress, using SHA-256.
energy-dataglobalgrid2050 / scripts/gridbot_solar_monthly_backfill.py · lines 1–119 of 119 · Entry point · pattern fetch_month (shared by 2 files)
- What it does
- It fetches pvlive solar daily candidate, pvlive solar daily browser and pvlive solar daily backfill progress. Defines 15 functions or classes, including utc_now, month_key, month_start, next_month, month_end. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file pvlive_solar_daily_candidate.json; JSON file pvlive_solar_daily_browser.json; JSON file pvlive_solar_daily_BACKFILL_PROGRESS.json; JSON file SOLAR_MONTHLY_BACKFILL_LATEST.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: GlobalGrid2050 Gridbot Solar Monthly Backfill Workflow (globalgrid2050); GlobalGrid2050 Gridbot Solar Monthly Backfill Auto Workflow (globalgrid2050).
- What it achieves
- It gets JSON (`get_json`), parses row (`parse_row`) and fetches month (`fetch_month`). Defines `utc_now`, `month_key`, `month_start` and 11 more. It accepts `--start-month`, `--end-month` and `--max-months`.
- Why it matters
- Run by GlobalGrid2050 Gridbot Solar Monthly Backfill Workflow and GlobalGrid2050 Gridbot Solar Monthly Backfill Auto Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, argparse, datetime, hashlib, json, urllib.parse, urllib.request, time
- Used by
- run by GlobalGrid2050 Gridbot Solar Monthly Backfill Workflow (workflow run), run by GlobalGrid2050 Gridbot Solar Monthly Backfill Auto Workflow (workflow run)
- Produces
- utc_now, month_key, month_start, next_month, month_end, iso_z, get_json, rows_from, parse_row, fetch_month, load_rows, load_progress
- Defines here
- utc_now, month_key, month_start, next_month, month_end, iso_z, get_json, rows_from, parse_row, fetch_month, load_rows, load_progress, write_json, write_report, 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_solar_monthly_backfill.py:1-119 · blob ea642ba8b2278876e482b3a15f1ff4813a0c5b03 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse, datetime as dt, hashlib, json, urllib.parse, urllib.request, time
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
CANDIDATE=ROOT/'data/confirmed/pvlive_solar_daily_candidate.json'
BROWSER=ROOT/'uk_energy_tracking_v6/generation_history/pvlive_solar_daily_browser.json'
PROGRESS=ROOT/'data/confirmed/pvlive_solar_daily_BACKFILL_PROGRESS.json'
REPORT=ROOT/'data_science_protocol/audit_reports/SOLAR_MONTHLY_BACKFILL_LATEST.md'
REPORT_JSON=ROOT/'data_science_protocol/audit_reports/json/SOLAR_MONTHLY_BACKFILL_LATEST.json'
API='https://api.solar.sheffield.ac.uk/pvlive/api/v4/gsp/0'
SOURCE='Sheffield Solar PVLive'
ATTRIBUTION='Sheffield Solar PVLive, solar.sheffield.ac.uk'
def utc_now(): return dt.datetime.now(dt.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
def month_key(d): return f'{d.year:04d}-{d.month:02d}'
def month_start(s):
y,m=map(int,s.split('-')[:2]); return dt.date(y,m,1)
def next_month(d): return dt.date(d.year+1,1,1) if d.month==12 else dt.date(d.year,d.month+1,1)
def month_end(d): return next_month(d)-dt.timedelta(days=1)
def iso_z(v):
try:
x=dt.datetime.fromisoformat(str(v).replace('Z','+00:00'))
if x.tzinfo is None: x=x.replace(tzinfo=dt.timezone.utc)
return x.astimezone(dt.timezone.utc).isoformat().replace('+00:00','Z')
except Exception: return ''
def get_json(url):
req=urllib.request.Request(url,headers={'User-Agent':'GlobalGrid2050 GridBot'})
with urllib.request.urlopen(req,timeout=90) as r: return json.loads(r.read().decode('utf-8'))
def rows_from(p):
if isinstance(p,list): return p
if isinstance(p,dict):
for k in ('data','results','items'):
if isinstance(p.get(k),list): return p[k]
return []
def parse_row(r):
if isinstance(r,list) and len(r)>=3: t,g=r[1],r[2]
elif isinstance(r,dict):
t=r.get('datetime_gmt') or r.get('datetime') or r.get('time') or r.get('timestamp') or r.get('periodStartUTC')
g=r.get('generation_mw') or r.get('generationMW') or r.get('generation') or r.get('power')
else: return None
try: mw=float(g)
except Exception: return None
z=iso_z(t)
if not z: return None
return z,mw
def fetch_month(mstart):
mend=month_end(mstart)
start=dt.datetime.combine(mstart,dt.time(0,0),tzinfo=dt.timezone.utc)
end=dt.datetime.combine(mend,dt.time(23,59),tzinfo=dt.timezone.utc)
url=API+'?'+urllib.parse.urlencode({'start':start.isoformat().replace('+00:00','Z'),'end':end.isoformat().replace('+00:00','Z')})
by_day={}
for raw in rows_from(get_json(url)):
parsed=parse_row(raw)
if parsed:
z,mw=parsed; by_day.setdefault(z[:10],[]).append(mw)
out=[]
for day,vals in sorted(by_day.items()):
mwh=round(sum(vals)*0.5,3)
out.append({'date':day,'technology':'Solar','averageMW':round(sum(vals)/len(vals),3),'highMW':round(max(vals),3),'lowMW':round(min(vals),3),'sampleCount':len(vals),'mwh':mwh,'source':SOURCE,'sourceAttribution':ATTRIBUTION,'methodState':'PVLIVE EMBEDDED ESTIMATE','status':'candidate','completeness':round(len(vals)/48,3)})
return out,url
def load_rows(path):
if not path.exists(): return {}
try:
p=json.loads(path.read_text(encoding='utf-8'))
return {r['date']:r for r in p.get('rows',[]) if isinstance(r,dict) and r.get('date')}
except Exception: return {}
def load_progress():
if not PROGRESS.exists(): return {'completeMonths':[],'failedMonths':[]}
try: return json.loads(PROGRESS.read_text(encoding='utf-8'))
except Exception: return {'completeMonths':[],'failedMonths':[]}
def write_json(path,payload):
path.parent.mkdir(parents=True,exist_ok=True)
text=json.dumps(payload,separators=(',',':'),ensure_ascii=False)
path.write_text(text,encoding='utf-8')
return text
def write_report(payload):
REPORT.parent.mkdir(parents=True,exist_ok=True); REPORT_JSON.parent.mkdir(parents=True,exist_ok=True)
REPORT.write_text('# Solar Monthly Backfill Report\n\n```json\n'+json.dumps(payload,indent=2)+'\n```\n',encoding='utf-8')
REPORT_JSON.write_text(json.dumps(payload,indent=2)+'\n',encoding='utf-8')
def main():
ap=argparse.ArgumentParser(); ap.add_argument('--start-month',default='2016-01'); ap.add_argument('--end-month',default=''); ap.add_argument('--max-months',type=int,default=12); ap.add_argument('--apply',action='store_true'); ap.add_argument('--resume',action='store_true')
args=ap.parse_args(); start=month_start(args.start_month); end=month_start(args.end_month) if args.end_month else dt.date(dt.datetime.now(dt.timezone.utc).year,dt.datetime.now(dt.timezone.utc).month,1)
existing=load_rows(CANDIDATE); progress=load_progress(); done=set(progress.get('completeMonths',[])) if args.resume else set()
months=[]; d=start
while d<=end and len(months)<args.max_months:
if month_key(d) not in done: months.append(d)
d=next_month(d)
fetched=[]; failures=[]; last_url=''
for m in months:
try:
rows,url=fetch_month(m); last_url=url
if not rows: failures.append({'month':month_key(m),'error':'no rows'})
else:
fetched.append(month_key(m))
for r in rows: existing[r['date']]=r
time.sleep(0.2)
except Exception as e: failures.append({'month':month_key(m),'error':str(e)[:240]})
merged=[existing[k] for k in sorted(existing)]
cand={'schemaVersion':'0.3.0-pvlive-solar-daily-candidate','generatedUTC':utc_now(),'source':SOURCE,'sourceAttribution':ATTRIBUTION,'sourceNote':'Solar generation is estimated from Sheffield Solar PVLive. It is not Elexon FUELHH transmission metered solar.','rows':merged}
browser={'schemaVersion':'0.3.0-pvlive-solar-daily-browser','generatedUTC':utc_now(),'source':SOURCE,'sourceAttribution':ATTRIBUTION,'sourceNote':cand['sourceNote'],'rows':merged}
ctext=json.dumps(cand,separators=(',',':'),ensure_ascii=False); btext=json.dumps(browser,separators=(',',':'),ensure_ascii=False)
passed=bool(fetched) and not failures and len(btext.encode())<3000000
if args.apply and passed:
write_json(CANDIDATE,cand); write_json(BROWSER,browser)
complete=sorted(set(progress.get('completeMonths',[])+fetched)); failed=[x for x in progress.get('failedMonths',[]) if x.get('month') not in fetched]+failures
write_json(PROGRESS,{'generatedUTC':utc_now(),'source':SOURCE,'completeMonths':complete,'failedMonths':failed,'lastRunMonths':fetched})
report={'mode':'apply' if args.apply else 'audit','startMonth':args.start_month,'endMonth':args.end_month or month_key(end),'monthsAttempted':[month_key(m) for m in months],'monthsFetched':fetched,'failures':failures,'rowsAfterMerge':len(merged),'candidateBytes':len(ctext.encode()),'browserBytes':len(btext.encode()),'candidateSha256':hashlib.sha256(ctext.encode()).hexdigest(),'browserSha256':h … [line shortened here: 513 characters; full line on GitHub]
write_report(report); print(json.dumps(report,indent=2)); return 0 if passed else 1
if __name__=='__main__': raise SystemExit(main())