Hugdrigo commited on
Commit
b0d3ecb
·
verified ·
1 Parent(s): c784d3e

Upload 3 files

Browse files
Files changed (3) hide show
  1. LICENSE +21 -0
  2. README.md +44 -6
  3. index.html +78 -17
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GridPilot contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,12 +1,50 @@
1
  ---
2
- title: Gridpilot Solar Storage Lab
3
- emoji: 🏆
4
- colorFrom: purple
5
- colorTo: pink
6
  sdk: static
 
7
  pinned: false
8
  license: mit
9
- short_description: Offline solar and battery scenario planning
 
 
 
 
 
 
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: "GridPilot | Solar & Battery Intelligence"
3
+ emoji: "☀️"
4
+ colorFrom: green
5
+ colorTo: blue
6
  sdk: static
7
+ app_file: index.html
8
  pinned: false
9
  license: mit
10
+ short_description: "Offline solar and battery scenario planning"
11
+ tags:
12
+ - energy
13
+ - solar
14
+ - optimization
15
+ - renewable-energy
16
+ - data-visualization
17
+ - simulation
18
+ - javascript
19
  ---
20
 
21
+ # GridPilot: Solar & Battery Planning Laboratory
22
+
23
+ **GridPilot** is a standalone, browser-based educational application for hourly solar PV and battery-storage analysis. It provides a reproducible energy-dispatch calculation, transparent tariff assumptions, discrete investment sizing, stress scenarios, 24/168-hour CSV import, and auditable CSV/JSON/Markdown exports.
24
+
25
+ ## Key features
26
+
27
+ - **Overview:** 7-day consumption, photovoltaic output, grid import, exports, self-consumption, annualized savings and simplified payback.
28
+ - **Dispatch Explorer:** hourly trace for energy use, battery state of charge, charging/discharging and grid activity.
29
+ - **Sizing Laboratory:** compares 35 discrete PV/battery combinations under an adjustable investment ceiling; ranks by modeled annual net savings, *not* a guaranteed financial optimum.
30
+ - **Tariff & Economics:** editable peak, off-peak and export tariffs; explicit cost formulas.
31
+ - **Stress & Resilience:** cloudy weather, demand spike, elevated peak rates and a combined stress case.
32
+ - **Data & Audit:** local CSV uploads, reproducible reports, hourly exports and a documented methodology.
33
+
34
+ ## How to run
35
+
36
+ Upload the three repository files (`README.md`, `index.html` and `LICENSE`) to a Hugging Face **Static / Blank / Public** Space. Alternatively open `index.html` in a modern browser. No backend, API key, package installation, CDN, cookies or telemetry are used.
37
+
38
+ ## CSV import format
39
+
40
+ UTF-8 CSV with exactly `hour,demand_kwh,solar_factor` columns and **24 or 168 contiguous records** beginning with hour 0. `solar_factor` must be between 0 and 1, and demand must be finite and nonnegative. A 24-row input is repeated across a 7-day simulation. The included downloadable template is fully round-trippable.
41
+
42
+ ## Method and caution
43
+
44
+ Hourly PV generation is modeled as PV capacity × synthetic solar factor × (1 − losses) × weather multiplier. The PV-first heuristic serves demand directly, then charges a battery, then exports surplus. Battery dispatch uses 90% round-trip efficiency. No grid charging or battery degradation is modeled. Weekly economics are annualized for illustration, with flat unit-cost assumptions and a 1.2% maintenance proxy.
45
+
46
+ **All bundled scenarios are synthetic.** No measured solar irradiance, local utility tariffs, demand charges, outage behavior, inverter performance, tax rules, interconnection limits, project financing or device degradation are included. Do not use this app for electrical design, site safety decisions or investment advice. Confirm assumptions with a qualified engineer and local electricity provider.
47
+
48
+ ## License
49
+
50
+ MIT License. See `LICENSE`.
index.html CHANGED
@@ -1,19 +1,80 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
5
+ <meta name="description" content="GridPilot is an offline solar and battery scenario laboratory with reproducible energy accounting.">
6
+ <title>GridPilot | Solar & Storage Intelligence</title>
7
+ <style>
8
+ :root{color-scheme:dark;--bg:#07111f;--pane:#0e1c2e;--pane2:#11243a;--stroke:#233950;--muted:#9eafc3;--text:#edf7ff;--teal:#34e4bd;--blue:#80baff;--orange:#ffcc84;--red:#ff868f;--green:#a6efb6;--radius:15px}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:14px/1.55 Inter,ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif}button,input,select{font:inherit}button{cursor:pointer}a{color:var(--teal)}.layout{display:grid;grid-template-columns:250px minmax(0,1fr);min-height:100vh}.sidebar{border-right:1px solid var(--stroke);background:#091625;padding:28px 17px;position:sticky;top:0;height:100vh;overflow-y:auto}.brand{display:flex;gap:11px;align-items:center;margin:0 8px 30px}.brand-symbol{width:39px;height:39px;display:grid;place-items:center;background:linear-gradient(130deg,#00d5a1,#1e99bd);border-radius:12px;color:#06232b;font-weight:900;font-size:22px}.brand strong{display:block;font-size:20px;letter-spacing:-.65px}.brand small{color:var(--muted);font-size:10px;letter-spacing:1.4px}.nav{display:flex;flex-direction:column;gap:6px}.nav button{border:1px solid transparent;background:transparent;text-align:left;color:#adc2d5;border-radius:10px;padding:12px 13px;display:flex;gap:10px;align-items:center;width:100%;white-space:nowrap}.nav button.active{color:#e3fff7;background:#12382f;border-color:#24594d;font-weight:700}.nav button:hover{background:#152a40}.side-foot{margin-top:34px;color:#8da6bb;font-size:12px;border-top:1px solid var(--stroke);padding:23px 9px}.side-foot b{color:var(--green)}.main{min-width:0;padding:26px clamp(18px,3.5vw,54px) 50px;max-width:1660px;width:100%;margin:auto}.topbar{display:flex;align-items:center;justify-content:space-between;gap:15px;margin-bottom:26px}.crumb{color:#95b6c9;font-size:12px;letter-spacing:1.2px;text-transform:uppercase;font-weight:700}.pill{font-size:11px;border-radius:100px;border:1px solid #2b594f;color:#6ff0bf;background:#0f312c;padding:6px 11px;white-space:nowrap}h1{font-size:clamp(27px,3.1vw,42px);line-height:1.17;margin:0 0 9px;font-weight:760;letter-spacing:-1.2px}h2{font-size:18px;margin:0 0 13px;letter-spacing:-.25px}p{margin:0 0 15px}.lead{color:var(--muted);font-size:14px;max-width:840px;margin-bottom:25px}.hero{border:1px solid #1f4e4c;border-radius:19px;padding:26px 28px;background:linear-gradient(108deg,#102f37,#14253b 65%,#142032);margin-bottom:21px;position:relative;overflow:hidden}.hero:after{content:"";position:absolute;right:-90px;top:-120px;width:400px;height:400px;pointer-events:none;background:radial-gradient(circle,#24cca32a,transparent 65%)}.hero .eyebrow{color:#5aebc2;text-transform:uppercase;font-size:11px;letter-spacing:1.65px;font-weight:800;margin-bottom:11px}.hero h1{max-width:850px}.hero .lead{margin-bottom:0}.panel{background:var(--pane);border:1px solid var(--stroke);border-radius:var(--radius);padding:20px;min-width:0}.subpanel{background:#0b1a2b;border:1px solid #1b3249;border-radius:11px;padding:13px}.grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:19px}.grid.two{grid-template-columns:repeat(2,minmax(0,1fr))}.grid.three{grid-template-columns:repeat(3,minmax(0,1fr))}.metric .tag{font-size:11px;color:var(--muted);font-weight:750;text-transform:uppercase;letter-spacing:1px}.metric .value{font-size:clamp(22px,2.3vw,30px);letter-spacing:-.8px;font-weight:800;margin:9px 0 4px;line-height:1.22}.metric .hint{color:#99b1c5;font-size:12px}.accent{color:var(--teal)}.warning{color:var(--orange)}.negative{color:var(--red)}.section-header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 14px}.section-header h2{margin:0}.soft{color:var(--muted)}.field{display:flex;flex-direction:column;gap:5px;min-width:0}.field label{color:#bdd0df;font-size:12px;font-weight:650}.field input,.field select,input[type=file]{background:#071625;border:1px solid #36516b;color:#e8f6ff;min-width:0;padding:10px 11px;border-radius:9px;width:100%;outline:none}.field input:focus,.field select:focus{border-color:var(--teal)}.controls{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:13px}.controls.three{grid-template-columns:repeat(3,minmax(0,1fr))}.controls.two{grid-template-columns:repeat(2,minmax(0,1fr))}.btn{border:1px solid #286552;background:#185749;color:#e5fff5;border-radius:9px;font-weight:750;padding:9px 13px}.btn:hover{filter:brightness(1.16)}.btn.secondary{border-color:#34536b;background:#183149;color:#ddeafa}.btn.ghost{border-color:var(--stroke);background:#11243a;color:#bfe9df}.btnrow{display:flex;flex-wrap:wrap;gap:9px}.note{font-size:12px;color:#a9c0ce;line-height:1.7}.notice{background:#122c37;border:1px solid #285b62;color:#c5eef0;padding:12px 15px;border-radius:10px;font-size:12px;margin-bottom:17px}.notice.warning{background:#332719;color:#ffe0a3;border-color:#745735}.chart{width:100%;height:auto;display:block}.chart-grid{stroke:#2b4759;stroke-width:1;stroke-dasharray:3 6}.chart-text{fill:#a8c2d3;font-size:10.5px}.legend{display:flex;flex-wrap:wrap;gap:16px;color:#b7ccd9;font-size:12px;margin:12px 0}.legend span:before{content:"";display:inline-block;width:10px;height:10px;background:var(--dot);border-radius:3px;margin-right:6px}.barrow{margin-bottom:12px}.barrow-head{display:flex;justify-content:space-between;font-size:12px;margin-bottom:5px}.barbg{height:9px;background:#23394a;border-radius:20px;overflow:hidden}.barfill{height:100%;background:var(--teal);border-radius:20px}table{width:100%;border-collapse:collapse;text-align:left;white-space:nowrap}th{font-size:11px;text-transform:uppercase;letter-spacing:.6px;color:#a1b8cc;padding:11px 10px;background:#14263b}td{border-top:1px solid #22384d;padding:11px 10px;color:#e1ecf5;font-size:12px}tbody tr:hover{background:#15283d}.table-wrap{overflow-x:auto;border-radius:10px;border:1px solid #22394c}code{color:#8bf0ce}.table-note{margin-top:9px;color:#9cb6c6;font-size:12px}.badge{font-size:11px;display:inline-block;border-radius:20px;border:1px solid #2e6356;color:#8cf3cb;background:#16372f;padding:3px 8px}.badge.dim{background:#28323c;color:#d4ddea;border-color:#415267}.groupnote{border-left:3px solid var(--teal);padding:8px 0 8px 14px;color:#afc9d7;margin-top:16px;font-size:13px}.mono{font-variant-numeric:tabular-nums}.footer{color:#819aad;font-size:11px;text-align:center;margin-top:30px}.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0)}.toast{position:fixed;z-index:15;bottom:18px;right:18px;max-width:410px;background:#204e43;color:#edfff6;border:1px solid #38b190;border-radius:11px;padding:14px 16px;box-shadow:0 10px 35px #0009}.toast.error{background:#53282c;border-color:#ba525e;color:white}.stat-pill{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:13px}.stat-pill span{font-size:11px;background:#142c40;border:1px solid #2c4b5d;padding:5px 8px;border-radius:7px;color:#d0e5f0}button:focus-visible{outline:2px solid var(--teal);outline-offset:2px}@media(max-width:1150px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}.controls{grid-template-columns:repeat(2,minmax(0,1fr))}.sidebar{width:205px}.layout{grid-template-columns:205px minmax(0,1fr)}}@media(max-width:750px){.layout{display:block}.sidebar{height:auto;padding:14px 12px 10px;position:relative;border-right:0;border-bottom:1px solid var(--stroke)}.brand{margin:0 0 11px}.brand strong{font-size:17px}.brand-symbol{width:33px;height:33px;font-size:18px}.nav{flex-direction:row;overflow-x:auto;padding-bottom:6px;gap:5px}.nav button{padding:9px 11px;font-size:12px}.side-foot{display:none}.main{padding:19px 12px 36px}.hero{padding:19px}.grid,.grid.two,.grid.three{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.controls,.controls.two,.controls.three{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.panel{padding:13px}.metric .value{font-size:22px}.topbar{margin-bottom:17px}}@media(max-width:410px){.grid,.grid.two,.grid.three{grid-template-columns:1fr 1fr}.metric .value{font-size:19px}.controls,.controls.two,.controls.three{grid-template-columns:1fr 1fr}.field input,.field select{padding:8px 5px}.hero h1{font-size:27px}}
9
+ </style>
10
+ </head>
11
+ <body>
12
+ <div class="layout"><aside class="sidebar"><div class="brand"><div class="brand-symbol">☀</div><div><strong>GridPilot</strong><small>SOLAR INTELLIGENCE</small></div></div><nav class="nav" aria-label="Main navigation"><button class="active" data-view="overview">◈ &nbsp; Overview</button><button data-view="dispatch">↗ &nbsp; Dispatch Explorer</button><button data-view="sizing">▦ &nbsp; Sizing Laboratory</button><button data-view="economics">$ &nbsp; Tariff & Economics</button><button data-view="stress">◇ &nbsp; Stress & Resilience</button><button data-view="data">▤ &nbsp; Data & Audit</button></nav><div class="side-foot"><b>● Browser-only model</b><p>Illustrative loads and solar production. No external APIs, telemetry, or paid services.</p><p>Version 1.0 · Project #59</p></div></aside><main class="main"><div class="topbar"><div class="crumb">GRIDPILOT / <span id="pageCrumb">OVERVIEW</span></div><span class="pill">● Local simulation · synthetic data</span></div><div id="app"><div class="panel">Loading simulation...</div></div><p class="footer">GRIDPILOT · Research demonstration · Not an engineering design, tariff quotation, or investment recommendation.</p></main></div><div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
13
+ <script>
14
+ 'use strict';
15
+ // CORE_START
16
+ const SUN_HOURS=24, WEEK_HOURS=168;
17
+ const DEFAULTS=Object.freeze({pvKW:7,batteryKWh:9,batteryKW:4,peakTariff:0.29,offTariff:0.14,exportTariff:0.045,derate:0.12,loadFactor:1,weatherFactor:1,capBudget:18000});
18
+ const PRESETS={
19
+ office:{name:'City office',type:'office',blurb:'Weekday daytime offices with after-hours server demand',base:3.4,morning:4.1,evening:0.6,peakHour:13,weekend:0.62,weather:[0.98,1.05,0.90,1.02,0.89,1.07,0.96]},
20
+ clinic:{name:'Community clinic',type:'clinic',blurb:'Extended service hours with continuous refrigeration load',base:6.7,morning:3.6,evening:3.8,peakHour:17,weekend:0.91,weather:[0.97,0.82,1.10,1.04,0.92,0.86,1.03]},
21
+ warehouse:{name:'Distribution hub',type:'warehouse',blurb:'Early shifts, high daytime machinery load and weekend dip',base:4.8,morning:7.0,evening:1.3,peakHour:11,weekend:0.45,weather:[1.05,0.94,0.72,0.83,1.01,1.13,0.95]}
22
+ };
23
+ function safeNum(x){return typeof x==='number'&&Number.isFinite(x);}
24
+ function sum(a){return a.reduce((n,v)=>n+v,0);}
25
+ function mean(a){return a.length?sum(a)/a.length:0;}
26
+ function rnd(n,p=2){return Number(n.toFixed(p));}
27
+ function clamp(v,a,b){return Math.max(a,Math.min(b,v));}
28
+ function solarFactor(hour){let s=Math.sin(Math.PI*(hour-6)/12);return Math.max(0,s)*0.91;}
29
+ function sampleProfile(presetName){const p=PRESETS[presetName];if(!p)throw Error('Unknown preset');return Array.from({length:168},(_,i)=>{let h=i%24, d=Math.floor(i/24);let morning=p.morning*Math.exp(-(((h-p.peakHour)/4.1)**2));let evening=p.evening*Math.exp(-(((h-19)/3.6)**2));let demand=(p.base+morning+evening)*(d>=5?p.weekend:1);let sun=clamp(solarFactor(h)*p.weather[d],0,1);return {hour:i,demand:rnd(demand,4),solar_factor:rnd(sun,5)};});}
30
+ function assertParams(p){const limits={pvKW:[0,50],batteryKWh:[0,200],batteryKW:[0,50],peakTariff:[0,5],offTariff:[0,5],exportTariff:[0,5],derate:[0,0.75],loadFactor:[0.1,5],weatherFactor:[0,2],capBudget:[0,250000]};for(const [key,range] of Object.entries(limits)){if(!safeNum(p[key])||p[key]<range[0]||p[key]>range[1])throw Error('Invalid configuration: '+key);}}
31
+ function validateProfile(rows){if(!Array.isArray(rows)||!([24,168].includes(rows.length)))throw Error('CSV must have exactly 24 or 168 hourly records');for(let i=0;i<rows.length;i++){let r=rows[i];if(!r||r.hour!==i||!safeNum(r.demand)||r.demand<0||r.demand>10000||!safeNum(r.solar_factor)||r.solar_factor<0||r.solar_factor>1)throw Error('Invalid record at hour '+i);}}
32
+ function tariff(hour,params){let h=hour%24;return h>=17&&h<22?params.peakTariff:params.offTariff;}
33
+ function capital(p){return (p.pvKW>0?400:0)+p.pvKW*920+p.batteryKWh*465;}
34
+ function simulate(rows,p){assertParams(p);validateProfile(rows);let profile=rows.length===24?Array.from({length:168},(_,i)=>({...rows[i%24],hour:i})):rows;let chargeEff=Math.sqrt(0.9),disEff=Math.sqrt(0.9),soc=0;let totals={demand:0,pv:0,direct:0,batteryIn:0,batteryOut:0,gridImport:0,gridExport:0,baselineCost:0,systemCost:0,loss:0};let hours=[];
35
+ for(const row of profile){let load=row.demand*p.loadFactor,pv=p.pvKW*row.solar_factor*p.weatherFactor*(1-p.derate);let direct=Math.min(load,pv),remaining=load-direct,excess=pv-direct;let charged=0,discharged=0;
36
+ if(p.batteryKWh>0&&p.batteryKW>0){charged=Math.min(excess,p.batteryKW,(p.batteryKWh-soc)/chargeEff);soc+=charged*chargeEff;excess-=charged;discharged=Math.min(remaining,p.batteryKW,soc*disEff);soc-=discharged/disEff;remaining-=discharged;}
37
+ if(soc<1e-9)soc=0;if(soc>p.batteryKWh-1e-9)soc=p.batteryKWh;let gridImport=Math.max(0,remaining),gridExport=Math.max(0,excess);let t=tariff(row.hour,p);let base=load*t,cost=gridImport*t-gridExport*p.exportTariff;
38
+ const h={hour:row.hour,demand:load,pv,direct,charged,discharged,soc,gridImport,gridExport,baselineCost:base,systemCost:cost,tariff:t};hours.push(h);
39
+ totals.demand+=load;totals.pv+=pv;totals.direct+=direct;totals.batteryIn+=charged;totals.batteryOut+=discharged;totals.gridImport+=gridImport;totals.gridExport+=gridExport;totals.baselineCost+=base;totals.systemCost+=cost;totals.loss+=charged-discharged;
40
+ }
41
+ let weeklySavings=totals.baselineCost-totals.systemCost,annualGross=weeklySavings*365/7,capex=capital(p),yearlyMaintenance=capex*0.012,annualNet=annualGross-yearlyMaintenance;let payback=annualNet>0?capex/annualNet:null;
42
+ return {hours,totals,weeklySavings,monthlySavings:weeklySavings*365.25/84,annualGross,annualNet,yearlyMaintenance,capex,payback,solarShare:totals.demand>0?1-totals.gridImport/totals.demand:0,selfConsumption:totals.pv>0?(totals.pv-totals.gridExport)/totals.pv:0};
43
+ }
44
+ function parseCSV(text){if(typeof text!=='string'||text.length>250000)throw Error('File is too large or invalid');if(text.charCodeAt(0)===0xfeff)text=text.slice(1);let cells=[],rows=[],cell='',quoted=false,afterQuote=false;for(let i=0;i<text.length;i++){let ch=text[i];if(quoted){if(ch==='"'){if(text[i+1]==='"'){cell+='"';i++;}else{quoted=false;afterQuote=true;}}else{cell+=ch;}}else if(afterQuote){if(ch===','){cells.push(cell);cell='';afterQuote=false;}else if(ch==='\n'||ch==='\r'){cells.push(cell);rows.push(cells);cells=[];cell='';afterQuote=false;if(ch==='\r'&&text[i+1]==='\n')i++;}else if(ch===' '||ch==='\t'){}else throw Error('Unexpected character after CSV quote');}else{if(ch==='"'){if(cell.trim())throw Error('Unexpected quote in CSV');quoted=true;}else if(ch===','){cells.push(cell);cell='';}else if(ch==='\n'||ch==='\r'){cells.push(cell);rows.push(cells);cells=[];cell='';if(ch==='\r'&&text[i+1]==='\n')i++;}else{cell+=ch;}}}if(quoted)throw Error('Unclosed CSV quote');if(cell!==''||cells.length){cells.push(cell);rows.push(cells);}rows=rows.filter(r=>r.some(c=>c.trim()!==''));if(!rows.length)throw Error('CSV is empty');let head=rows.shift().map(x=>x.trim().toLowerCase());if(head.length!==3||head[0]!=='hour'||head[1]!=='demand_kwh'||head[2]!=='solar_factor')throw Error('Expected CSV columns: hour,demand_kwh,solar_factor');let parsed=rows.map((r,i)=>{if(r.length!==3)throw Error('Invalid number of columns at record '+(i+1));if(r.some(v=>v.trim()===''))throw Error('Blank numeric value at record '+(i+1));return {hour:Number(r[0]),demand:Number(r[1]),solar_factor:Number(r[2])};});validateProfile(parsed);return parsed;}
45
+ function csvCell(v){let s=String(v??'');if(/^[\s]*[=+@-]/.test(s)&&!(/^\s*-\d+(\.\d+)?\s*$/.test(s)))s="'"+s;return /[",\r\n]/.test(s)?'"'+s.replace(/"/g,'""')+'"':s;}
46
+ function csv(rows){return rows.map(r=>r.map(csvCell).join(',')).join('\r\n')+'\r\n';}
47
+ function hourAverages(hours){return Array.from({length:24},(_,i)=>{let part=hours.filter(h=>h.hour%24===i);return {hour:i,demand:mean(part.map(h=>h.demand)),pv:mean(part.map(h=>h.pv)),grid:mean(part.map(h=>h.gridImport)),soc:mean(part.map(h=>h.soc))};});}
48
+ function gridSearch(rows,p){let candidates=[];for(let pv of [0,2,4,6,8,10,12])for(let bat of [0,4,8,12,16]){let q={...p,pvKW:pv,batteryKWh:bat,batteryKW:bat?Math.min(6,bat/2):0};let r=simulate(rows,q);if(r.capex<=p.capBudget)candidates.push({pv,bat,annualNet:r.annualNet,payback:r.payback,capex:r.capex,solarShare:r.solarShare,monthly:r.monthlySavings});}candidates.sort((a,b)=>b.annualNet-a.annualNet||a.capex-b.capex);return candidates;}
49
+ function stressTest(rows,p){return [{name:'Baseline',loadFactor:1,weatherFactor:1,peakMult:1},{name:'Cloudy week',loadFactor:1,weatherFactor:0.55,peakMult:1},{name:'High demand',loadFactor:1.3,weatherFactor:1,peakMult:1},{name:'High peak tariff',loadFactor:1,weatherFactor:1,peakMult:1.45},{name:'Combined shock',loadFactor:1.3,weatherFactor:0.5,peakMult:1.45}].map(x=>{let a=simulate(rows,{...p,loadFactor:p.loadFactor*x.loadFactor,weatherFactor:p.weatherFactor*x.weatherFactor,peakTariff:p.peakTariff*x.peakMult});return {...x,...a};});}
50
+ // CORE_END
51
+ const fmt=(n,d=1)=>new Intl.NumberFormat('en-US',{maximumFractionDigits:d,minimumFractionDigits:d}).format(n);
52
+ const usd=(n,d=0)=>'$'+new Intl.NumberFormat('en-US',{maximumFractionDigits:d,minimumFractionDigits:d}).format(n);
53
+ const pct=n=>fmt(100*n,1)+'%';
54
+ function esc(s){return String(s).replace(/[&<>"']/g,x=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[x]));}
55
+ let state={preset:'office',profile:sampleProfile('office'),params:{...DEFAULTS},view:'overview',day:0,imported:false};
56
+ function panel(content,extra=''){return `<section class="panel ${extra}">${content}</section>`;}
57
+ function m(label,value,hint,color=''){return `<div class="panel metric"><div class="tag">${label}</div><div class="value ${color}">${value}</div><div class="hint">${hint}</div></div>`;}
58
+ function field(label,id,val,min,max,step='1'){return `<div class="field"><label for="${id}">${label}</label><input id="${id}" data-parameter="${id}" type="number" min="${min}" max="${max}" step="${step}" value="${val}"></div>`;}
59
+ function hrule(){return `<div class="legend"><span style="--dot:#34e4bd">Demand</span><span style="--dot:#80baff">Solar PV</span><span style="--dot:#ffcc84">Grid import</span></div>`;}
60
+ function lineChart(series,{maxY=null,minY=0,width=940,height=285}={}){let pad={l:45,r:15,t:24,b:31},W=width-pad.l-pad.r,H=height-pad.t-pad.b;let v=series.flatMap(s=>s.values);let top=maxY??Math.max(1,...v)*1.13;let y=x=>pad.t+H-(x-minY)/(top-minY)*H;let n=series[0]?.values?.length||1;let x=i=>pad.l+(i/(n-1||1))*W;let grids=[0,.25,.5,.75,1].map(f=>`<line class="chart-grid" x1="${pad.l}" y1="${y(minY+f*(top-minY))}" x2="${pad.l+W}" y2="${y(minY+f*(top-minY))}"/><text class="chart-text" x="${pad.l-6}" y="${y(minY+f*(top-minY))+4}" text-anchor="end">${fmt(minY+f*(top-minY),1)}</text>`).join('');let ticks=Array.from({length:7},(_,i)=>{let at=Math.round(i*(n-1)/6);return `<text class="chart-text" x="${x(at)}" y="${height-8}" text-anchor="middle">${at}:00</text>`;}).join('');let lines=series.map(s=>`<polyline points="${s.values.map((v,i)=>x(i).toFixed(2)+','+y(v).toFixed(2)).join(' ')}" fill="none" stroke="${s.color}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" />`).join('');return `<svg class="chart" viewBox="0 0 ${width} ${height}" role="img" aria-label="Hourly energy chart with demand, generation and import">${grids}${ticks}${lines}</svg>`;}
61
+ function bars(items,total){return items.map((a,i)=>`<div class="barrow"><div class="barrow-head"><span>${esc(a.label)}</span><strong class="mono">${esc(a.text||fmt(a.value,1))}</strong></div><div class="barbg"><div class="barfill" style="width:${clamp(a.value/(total||1)*100,0,100)}%;background:${a.color||['#34e4bd','#80baff','#ffcc84','#d7a1ff'][i%4]}"></div></div></div>`).join('');}
62
+ function metricLegend(){return '<div class="notice">All amounts are modeled from synthetic electricity profiles. This is an educational planning tool, not an engineering assessment or utility tariff quote.</div>';}
63
+ function overview(result){let t=result.totals;let h=hourAverages(result.hours);return `<div class="hero"><div class="eyebrow">Solar and storage planning</div><h1>Make every kilowatt-hour count.</h1><p class="lead">Explore transparent hourly dispatch, utility costs and investment decisions. No cloud services, hidden APIs or live electricity data.</p></div>${metricLegend()}<div class="grid">${m('Solar share of demand',pct(result.solarShare),'Energy supplied by solar and battery','accent')}${m('Monthly bill reduction',usd(result.monthlySavings),'30.44-day equivalent','accent')}${m('Grid import',fmt(t.gridImport,0)+' kWh','Seven-day energy purchased')}${m('Estimated payback',result.payback===null?'Not reached':fmt(result.payback,1)+' yr','Simplified annual net savings',result.payback===null?'warning':'')}</div><div class="grid two">${panel(`<div class="section-header"><h2>24-hour average dispatch</h2><span class="badge">7 synthetic days</span></div>${hrule()}${lineChart([{values:h.map(x=>x.demand),color:'#34e4bd'},{values:h.map(x=>x.pv),color:'#80baff'},{values:h.map(x=>x.grid),color:'#ffcc84'}])}<p class="note">Hourly solar production is a stylized shape, not a measured irradiance forecast.</p>`)}${panel(`<h2>Energy accounting · 7 days</h2>${bars([{label:'Direct solar consumption',value:t.direct,color:'#34e4bd',text:fmt(t.direct,0)+' kWh'},{label:'Battery delivered to loads',value:t.batteryOut,color:'#80baff',text:fmt(t.batteryOut,0)+' kWh'},{label:'Grid import',value:t.gridImport,color:'#ffcc84',text:fmt(t.gridImport,0)+' kWh'}],t.demand)}<div class="stat-pill"><span>Demand: ${fmt(t.demand,0)} kWh</span><span>Solar: ${fmt(t.pv,0)} kWh</span><span>Exported: ${fmt(t.gridExport,0)} kWh</span></div><div class="groupnote">Your scenario: <b>${esc(state.imported?'Imported CSV profile':PRESETS[state.preset].name)}</b>. ${esc(state.imported?'User-provided hypothetical input.':PRESETS[state.preset].blurb)}.</div>`)} </div>${panel(`<div class="section-header"><h2>Model configuration</h2><span class="badge">Live recalculation</span></div><div class="controls">${field('Solar capacity (kWp)','pvKW',state.params.pvKW,0,50,0.5)}${field('Battery storage (kWh)','batteryKWh',state.params.batteryKWh,0,200,1)}${field('Battery power (kW)','batteryKW',state.params.batteryKW,0,50,0.5)}${field('Solar loss fraction (0–0.75)','derate',state.params.derate,0,0.75,0.01)}</div><p class="table-note">Charging/discharging is modeled at 90% round-trip efficiency. Battery aging, taxes, outages and grid interconnection restrictions are not modeled.</p>`)}`;}
64
+ function dispatch(r){const hs=r.hours.slice(state.day*24,state.day*24+24),max=Math.max(...hs.map(h=>Math.max(h.demand,h.pv,h.gridImport)));return `<div class="hero"><div class="eyebrow">Dispatch explorer</div><h1>Trace every unit of energy.</h1><p class="lead">Inspect direct solar consumption, charging, discharge, imports and exports hour by hour.</p></div><div class="grid">${m('Solar generated',fmt(r.totals.pv,0)+' kWh','Seven-day production')}${m('Battery discharge',fmt(r.totals.batteryOut,0)+' kWh','Delivered to load')}${m('Solar exported',fmt(r.totals.gridExport,0)+' kWh','Excess generation')}${m('PV self-consumption',pct(r.selfConsumption),'Direct use plus storage charging')}</div>${panel(`<div class="section-header"><h2>Hourly dispatch · selected day</h2><div class="field"><label for="daySelect">Day</label><select id="daySelect" data-setting="day">${Array.from({length:7},(_,i)=>`<option value="${i}" ${state.day===i?'selected':''}>Day ${i+1}</option>`).join('')}</select></div></div>${hrule()}${lineChart([{values:hs.map(h=>h.demand),color:'#34e4bd'},{values:hs.map(h=>h.pv),color:'#80baff'},{values:hs.map(h=>h.gridImport),color:'#ffcc84'}])}`)}<div style="height:16px"></div>${panel(`<div class="section-header"><h2>Auditable hourly ledger</h2><button class="btn secondary" data-download="dispatch">Export hourly CSV</button></div><div class="table-wrap"><table><thead><tr><th>Hour</th><th>Demand</th><th>PV</th><th>Charge</th><th>Discharge</th><th>Grid import</th><th>Export</th><th>Battery SOC</th></tr></thead><tbody>${hs.map(h=>`<tr>${[h.hour, h.demand,h.pv,h.charged,h.discharged,h.gridImport,h.gridExport,h.soc].map((v,i)=>`<td class="mono">${i===0?v%24+':00':fmt(v,2)}</td>`).join('')}</tr>`).join('')}</tbody></table></div><p class="table-note">All energy units kWh; SOC is usable battery energy at the end of each hour. Dispatch is a transparent heuristic, not an optimal power-flow solver.</p>`)}`;}
65
+ function sizing(r){let candidates=gridSearch(state.profile,state.params),best=candidates[0],highest=candidates.slice(0,15);return `<div class="hero"><div class="eyebrow">Constrained discrete search</div><h1>Find a practical system size.</h1><p class="lead">Compare 35 solar-battery configurations and rank those below a user-defined capital budget. Optimizes annual net savings only over the stated grid.</p></div>${panel(`<div class="section-header"><h2>Investment limit</h2><span class="badge">7 solar levels × 5 battery levels</span></div><div class="controls two">${field('Maximum initial investment (USD)','capBudget',state.params.capBudget,0,250000,250)}<div class="subpanel"><div class="note">Current configuration upfront investment</div><div style="font-size:24px;font-weight:800">${usd(r.capex)}</div></div></div><p class="table-note">Candidate solar sizes 0, 2, 4, 6, 8, 10, 12 kWp; batteries 0, 4, 8, 12, 16 kWh. Other sizes are not searched.</p>`)}<div style="height:16px"></div>${best?`<div class="grid three">${m('Top modeled solar size',fmt(best.pv,0)+' kWp','Within current capital limit','accent')}${m('Top modeled battery',fmt(best.bat,0)+' kWh',`Capex ${usd(best.capex)}`)}${m('Modeled annual net benefit',usd(best.annualNet),'Includes 1.2% annual maintenance','accent')}</div>`:'<div class="notice warning">No candidates fit your budget. Increase the investment limit to compare options.</div>'}${panel(`<div class="section-header"><h2>Candidate ranking</h2><button class="btn secondary" data-download="sizing">Download rankings</button></div><div class="table-wrap"><table><thead><tr><th>Rank</th><th>Solar</th><th>Battery</th><th>Capex</th><th>Annual net</th><th>Payback</th><th>Solar share</th></tr></thead><tbody>${highest.map((x,i)=>`<tr><td>${i+1}</td><td>${x.pv} kWp</td><td>${x.bat} kWh</td><td>${usd(x.capex)}</td><td>${usd(x.annualNet)}</td><td>${x.payback===null?'Not reached':fmt(x.payback,1)+' yr'}</td><td>${pct(x.solarShare)}</td></tr>`).join('')}</tbody></table></div><p class="table-note">Ranking maximizes annual net savings, not net present value; interest, inflation, battery replacement and financing are not included.</p>`)}`;}
66
+ function economics(r){let t=r.totals,s=r.monthlySavings;return `<div class="hero"><div class="eyebrow">Tariffs and investment</div><h1>Audit every financial assumption.</h1><p class="lead">Compare utility costs before and after on-site solar and storage, with explicit tariff assumptions and transparent operating expenses.</p></div><div class="grid">${m('Baseline weekly bill',usd(t.baselineCost,2),'No on-site generation')}${m('Modeled weekly bill',usd(t.systemCost,2),'Includes export credit')}${m('Annual net benefit',usd(r.annualNet),'Less 1.2% capex maintenance','accent')}${m('Upfront investment',usd(r.capex),'Illustrative USD unit costs')}</div>${panel(`<h2>Electricity and export assumptions</h2><div class="controls">${field('Off-peak tariff ($/kWh)','offTariff',state.params.offTariff,0,5,.01)}${field('Peak tariff ($/kWh)','peakTariff',state.params.peakTariff,0,5,.01)}${field('Export credit ($/kWh)','exportTariff',state.params.exportTariff,0,5,.005)}${field('PV derating fraction','derate',state.params.derate,0,.75,.01)}</div><p class="table-note">Peak window 17:00–21:59; all other hours off-peak. Figures are illustrative, not actual tariffs in Bolivia, Argentina or Paraguay.</p>`)}<div style="height:16px"></div><div class="grid two">${panel(`<h2>Financial bridge</h2>${bars([{label:'Baseline grid spending',value:Math.max(0,t.baselineCost),text:usd(t.baselineCost,2),color:'#ffcc84'},{label:'Net electricity bill',value:Math.max(0,t.systemCost),text:usd(t.systemCost,2),color:'#80baff'},{label:'Seven-day savings',value:Math.max(0,r.weeklySavings),text:usd(r.weeklySavings,2),color:'#34e4bd'}],Math.max(1,t.baselineCost))}<p class="note">A negative net bill means export credits exceed imports in the demonstration model. Real net-metering limitations may prevent this.</p>`)}${panel(`<h2>Annualization methodology</h2><div class="stat-pill"><span>Weekly savings: ${usd(r.weeklySavings,2)}</span><span>Annual gross: ${usd(r.annualGross,0)}</span><span>Annual maintenance: ${usd(r.yearlyMaintenance,0)}</span></div><p class="note">Annualized benefit = weekly savings × 365/7 − (1.2% × modeled initial investment). Simple payback = investment ÷ annualized benefit, only when annualized benefit is positive.</p><p class="note">Upfront cost = PV × $920/kWp + battery × $465/kWh + $400 installation allowance when PV is installed. No discounting or tax effects.</p>`)}</div>`;}
67
+ function stress(r){const tests=stressTest(state.profile,state.params);return `<div class="hero"><div class="eyebrow">Sensitivity and resilience</div><h1>See how assumptions change outcomes.</h1><p class="lead">Five reproducible scenarios vary demand, sunshine and peak tariffs. These are stress tests, not probabilistic forecasts.</p></div><div class="grid three">${m('Base monthly savings',usd(tests[0].monthlySavings),'30.44-day equivalent')}${m('Combined stress monthly',usd(tests[4].monthlySavings),'Solar × 0.5, load × 1.3','warning')}${m('Combined stress solar share',pct(tests[4].solarShare),'Share of load supplied locally')}</div>${panel(`<div class="section-header"><h2>Five scenario comparisons</h2><button class="btn secondary" data-download="stress">Export scenarios</button></div><div class="table-wrap"><table><thead><tr><th>Scenario</th><th>Load multiplier</th><th>Solar multiplier</th><th>Peak rate multiplier</th><th>Monthly savings</th><th>Grid import (kWh)</th><th>Solar share</th></tr></thead><tbody>${tests.map(x=>`<tr><td>${esc(x.name)}</td><td>${fmt(x.loadFactor,2)}×</td><td>${fmt(x.weatherFactor,2)}×</td><td>${fmt(x.peakMult,2)}×</td><td>${usd(x.monthlySavings,1)}</td><td>${fmt(x.totals.gridImport,0)}</td><td>${pct(x.solarShare)}</td></tr>`).join('')}</tbody></table></div>`)}<div style="height:16px"></div>${panel(`<h2>Customize your case</h2><div class="controls two">${field('Demand multiplier','loadFactor',state.params.loadFactor,.1,5,.05)}${field('Sunlight multiplier','weatherFactor',state.params.weatherFactor,0,2,.05)}</div><p class="table-note">When you change these inputs, all tabs use the new scenario; reset from Data & Audit to return to the default. Weather uncertainty is not estimated from actual measurements.</p>`)}`;}
68
+ function dataView(r){let example=state.profile.slice(0,4);return `<div class="hero"><div class="eyebrow">Data, reproducibility and methods</div><h1>Bring your own hourly data.</h1><p class="lead">Upload a 24-hour or 168-hour CSV profile. Analysis runs entirely in the browser and is not uploaded to a server by this page.</p></div>${panel(`<div class="section-header"><h2>Import hourly energy data</h2><span class="badge">CSV · 24 or 168 records</span></div><div class="controls two"><div class="field"><label for="dataFile">Select CSV file</label><input id="dataFile" type="file" accept=".csv,text/csv" /></div><div class="subpanel"><div class="note">Required columns</div><code>hour,demand_kwh,solar_factor</code><div class="note">hour: consecutive 0 to 23 or 0 to 167; solar_factor: 0 to 1</div></div></div><p class="table-note">A 24-row profile repeats across 7 days. The solar_factor is an hourly modeled output fraction, not measured irradiance. Imported data will replace the current synthetic profile only after validation succeeds.</p><div class="btnrow"><button class="btn secondary" data-download="template">Download 24-hour template</button><button class="btn ghost" data-action="reset">Restore demo data</button></div>`)}<div style="height:16px"></div>${panel(`<div class="section-header"><h2>Exports and audit trail</h2><span class="badge">No account required</span></div><div class="btnrow"><button class="btn" data-download="report">Download JSON report</button><button class="btn secondary" data-download="dispatch">Hourly dispatch CSV</button><button class="btn secondary" data-download="profile">Input data CSV</button><button class="btn secondary" data-download="sizing">Sizing table CSV</button><button class="btn secondary" data-download="stress">Stress comparison CSV</button><button class="btn secondary" data-download="method">Methods Markdown</button></div><p class="table-note">Exports are calculated from the current UI settings. All spreadsheets escape formula-like text fields.</p>`)}<div style="height:16px"></div><div class="grid two">${panel(`<h2>Dataset preview</h2><div class="table-wrap"><table><thead><tr><th>Hour</th><th>Demand (kWh)</th><th>Solar fraction</th></tr></thead><tbody>${example.map(x=>`<tr><td>${x.hour}</td><td>${fmt(x.demand,3)}</td><td>${fmt(x.solar_factor,3)}</td></tr>`).join('')}</tbody></table></div><p class="note">Current source: ${state.imported?'user-imported CSV':esc(PRESETS[state.preset].name+' synthetic scenario')}.</p>`)}${panel(`<h2>Methodological boundaries</h2><p class="note">PV generation = PV kWp × solar fraction × (1 − derating). Battery is dispatched to serve remaining demand, never charges from the grid, and uses 90% round-trip efficiency.</p><p class="note">The project does not model electrical topology, reserve power, demand charges, system degradation, inverter constraints, actual weather forecasts, regulatory approval, project financing or grid outages.</p><p class="note">No measured consumption is built in. Assess safety, engineering feasibility and tariff rules with qualified professionals before investing.</p>`)}</div>`;}
69
+ const views={overview:'Overview',dispatch:'Dispatch Explorer',sizing:'Sizing Laboratory',economics:'Tariff & Economics',stress:'Stress & Resilience',data:'Data & Audit'};
70
+ function render(){const r=simulate(state.profile,state.params);document.getElementById('pageCrumb').textContent=views[state.view].toUpperCase();document.getElementById('app').innerHTML=`<div class="section-header" style="margin-bottom:15px"><div class="field" style="min-width:200px;max-width:380px;flex:1"><label for="datasetSelect">Current demonstration scenario</label><select id="datasetSelect" data-setting="preset"><option value="office" ${state.preset==='office'?'selected':''}>City office</option><option value="clinic" ${state.preset==='clinic'?'selected':''}>Community clinic</option><option value="warehouse" ${state.preset==='warehouse'?'selected':''}>Distribution hub</option>${state.imported?'<option value="custom" selected>Imported CSV</option>':''}</select></div><span class="pill">${state.profile.length===24?'24h':state.profile.length+'h'} · ${state.imported?'imported':'synthetic'} profile</span></div>${({overview,dispatch,sizing,economics,stress,data:dataView})[state.view](r)}`;document.querySelectorAll('.nav button').forEach(b=>{b.classList.toggle('active',b.dataset.view===state.view);b.setAttribute('aria-current',b.dataset.view===state.view?'page':'false');});}
71
+ let toastTimeout;function toast(msg,error=false){const el=document.getElementById('toast');el.textContent=msg;el.className='toast'+(error?' error':'');el.hidden=false;clearTimeout(toastTimeout);toastTimeout=setTimeout(()=>el.hidden=true,4500);}
72
+ function dl(name,content,type='text/plain'){const blob=new Blob([content],{type:type+';charset=utf-8'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(a.href),1500);}
73
+ const HEAD=['hour','demand_kwh','solar_factor'];
74
+ function exportData(kind){let r=simulate(state.profile,state.params),prefix='gridpilot_'+kind;let dd=(name,rows)=>dl(prefix+'.csv',csv([name,...rows]),'text/csv');if(kind==='template')return dl('gridpilot_hourly_template.csv',csv([HEAD,...sampleProfile('office').slice(0,24).map(h=>[h.hour,h.demand,h.solar_factor])]),'text/csv');if(kind==='profile')return dd(HEAD,state.profile.map(h=>[h.hour,rnd(h.demand,4),h.solar_factor]));if(kind==='dispatch')return dd(['hour','demand_kwh','pv_kwh','direct_kwh','battery_charge_kwh','battery_discharge_kwh','grid_import_kwh','grid_export_kwh','battery_soc_kwh','hourly_cost_usd'],r.hours.map(h=>[h.hour,...[h.demand,h.pv,h.direct,h.charged,h.discharged,h.gridImport,h.gridExport,h.soc,h.systemCost].map(v=>rnd(v,5))]));if(kind==='sizing')return dd(['solar_kwp','battery_kwh','initial_cost_usd','annual_net_benefit_usd','simple_payback_years','solar_share'],gridSearch(state.profile,state.params).map(a=>[a.pv,a.bat,rnd(a.capex,2),rnd(a.annualNet,2),a.payback===null?'':rnd(a.payback,2),rnd(a.solarShare,4)]));if(kind==='stress')return dd(['scenario','load_multiplier','solar_multiplier','peak_tariff_multiplier','monthly_savings_usd','grid_import_kwh','solar_share'],stressTest(state.profile,state.params).map(a=>[a.name,a.loadFactor,a.weatherFactor,a.peakMult,rnd(a.monthlySavings,2),rnd(a.totals.gridImport,2),rnd(a.solarShare,5)]));if(kind==='method')return dl('gridpilot_methods.md',`# GridPilot methodology\n\nAll demonstration data are synthetic. GridPilot is a deterministic, browser-only energy balance simulator.\n\n- PV generation: solar_kWp × hourly_solar_factor × weather_multiplier × (1 − derate).\n- Solar serves load first. Excess generation charges the battery. Remaining excess is exported.\n- Battery discharge serves residual load, subject to stored energy and battery power limits.\n- Charging and discharging efficiencies: sqrt(0.9) each. No grid charging.\n- Tariff peak: 17:00–21:59. Otherwise off-peak.\n- Weekly bill = sum(grid_import × tariff − exports × credit).\n- Annual net benefit = weekly savings × 365/7 − 1.2% × capex.\n- Solar capex = $920/kWp plus $400 installation allowance if PV > 0; storage = $465/kWh.\n- Candidate sizing exhaustive only on discrete set: 0,2,4,6,8,10,12 kWp × 0,4,8,12,16 kWh.\n\nLimitations: no battery wear, demand charges, grid outages, finance, inverter constraints or certified engineering calculations.\n\nConfiguration: ${JSON.stringify(state.params)}\n`,'text/markdown');let report={project:'GridPilot',version:'1.0',synthetic:!state.imported,source:state.imported?'imported CSV':state.preset,rows:state.profile.length,parameters:state.params,totals:r.totals,weeklySavings:r.weeklySavings,monthlySavings:r.monthlySavings,annualNetBenefit:r.annualNet,capex:r.capex,paybackYears:r.payback,solarShare:r.solarShare,selfConsumption:r.selfConsumption,method:'PV-first battery heuristic, 90% round-trip efficiency, weekly normalized economics',limitations:['Not a physical electrical design','Synthetic weather, no real tariffs','No battery degradation, financing or grid regulations']};return dl('gridpilot_audit_report.json',JSON.stringify(report,null,2),'application/json');}
75
+ document.addEventListener('click',e=>{let nav=e.target.closest('button[data-view]');if(nav){state.view=nav.dataset.view;render();return;}let button=e.target.closest('button[data-download]');if(button){try{exportData(button.dataset.download);toast('File prepared for download.');}catch(err){toast(err.message,true);}return;}let reset=e.target.closest('button[data-action=reset]');if(reset){state={preset:'office',profile:sampleProfile('office'),params:{...DEFAULTS},view:'data',day:0,imported:false};render();toast('Demo scenario restored.');}});
76
+ document.addEventListener('change',async e=>{let el=e.target;if(el.dataset.parameter){let key=el.dataset.parameter,v=Number(el.value),p={...state.params,[key]:v};try{assertParams(p);state.params=p;render();}catch(err){toast(err.message,true);render();}return;}if(el.dataset.setting==='day'){state.day=clamp(Number(el.value),0,6);render();return;}if(el.dataset.setting==='preset'){if(el.value==='custom')return;state.preset=el.value;state.profile=sampleProfile(el.value);state.imported=false;state.day=0;render();toast('Scenario loaded.');return;}if(el.id==='dataFile'&&el.files?.length){let file=el.files[0];try{if(file.size>250000)throw Error('CSV file exceeds the 250 KB limit');let profile=parseCSV(await file.text());state.profile=profile;state.imported=true;state.preset='custom';state.day=0;render();toast('CSV imported: '+profile.length+' hourly records.');}catch(err){toast(err.message,true);el.value='';}}});
77
+ render();
78
+ </script>
79
+ </body>
80
  </html>