Spaces:
Running
Running
Add interactive seasonal Grid Atlas
Browse files12342 unmodified lines789101112133 unmodified lines171819202122232411 unmodified lines36373839404142434445464748495051import React,{useState,useEffect,useRef} from 'react';import {Zap,Activity,BarChart3,ReceiptText,Network,FileJson,ArrowUpRight,Upload,ArrowRight,Play,CheckCircle2,AlertCircle,Download,RefreshCw,ChevronRight,Info} from 'lucide-react';import Papa from 'papaparse';import AnalysisPanel,{AuditDatasets} from './AnalysisPanel.jsx';2 unmodified linesimport ChallengePanel from './ChallengePanel.jsx';import './live.css';const markets={PT:{name:'Portugal',scope:'Mainland grid',currency:'EUR',region:'PT-mainland',flag:'🇵🇹'},DE:{name:'Germany',scope:'National grid load',currency:'EUR',region:'DE-local-grid',flag:'🇩🇪'},AU:{name:'Australia',scope:'NEM · five regions',currency:'AUD',region:'NSW1',flag:'🇦🇺'}};const nav=[['live','Analyze now',Zap],['quotes','Quote explorer',Zap],['bills','Your bill profile',ReceiptText],['analysis','Import bills & swaps',Network],['benchmark','Forecast lab',Activity],['challenge','LLM challenge',BarChart3],['models','Model evidence',BarChart3],['sources','Official feeds',Network],['api','API & methods',FileJson]];async function request(path,payload){let r=await fetch(path,{signal:AbortSignal.timeout(path==='/api/benchmark'?240000:120000),method:payload===undefined?'GET':'POST',headers:payload===undefined?{}:{'Content-Type':'application/json'},body:payload===undefined?undefined:JSON.stringify(payload)});if(!r.headers.get('content-type')?.includes('application/json'))throw Error(`Service returned HTTP ${r.status} instead of JSON. Retry the connection.`);let data=await r.json();if(!r.ok)throw Error(data.detail||'Request failed');return data;}const num=(n,d=0)=>Number(n).toLocaleString(undefined,{maximumFractionDigits:d});function Json({value}){return <pre className="json">{JSON.stringify(value,null,2)}</pre>}3 unmodified linesfunction CsvUpload({label,onData,onError,help}){return <label className="upload"><Upload size={20}/><b>{label}</b><span>{help||'CSV · maximum 2 MB'}</span><input type="file" accept=".csv" aria-label={label} onChange={e=>{let f=e.target.files[0];if(!f)return;if(f.size>2000000){onError('CSV limit is 2 MB.');return;}Papa.parse(f,{header:true,skipEmptyLines:true,complete:r=>{if(r.errors.length){onError(r.errors[0].message);return;}onData(r.data);},error:e=>onError(e.message)});e.target.value='';}}/></label>}function Field({label,children}){return <label className="field"><span>{label}</span>{children}</label>}function download(value,name){let url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));let a=document.createElement('a');a.href=url;a.download=name;a.click();URL.revokeObjectURL(url);}export default function App(){const [boot,setBoot]=useState(null),[country,setCountry]=useState('PT'),[tab,setTab]=useState(()=>window.location.hash==='#challenge'?'challenge':'live'),[error,setError]=useState(''),[busy,setBusy]=useState(false);const [usage,setUsage]=useState(''),[bill,setBill]=useState(''),[region,setRegion]=useState('PT-mainland'),[meter,setMeter]=useState('standard'),[peak,setPeak]=useState(.5),[powerKva,setPowerKva]=useState(''),[profileSource,setProfileSource]=useState('annual_user_input'),[demo,setDemo]=useState(false),[quotes,setQuotes]=useState(null),[bills,setBills]=useState(null),[accepted,setAccepted]=useState(''),[comparison,setComparison]=useState(null);const [kind,setKind]=useState('demand'),[monthly,setMonthly]=useState(null),[provider,setProvider]=useState(''),[bench,setBench]=useState(null),[evidence,setEvidence]=useState(null);const [runtime,setRuntime]=useState(null),[runtimeError,setRuntimeError]=useState(''),[liveBusy,setLiveBusy]=useState(false);11 unmodified linesconst best=comparison?.ranked_offers?.[0];let billingUsage=bills?bills.reduce((s,r)=>s+Number(r.kwh||0),0):Number(usage);let billingTotal=bills?bills.reduce((s,r)=>s+Number(r.billed_total||0),0):Number(bill);return <div className="app-shell"><aside className="sidebar"><a className="brand" href="#" onClick={e=>{e.preventDefault();setTab('live')}}><div className="brand-symbol"><Zap size={23} fill="currentColor"/></div><div><strong>XenoWAttz</strong><small>WITH BHOR BOHR</small></div></a><div className="side-divider"/><div className="side-label">ELECTROCHEAP WORKSPACE</div><nav>{nav.map(([id,label,Icon])=><button key={id} onClick={()=>{setTab(id);window.history.replaceState(null,'','#'+id);setError('')}} className={tab===id?'nav-item active':'nav-item'}><Icon size={19}/>{label}{id===tab&&<ChevronRight size={15} className="nav-arrow"/>}</button>)}</nav><div className="side-character"><img src="/brand/xenowattz-poster.png" alt="Bhor Bohr, the XenoWAttz energy rebel" loading="lazy"/><div><span className="tiny-dot"/>Bhor Bohr is in the grid.</div></div><div className="side-foot"><span className="status-dot"/>CPU research space<small>Source first. Estimate second.</small></div></aside><main><header className="topbar"><div className="crumb">XenoWAttz <ChevronRight size={13}/><b>Electrocheap</b></div><div className="top-links"><span className="research-badge">RESEARCH PREVIEW</span><a href="/docs" target="_blank" rel="noreferrer">API docs <ArrowUpRight size={14}/></a></div></header><div className="page"><div hidden={tab!=='live'}><EnergyIntro active={tab==='live'} onStart={focusAnalysis}/></div><div className="page-heading" ref={analysisStartRef} tabIndex={-1}><div><div className="eyebrow">ELECTRICITY, WITH THE EVIDENCE ATTACHED</div><h1>{tab==='live'?'Your data. A fresh analysis.':tab==='quotes'?'More clarity. Less bill shock.':tab==='bills'?'Your year, in kilowatt-hours.':tab==='analysis'?'From billing archive to scenario.':tab==='benchmark'?'Challenge the forecast.':tab==='challenge'?'Put our model to the test.':tab==='models'?'Every model earns its place.':tab==='sources'?'Go straight to the source.':'The engine behind XenoWAttz.'}</h1><p>{tab==='live'?'Run a forecast, compare supplied offers, and check the market when you need it.':tab==='quotes'?'Compare the offers you can actually use, with every supplied cost included.':tab==='bills'?'A complete bill profile makes a better starting point than a national average.':tab==='analysis'?'Import compressed bills, inspect tariffs, and compare constrained provider plans.':tab==='benchmark'?'Chronological calibration, validation and test. Complexity gets no free pass.':tab==='challenge'?'Portable prompts, matched predictions and fine-tuning files.':tab==='models'?'TSF, transformers and Astra — inspect the versions and the measured evidence.':tab==='sources'?'Published demand, wholesale prices and Australian retailer plan data.':'React on the surface. Reproducible Python underneath.'}</p></div><div className="market-switch">{Object.entries(markets).map(([c,m])=><button key={c} className={c===country?'selected':''} disabled={liveBusy} title={liveBusy?'Wait for the current analysis before changing markets':undefined} onClick={()=>changeMarket(c)}>{m.flag} {c}</button>)}</div></div>{error&&<div className="error" role="alert"><AlertCircle size={18}/>{error}<button onClick={()=>setError('')}>×</button></div>}{tab!=='live'&&<div className="stats-row"><div><span>SELECTED MARKET</span><strong>{market.name}<small>{market.flag}</small></strong><p>{market.scope}</p></div><div><span>YOUR CONSUMPTION SCENARIO</span><strong>{bills||usage!==''?num(billingUsage):'—'}<small>kWh / year</small></strong><p>{bills?'From uploaded monthly bills':profileSource==='annual_user_input'?(usage!==''?'From your annual input':'Enter your consumption'):'Reviewed annualized invoice estimate'}</p></div><div><span>YOUR CURRENT BILL</span><strong>{bills||bill!==''?num(billingTotal,2):'—'}<small>{market.currency} / year</small></strong><p>{bills?`${bills.length} supplied monthly records`:bill!==''?'Full electricity cost, tax included':'Enter your electricity cost'}</p></div></div>}<div hidden={tab!=='live'}><LiveWorkspace key={country} country={country} market={market} runtime={runtime} runtimeError={runtimeError} onPendingChange={setLiveBusy} onOpenBills={()=>setTab('analysis')}/></div>{tab!=='live'&&!boot&&<section className="panel" role="status"><h2>Loading this workspace</h2><p>{error||'Retrieving the archive and source registry…'}</p>{error&&<button className="secondary" onClick={()=>{setError('');request('/api/bootstrap').then(setBoot).catch(e=>setError(e.message))}}>Retry</button>}</section>}{boot&&<><div hidden={tab!=='analysis'}><AnalysisPanel country={country} quotes={quotes} onError={setError} onProfile={p=>{setCountry(p.country);setRegion(p.region);setUsage(p.annual_kwh);setBill(p.current_annual_bill);setMeter(p.meter_type);setPowerKva(p.contracted_power_kva??'');setProfileSource(p.profile_source);setBills(null);setComparison(null);setTab('quotes')}}/></div>{tab==='quotes'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><Zap size={18}/></span><div><h2>Build your comparison</h2><p>Complete quotes. One consistent usage scenario.</p></div><span className="step">01</span></div><div className="form-grid"><Field label="Annual usage · kWh"><input type="number" min="1" value={bills?billingUsage:usage} disabled={!!bills} onChange={e=>setUsage(e.target.value)}/></Field><Field label={`Current annual cost · ${market.currency}`}><input type="number" min="0" value={bills?billingTotal:bill} disabled={!!bills} onChange={e=>setBill(e.target.value)}/></Field><Field label="Eligibility region / grid"><input value={region} onChange={e=>setRegion(e.target.value)}/></Field><Field label="Contracted power · kVA (when applicable)"><input type="number" value={powerKva} placeholder="e.g. 3.45" min="0.1" step="0.05" onChange={e=>setPowerKva(e.target.value)}/></Field><Field label="Meter type"><select value={meter} onChange={e=>setMeter(e.target.value)}><option value="standard">Standard</option><option value="smart">Smart / time of use</option></select></Field></div>{meter==='smart'&&<Field label={`Peak usage share · ${Math.round(peak*100)}%`}><input type="range" min="0" max="1" step=".01" value={peak} onChange={e=>setPeak(e.target.value)}/></Field>}<CsvUpload label={quotes?`${quotes.length} supplied quotes loaded`:'Add your provider quotes'} onData={d=>{setQuotes(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/quote_template.csv" download>Get the empty template <Download size={13}/></a><button onClick={()=>setTab('bills')}>{bills?'Edit bill profile':'Use monthly bills'} <ArrowRight size={13}/></button></div><Field label="Acknowledged offer condition IDs · optional"><input value={accepted} placeholder="Comma-separated IDs" onChange={e=>setAccepted(e.target.value)}/></Field><label className="check-row"><input type="checkbox" checked={demo} onChange={e=>{setDemo(e.target.checked);setComparison(null)}}/><span>Try fictional example quotes<small>Illustrative sandbox · explicitly enabled</small></span></label><button className="primary full" disabled={busy} onClick={()=>run(async()=>setComparison(await request('/api/consumer_compare',payload())))}>{busy?<RefreshCw size={16}/>:<Zap size={16}/>}Compare eligible quotes<ArrowRight size={16}/></button></section><div className="right-stack"><section className="panel grid-card"><div className="section-title"><div><div className="eyebrow">ARCHIVED MARKET CONTEXT</div><h2>{market.name} · grid demand</h2></div><span className="source-pill">{country==='PT'?'REN':country==='DE'?'SMARD':'AEMO'}</span></div><Chart series={[{name:'Published monthly grid energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/><div className="chart-caption">{history.length} archived monthly records · {String(history[0]?.timestamp||'').slice(0,7)}–{String(history.at(-1)?.timestamp||'').slice(0,7)}<span>GWh</span></div><p className="subtle">Grid demand provides context. It does not describe an individual retailer or predict your bill.</p></section><section className="how-card"><span className="icon-box"><CheckCircle2 size={19}/></span><h3>The whole quoted cost.</h3><p>Energy + supply charges + annual fees + switching costs − guaranteed credits.</p><div className="how-tags"><span>Tax included</span><span>Eligibility checked</span><span>Dated evidence</span></div></section></div></div>{comparison&&<section className="panel result-panel"><div className="section-title"><div><div className="eyebrow">{demo?'ILLUSTRATIVE SCENARIO':'SUPPLIED QUOTE SCENARIO'}</div><h2>{best?`${best.provider} · lowest supplied first-year cost`:'No eligible quotes'}</h2></div>{best&&<strong className="result-cost">{num(best.first_year_cost,2)} <small>{market.currency}</small></strong>}</div>{best&&<p>Estimated difference from your supplied annual bill: <b>{num(best.estimated_saving,2)} {market.currency}</b>. {best.price_basis}.</p>}<Table rows={comparison.ranked_offers} columns={[["provider","Provider"],["first_year_cost","First-year cost"],["recurring_annual_cost","Recurring cost"],["estimated_saving","Estimated saving"],["evidence","Evidence"]]}/>{comparison.excluded_offers.length>0&&<details><summary>Excluded quotes and reasons ({comparison.excluded_offers.length})</summary><Table rows={comparison.excluded_offers} columns={[["offer_id","Offer"],["reason","Reason"]]}/></details>}<details><summary>Calculation evidence</summary><Json value={comparison}/></details></section>}<Notice>Quotes must be complete and tax inclusive. The comparison covers eligible supplied offers; it is not a whole-market promise. Complex indexed, tiered, demand-charge or export tariffs need a complete scoped quote.</Notice></>}{tab==='bills'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><ReceiptText size={18}/></span><div><h2>A complete latest-year profile</h2><p>Twelve complete months before the current month.</p></div></div><button className="secondary full" onClick={()=>setTab('analysis')}><Upload size={16}/>Import ZIP / PDF billing archives</button><CsvUpload label="Upload anonymous monthly bills" help="month, kwh, billed_total, currency · optional peak_kwh" onData={d=>{setBills(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/example_billing_months.csv" download>Download fictional EUR sample <Download size={13}/></a>{country==='PT'&&<button onClick={()=>{setBills(boot.example_bills);setComparison(null)}}>Load fictional sample</button>}</div><Notice>Use actual tax-inclusive electricity charges, not bank-payment instalments. Remove names, addresses and account numbers. Each month must appear once, in the selected market currency.</Notice><button className="primary full" onClick={()=>setTab('quotes')}>Compare using this profile <ArrowRight size={16}/></button>{bills&&<button className="text-button" onClick={()=>{setBills(null);setComparison(null)}}>Clear monthly profile</button>}</section><section className="panel"><h2>What your data can tell us</h2><div className="explain-row"><span>01</span><div><b>Consumption and current cost</b><p>Your latest-year totals replace the manual annual fields.</p></div></div><div className="explain-row"><span>02</span><div><b>Peak and off-peak allocation</b><p>Supply peak_kwh for every month, or supply your measured peak share separately.</p></div></div><div className="explain-row"><span>03</span><div><b>A starting scenario, not a model winner</b><p>Twelve monthly bills cover only one annual cycle. The grid-model leaderboard cannot select a reliable household forecaster.</p></div></div></section></div>{bills&&<section className="panel"><h2>Supplied monthly profile</h2><Chart series={[{name:'Monthly consumption',values:bills.map(x=>Number(x.kwh))}]} labels={bills.map(x=>x.month)} unit="kWh"/><Table rows={bills} columns={[["month","Month"],["kwh","Consumption · kWh"],["billed_total","Billed electricity cost"],["currency","Currency"]]}/></section>}</>}{tab==='benchmark'&&<><section className="panel"><div className="section-title"><div><h2>The forecast laboratory</h2><p>Same series. Same origins. Validation chooses; test measures.</p></div><span className="source-pill">PROTOCOL V2</span></div><div className="form-grid three"><Field label="Forecast target"><select value={kind} onChange={e=>{setKind(e.target.value);setBench(null)}}><option value="demand">Monthly grid energy · GWh</option><option value="price">Monthly wholesale price · {market.currency}/MWh</option></select></Field><Field label="Provider label · uploaded data only"><input value={provider} placeholder="Exact provider column value" onChange={e=>setProvider(e.target.value)}/></Field><div className="worker-note"><span className="status-dot"/>Single CPU benchmark worker<br/><small>No paid model calls</small></div></div><CsvUpload label={monthly?`${monthly.length} monthly records loaded`:'Use an optional monthly series'} help="timestamp,value,unit,coverage · ≥72 complete months" onData={d=>{setMonthly(d);setBench(null)}} onError={setError}/>{monthly&&<button className="text-button" onClick={()=>{setMonthly(null);setBench(null)}}>Use bundled grid snapshot instead</button>}<div className="protocol-strip"><span><b>1.</b> Training prefix</span><ArrowRight size={14}/><span><b>2.</b> Calibration</span><ArrowRight size={14}/><span><b>3.</b> Validation</span><ArrowRight size={14}/><span><b>4.</b> Test</span></div><div className="button-row"><button className="primary" disabled={busy} onClick={()=>run(async()=>setBench(await request('/api/benchmark',{country,kind,records:monthly,provider})))}>{busy?<RefreshCw size={16}/>:<Play size={16}/>}Run CPU benchmark</button><span className="subtle">Seasonal baselines · SARIMA · Grokked · SARIMAX · GARCH</span></div></section>{!bench&&<section className="panel"><div className="section-title"><h2>Published historical context</h2><span className="source-pill">{market.scope}</span></div>{kind==='demand'?<Chart series={[{name:'Monthly energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/>:<div className="empty">Wholesale history is not bundled. Upload a complete monthly price series to run a pricing benchmark.</div>}</section>}{bench&&<section className="panel"><div className="section-title"><div><div className="eyebrow">VALIDATION-SELECTED</div><h2>{bench.selected_model}</h2><p>{bench.series_scope} · held-out test starts {bench.test_start}</p></div><button className="secondary" onClick={()=>download(bench,'electrocheap-benchmark.json')}><Download size={15}/>Evidence JSON</button></div><Chart unit={bench.unit} labels={bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.timestamp)} series={[{name:'Actual',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.actual),color:'#243344'},{name:bench.selected_model,values:bench.predictions.filter(p=>p.split==='test'&&p.model===bench.selected_model).map(p=>p.forecast),color:'#18a184'},{name:'Seasonal naive',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.forecast),color:'#e59b39',dashed:true}]}/><Table rows={bench.scores.filter(s=>s.split==='test')} columns={[["model","Model"],["MAE","MAE"],["RMSE","RMSE"],["MASE","MASE"],["selected_on_validation","Selected"]]}/><details><summary>Residual GARCH volatility and protocol</summary><Json value={{volatility:bench.residual_volatility,claim:bench.claim,input_sha256:bench.input_sha256,implementation_sha256:bench.implementation_sha256}}/></details></section>}<Notice>At least 72 consecutive complete months. No interpolation. Bias is frozen after calibration; a candidate needs 5% better validation MAE to replace the baseline. GARCH estimates residual volatility and keeps the SARIMAX mean unchanged. Tests are retrospective and descriptive.</Notice></>}{tab==='challenge'&&<ChallengePanel key={country} country={country}/>}{tab==='models'&&<><AuditDatasets/><section className="panel"><div className="section-title"><div><h2>The full recorded model family</h2><p>Archived grid-demand evidence · 24 test targets · six-month forecasts</p></div><span className="source-pill">2026-10-09 ARCHIVE</span></div><Table rows={evidence?.scores} columns={[["model","Model / variant"],["mae_gwh","MAE · GWh"],["mase","MASE"],["skill_vs_seasonal_naive_pct","Skill vs baseline · %"],["selected_on_validation","Selected"]]}/></section><div className="model-cards"><section className="panel"><div className="eyebrow">LIVE CPU CANDIDATES</div><h2>Statistical & Grokked</h2><p>Seasonal baselines, SARIMA, the explicit 80/20 Grokked blend, calendar SARIMAX and residual GARCH.</p><span className="availability live"><CheckCircle2 size={14}/>Runnable in Forecast lab</span></section><section className="panel"><div className="eyebrow">PINNED TRANSFORMERS</div><h2>TimesFM 2.5 · Chronos-2</h2><p>Exact checkpoint revisions and Python package versions preserved from the measured archived runs.</p><span className="availability"><BarChart3 size={14}/>Cached measured evidence</span></section><section className="panel"><div className="eyebrow">HOSTED MODEL DIAGNOSTICS</div><h2>Astra · Sol</h2><p>Archived delegated test diagnostics. No separately authenticated customer inference API is configured.</p><span className="availability"><BarChart3 size={14}/>Diagnostic only</span></section></div><Notice>A separate Super Grokked implementation and the original KMLAIOps SARIMAX-GARCHX source are unavailable. Newly written adapters are not presented under those identities. Grid scores do not establish household accuracy or bill savings.</Notice><section className="panel"><details><summary>Inspect exact versions, source commits and availability</summary><Json value={evidence}/></details></section></>}12342 unmodified lines789101112133 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126211 unmodified lines274275276277278279280281282283284285286287288289290import React,{useState,useEffect,useRef,useMemo} from 'react';import {Zap,Activity,BarChart3,ReceiptText,Network,FileJson,ArrowUpRight,Upload,ArrowRight,Play,CheckCircle2,AlertCircle,Download,RefreshCw,ChevronRight,Info} from 'lucide-react';import Papa from 'papaparse';import AnalysisPanel,{AuditDatasets} from './AnalysisPanel.jsx';2 unmodified linesimport ChallengePanel from './ChallengePanel.jsx';import './live.css';const markets={PT:{name:'Portugal',scope:'Mainland grid',currency:'EUR',region:'PT-mainland',flag:'🇵🇹'},DE:{name:'Germany',scope:'National grid load',currency:'EUR',region:'DE-local-grid',flag:'🇩🇪'},AU:{name:'Australia',scope:'NEM · five regions',currency:'AUD',region:'NSW1',flag:'🇦🇺'}};const nav=[['live','Analyze now',Zap],['atlas','Grid Atlas',Activity],['quotes','Quote explorer',Zap],['bills','Your bill profile',ReceiptText],['analysis','Import bills & swaps',Network],['benchmark','Forecast lab',Activity],['challenge','LLM challenge',BarChart3],['models','Model evidence',BarChart3],['sources','Official feeds',Network],['api','API & methods',FileJson]];async function request(path,payload){let r=await fetch(path,{signal:AbortSignal.timeout(path==='/api/benchmark'?240000:120000),method:payload===undefined?'GET':'POST',headers:payload===undefined?{}:{'Content-Type':'application/json'},body:payload===undefined?undefined:JSON.stringify(payload)});if(!r.headers.get('content-type')?.includes('application/json'))throw Error(`Service returned HTTP ${r.status} instead of JSON. Retry the connection.`);let data=await r.json();if(!r.ok)throw Error(data.detail||'Request failed');return data;}const num=(n,d=0)=>Number(n).toLocaleString(undefined,{maximumFractionDigits:d});function Json({value}){return <pre className="json">{JSON.stringify(value,null,2)}</pre>}3 unmodified linesfunction CsvUpload({label,onData,onError,help}){return <label className="upload"><Upload size={20}/><b>{label}</b><span>{help||'CSV · maximum 2 MB'}</span><input type="file" accept=".csv" aria-label={label} onChange={e=>{let f=e.target.files[0];if(!f)return;if(f.size>2000000){onError('CSV limit is 2 MB.');return;}Papa.parse(f,{header:true,skipEmptyLines:true,complete:r=>{if(r.errors.length){onError(r.errors[0].message);return;}onData(r.data);},error:e=>onError(e.message)});e.target.value='';}}/></label>}function Field({label,children}){return <label className="field"><span>{label}</span>{children}</label>}function download(value,name){let url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));let a=document.createElement('a');a.href=url;a.download=name;a.click();URL.revokeObjectURL(url);}const atlasMonthLabels = Array.from({length: 12}, (_, month) =>new Intl.DateTimeFormat('en', {month: 'short', timeZone: 'UTC'}).format(Date.UTC(2024, month)));function AtlasWheel({points, selection, onSelect, low, high}) {const canvas = useRef(null);const hitTargets = useRef([]);const drag = useRef(null);const [angle, setAngle] = useState(-0.52);useEffect(() => {const element = canvas.current;function draw() {const width = element.clientWidth;const height = element.clientHeight;if (!width || !height) return;const scale = window.devicePixelRatio || 1;element.width = Math.round(width * scale);element.height = Math.round(height * scale);const ctx = element.getContext('2d');ctx.scale(scale, scale);const radius = Math.min(width * .31, height * .40);const firstYear = points[0].year;const lastYear = points.at(-1).year;const vertical = height * .52;function project(month, year, factor) {const phase = angle + month * Math.PI / 6;const depth = Math.sin(phase) * radius * factor;const level = (year - firstYear) / Math.max(lastYear - firstYear, 1);return {x: width / 2 + Math.cos(phase) * radius * factor,y: height * .76 - (lastYear === firstYear ? .5 : level) * vertical + depth * .40,depth};}function line(nodes, color, weight = 1) {ctx.beginPath();nodes.forEach((p, index) => index ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y));ctx.strokeStyle = color;ctx.lineWidth = weight;ctx.stroke();}const yearStep = Math.max(1, Math.ceil((lastYear - firstYear) / 7));for (let year = firstYear; year <= lastYear; year += yearStep) {const ring = Array.from({length: 73}, (_, index) => project(index / 6, year, 1.08));line(ring, '#f6ddb150');ctx.font = '11px system-ui';ctx.fillStyle = '#e3cfae';ctx.fillText(year, Math.min(width - 33, width / 2 + radius * 1.12), ring[0].y);}for (let month = 0; month < 12; month += 3) {const start = project(month, firstYear, 1.08);const end = project(month, lastYear, 1.08);line([start, end], '#f6ddb150');ctx.font = '11px system-ui';ctx.fillStyle = '#e3cfae';ctx.fillText(atlasMonthLabels[month], start.x - 9, start.y + 20 + (lastYear === firstYear ? 4 : 0));}const nodes = points.map(point => {const fraction = (point.value - low) / (high - low || 1);return {...project(point.month, point.year, .31 + .69 * fraction), point, fraction};});for (let i = 1; i < nodes.length; i++) {const before = nodes[i - 1];const after = nodes[i];if (after.point.index - before.point.index === 1) line([before, after], '#f9a94e82', 1.6);}hitTargets.current = [...nodes].sort((a, b) => a.depth - b.depth);for (const node of hitTargets.current) {const active = node.point.key === selection;ctx.beginPath();ctx.arc(node.x, node.y, active ? 8 : 3.4 + node.fraction * 1.2, 0, Math.PI * 2);ctx.fillStyle = active ? '#fff5d5' : `hsl(${21 + node.fraction * 29} 96% ${51 + node.fraction * 19}%)`;ctx.fill();if (active) {ctx.strokeStyle = '#ffb852';ctx.lineWidth = 2.5;ctx.stroke();}}}const observer = new ResizeObserver(draw);observer.observe(element);draw();return () => observer.disconnect();}, [points, selection, angle, low, high]);function endDrag(event) {const start = drag.current;drag.current = null;if (!start || start.moved) return;const bounds = event.currentTarget.getBoundingClientRect();const x = event.clientX - bounds.left;const y = event.clientY - bounds.top;const nearest = hitTargets.current.reduce((best, point) => {const distance = Math.hypot(point.x - x, point.y - y);return distance <= best.distance ? {distance, point} : best;}, {distance: 16});if (nearest.point) onSelect(nearest.point.point.key);}return <div className="atlas-wheel"><canvas ref={canvas} aria-label="Seasonal grid demand in 3D. Use the month selector to inspect exact values."onPointerDown={event => {drag.current = {x: event.clientX, angle, moved: false};event.currentTarget.setPointerCapture(event.pointerId);}}onPointerMove={event => {if (!drag.current) return;const delta = event.clientX - drag.current.x;drag.current.moved ||= Math.abs(delta) > 5;if (drag.current.moved) setAngle(drag.current.angle + delta / 115);}}onPointerUp={endDrag} onPointerCancel={() => {drag.current = null;}} /><div className="atlas-camera" aria-label="View rotation"><button type="button" aria-label="Rotate left" onClick={() => setAngle(value => value - .45)}>←</button><button type="button" onClick={() => setAngle(-.52)}>Reset view</button><button type="button" aria-label="Rotate right" onClick={() => setAngle(value => value + .45)}>→</button></div></div>;}function GridAtlas({history, market, source, loaded}) {const [mode, setMode] = useState('wheel');const [windowSize, setWindowSize] = useState('5');const [selectedKey, setSelectedKey] = useState(null);const all = useMemo(() => {const unique = new Map();for (const row of history) {const stamp = typeof row.timestamp === 'string' ? row.timestamp : '';const match = /^(\d{4})-(0[1-9]|1[0-2])/.exec(stamp || '');if (!match || row.value == null || !Number.isFinite(Number(row.value))) continue;const year = Number(match[1]);const month = Number(match[2]) - 1;const key = match[0];unique.set(key, {year, month, key, index: year * 12 + month, value: Number(row.value), coverage: row.coverage});}return [...unique.values()].sort((a, b) => a.index - b.index);}, [history]);const latest = all.at(-1);const points = useMemo(() => {if (!latest || windowSize === 'all') return all;return all.filter(point => point.year > latest.year - Number(windowSize));}, [all, latest, windowSize]);if (!latest) return <section className="panel"><p role="status">{loaded ? 'No published monthly grid data for this market.' : 'Loading the published grid snapshot…'}</p></section>;const selected = points.find(point => point.key === selectedKey) || latest;const previous = all.find(point => point.index === selected.index - 12);const delta = previous?.value ? (selected.value - previous.value) / previous.value * 100 : null;const low = Math.min(...points.map(point => point.value));const high = Math.max(...points.map(point => point.value));const years = [...new Set(points.map(point => point.year))].reverse();const byDate = new Map(points.map(point => [point.year * 12 + point.month, point]));const position = points.indexOf(selected);const publisher = source?.publisher || 'Published';return <section className="panel grid-atlas" aria-label="Grid Atlas"><style>{gridAtlasStyles}</style><div className="atlas-heading"><div><p className="atlas-kicker">{publisher} grid history</p><h2>Grid Atlas</h2><p>{market.scope} · {points[0].key} to {latest.key}</p></div><div className="atlas-modes" aria-label="Visualization"><button type="button" aria-pressed={mode === 'wheel'} onClick={() => setMode('wheel')}>Seasonal orbit</button><button type="button" aria-pressed={mode === 'calendar'} onClick={() => setMode('calendar')}>Calendar</button></div></div><div className="atlas-body"><div className="atlas-visual">{mode === 'wheel' ? <AtlasWheel points={points} selection={selected.key} onSelect={setSelectedKey} low={low} high={high}/> :<div className="atlas-calendar" tabIndex={0} role="region" aria-label="Scrollable calendar of monthly grid energy"><div className="atlas-calendar-row"><span>Year</span>{atlasMonthLabels.map(label => <span key={label}>{label}</span>)}</div>{years.map(year => <div className="atlas-calendar-row" key={year}><strong>{year}</strong>{atlasMonthLabels.map((label, month) => {const point = byDate.get(year * 12 + month);const amount = point ? (point.value - low) / (high - low || 1) : 0;return point ? <button type="button" key={label} aria-pressed={point.key === selected.key}aria-label={`${label} ${year}, ${num(point.value, 1)} GWh`}title={`${label} ${year} · ${num(point.value, 1)} GWh`}style={{backgroundColor: `hsl(${44 - 23 * amount} 90% ${92 - 40 * amount}%)`}}onClick={() => setSelectedKey(point.key)} /> :<span key={label} className="atlas-gap" title={`${label} ${year} · no record`}>—</span>;})}</div>)}</div>}<p className="atlas-scale">{mode === 'wheel' ? 'One turn per year · farther from the centre means more energy. Drag to rotate.' : 'Darker orange means more energy. Blank cells mark months without a record.'}<span>{num(low)}–{num(high)} GWh</span></p></div><div className="atlas-detail"><label>History range<select value={windowSize} onChange={event => setWindowSize(event.target.value)}><option value="3">Last 3 calendar years</option><option value="5">Last 5 calendar years</option><option value="all">All available years</option></select></label><div className="atlas-readout" aria-live="polite"><span>{atlasMonthLabels[selected.month]} {selected.year}</span><strong>{num(selected.value, 1)} <small>GWh</small></strong>{Number.isFinite(selected.coverage)&&selected.coverage<1&&<p>{num(selected.coverage*100,1)}% source coverage</p>}<p>{delta === null ? 'Same month last year unavailable' : `${delta > 0 ? '+' : ''}${num(delta, 1)}% vs the same month last year`}</p></div><label>Month<input type="range" min="0" max={points.length - 1} value={position}aria-valuetext={`${atlasMonthLabels[selected.month]} ${selected.year}`}onChange={event => setSelectedKey(points[Number(event.target.value)].key)} /></label>{source?.link&&<a href={source.link} target="_blank" rel="noreferrer">Open {publisher} source ↗</a>}</div></div></section>;}const gridAtlasStyles = `.grid-atlas{border-radius:22px;background:#fffdf8;color:#27211e;padding:clamp(15px,3vw,28px);border:1px solid #efded0}.atlas-heading,.atlas-modes,.atlas-camera,.atlas-scale{display:flex;align-items:center;gap:9px}.atlas-heading{justify-content:space-between;flex-wrap:wrap;margin-bottom:18px}.atlas-heading h2{font-size:clamp(32px,5vw,50px);letter-spacing:-.068em;margin:0;line-height:1.05;font-weight:710}.atlas-heading p{margin:6px 0 0;color:#675349;font-size:13px}.atlas-heading .atlas-kicker{color:#99501d;font-size:11px;font-weight:750;letter-spacing:.13em;text-transform:uppercase;margin:0 0 5px}.atlas-modes button,.atlas-camera button{background:#fff5e7;color:#311f17;border:1px solid #ead0b7;border-radius:999px;padding:6px 11px;cursor:pointer;font-size:12px;font-weight:700}.atlas-modes button[aria-pressed=true]{background:#ffb660;border-color:#b96725}.atlas-body{display:grid;grid-template-columns:minmax(0,1fr) minmax(175px,.36fr);gap:16px}.atlas-visual{min-width:0}.atlas-wheel{overflow:hidden;position:relative;border-radius:15px;background:radial-gradient(ellipse at 47% 43%,#49291f,#1d1516 77%);border:1px solid #1d1516}.atlas-wheel canvas{display:block;width:100%;height:clamp(285px,43vw,430px);touch-action:pan-y;cursor:grab}.atlas-wheel canvas:active{cursor:grabbing}.atlas-camera{position:absolute;bottom:10px;left:50%;transform:translateX(-50%);white-space:nowrap}.atlas-camera button{background:#31201f;color:#ffe7c2;border-color:#805a43}.atlas-detail{display:grid;align-content:start;gap:17px;background:#fff3e2;border:1px solid #f0dac4;border-radius:15px;padding:15px}.atlas-detail label{display:grid;gap:6px;font-size:12px;font-weight:700;color:#57372b}.atlas-detail select{width:100%;border-radius:9px;padding:7px;background:#fffdf7;color:#332219;border:1px solid #dbbca2}.atlas-detail input{width:100%;min-width:0;accent-color:#b34f15}.atlas-detail a{font-size:12px;font-weight:700;color:#814316;text-underline-offset:3px}.atlas-readout span,.atlas-readout p{font-size:12px;color:#654032;margin:4px 0}.atlas-readout strong{display:block;font-size:clamp(25px,4vw,38px);letter-spacing:-.05em;line-height:1.15;overflow-wrap:anywhere}.atlas-readout small{font-size:13px;letter-spacing:0}.atlas-scale{justify-content:space-between;flex-wrap:wrap;color:#685247;font-size:12px;margin:8px 0 0}.atlas-scale span{white-space:nowrap;font-variant-numeric:tabular-nums}.atlas-calendar{overflow:auto;max-height:430px;border:1px solid #f0dac4;border-radius:15px;padding:10px;background:#fff9ee}.atlas-calendar-row{min-width:430px;display:grid;grid-template-columns:45px repeat(12,minmax(25px,1fr));gap:4px;align-items:center;text-align:center;color:#5c473a;font-size:10px;padding:3px 0}.atlas-calendar-row button,.atlas-gap{height:23px;border:1px solid transparent;border-radius:4px}.atlas-calendar-row button{cursor:pointer}.atlas-calendar-row button[aria-pressed=true]{border:2px solid #342014}.grid-atlas button:focus-visible,.grid-atlas select:focus-visible,.grid-atlas input:focus-visible,.grid-atlas a:focus-visible{outline:2px solid #944511;outline-offset:2px}@media(max-width:820px){.atlas-body{grid-template-columns:minmax(0,1fr)}}`;export default function App(){const [boot,setBoot]=useState(null),[country,setCountry]=useState('PT'),[tab,setTab]=useState(()=>nav.find(([id])=>window.location.hash==='#'+id)?.[0]||'live'),[error,setError]=useState(''),[busy,setBusy]=useState(false);const [usage,setUsage]=useState(''),[bill,setBill]=useState(''),[region,setRegion]=useState('PT-mainland'),[meter,setMeter]=useState('standard'),[peak,setPeak]=useState(.5),[powerKva,setPowerKva]=useState(''),[profileSource,setProfileSource]=useState('annual_user_input'),[demo,setDemo]=useState(false),[quotes,setQuotes]=useState(null),[bills,setBills]=useState(null),[accepted,setAccepted]=useState(''),[comparison,setComparison]=useState(null);const [kind,setKind]=useState('demand'),[monthly,setMonthly]=useState(null),[provider,setProvider]=useState(''),[bench,setBench]=useState(null),[evidence,setEvidence]=useState(null);const [runtime,setRuntime]=useState(null),[runtimeError,setRuntimeError]=useState(''),[liveBusy,setLiveBusy]=useState(false);11 unmodified linesconst best=comparison?.ranked_offers?.[0];let billingUsage=bills?bills.reduce((s,r)=>s+Number(r.kwh||0),0):Number(usage);let billingTotal=bills?bills.reduce((s,r)=>s+Number(r.billed_total||0),0):Number(bill);return <div className="app-shell"><aside className="sidebar"><a className="brand" href="#" onClick={e=>{e.preventDefault();setTab('live');window.history.replaceState(null,'','#live')}}><div className="brand-symbol"><Zap size={23} fill="currentColor"/></div><div><strong>XenoWAttz</strong><small>WITH BHOR BOHR</small></div></a><div className="side-divider"/><div className="side-label">ELECTROCHEAP WORKSPACE</div><nav>{nav.map(([id,label,Icon])=><button key={id} aria-current={id===tab?'page':undefined} onClick={()=>{setTab(id);window.history.replaceState(null,'','#'+id);setError('')}} className={tab===id?'nav-item active':'nav-item'}><Icon size={19}/>{label}{id===tab&&<ChevronRight size={15} className="nav-arrow"/>}</button>)}</nav><div className="side-character"><img src="/brand/xenowattz-poster.png" alt="Bhor Bohr, the XenoWAttz energy rebel" loading="lazy"/><div><span className="tiny-dot"/>Bhor Bohr is in the grid.</div></div><div className="side-foot"><span className="status-dot"/>CPU research space<small>Source first. Estimate second.</small></div></aside><main><header className="topbar"><div className="crumb">XenoWAttz <ChevronRight size={13}/><b>Electrocheap</b></div><div className="top-links"><span className="research-badge">RESEARCH PREVIEW</span><a href="/docs" target="_blank" rel="noreferrer">API docs <ArrowUpRight size={14}/></a></div></header><div className="page"><div hidden={tab!=='live'}><EnergyIntro active={tab==='live'} onStart={focusAnalysis}/></div><div className="page-heading" ref={analysisStartRef} tabIndex={-1}><div><div className="eyebrow">ELECTRICITY, WITH THE EVIDENCE ATTACHED</div><h1>{tab==='live'?'Your data. A fresh analysis.':tab==='atlas'?'Explore grid demand.':tab==='quotes'?'More clarity. Less bill shock.':tab==='bills'?'Your year, in kilowatt-hours.':tab==='analysis'?'From billing archive to scenario.':tab==='benchmark'?'Challenge the forecast.':tab==='challenge'?'Put our model to the test.':tab==='models'?'Every model earns its place.':tab==='sources'?'Go straight to the source.':'The engine behind XenoWAttz.'}</h1><p>{tab==='live'?'Run a forecast, compare supplied offers, and check the market when you need it.':tab==='atlas'?'Follow seasonal demand through the published monthly series for Portugal, Germany and Australia.':tab==='quotes'?'Compare the offers you can actually use, with every supplied cost included.':tab==='bills'?'A complete bill profile makes a better starting point than a national average.':tab==='analysis'?'Import compressed bills, inspect tariffs, and compare constrained provider plans.':tab==='benchmark'?'Chronological calibration, validation and test. Complexity gets no free pass.':tab==='challenge'?'Portable prompts, matched predictions and fine-tuning files.':tab==='models'?'TSF, transformers and Astra — inspect the versions and the measured evidence.':tab==='sources'?'Published demand, wholesale prices and Australian retailer plan data.':'React on the surface. Reproducible Python underneath.'}</p></div><div className="market-switch">{Object.entries(markets).map(([c,m])=><button key={c} className={c===country?'selected':''} disabled={liveBusy} title={liveBusy?'Wait for the current analysis before changing markets':undefined} onClick={()=>changeMarket(c)}>{m.flag} {c}</button>)}</div></div>{error&&<div className="error" role="alert"><AlertCircle size={18}/>{error}<button onClick={()=>setError('')}>×</button></div>}{tab!=='live'&&tab!=='atlas'&&<div className="stats-row"><div><span>SELECTED MARKET</span><strong>{market.name}<small>{market.flag}</small></strong><p>{market.scope}</p></div><div><span>YOUR CONSUMPTION SCENARIO</span><strong>{bills||usage!==''?num(billingUsage):'—'}<small>kWh / year</small></strong><p>{bills?'From uploaded monthly bills':profileSource==='annual_user_input'?(usage!==''?'From your annual input':'Enter your consumption'):'Reviewed annualized invoice estimate'}</p></div><div><span>YOUR CURRENT BILL</span><strong>{bills||bill!==''?num(billingTotal,2):'—'}<small>{market.currency} / year</small></strong><p>{bills?`${bills.length} supplied monthly records`:bill!==''?'Full electricity cost, tax included':'Enter your electricity cost'}</p></div></div>}<div hidden={tab!=='live'}><LiveWorkspace key={country} country={country} market={market} runtime={runtime} runtimeError={runtimeError} onPendingChange={setLiveBusy} onOpenBills={()=>setTab('analysis')}/></div>{tab!=='live'&&!boot&&<section className="panel" role="status"><h2>Loading this workspace</h2><p>{error||'Retrieving the archive and source registry…'}</p>{error&&<button className="secondary" onClick={()=>{setError('');request('/api/bootstrap').then(setBoot).catch(e=>setError(e.message))}}>Retry</button>}</section>}{boot&&<><div hidden={tab!=='analysis'}><AnalysisPanel country={country} quotes={quotes} onError={setError} onProfile={p=>{setCountry(p.country);setRegion(p.region);setUsage(p.annual_kwh);setBill(p.current_annual_bill);setMeter(p.meter_type);setPowerKva(p.contracted_power_kva??'');setProfileSource(p.profile_source);setBills(null);setComparison(null);setTab('quotes')}}/></div>{tab==='quotes'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><Zap size={18}/></span><div><h2>Build your comparison</h2><p>Complete quotes. One consistent usage scenario.</p></div><span className="step">01</span></div><div className="form-grid"><Field label="Annual usage · kWh"><input type="number" min="1" value={bills?billingUsage:usage} disabled={!!bills} onChange={e=>setUsage(e.target.value)}/></Field><Field label={`Current annual cost · ${market.currency}`}><input type="number" min="0" value={bills?billingTotal:bill} disabled={!!bills} onChange={e=>setBill(e.target.value)}/></Field><Field label="Eligibility region / grid"><input value={region} onChange={e=>setRegion(e.target.value)}/></Field><Field label="Contracted power · kVA (when applicable)"><input type="number" value={powerKva} placeholder="e.g. 3.45" min="0.1" step="0.05" onChange={e=>setPowerKva(e.target.value)}/></Field><Field label="Meter type"><select value={meter} onChange={e=>setMeter(e.target.value)}><option value="standard">Standard</option><option value="smart">Smart / time of use</option></select></Field></div>{meter==='smart'&&<Field label={`Peak usage share · ${Math.round(peak*100)}%`}><input type="range" min="0" max="1" step=".01" value={peak} onChange={e=>setPeak(e.target.value)}/></Field>}<CsvUpload label={quotes?`${quotes.length} supplied quotes loaded`:'Add your provider quotes'} onData={d=>{setQuotes(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/quote_template.csv" download>Get the empty template <Download size={13}/></a><button onClick={()=>setTab('bills')}>{bills?'Edit bill profile':'Use monthly bills'} <ArrowRight size={13}/></button></div><Field label="Acknowledged offer condition IDs · optional"><input value={accepted} placeholder="Comma-separated IDs" onChange={e=>setAccepted(e.target.value)}/></Field><label className="check-row"><input type="checkbox" checked={demo} onChange={e=>{setDemo(e.target.checked);setComparison(null)}}/><span>Try fictional example quotes<small>Illustrative sandbox · explicitly enabled</small></span></label><button className="primary full" disabled={busy} onClick={()=>run(async()=>setComparison(await request('/api/consumer_compare',payload())))}>{busy?<RefreshCw size={16}/>:<Zap size={16}/>}Compare eligible quotes<ArrowRight size={16}/></button></section><div className="right-stack"><section className="panel grid-card"><div className="section-title"><div><div className="eyebrow">ARCHIVED MARKET CONTEXT</div><h2>{market.name} · grid demand</h2></div><span className="source-pill">{country==='PT'?'REN':country==='DE'?'SMARD':'AEMO'}</span></div><Chart series={[{name:'Published monthly grid energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/><div className="chart-caption">{history.length} archived monthly records · {String(history[0]?.timestamp||'').slice(0,7)}–{String(history.at(-1)?.timestamp||'').slice(0,7)}<span>GWh</span></div><p className="subtle">Grid demand provides context. It does not describe an individual retailer or predict your bill.</p></section><section className="how-card"><span className="icon-box"><CheckCircle2 size={19}/></span><h3>The whole quoted cost.</h3><p>Energy + supply charges + annual fees + switching costs − guaranteed credits.</p><div className="how-tags"><span>Tax included</span><span>Eligibility checked</span><span>Dated evidence</span></div></section></div></div>{comparison&&<section className="panel result-panel"><div className="section-title"><div><div className="eyebrow">{demo?'ILLUSTRATIVE SCENARIO':'SUPPLIED QUOTE SCENARIO'}</div><h2>{best?`${best.provider} · lowest supplied first-year cost`:'No eligible quotes'}</h2></div>{best&&<strong className="result-cost">{num(best.first_year_cost,2)} <small>{market.currency}</small></strong>}</div>{best&&<p>Estimated difference from your supplied annual bill: <b>{num(best.estimated_saving,2)} {market.currency}</b>. {best.price_basis}.</p>}<Table rows={comparison.ranked_offers} columns={[["provider","Provider"],["first_year_cost","First-year cost"],["recurring_annual_cost","Recurring cost"],["estimated_saving","Estimated saving"],["evidence","Evidence"]]}/>{comparison.excluded_offers.length>0&&<details><summary>Excluded quotes and reasons ({comparison.excluded_offers.length})</summary><Table rows={comparison.excluded_offers} columns={[["offer_id","Offer"],["reason","Reason"]]}/></details>}<details><summary>Calculation evidence</summary><Json value={comparison}/></details></section>}<Notice>Quotes must be complete and tax inclusive. The comparison covers eligible supplied offers; it is not a whole-market promise. Complex indexed, tiered, demand-charge or export tariffs need a complete scoped quote.</Notice></>}{tab==='bills'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><ReceiptText size={18}/></span><div><h2>A complete latest-year profile</h2><p>Twelve complete months before the current month.</p></div></div><button className="secondary full" onClick={()=>setTab('analysis')}><Upload size={16}/>Import ZIP / PDF billing archives</button><CsvUpload label="Upload anonymous monthly bills" help="month, kwh, billed_total, currency · optional peak_kwh" onData={d=>{setBills(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/example_billing_months.csv" download>Download fictional EUR sample <Download size={13}/></a>{country==='PT'&&<button onClick={()=>{setBills(boot.example_bills);setComparison(null)}}>Load fictional sample</button>}</div><Notice>Use actual tax-inclusive electricity charges, not bank-payment instalments. Remove names, addresses and account numbers. Each month must appear once, in the selected market currency.</Notice><button className="primary full" onClick={()=>setTab('quotes')}>Compare using this profile <ArrowRight size={16}/></button>{bills&&<button className="text-button" onClick={()=>{setBills(null);setComparison(null)}}>Clear monthly profile</button>}</section><section className="panel"><h2>What your data can tell us</h2><div className="explain-row"><span>01</span><div><b>Consumption and current cost</b><p>Your latest-year totals replace the manual annual fields.</p></div></div><div className="explain-row"><span>02</span><div><b>Peak and off-peak allocation</b><p>Supply peak_kwh for every month, or supply your measured peak share separately.</p></div></div><div className="explain-row"><span>03</span><div><b>A starting scenario, not a model winner</b><p>Twelve monthly bills cover only one annual cycle. The grid-model leaderboard cannot select a reliable household forecaster.</p></div></div></section></div>{bills&&<section className="panel"><h2>Supplied monthly profile</h2><Chart series={[{name:'Monthly consumption',values:bills.map(x=>Number(x.kwh))}]} labels={bills.map(x=>x.month)} unit="kWh"/><Table rows={bills} columns={[["month","Month"],["kwh","Consumption · kWh"],["billed_total","Billed electricity cost"],["currency","Currency"]]}/></section>}</>}{tab==='atlas'&&<GridAtlas key={country} history={history} market={market} source={boot?.sources?.find(entry=>entry.market===market.name)} loaded={!!boot}/>}{tab==='benchmark'&&<><section className="panel"><div className="section-title"><div><h2>The forecast laboratory</h2><p>Same series. Same origins. Validation chooses; test measures.</p></div><span className="source-pill">PROTOCOL V2</span></div><div className="form-grid three"><Field label="Forecast target"><select value={kind} onChange={e=>{setKind(e.target.value);setBench(null)}}><option value="demand">Monthly grid energy · GWh</option><option value="price">Monthly wholesale price · {market.currency}/MWh</option></select></Field><Field label="Provider label · uploaded data only"><input value={provider} placeholder="Exact provider column value" onChange={e=>setProvider(e.target.value)}/></Field><div className="worker-note"><span className="status-dot"/>Single CPU benchmark worker<br/><small>No paid model calls</small></div></div><CsvUpload label={monthly?`${monthly.length} monthly records loaded`:'Use an optional monthly series'} help="timestamp,value,unit,coverage · ≥72 complete months" onData={d=>{setMonthly(d);setBench(null)}} onError={setError}/>{monthly&&<button className="text-button" onClick={()=>{setMonthly(null);setBench(null)}}>Use bundled grid snapshot instead</button>}<div className="protocol-strip"><span><b>1.</b> Training prefix</span><ArrowRight size={14}/><span><b>2.</b> Calibration</span><ArrowRight size={14}/><span><b>3.</b> Validation</span><ArrowRight size={14}/><span><b>4.</b> Test</span></div><div className="button-row"><button className="primary" disabled={busy} onClick={()=>run(async()=>setBench(await request('/api/benchmark',{country,kind,records:monthly,provider})))}>{busy?<RefreshCw size={16}/>:<Play size={16}/>}Run CPU benchmark</button><span className="subtle">Seasonal baselines · SARIMA · Grokked · SARIMAX · GARCH</span></div></section>{!bench&&<section className="panel"><div className="section-title"><h2>Published historical context</h2><span className="source-pill">{market.scope}</span></div>{kind==='demand'?<Chart series={[{name:'Monthly energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/>:<div className="empty">Wholesale history is not bundled. Upload a complete monthly price series to run a pricing benchmark.</div>}</section>}{bench&&<section className="panel"><div className="section-title"><div><div className="eyebrow">VALIDATION-SELECTED</div><h2>{bench.selected_model}</h2><p>{bench.series_scope} · held-out test starts {bench.test_start}</p></div><button className="secondary" onClick={()=>download(bench,'electrocheap-benchmark.json')}><Download size={15}/>Evidence JSON</button></div><Chart unit={bench.unit} labels={bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.timestamp)} series={[{name:'Actual',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.actual),color:'#243344'},{name:bench.selected_model,values:bench.predictions.filter(p=>p.split==='test'&&p.model===bench.selected_model).map(p=>p.forecast),color:'#18a184'},{name:'Seasonal naive',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.forecast),color:'#e59b39',dashed:true}]}/><Table rows={bench.scores.filter(s=>s.split==='test')} columns={[["model","Model"],["MAE","MAE"],["RMSE","RMSE"],["MASE","MASE"],["selected_on_validation","Selected"]]}/><details><summary>Residual GARCH volatility and protocol</summary><Json value={{volatility:bench.residual_volatility,claim:bench.claim,input_sha256:bench.input_sha256,implementation_sha256:bench.implementation_sha256}}/></details></section>}<Notice>At least 72 consecutive complete months. No interpolation. Bias is frozen after calibration; a candidate needs 5% better validation MAE to replace the baseline. GARCH estimates residual volatility and keeps the SARIMAX mean unchanged. Tests are retrospective and descriptive.</Notice></>}{tab==='challenge'&&<ChallengePanel key={country} country={country}/>}{tab==='models'&&<><AuditDatasets/><section className="panel"><div className="section-title"><div><h2>The full recorded model family</h2><p>Archived grid-demand evidence · 24 test targets · six-month forecasts</p></div><span className="source-pill">2026-10-09 ARCHIVE</span></div><Table rows={evidence?.scores} columns={[["model","Model / variant"],["mae_gwh","MAE · GWh"],["mase","MASE"],["skill_vs_seasonal_naive_pct","Skill vs baseline · %"],["selected_on_validation","Selected"]]}/></section><div className="model-cards"><section className="panel"><div className="eyebrow">LIVE CPU CANDIDATES</div><h2>Statistical & Grokked</h2><p>Seasonal baselines, SARIMA, the explicit 80/20 Grokked blend, calendar SARIMAX and residual GARCH.</p><span className="availability live"><CheckCircle2 size={14}/>Runnable in Forecast lab</span></section><section className="panel"><div className="eyebrow">PINNED TRANSFORMERS</div><h2>TimesFM 2.5 · Chronos-2</h2><p>Exact checkpoint revisions and Python package versions preserved from the measured archived runs.</p><span className="availability"><BarChart3 size={14}/>Cached measured evidence</span></section><section className="panel"><div className="eyebrow">HOSTED MODEL DIAGNOSTICS</div><h2>Astra · Sol</h2><p>Archived delegated test diagnostics. No separately authenticated customer inference API is configured.</p><span className="availability"><BarChart3 size={14}/>Diagnostic only</span></section></div><Notice>A separate Super Grokked implementation and the original KMLAIOps SARIMAX-GARCHX source are unavailable. Newly written adapters are not presented under those identities. Grid scores do not establish household accuracy or bill savings.</Notice><section className="panel"><details><summary>Inspect exact versions, source commits and availability</summary><Json value={evidence}/></details></section></>}
App.jsx+245-6