App · project 27 of 37
Solar Go/No-Go.
Should a house go solar, how big, and how to pay? Five roof layouts priced on real El Paso rates and 2026 tax rules, with a go or no-go for each.
BeforeThree installer quotes that disagree, a summer-heavy power bill, a tax credit that may be gone, and no way to tell which size or which way to pay actually pays back.
AfterFive roof layouts priced on the utility's real rates and today's tax rules, with a go or no-go for every size and every way to pay, and the money behind each one.
What it is worthThe right size and the right way to pay, decided on real rates: here the bill-sized system wins and the biggest one sells most of its power for 1.6¢. Instead of taking the salesman's payback number on trust.
How to use it
- Press Show me how for the six-step tour, or read the Decision tab: the badge is the verdict for the bill-sized design E paid in cash.
- Tap any cell in the matrix (a size and a way to pay) to see its payback, return, bill before and after, and power sold back.
- Open Change the assumptions and put in your own price per watt, years you will stay, peak demand, utility price rise or a battery; every number updates. Reset brings back the dated values.
- On the Roof tab, switch designs A to E to see where the panels go, turn the 3D view, and copy the module list.
- On the Money tab, compare every design side by side and read the month-by-month bill; on Checks and Data, see what a real house still needs and where every number comes from.
Where it helps most
- Homeowners in El Paso, or anywhere with monthly netting and a low buy-back price, holding quotes that disagree on size, price and payback.
- Choosing between cash, a lease and a PPA now that the homeowner credit is gone and the business credit has a deadline.
- Showing a client or a family member why a smaller system or a different way to pay is the better buy, with the rates and sources on the page.
The idea
I worked out whether solar makes sense for a house in El Paso, and the answer was not what the quotes said. The utility nets solar month by month and pays about 1.6¢ for surplus power while a kWh used at home saves about 13¢, the homeowner tax credit ended in 2025, and new solar customers pay a demand charge. So the biggest system is the worst buy, and the cheapest way in is a lease that still carries the business credit, for about another year. I wanted that reasoning in one place anyone can check, with the house made up so nothing points to a real address.
The build
Claude built it from the study it ran for a real house, then rebuilt the whole thing on an invented house: the roof outline is lengthened and mirrored, the street moved to the other side, and the year of use is made up, so no address, lot, owner, bill or aerial photo is in it. The roof model (Python, shapely) cuts setbacks on the sloped surface by edge type, packs 430 W modules in rows square to each eave, applies the 2021 IRC pathway and ridge rules, and drops any spot that loses over 20% of its direct sun in a simple shading model of the house and a neighbour. A separate check rebuilds every module from its centre and angles and finds no overlaps or clearance misses. Output per roof face comes from NREL PVWatts v8 for El Paso. The money model (JavaScript, runs in the browser) uses El Paso Electric's Texas Rate 01 standard and distributed-generation tariffs effective Aug 1, 2026, the riders, monthly netting and the Rate 48 surplus price, EnergySage price data, and the 2026 tax rules (25D gone, 48E through leases until Dec 31, 2027). Limits, stated on the page: pitches, heights, module size, peak demand and the 120% panel fix are assumptions; the shading is a clear-sky model; there is no electrical or structural design, so it cannot be filed as a permit.
Free to take
Build your own.
Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›
Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other
# Master prompt: Solar Go/No-Go
You are a solar designer who also prices projects, and a front-end developer. Build "Solar Go/No-Go": a free web tool that answers three questions for one house: should it go solar, how big, and how should it pay. It works through one worked example on an INVENTED two-storey house in El Paso, Texas, priced on the utility's real rates and today's tax rules. It is a layout and money study, not an electrical, structural or fire-code design, and it says so at the top.
PRIVACY
- The house, its roof and its year of electricity use are invented. No real address, lot, owner, account number, bill or aerial photo anywhere, not in code comments either. If the work started from a real house, change its outline (lengthen a block, mirror it) and its use profile before anything is published.
THE ROOF MODEL (Python, shapely, numpy; local metres, x east, y north)
- Each roof face: plan outline, downhill azimuth, eave height and a type for every edge (eave, rake, wall, hip, valley, ridge). Pitch 5:12 (22.6°) and heights are ASSUMED and labelled so.
- Usable area: cut a band along each edge on the sloped surface (A/B: 0.25 m edges, 18 in at hips, valleys and ridges; C/D/E: 2021 IRC minimum, 18 in at ridges and 6 in elsewhere), keep 0.35 m around every vent, keep the street-side hip and the north slope free as the two 36 in pathways (IRC R324.6). If the array covers over 33% of the plan roof, the ridge setback becomes 36 in.
- Pack 1722 x 1134 mm, 430 W modules (ASSUMED) in rows square to the eave: try landscape and portrait, aligned grid and greedy rows over many phase offsets, keep the best; optionally fill what is left with the other orientation.
- Shading: own house plus a same-size neighbour one lot south, sun path every 2 days and every 30 min, clear-sky beam weighting, five sample points per module. Leave empty any spot that loses over 20% of a year's direct sun.
- Five designs: A Conservative, B Street-quiet (nothing facing the street), C Dense (code minimum plus the garage roof), D Maximum (plus the north slope and street hip, two 36 in strips, vents rerouted), E Sized to use (C's spacing on the house roof, best-producing panels only, until a year's output is 88% of the use).
- Independent QC with separate maths: rebuild each module from its centre, long-side bearing, orientation, pitch and azimuth; report overlaps, edge-clearance misses, modules in pathway strips, smallest gap, height off the plane, squareness, vents covered, panels facing the street or seen at an angle, array share of the roof.
- Yield per kW from NREL PVWatts v8 for the city at 22.6°, 14% losses (south 1,900, east 1,626, west 1,589, north 1,237 kWh per kW a year), times (1 − 0.85 × shade). Monthly spread from the PVWatts south monthly pattern.
THE MONEY MODEL (JavaScript, runs in the browser and in Node)
- Bill today: El Paso Electric Texas Rate 01 Standard ($13.71/month; May–Oct $0.12897 first 600 kWh, $0.13897 above; Nov–Apr $0.10897) plus riders ($0.042255/kWh, $2.70 meter, about $0.64 military factor).
- Bill with solar: Rate 01 Distributed Generation ($13.71 + $5.65 per kW of the highest 60-min demand; Jun–Sep $0.09564/$0.10564; Oct–May $0.07564), netted month by month; any month's surplus is credited at the Rate 48 price, $0.016154/kWh.
- Up-front: kW × $/W × a size factor (1.12 at 4 kW down to 0.93 at 20 kW) + $85 application + extras ($2,150 main-panel fix when AC is over 7.7 kW on a 200 A panel; $1,500 vent rerouting for D).
- Four ways to pay: cash (no federal credit in 2026), cash + 30% (only if 25D returns), prepaid lease (48E passed through as a lower price, must be running by Dec 31, 2027), PPA ($0 down, $/kWh with a yearly rise).
- 25 years with utility price rise and panel output loss: payback, ROI, IRR by bisection, NPV, 25-year net, cash position if you leave at year N, power sold back and its revenue. Verdict: Go if payback is within the years you will stay and IRR beats your discount rate; Go if you stay if IRR is fine but payback is later; No-go otherwise; a PPA is Go if it saves from year 1 and over its life.
- A Powerwall only trims the demand charge under monthly netting; show why it is a no-go on money.
- Clamp every input (price 0.5–6 $/W, years 1–25 and so on) so nothing can print NaN or a negative cost.
VIEWS AND CONTROLS (one page, tabs: Decision, Roof, Money, Checks, Data)
- Decision: a big Go / Go if you stay / No-go badge for the picked cell, the reason, eight numbers (up-front, bill now → year 1, year-1 saving, payback, ROI, IRR, 25-year net, sold back); a matrix of every design × every way to pay, each cell coloured and tappable; "Change the assumptions" with dated defaults and a reset.
- Roof: design buttons A–E, the plan from above (street, lot line, setbacks dashed, pathways hatched, vents, module ids, legend, scale, north), a 3D view drawn on a canvas with drag to turn and four camera buttons, panels per face, the module list with Copy CSV.
- Money: one table comparing every design on roof, energy and money with the best value marked; cash over 25 years chart with a line per design and a dashed line at the years you stay; power sold back; full numbers; month by month for any design; Powerwall; tax incentives (25D gone, 48E through a lease, Texas property-tax exemption, no state credit, no utility rebate); connection and other costs.
- Checks: the QC table (confirmed, issue, blocker), how a house is permitted in El Paso, and what to measure before signing.
- Data: every value with its source and date; INVENTED and ASSUMED marked.
TUTORIAL
- "Show me how" is a six-step tour (verdict, matrix, assumptions, roof plan, sold-back power, checks): it switches tabs, lights the part and keeps its card off the lit part; ?tour=1 starts it; Esc closes it.
FINISH
- No libraries and no outside fonts; no inline scripts or style attributes (strict Content-Security-Policy). Light background so the plans read. Works from 320 px wide to desktop and on a phone held sideways; wide tables scroll inside their panel; tab buttons scroll the page to the tabs.
STRESS TEST
- Every tab at 320×568, 393×700, 740×360 and 1366×800: no console errors, no sideways scroll. Click all 20 matrix cells; set every input to 0, negative, huge and empty and check for NaN or Infinity; tick the battery; switch tabs 40 times at random; every design and camera; drag the 3D view; every way to pay in the chart. In Node, sweep the money model over the extremes: costs never negative, payback within 0–25 years or none, and payback gets longer when the price per watt goes up.
Get the code9 files, exactly as they run on this site · free under the MIT license
The page also loads data.js and plan-A.svg to plan-E.svg; build.py writes them from the Python model (steps in docs/solar-go-no-go/README.md), so they are not listed here.
index.html (page, tax and data tables, sources)227 lines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Solar Go/No-Go: should this house go solar?</title>
<meta name="description" content="Free worked study: five rooftop solar layouts on an invented El Paso house, priced on real El Paso Electric rates and 2026 tax rules, with a go/no-go for each.">
<link rel="icon" href="../../favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./sgo.css">
</head>
<body>
<div class="wrap">
<header class="mast">
<div class="mrow">
<div>
<div class="eyebrow">Free tool · rooftop solar · El Paso, Texas</div>
<h1>Solar Go/No-Go</h1>
<p class="sub">Should this house go solar, how big, and how should it pay? Five roof layouts on a two-storey house, priced on El Paso Electric's real rates and today's tax rules, with a go or no-go for every size and every way to pay. Change any assumption and every number updates.</p>
</div>
<div class="mastbtns">
<button type="button" class="btn pri" id="tourBtn">Show me how</button>
<a class="btn" href="/all/">Free tools ›</a>
</div>
</div>
<div class="banner"><b>An invented house, real rates.</b> The house, its roof and its year of electricity use are made up: no real address, owner, bill or aerial photo. The rates, prices, tax rules, sun data and codes are real and dated, with sources on the Data tab. This is a layout and money study, not an electrical, structural or fire-code design.</div>
</header>
</div>
<nav class="tabs" aria-label="Sections"><div class="in" role="tablist" id="tabs">
<button type="button" role="tab" data-t="decision" aria-selected="true">Decision</button>
<button type="button" role="tab" data-t="roof" aria-selected="false">Roof</button>
<button type="button" role="tab" data-t="money" aria-selected="false">Money</button>
<button type="button" role="tab" data-t="checks" aria-selected="false">Checks</button>
<button type="button" role="tab" data-t="data" aria-selected="false">Data</button>
</div></nav>
<main class="wrap">
<section class="tab on" id="decision" role="tabpanel" aria-label="Decision">
<div class="panel" id="heroPanel">
<div class="kick">Decision</div>
<div class="hero"><div class="big" id="ev-badge">–</div><div><h2 id="ev-title"></h2><p id="ev-why"></p></div></div>
<div class="kpis" id="ev-kpis"></div>
<p class="note" id="ev-rule"></p>
</div>
<div class="panel scroll" id="mxPanel"><h2>Go / no-go: every size × every way to pay</h2>
<p class="note top">Tap a cell to open it above. Green = Go, amber = Go only if you stay long enough, red = No-go. Each cell: payback · return over 25 years (with a PPA, year-1 and 25-year savings).</p>
<table class="mx" id="ev-mx"></table>
<p class="note"><b>Cash today</b>: you own it, no federal credit in 2026. <b>Cash + 30% credit</b>: only if Congress brings back the homeowner credit (25D); not current law. <b>Prepaid lease</b>: a company owns the panels, claims the 30% business credit (48E) and passes it on as a lower up-front price; it must be running by Dec 31, 2027. <b>PPA</b>: $0 down, you pay for each kWh the panels make.</p>
</div>
<div class="panel" id="asmPanel"><details id="asm"><summary>Change the assumptions</summary>
<div class="ecin">
<label>Installed price ($/W)<input id="ev-price" type="number" step="0.05" min="0.5" max="6" value="2.30"><small>EnergySage El Paso, Sep 2026: $2.30/W</small></label>
<label>Prepaid-lease discount vs cash (%)<input id="ev-pre" type="number" step="1" min="0" max="80" value="39"><small>EnergySage H1 2026: 39% cheaper per kWh</small></label>
<label>PPA price ($/kWh)<input id="ev-ppa" type="number" step="0.005" min="0" max="0.5" value="0.10"><small>Texas PPAs $0.08–0.12</small></label>
<label>PPA price rise (%/yr)<input id="ev-ppaesc" type="number" step="0.5" min="0" max="10" value="1"><small>Usually 0–3%/yr</small></label>
<label>Utility price rise (%/yr)<input id="ev-esc" type="number" step="0.5" min="-5" max="15" value="2.5"><small>ASSUMED</small></label>
<label>Peak 60-min demand Jun–Sep (kW)<input id="ev-ds" type="number" step="0.5" min="0" max="30" value="5"><small>ASSUMED: read yours from the utility</small></label>
<label>Peak 60-min demand Oct–May (kW)<input id="ev-dw" type="number" step="0.5" min="0" max="30" value="3.5"><small>ASSUMED</small></label>
<label>Years you expect to stay<input id="ev-yrs" type="number" step="1" min="1" max="25" value="10"></label>
<label>Discount rate (%)<input id="ev-disc" type="number" step="0.5" min="0" max="20" value="5"><small>ASSUMED: what your money earns elsewhere</small></label>
<label>Panel output loss (%/yr)<input id="ev-deg" type="number" step="0.1" min="0" max="3" value="0.5"><small>ASSUMED</small></label>
<label class="chk"><input id="ev-pw" type="checkbox"> Add one Tesla Powerwall 3</label>
</div>
<div class="btns"><button type="button" class="btn" id="ev-reset">Reset to the dated values</button></div>
</details></div>
</section>
<section class="tab" id="roof" role="tabpanel" aria-label="Roof">
<div class="seg" id="dseg" role="group" aria-label="Design"></div>
<p class="note top" id="dnote"></p>
<div class="panel plan" id="planPanel"><img id="planImg" src="./plan-E.svg" alt="Roof plan from above, design E" width="900" height="600">
<p class="note">From above, north up, street to the east. Grid in metres from the west end of the house's south eave. Setbacks are measured on the sloped roof. Pitch 5:12 and heights are ASSUMED; the house is invented.</p></div>
<div class="panel" id="d3Panel"><h2>In 3D</h2>
<canvas id="cv" width="1100" height="640" aria-label="3D view of the house and panels. Drag to turn."></canvas>
<div class="btns"><button type="button" class="btn" data-cam="street">From the street</button><button type="button" class="btn" data-cam="south">From the south</button><button type="button" class="btn" data-cam="rear">From the back yard</button><button type="button" class="btn" data-cam="top">Top</button></div>
<p class="note">Drag to turn. Simplified model: walls at the eave line, porch flat.</p></div>
<div class="panel scroll"><h2>Panels per roof face</h2><table id="faceTable"></table></div>
<div class="panel"><h2>Module list, <span id="lsName"></span></h2>
<div class="btns"><button type="button" class="btn pri" id="copyCsv">Copy CSV</button><span id="copied" class="note" aria-live="polite"></span></div>
<div class="scroll"><table class="mods" id="modTable"></table></div>
<p class="note">Pitch and heights ASSUMED. Module 1722 × 1134 mm, 430 W, all-black, ASSUMED until a datasheet is picked. Shade % = share of a year's direct sun blocked, from a simple model of the house and a same-size neighbour one lot south. Spots losing over 20% are left empty.</p></div>
</section>
<section class="tab" id="money" role="tabpanel" aria-label="Money">
<div class="panel scroll" id="cmpPanel"><h2>Compare every design: roof, energy and money</h2>
<p class="note top">One column per design. Green marks the best value in a money row. It updates when you change the assumptions on the Decision tab.</p>
<table class="wide" id="cmp-table"></table></div>
<div class="panel" id="chartPanel"><h2>Money over time: <span id="ev-fin-name"></span></h2>
<div class="seg2" id="ev-fin"></div>
<div class="chart" id="ev-chart"></div>
<div class="leg" id="ev-leg"></div>
<p class="note">Cash in your pocket after N years: bill savings so far plus power sold back, minus what you paid. Where a line crosses $0 is the payback year; the dashed line is how long you expect to stay.</p></div>
<div class="panel scroll" id="soldPanel"><h2>Power sold back to El Paso Electric</h2>
<table class="wide" id="ev-export"></table>
<p class="note">El Paso Electric nets solar against use each month and buys any month's surplus at its Rate 48 price: $0.016154/kWh for Mar–Sep 2026, about one-eighth of what a kWh used at home saves. Sold-back power is a by-product, not income.</p></div>
<div class="panel scroll"><h2>Full numbers: <span id="ev-fin-name2"></span></h2>
<table class="cmp wide" id="ev-table"></table>
<p class="note">Up-front = kW × price × size factor + $85 El Paso Electric application + extras (main-panel fix for C and D, vent rerouting for D). ROI = 25-year net ÷ up-front. IRR = yearly return on the money put in. NPV at your discount rate. "Leave at year N" = cash position if you move then, with no credit for the system at sale.</p></div>
<div class="panel scroll"><h2>Month by month: <select id="ev-pick" aria-label="Design"></select> · <span id="ev-fin-name3"></span></h2>
<table class="wide" id="ev-months"></table>
<p class="note">Use = the sample household's year (invented). Solar = PVWatts v8 for El Paso (south 1,900 · east 1,626 · west 1,589 · north 1,237 kWh per kW per year at 22.6°) after the shading check, spread by PVWatts' monthly pattern. Bill now = Rate 01 Standard + riders. Bill with solar = Rate 01 Distributed Generation ($5.65/kW demand) + riders on net kWh − surplus × $0.016154.</p></div>
<div class="panel" id="pwPanel"><h2>Tesla Powerwall 3</h2><div id="ev-pwtext"></div></div>
<div class="panel scroll"><h2>Tax incentives: what you can and can't get</h2>
<table><tbody>
<tr><td><span class="pill bad">Gone</span></td><td><b>Federal homeowner credit (25D, 30%)</b></td><td>Ended for systems installed after Dec 31, 2025 (One Big Beautiful Bill Act). Bills to restore it were filed in 2026; none has passed. "Cash + 30% credit" shows what it would be worth if it came back.</td></tr>
<tr><td><span class="pill ok">Available</span></td><td><b>Business credit through a lease or PPA (48E, 30%)</b></td><td>The company that owns the panels claims it and should pass it on as a lower price. Projects started after July 4, 2026 must be in service by Dec 31, 2027. Ask every installer for the price with and without it.</td></tr>
<tr><td><span class="pill ok">Available</span></td><td><b>Texas property-tax exemption (Tax Code §11.27)</b></td><td>The value solar adds to a home is not taxed. File Form 50-123 with the county appraisal district after install.</td></tr>
<tr><td><span class="pill warn">None</span></td><td><b>State income-tax credit</b></td><td>Texas has no state income tax, so there is no state solar credit.</td></tr>
<tr><td><span class="pill warn">None</span></td><td><b>El Paso Electric rebate</b></td><td>No current residential solar rebate; Tesla's $500 Powerwall rebate closed June 30, 2026.</td></tr>
</tbody></table></div>
<div class="panel scroll"><h2>Connection and other costs</h2>
<table><thead><tr><th>Item</th><th>What applies</th><th>Cost used</th></tr></thead><tbody id="costRows"></tbody></table></div>
</section>
<section class="tab" id="checks" role="tabpanel" aria-label="Checks">
<div class="panel" id="qcPanel"><h2>Independent checks</h2>
<p><b>Ready to file?</b> <span class="pill bad">Not yet</span> Every layout passes every geometry check, but two things block a permit on any real house: the pitches and heights here are assumed, and there are no electrical or structural sheets.</p>
<div class="scroll"><table id="qcTable"></table></div></div>
<div class="panel"><h2>How a house like this gets permitted in El Paso</h2>
<ul class="steps">
<li><b>City permit.</b> Planning & Inspections reviews it, filed online through the City's Citizen Access Portal; a $200 residential submittal deposit is credited to the permit fee. Codes in force: 2021 IRC and IFC, 2020 NEC; El Paso's amendments do not change the IRC solar section (R324). Design values: 105 mph wind, 5 psf ground snow.</li>
<li><b>What the counter needs.</b> Site plan and roof plan with pathways and setbacks; module list; electrical single-line and calculations; structural letter or attachment details for 105 mph; module (UL 61730), inverter (UL 1741) and racking (UL 2703) datasheets.</li>
<li><b>Who pulls it.</b> Normally the installer's TDLR-licensed electrical contractor. Inspections: electrical rough and final.</li>
<li><b>Utility.</b> The installer files El Paso Electric's Standard Interconnection Application ($85 up to 100 kW) with the single-line diagram; the utility fits a two-way meter.</li>
<li><b>Association.</b> If a property owners' association exists, Texas Property Code §202.010 bars it from banning solar; it may require panels within the roofline, parallel to the roof, with black, silver or bronze frames, in a set area unless another spot makes over 10% more.</li>
</ul></div>
<div class="panel"><h2>Before signing a quote on a real house</h2>
<ul class="chk">
<li>Measure each roof pitch (a phone level on a rafter tail, or the installer's survey).</li>
<li>Mark every vent and flue on the roof plan.</li>
<li>Read the main panel label: busbar and main breaker size decide the 120% rule.</li>
<li>Download 12 months of use and the 60-minute peak demand from the utility, and replace the sample year here.</li>
<li>Pick the module and inverter; microinverters or optimisers where any panel is shaded.</li>
<li>Ask the counter whether they want 18 in along hips and valleys (C, D and E use 6 in).</li>
<li>Get the price with and without the 48E credit, and the in-service date in writing.</li>
</ul>
<p class="note">The free <a href="/tools/solar-permit-check/">Solar Permit Check</a> runs the geometry checks on any roof.</p></div>
</section>
<section class="tab" id="data" role="tabpanel" aria-label="Data">
<div class="panel scroll" id="dataPanel"><h2>All data: value, source, date</h2>
<p class="note top">Every fact the study rests on. INVENTED = made up for the sample house; ASSUMED = no published value; everything else is quoted from the source named.</p>
<table class="dt"><thead><tr><th>Item</th><th>Value</th><th>Source</th><th>Date</th></tr></thead><tbody>
<tr><td colspan="4" class="dh">Sample house (invented)</td></tr>
<tr><td>House</td><td>Two storeys, cross-hip roof with a south gable wing, one-storey garage and rear roofs, street to the east; roof plan area <span id="roofM2"></span> m²</td><td>INVENTED</td><td>–</td></tr>
<tr><td>Pitch, eave heights</td><td>5:12 (22.6°); 5.8 m upper, 2.9 m lower</td><td>ASSUMED</td><td>–</td></tr>
<tr><td>Year of use</td><td id="useRow"></td><td>INVENTED, shaped like a summer-peaking El Paso home</td><td>–</td></tr>
<tr><td>Peak 60-min demand</td><td>5 kW summer, 3.5 kW winter</td><td>ASSUMED</td><td>–</td></tr>
<tr><td colspan="4" class="dh">Codes and permit</td></tr>
<tr><td>Codes in force</td><td>2021 IRC, IBC, IFC, IECC; 2020 NEC; local amendments leave IRC R324 (solar) as written</td><td>City of El Paso adopted codes; Municipal Code Ch. 18.10</td><td>2026</td></tr>
<tr><td>Design loads</td><td>Wind 105 mph; ground snow 5 psf</td><td>Ch. 18.10.050 (Table R301.2(1))</td><td>2026</td></tr>
<tr><td>Roof access</td><td>Two 36 in pathways (one on the street side); 18 in each side of the ridge if the array is ≤ 33% of plan roof, 36 in above</td><td>2021 IRC R324.6</td><td>2021</td></tr>
<tr><td>Filing</td><td>Citizen Access Portal; $200 residential submittal deposit credited to the fee</td><td>City Planning & Inspections</td><td>2026</td></tr>
<tr><td>Association rules</td><td>A POA may not ban solar; it may require flush, within-roofline, black/silver/bronze frames</td><td>Tex. Prop. Code §202.010</td><td>current</td></tr>
<tr><td colspan="4" class="dh">El Paso Electric rates (Texas)</td></tr>
<tr><td>Standard Rate 01</td><td>$13.71/mo; May–Oct $0.12897/kWh first 600, $0.13897 above; Nov–Apr $0.10897</td><td>EPE Rate 01 tariff</td><td>eff. Aug 1, 2026</td></tr>
<tr><td>Distributed Generation rate (new solar)</td><td>$13.71/mo + $5.65 per kW of highest 60-min demand; Jun–Sep $0.09564 first 600, $0.10564 above; Oct–May $0.07564</td><td>EPE Rate 01 tariff, DG section</td><td>eff. Aug 1, 2026</td></tr>
<tr><td>Grandfathering</td><td>Existing solar customers keep the old structure</td><td>City of El Paso rate-case release</td><td>Feb 20, 2026</td></tr>
<tr><td>Demand-charge figure</td><td>Tariff shows $5.65/kW; an advocacy report cited $4.75/kW; this study uses the tariff</td><td>EPE tariff; Vote Solar</td><td>2026</td></tr>
<tr><td>Riders</td><td>Fuel $0.016154 · relate-back $0.01924 · GCRR $0.00349 · retiring plant $0.001825 · EECRF $0.000687 · asset $0.000498 · rate case $0.000361 per kWh · meter $2.70/mo · military factor about $0.64/mo</td><td>An EPE residential bill</td><td>Nov 2026</td></tr>
<tr><td>Power sold back (Rate 48)</td><td>$0.015950/kWh Jan–Feb 2026; $0.016154 Mar–Sep 2026</td><td>EPE purchased-power factors</td><td>Sep 2026</td></tr>
<tr><td>Netting</td><td>Generation netted against use each month; surplus bought at avoided cost</td><td>EPE Texas net-metering FAQ</td><td>–</td></tr>
<tr><td>Interconnection</td><td>$85 application up to 100 kW; utility installs the two-way meter</td><td>EPE Texas interconnection page</td><td>2026</td></tr>
<tr><td colspan="4" class="dh">Solar output</td></tr>
<tr><td>Yield at 22.6°, 14% losses</td><td>South 1,900 · east 1,626 · west 1,589 · north 1,237 kWh per kW per year; south monthly 137 (Dec) to 184 (May)</td><td>NREL PVWatts v8, El Paso TMY weather</td><td>Nov 2026</td></tr>
<tr><td>Shading</td><td>Own model: the house itself and a same-size neighbour one lot south, clear-sky sun path every 2 days, every 30 min. Spots over 20% loss left empty.</td><td>Calculated</td><td>Nov 2026</td></tr>
<tr><td colspan="4" class="dh">Market prices</td></tr>
<tr><td>Installed solar, El Paso</td><td>$2.30/W; 12.3 kW average $28,080; 5 kW ≈ $11,417</td><td>EnergySage El Paso</td><td>Sep–Oct 2026</td></tr>
<tr><td>Installed solar, Texas</td><td>$2.25/W</td><td>EnergySage Texas</td><td>Nov 2026</td></tr>
<tr><td>Prepaid lease</td><td>39% cheaper per kWh than cash; lease price rises usually 1–3%/yr</td><td>EnergySage</td><td>H1 2026</td></tr>
<tr><td>Texas lease / PPA</td><td>Lease $80–130/mo; PPA $0.08–0.12/kWh</td><td>NuWatt</td><td>2026</td></tr>
<tr><td colspan="4" class="dh">Tax incentives</td></tr>
<tr><td>Homeowner credit (25D)</td><td>0% for systems after Dec 31, 2025</td><td>One Big Beautiful Bill Act; SEIA; EnergySage</td><td>Jul 4, 2025</td></tr>
<tr><td>Business credit (48E) via lease/PPA</td><td>30%; start construction by Jul 4, 2026 or be in service by Dec 31, 2027</td><td>SEIA; EnergySage</td><td>2025–2026</td></tr>
<tr><td>Restoration bill</td><td>Introduced Mar 18, 2026; not passed</td><td>Inside Climate News</td><td>Mar 2026</td></tr>
<tr><td>Property tax</td><td>Value added by solar exempt; Form 50-123</td><td>Tex. Tax Code §11.27</td><td>current</td></tr>
<tr><td colspan="4" class="dh">Batteries and other costs</td></tr>
<tr><td>Tesla Powerwall 3</td><td>$13,473 typical installed; 13.5 kWh; 11.5 kW; 10-yr warranty to 70%</td><td>EnergySage</td><td>2026</td></tr>
<tr><td>Main panel upgrade</td><td>200 A: $1,300–3,000, average $2,150</td><td>This Old House</td><td>2026</td></tr>
<tr><td>Utility upgrades</td><td>No study fee under 20 kW on secondary networks; the utility must quote any upgrade before work</td><td>16 TAC §25.211</td><td>current</td></tr>
<tr><td>Vent rerouting</td><td>$1,500 for the vents under design D</td><td>ASSUMED</td><td>–</td></tr>
</tbody></table></div>
<div class="panel"><h2>Sources</h2>
<ul class="src">
<li><a href="https://www.epelectric.com/el-paso-electric/uploads/regulatory/section-1-sheet-040-schedule-01-residential-service-rate-eff_08-01-2026.pdf">El Paso Electric: Texas Rate 01 (Standard and Distributed Generation)</a></li>
<li><a href="https://www.epelectric.com/el-paso-electric/uploads/regulatory/tx-fuel-purchased-power-and-adjustment-factors-for-september-2026.pdf">El Paso Electric: Rate 48 purchased-power factors, Sep 2026</a></li>
<li><a href="https://www.epelectric.com/files/html/Dist._Gen._Interconnection/TX/FAQs_Texas_Net_Metering_Revised_09-06-2011.pdf">El Paso Electric: Texas net-metering FAQ (monthly netting)</a></li>
<li><a href="https://www.epelectric.com/residential/rooftop-solar/texas-interconnection-of-facilities-up-to-10-mw">El Paso Electric: Texas interconnection ($85 fee)</a></li>
<li><a href="https://www.elpasotexas.gov/assets/Press-Releases/2026.02.20-NEWS-RELEASE_City-of-El-Paso-Secures-Key-Savings-for-Customers-in-El-Paso-Electric-Rate-Case.pdf">City of El Paso: Feb 2026 rate case (existing solar grandfathered)</a></li>
<li><a href="https://www.energysage.com/local-data/solar-panel-cost/tx/el-paso-county/el-paso/">EnergySage: El Paso solar cost</a></li>
<li><a href="https://www.energysage.com/solar/solar-tax-credit-explained">EnergySage: 25D ended; leases and PPAs still get 48E</a></li>
<li><a href="https://www.energysage.com/news/trumps-tax-changes-impact-tpo-solar/">EnergySage: 48E deadlines for leases and PPAs</a></li>
<li><a href="https://seia.org/wp-content/uploads/2025/07/OBBB-fact-sheet_july-2025.pdf">SEIA: One Big Beautiful Bill fact sheet</a></li>
<li><a href="https://energysage.com/solar/solar-leases">EnergySage: solar leases</a></li>
<li><a href="https://nuwattenergy.com/texas/solar-lease-ppa-2026">NuWatt: Texas lease and PPA pricing 2026</a></li>
<li><a href="https://insideclimatenews.org/news/18032026/house-democrats-propose-clean-energy-tax-credits-legislation/">Inside Climate News: 2026 bill to restore the credits</a></li>
<li><a href="https://texas.public.law/statutes/tex._tax_code_section_11.27">Texas Tax Code §11.27: solar property-tax exemption</a></li>
<li><a href="https://www.energysage.com/solar/solar-energy-storage/tesla-powerwall-home-battery/">EnergySage: Powerwall 3 price</a></li>
<li><a href="https://www.thisoldhouse.com/electrical/cost-to-upgrade-electrical-panel">This Old House: panel upgrade cost</a></li>
<li><a href="https://pvwatts.nrel.gov/">NREL PVWatts v8</a></li>
</ul></div>
</section>
</main>
<div class="wrap"><footer class="foot">Solar Go/No-Go · prepared Nov 2026 · rates and rules change: check the dated sources before deciding. Not financial, tax, electrical or structural advice.</footer></div>
<div id="tour" role="dialog" aria-modal="false" aria-labelledby="tourH" hidden>
<h3 id="tourH"></h3><p id="tourP"></p>
<div class="tb"><span id="tourN"></span><div><button type="button" class="btn" id="tourBack">Back</button><button type="button" class="btn pri" id="tourNext">Next</button><button type="button" class="btn" id="tourEnd">Close</button></div></div>
</div>
<script src="./data.js"></script>
<script src="./econ.js"></script>
<script src="./sgo.js"></script>
</body>
</html>
econ.js (the money model: rates, netting, four ways to pay, verdicts, charts, comparison)228 lines
/* Solar Go/No-Go: the money model. El Paso Electric (Texas) Rate 01, monthly netting, surplus at Rate 48.
Every rate below is dated and sourced on the Data tab. Runs in the browser; also loads in Node for tests. */
(function (root) {
'use strict';
const S = root.SGO;
const MONTHS = ["Dec","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov"];
const USE = S.use; // sample household, Dec..Nov (invented)
const UT = USE.reduce((a, b) => a + b, 0);
const SMON = {Jan:146.41,Feb:145.33,Mar:173.90,Apr:177.61,May:184.26,Jun:165.00,Jul:159.34,Aug:159.67,Sep:154.53,Oct:155.07,Nov:141.35,Dec:137.08}; // PVWatts v8, south, kWh/kW
const STOT = Object.values(SMON).reduce((a, b) => a + b, 0);
const RIDERS = 0.016154+0.000687+0.00349+0.01924+0.000498+0.001825+0.000361, FIXED = 13.71+2.70, MIL = 0.64;
const EXPORT = 0.016154, DEMAND = 5.65, APP = 85;
const STD_SUM = new Set(["May","Jun","Jul","Aug","Sep","Oct"]), DG_SUM = new Set(["Jun","Jul","Aug","Sep"]);
const PW_COST = 13473, PW_CUT_S = 3, PW_CUT_W = 2;
const ORDER = ["B","A","E","C","D"];
const DES = ORDER.map(k => { const d = S.designs.find(x => x.k === k); return Object.assign({}, d, {label: d.k + " · " + d.name}); });
const FIN = [
{k:"cash", name:"Cash today", short:"Cash today"},
{k:"credit", name:"Cash + 30% credit (if 25D returns)", short:"Cash + 30% credit"},
{k:"prepaid", name:"Prepaid lease (48E passed through)", short:"Prepaid lease"},
{k:"ppa", name:"PPA, $0 down", short:"PPA"}];
const COL = {E:"#2f7d4f", A:"#1f5fa8", B:"#8a8373", C:"#1f2a38", D:"#c7462f"};
const DEF = {price:2.30, pre:39, ppa:0.10, ppaesc:1, esc:2.5, ds:5, dw:3.5, yrs:10, disc:5, deg:0.5};
const interp = (x, xs, ys) => { if (x <= xs[0]) return ys[0]; for (let i = 1; i < xs.length; i++) { if (x <= xs[i]) { const t = (x-xs[i-1])/(xs[i]-xs[i-1]); return ys[i-1]+t*(ys[i]-ys[i-1]); } } return ys[ys.length-1]; };
const sizeF = kw => interp(kw, [4,8,12,15,20], [1.12,1.015,1.0,0.957,0.93]); // smaller systems cost more per watt
const stdE = (m, k) => STD_SUM.has(m) ? 0.12897*Math.min(k,600)+0.13897*Math.max(0,k-600) : 0.10897*k;
const dgE = (m, k) => DG_SUM.has(m) ? 0.09564*Math.min(k,600)+0.10564*Math.max(0,k-600) : 0.07564*k;
const sum = a => a.reduce((x, y) => x + y, 0);
const billNow = () => MONTHS.map((m, i) => FIXED + MIL + stdE(m, USE[i]) + RIDERS*USE[i]);
const prodOf = (kwh, f) => MONTHS.map(m => kwh*SMON[m]/STOT*f);
function billDG(prod, ds, dw) {
let exp = 0;
const b = MONTHS.map((m, i) => { const net = USE[i]-prod[i]; const d = DG_SUM.has(m) ? ds : dw; let x = FIXED+MIL+DEMAND*d;
if (net >= 0) x += dgE(m, net)+RIDERS*net; else { x -= EXPORT*(-net); exp += -net; } return x; });
return {b, exp};
}
const num = (v, lo, hi, d) => { v = parseFloat(v); if (!isFinite(v)) v = d; return Math.min(hi, Math.max(lo, v)); };
function run(d, f, p) {
const gross = d.kw*1000*p.price*sizeF(d.kw);
let cost;
if (f === "cash") cost = gross+APP+d.extra;
else if (f === "credit") cost = 0.7*gross+APP+d.extra;
else if (f === "prepaid") cost = (1-p.pre)*gross+APP+d.extra;
else cost = APP+d.extra;
if (p.pw) cost += PW_COST*(f === "cash" ? 1 : 0.7);
const base = sum(billNow());
const ds = Math.max(0, p.ds-(p.pw ? PW_CUT_S : 0)), dw = Math.max(0, p.dw-(p.pw ? PW_CUT_W : 0));
const cf = [-cost]; let cum = -cost, pay = null; const cumBy = [-cost]; let exp1 = 0, expRev25 = 0, yr1 = 0, after1 = 0;
for (let y = 1; y <= 25; y++) {
const fe = Math.pow(1+p.esc, y-1), fp = Math.pow(1-p.deg, y-1);
const prod = prodOf(d.kwh, fp); const r = billDG(prod, ds, dw);
let sav = (base-sum(r.b))*fe;
if (f === "ppa") sav -= p.ppa*Math.pow(1+p.ppaesc, y-1)*sum(prod);
if (y === 1) { exp1 = r.exp; yr1 = sav; after1 = sum(r.b)+(f === "ppa" ? p.ppa*sum(prod) : 0); }
expRev25 += r.exp*EXPORT;
cf.push(sav); if (pay === null && sav > 0 && cum+sav >= 0) pay = y-1+(-cum)/sav; cum += sav; cumBy.push(cum);
}
if (pay !== null && pay < 0) pay = 0;
const npv = r => cf.reduce((a, c, i) => a+c/Math.pow(1+r, i), 0);
let irr = null;
if (cost > 200) { // bisection between -90% and +100% a year
let lo = -0.9, hi = 1;
if (npv(lo) > 0 && npv(hi) < 0) { for (let i = 0; i < 200; i++) { const mid = (lo+hi)/2; npv(mid) > 0 ? lo = mid : hi = mid; } irr = lo; }
else if (npv(hi) >= 0) irr = hi;
}
return {cost, base, after1, yr1, pay, net25: sum(cf), roi: cost > 200 ? sum(cf)/cost : null, irr, npv: npv(p.disc), cumBy, exp1, expRev1: exp1*EXPORT, expRev25, selfUse: d.kwh-exp1};
}
function verdict(r, f, p) {
if (f === "ppa") { if (r.yr1 > 0 && r.npv > 0) return ["Go","g","saves from year 1"]; if (r.npv > 0) return ["Go if you stay","y","costs more at first, gains later"]; return ["No-go","r","costs more than it saves"]; }
if (r.pay === null || r.pay > 25) return ["No-go","r","never pays back in 25 years"];
if (r.pay <= p.yrs && r.irr !== null && r.irr >= p.disc) return ["Go","g","pays back in "+r.pay.toFixed(1)+" yr, inside the "+p.yrs+" yr you expect to stay"];
if (r.irr !== null && r.irr >= p.disc) return ["Go if you stay","y","pays back in "+r.pay.toFixed(1)+" yr, after the "+p.yrs+" yr you expect to stay"];
return ["No-go","r","return "+(r.irr === null ? "n/a" : (100*r.irr).toFixed(1)+"%")+" is below your "+(100*p.disc).toFixed(1)+"%"];
}
const money = v => (v < 0 ? "−$" : "$")+Math.abs(Math.round(v)).toLocaleString("en-US");
const fmtK = v => Math.round(v).toLocaleString("en-US");
const pillOf = v => `<span class="pill ${v[1] === "g" ? "ok" : v[1] === "y" ? "warn" : "bad"}">${v[0]}</span>`;
const api = {MONTHS, USE, UT, DES, FIN, DEF, COL, run, verdict, money, sizeF, billNow, prodOf, billDG, EXPORT, DEMAND, PW_COST, PW_CUT_S, PW_CUT_W};
root.SGOE = api;
if (typeof document === "undefined") return; // Node: model only
const $ = id => document.getElementById(id);
const IDS = {price:"ev-price", pre:"ev-pre", ppa:"ev-ppa", ppaesc:"ev-ppaesc", esc:"ev-esc", ds:"ev-ds", dw:"ev-dw", yrs:"ev-yrs", disc:"ev-disc", deg:"ev-deg"};
const P = () => ({price: num($("ev-price").value, 0.5, 6, DEF.price), pre: num($("ev-pre").value, 0, 80, DEF.pre)/100,
ppa: num($("ev-ppa").value, 0, 0.5, DEF.ppa), ppaesc: num($("ev-ppaesc").value, 0, 10, DEF.ppaesc)/100,
esc: num($("ev-esc").value, -5, 15, DEF.esc)/100, ds: num($("ev-ds").value, 0, 30, DEF.ds), dw: num($("ev-dw").value, 0, 30, DEF.dw),
yrs: Math.round(num($("ev-yrs").value, 1, 25, DEF.yrs)), disc: num($("ev-disc").value, 0, 20, DEF.disc)/100,
deg: num($("ev-deg").value, 0, 3, DEF.deg)/100, pw: $("ev-pw").checked});
let FSEL = "cash", DSEL = "E", PICK = "E";
function render() {
const p = P();
const R = {}; DES.forEach(d => { R[d.k] = {}; FIN.forEach(f => R[d.k][f.k] = run(d, f.k, p)); });
// matrix
let h = "<tr><th></th>"+FIN.map(f => `<th scope="col">${f.short}</th>`).join("")+"</tr>";
DES.forEach(d => { h += `<tr><td class="rowh">${d.label}<br><small>${d.n} panels · ${d.kw} kW</small></td>`;
FIN.forEach(f => { const r = R[d.k][f.k], v = verdict(r, f.k, p);
const line = f.k === "ppa" ? `yr 1 ${money(r.yr1)} · 25 yr ${money(r.net25)}` : `${r.pay === null ? "> 25" : r.pay.toFixed(1)} yr · ROI ${r.roi === null ? "–" : Math.round(100*r.roi)+"%"}`;
h += `<td class="c${v[1]}${d.k === DSEL && f.k === FSEL ? " sel" : ""}" data-d="${d.k}" data-f="${f.k}" tabindex="0" role="button" aria-label="${d.label}, ${f.short}: ${v[0]}"><b>${v[0]}</b>${line}</td>`; });
h += "</tr>"; });
$("ev-mx").innerHTML = h;
$("ev-mx").querySelectorAll("td[data-d]").forEach(td => { const go = () => { DSEL = td.dataset.d; FSEL = td.dataset.f; PICK = DSEL; render(); };
td.addEventListener("click", go); td.addEventListener("keydown", e => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } }); });
// hero
const cand = []; DES.forEach(d => ["cash","prepaid","ppa"].forEach(f => cand.push({d, f, r: R[d.k][f]})));
const best = cand.reduce((a, b) => b.r.npv > a.r.npv ? b : a);
const sd = DES.find(x => x.k === DSEL), sr = R[DSEL][FSEL], v = verdict(sr, FSEL, p);
const fname = FIN.find(x => x.k === FSEL).name, fshort = FIN.find(x => x.k === FSEL).short;
$("ev-badge").className = "big "+v[1]; $("ev-badge").innerHTML = `${v[0]}<small>${sd.k} · ${fshort}</small>`;
$("ev-title").textContent = `${sd.label}: ${sd.n} panels, ${sd.kw} kW, ${fname}`;
const ec = R.E.cash, ep = R.E.prepaid;
const pay = r => r.pay === null ? "over 25 yr" : r.pay.toFixed(1)+" yr";
$("ev-why").innerHTML = `${v[2].charAt(0).toUpperCase()+v[2].slice(1)}. Best value today: <b>${best.d.label}, ${FIN.find(x => x.k === best.f).short}</b> (NPV ${money(best.r.npv)}). The bill-sized design E for cash: ${money(ec.cost)}, payback ${pay(ec)}, ROI ${ec.roi === null ? "–" : Math.round(100*ec.roi)+"%"}. The same panels as a prepaid lease (the installer keeps the 30% credit and lowers the price): ${money(ep.cost)}, payback ${pay(ep)}, if it is running by Dec 31, 2027.`;
const k = [[money(sr.cost),"up-front"],[money(sr.base)+" → "+money(sr.after1),"yearly bill, now → year 1"],[money(sr.yr1),"year-1 saving"],
[FSEL === "ppa" ? "none" : pay(sr),"payback"],[sr.roi === null ? "n/a" : Math.round(100*sr.roi)+"%","ROI, 25 yr"],
[sr.irr === null ? "n/a" : (100*sr.irr).toFixed(1)+"%","IRR"],[money(sr.net25),"25-yr net"],[money(sr.expRev1)+"/yr","sold back ("+fmtK(sr.exp1)+" kWh)"]];
$("ev-kpis").innerHTML = k.map(x => `<div class="kpi"><b>${x[0]}</b><span>${x[1]}</span></div>`).join("");
$("ev-rule").textContent = `Rule: Go if payback is within the ${p.yrs} years you expect to stay and the return beats your ${(100*p.disc).toFixed(1)}% discount rate; "Go if you stay" if the return is good but payback comes later; No-go otherwise. A PPA is Go if it saves from year 1 and over its life.`;
// financing buttons + chart
$("ev-fin").innerHTML = FIN.map(f => `<button type="button" data-f="${f.k}" class="${f.k === FSEL ? "on" : ""}" aria-pressed="${f.k === FSEL}">${f.short}</button>`).join("");
$("ev-fin").querySelectorAll("button").forEach(b => b.addEventListener("click", () => { FSEL = b.dataset.f; render(); }));
["ev-fin-name","ev-fin-name2","ev-fin-name3"].forEach(id => $(id).textContent = fname);
chart(R, p);
// sold back
let e = "<thead><tr><th>Design</th><th>Made kWh/yr</th><th>Used at home</th><th>Sold back kWh/yr</th><th>Sold-back revenue yr 1</th><th>Over 25 yr</th><th>Same kWh used at home would save</th></tr></thead><tbody>";
DES.forEach(d => { const x = R[d.k].cash; e += `<tr${d.k === "E" ? ' class="rec"' : ""}><td><b>${d.label}</b></td><td>${fmtK(d.kwh)}</td><td>${fmtK(x.selfUse)} (${Math.round(100*x.selfUse/UT)}% of use)</td><td>${fmtK(x.exp1)}</td><td>${money(x.expRev1)}</td><td>${money(x.expRev25)}</td><td>≈ ${money(x.exp1*0.125)}/yr</td></tr>`; });
$("ev-export").innerHTML = e+"</tbody>";
// full table
let t = "<thead><tr><th>Design</th><th>Up-front</th><th>Bill now → yr 1</th><th>Yr-1 saving</th><th>Payback</th><th>ROI</th><th>IRR</th><th>NPV</th><th>25-yr net</th><th>Sold back yr 1</th><th>Leave at yr "+p.yrs+"</th><th>Verdict</th></tr></thead><tbody>";
DES.forEach(d => { const x = R[d.k][FSEL], vv = verdict(x, FSEL, p); t += `<tr${d.k === DSEL ? ' class="rec"' : ""}><td><b>${d.label}</b> · ${d.n} panels</td><td>${money(x.cost)}</td><td>${money(x.base)} → ${money(x.after1)}</td><td>${money(x.yr1)}</td><td>${FSEL === "ppa" ? "–" : pay(x)}</td><td>${x.roi === null ? "–" : Math.round(100*x.roi)+"%"}</td><td>${x.irr === null ? "–" : (100*x.irr).toFixed(1)+"%"}</td><td>${money(x.npv)}</td><td>${money(x.net25)}</td><td>${money(x.expRev1)}</td><td>${money(x.cumBy[p.yrs])}</td><td>${pillOf(vv)}</td></tr>`; });
$("ev-table").innerHTML = t+"</tbody>";
// months
$("ev-pick").value = PICK;
const d = DES.find(x => x.k === PICK), now = billNow(), pd = prodOf(d.kwh, 1);
const rr = billDG(pd, Math.max(0, p.ds-(p.pw ? PW_CUT_S : 0)), Math.max(0, p.dw-(p.pw ? PW_CUT_W : 0)));
const ppaM = pd.map(x => FSEL === "ppa" ? x*p.ppa : 0);
let m = "<thead><tr><th>Month</th><th>Use kWh</th><th>Solar kWh</th><th>Sold back kWh</th><th>Bill now</th><th>Bill with solar</th>"+(FSEL === "ppa" ? "<th>PPA payment</th>" : "")+"<th>Saving</th></tr></thead><tbody>";
MONTHS.forEach((mm, i) => { const sb = Math.max(0, pd[i]-USE[i]); m += `<tr><td>${mm}</td><td>${fmtK(USE[i])}</td><td>${fmtK(pd[i])}</td><td>${fmtK(sb)}</td><td>${money(now[i])}</td><td>${money(rr.b[i])}</td>${FSEL === "ppa" ? `<td>${money(ppaM[i])}</td>` : ""}<td>${money(now[i]-rr.b[i]-ppaM[i])}</td></tr>`; });
m += `<tr class="tot"><td>Year</td><td>${fmtK(UT)}</td><td>${fmtK(sum(pd))}</td><td>${fmtK(rr.exp)}</td><td>${money(sum(now))}</td><td>${money(sum(rr.b))}</td>${FSEL === "ppa" ? `<td>${money(sum(ppaM))}</td>` : ""}<td>${money(sum(now)-sum(rr.b)-sum(ppaM))}</td></tr>`;
$("ev-months").innerHTML = m+"</tbody>";
// powerwall
const pwSave = DEMAND*(PW_CUT_S*4+PW_CUT_W*8)-15;
$("ev-pwtext").innerHTML = `<p><span class="pill bad">No-go on money</span> El Paso Electric nets solar over the whole month, so moving daytime solar into the evening does not change the kWh billed. The battery's only bill value is trimming the <b>$5.65/kW demand charge</b>: about ${PW_CUT_S} kW in summer and ${PW_CUT_W} kW in winter if set for peak shaving (ASSUMED), about <b>${money(pwSave)}/yr</b> against <b>${money(PW_COST)}</b> installed, a ${Math.round(PW_COST/pwSave)}-year payback, longer than its 10-year warranty. Through a lease the 30% business credit could bring it to about ${money(PW_COST*0.7)}: still a ${Math.round(PW_COST*0.7/pwSave)}-year payback. Buy it for outage backup, not for the bill. Tick "Add one Tesla Powerwall 3" under the assumptions to see it in every cell.</p>`;
cmp(R, p);
if (root.SGOUI && root.SGOUI.onEcon) root.SGOUI.onEcon();
}
function chart(R, p) {
const W = 760, H = 320, L = 66, Rr = 12, T = 14, B = 34;
const series = DES.map(d => ({d, v: R[d.k][FSEL].cumBy}));
let mn = 0, mx = 0; series.forEach(s => s.v.forEach(x => { mn = Math.min(mn, x); mx = Math.max(mx, x); }));
const span = Math.max(1, mx-mn), step = span > 150000 ? 50000 : span > 60000 ? 20000 : span > 20000 ? 10000 : 5000;
mn = Math.floor(mn/step)*step; mx = Math.ceil(mx/step)*step; if (mx === mn) mx = mn+step;
const X = y => L+(W-L-Rr)*y/25, Y = v => T+(H-T-B)*(mx-v)/(mx-mn);
let s = `<svg viewBox="0 0 ${W} ${H}" xmlns="http://www.w3.org/2000/svg" font-family="system-ui,Arial" font-size="11" role="img" aria-label="Cash position over 25 years for each design">`;
for (let v = mn; v <= mx+1e-6; v += step) s += `<line x1="${L}" x2="${W-Rr}" y1="${Y(v).toFixed(1)}" y2="${Y(v).toFixed(1)}" stroke="${v === 0 ? "#24211c" : "#e4dfd4"}" stroke-width="${v === 0 ? 1.4 : 1}"/><text x="${L-6}" y="${(Y(v)+4).toFixed(1)}" text-anchor="end" fill="#6f685b">${money(v)}</text>`;
for (let y = 0; y <= 25; y += 5) s += `<text x="${X(y).toFixed(1)}" y="${H-B+16}" text-anchor="middle" fill="#6f685b">${y}</text>`;
s += `<text x="${(L+W)/2}" y="${H-4}" text-anchor="middle" fill="#6f685b">years after install</text>`;
s += `<line x1="${X(p.yrs).toFixed(1)}" x2="${X(p.yrs).toFixed(1)}" y1="${T}" y2="${H-B}" stroke="#b7791f" stroke-dasharray="5 4" stroke-width="1.5"/><text x="${(X(p.yrs)+(p.yrs > 20 ? -4 : 4)).toFixed(1)}" y="${T+10}" fill="#9a6514" text-anchor="${p.yrs > 20 ? "end" : "start"}">you stay ${p.yrs} yr</text>`;
series.forEach(({d, v}) => { s += `<polyline points="${v.map((x, i) => X(i).toFixed(1)+","+Y(x).toFixed(1)).join(" ")}" fill="none" stroke="${COL[d.k]}" stroke-width="${d.k === DSEL ? 3.2 : 1.8}" opacity="${d.k === DSEL ? 1 : .75}"/>`; });
$("ev-chart").innerHTML = s+"</svg>";
$("ev-leg").innerHTML = DES.map(d => `<span><svg viewBox="0 0 18 6" aria-hidden="true"><line x1="0" x2="18" y1="3" y2="3" stroke="${COL[d.k]}" stroke-width="4"/></svg>${d.label}</span>`).join("");
}
function cmp(R, p) {
const yrs = x => x.toFixed(1)+" yr", pct = x => Math.round(100*x)+"%", ir = x => (100*x).toFixed(1)+"%";
const SITE = k => { const d = DES.find(x => x.k === k);
return {faces: Object.keys(d.per).join(", "), street: `${d.street} / ${d.angle}`, pct: d.pct+"%", ridge: d.ridge > 0.5 ? "36 in (array over 33%)" : "18 in",
clr: (k === "A" || k === "B") ? "0.25 m edges; 18 in hips and valleys" : "6 in edges, hips and valleys", vents: d.vents ? d.vents+" rerouted" : "0",
shade: d.shade.toFixed(0)+"%", panel: (d.ac <= 7.7 ? "Fits" : "Needs a fix")+` (≈${d.ac} kW AC)`, xfmr: d.kw >= 15 ? "Ask the utility first ("+d.kw+" kW)" : d.kw >= 9 ? "Ask the utility" : "Low" }; };
const head = "<thead><tr><th></th>"+DES.map(d => `<th${d.k === "E" ? ' class="recc"' : ""} scope="col">${d.label}</th>`).join("")+"</tr></thead>";
const sec = t => `<tr><td colspan="${DES.length+1}" class="dh">${t}</td></tr>`;
const row = (lab, f) => `<tr><td><b>${lab}</b></td>`+DES.map(d => `<td>${f(d.k)}</td>`).join("")+"</tr>";
const best = (lab, f, fmt, hi) => { const vals = DES.map(d => f(d.k)); const ok = vals.filter(v => v != null); const b = ok.length ? (hi ? Math.max(...ok) : Math.min(...ok)) : null;
return `<tr><td><b>${lab}</b></td>`+vals.map(v => `<td${v === b && v != null ? ' class="bestc"' : ""}>${v == null ? "–" : fmt(v)}</td>`).join("")+"</tr>"; };
let h = head+"<tbody>"+sec("Roof and site");
h += row("Panels · kW DC", k => { const d = DES.find(x => x.k === k); return `${d.n} · ${d.kw}`; });
h += row("Roof faces used", k => SITE(k).faces);
h += row("Facing street / at an angle", k => SITE(k).street);
h += row("Array share of roof (fire code)", k => SITE(k).pct);
h += row("Ridge setback", k => SITE(k).ridge);
h += row("Other clearances", k => SITE(k).clr);
h += row("Roof vents under panels", k => SITE(k).vents);
h += row("Worst shading on a kept panel", k => SITE(k).shade);
h += row("200 A main panel (120% rule)", k => SITE(k).panel);
h += row("Transformer / utility review", k => SITE(k).xfmr);
h += sec("Energy (year 1)");
h += row("Made, kWh/yr", k => fmtK(DES.find(x => x.k === k).kwh));
h += best(`Used at home, % of ${fmtK(UT)} kWh`, k => R[k].cash.selfUse/UT, pct, true);
h += row("Sold back, kWh/yr", k => fmtK(R[k].cash.exp1));
h += row("Sold-back revenue, yr 1 / 25 yr", k => `${money(R[k].cash.expRev1)} / ${money(R[k].cash.expRev25)}`);
h += row("Bill, now → year 1", k => `${money(R[k].cash.base)} → ${money(R[k].cash.after1)}`);
[["cash","Cash today: no credit"],["credit","Cash + 30% credit: only if 25D returns"],["prepaid","Prepaid lease: 48E passed through, running by Dec 31, 2027"]].forEach(([f, t]) => {
h += sec(t);
h += best("Up-front", k => R[k][f].cost, money, false);
h += best("Payback", k => R[k][f].pay, yrs, false);
h += best("ROI, 25 yr", k => R[k][f].roi, pct, true);
h += best("IRR", k => R[k][f].irr, ir, true);
h += best("NPV at "+(100*p.disc).toFixed(1)+"%", k => R[k][f].npv, money, true);
h += row("Verdict", k => pillOf(verdict(R[k][f], f, p))); });
h += sec("PPA: $0 down, $"+p.ppa.toFixed(3)+"/kWh");
h += best("Saving, year 1", k => R[k].ppa.yr1, money, true);
h += best("Net over 25 yr", k => R[k].ppa.net25, money, true);
h += row("Verdict", k => pillOf(verdict(R[k].ppa, "ppa", p)));
$("cmp-table").innerHTML = h+"</tbody>";
}
function costs() {
const C = DES.find(x => x.k === "C"), D = DES.find(x => x.k === "D"), E = DES.find(x => x.k === "E");
$("costRows").innerHTML = [
["El Paso Electric application", "$85 for systems up to 100 kW; the utility fits the two-way meter at no charge", "$85, every design"],
["Transformer / line upgrade", `Texas rule 16 TAC §25.211: no study fee under 20 kW, and the utility must quote any upgrade before work. Unlikely for E (${E.kw} kW); ask first for C and D (${D.kw} kW).`, "$0 (flagged for C and D)"],
["Main panel: NEC 705.12, 120% rule", `A 200 A panel with a 200 A main takes 40 A of solar backfeed (≈ 7.7 kW AC). E ≈ ${E.ac} kW AC fits; C (≈ ${C.ac} kW AC) and D need a supply-side tap, a smaller main or a panel upgrade.`, "$2,150 for C and D"],
["Vent rerouting", `Only design D covers roof vents (${D.vents})`, "$1,500 for D (ASSUMED)"],
["City permit", "$200 residential submittal deposit, credited to the permit fee", "Inside the $/W price"],
["Microinverters", "Needed where panels see some shade; 25-year warranties, so no inverter replacement modelled", "Inside the $/W price"]
].map(r => `<tr><td><b>${r[0]}</b></td><td>${r[1]}</td><td>${r[2]}</td></tr>`).join("");
}
function init() {
const sel = $("ev-pick");
DES.forEach(d => { const o = document.createElement("option"); o.value = d.k; o.textContent = d.label; sel.appendChild(o); });
sel.addEventListener("change", () => { PICK = sel.value; render(); });
document.querySelectorAll(".ecin input").forEach(e => e.addEventListener("input", render));
$("ev-reset").addEventListener("click", () => { Object.keys(IDS).forEach(k => $(IDS[k]).value = DEF[k]); $("ev-pw").checked = false; render(); });
costs(); render();
}
api.select = (d, f) => { if (d) { DSEL = d; PICK = d; } if (f) FSEL = f; render(); };
api.render = () => render();
api.state = () => ({DSEL, FSEL});
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
})(typeof window !== "undefined" ? window : globalThis);
sgo.js (tabs, plan, 3D view, module list, checks, tour)173 lines
/* Solar Go/No-Go: tabs, roof views (plan, 3D, tables), checks and the "Show me how" tour. */
(function () {
'use strict';
const S = window.SGO, E = window.SGOE;
const $ = id => document.getElementById(id);
const esc = t => String(t).replace(/[&<>"]/g, c => ({"&":"&","<":"<",">":">",'"':"""}[c]));
const DIR = {180: "South", 90: "East (street)", 270: "West (rear)", 0: "North"};
const NAMES = Object.fromEntries(S.designs.map(d => [d.k, d.name]));
let design = "E";
/* ---------- tabs ---------- */
const tabs = [...document.querySelectorAll("#tabs button")];
function show(t, push) {
if (!$(t)) return;
tabs.forEach(b => b.setAttribute("aria-selected", b.dataset.t === t ? "true" : "false"));
document.querySelectorAll("section.tab").forEach(s => s.classList.toggle("on", s.id === t));
if (t === "roof") draw();
if (push) {
try { history.replaceState(null, "", "#" + t); } catch (e) { /* sandboxed */ }
const nav = document.querySelector("nav.tabs"), top = nav.getBoundingClientRect().top + window.scrollY;
if (Math.abs(window.scrollY - top) > 2) window.scrollTo(0, top);
}
}
tabs.forEach(b => b.addEventListener("click", () => show(b.dataset.t, true)));
document.getElementById("tabs").addEventListener("keydown", e => {
const i = tabs.findIndex(b => b.getAttribute("aria-selected") === "true");
if (e.key === "ArrowRight" || e.key === "ArrowLeft") { const n = tabs[(i + (e.key === "ArrowRight" ? 1 : tabs.length - 1)) % tabs.length]; show(n.dataset.t, true); n.focus(); }
});
/* ---------- roof: design switch ---------- */
const dseg = $("dseg");
dseg.innerHTML = S.designs.map(d => `<button type="button" data-v="${d.k}" aria-pressed="${d.k === design}">${d.k} · ${esc(d.name)} · ${d.n}</button>`).join("");
dseg.querySelectorAll("button").forEach(b => b.addEventListener("click", () => setDesign(b.dataset.v)));
function setDesign(k) {
design = k;
dseg.querySelectorAll("button").forEach(b => b.setAttribute("aria-pressed", b.dataset.v === k ? "true" : "false"));
const d = S.designs.find(x => x.k === k);
$("planImg").src = "./plan-" + k + ".svg"; $("planImg").alt = "Roof plan from above, design " + k + " (" + d.name + "), " + d.n + " panels";
$("dnote").innerHTML = `<b>${k} · ${esc(d.name)}</b>: ${d.n} panels, ${d.kw} kW, about ${d.kwh.toLocaleString("en-US")} kWh a year. ${esc(d.rule)}. ${d.street} panels face the street, ${d.angle} are seen from it at an angle.`;
$("lsName").textContent = k + " · " + d.name;
modTable(); draw();
}
function faceTable() {
const ks = S.designs.map(d => d.k);
let h = "<thead><tr><th>Face</th><th>Description</th><th>Faces</th>" + ks.map(k => `<th>${k}</th>`).join("") + "</tr></thead><tbody>";
Object.entries(S.faces).forEach(([id, f]) => { h += `<tr><td><b>${id}</b></td><td>${esc(f.desc)}${f.free ? " (kept free)" : ""}</td><td>${DIR[f.az]}</td>` + S.designs.map(d => `<td>${d.per[id] || 0}</td>`).join("") + "</tr>"; });
h += `<tr class="tot"><td colspan="3">Total</td>` + S.designs.map(d => `<td>${d.n} · ${d.kw} kW</td>`).join("") + "</tr></tbody>";
$("faceTable").innerHTML = h;
}
const HEAD = ["ID","Face","Orient.","Long side °","East m","North m","Height m","Pitch °","Azimuth °","Pitch","Height","Outline","Size mm","W","Street","Shade %"];
function modTable() {
const rows = S.csv[design].trim().split("\n").slice(1).map(r => r.split(","));
$("modTable").innerHTML = "<thead><tr>" + HEAD.map(h => `<th>${h}</th>`).join("") + "</tr></thead><tbody>" +
rows.map(r => "<tr>" + r.map(c => `<td>${esc(c === "" ? "–" : c)}</td>`).join("") + "</tr>").join("") + "</tbody>";
}
$("copyCsv").addEventListener("click", async () => {
try { await navigator.clipboard.writeText(S.csv[design]); $("copied").textContent = "Copied design " + design + "."; }
catch (e) { $("copied").textContent = "Copy was blocked: select the table and copy it instead."; }
});
/* ---------- 3D (painter's algorithm on a 2D canvas) ---------- */
const cv = $("cv"), cx = cv.getContext("2d"), B = S.scene.body;
let yaw = -0.75, pit = 0.5;
const CAMS = {street: [-1.5, 0.32], south: [0.15, 0.42], rear: [1.65, 0.45], top: [0, 1.5]};
document.querySelectorAll("[data-cam]").forEach(b => b.addEventListener("click", () => { [yaw, pit] = CAMS[b.dataset.cam]; draw(); }));
const WALL = [236, 232, 224];
function walls(poly, h0, h1, closed) { const o = []; const n = closed ? poly.length : poly.length - 1;
for (let i = 0; i < n; i++) { const a = poly[i], b = poly[(i + 1) % poly.length]; o.push({p: [[a[0], a[1], h0], [b[0], b[1], h0], [b[0], b[1], h1], [a[0], a[1], h1]], c: WALL}); } return o; }
function build(k) {
let P = [{p: B.ground, c: [226, 214, 190], g: 1}, {p: B.street, c: [200, 198, 192], g: 1}];
B.walls.forEach(w => { P = P.concat(walls(w.poly, w.h0, w.h1, w.closed)); });
B.flats.forEach(f => P.push({p: f, c: [150, 132, 116]}));
B.tris.forEach(t => P.push({p: t, c: WALL}));
S.scene.designs[k].faces.forEach(f => P.push({p: f.pts, c: [112, 94, 82], roof: 1}));
S.scene.designs[k].mods.forEach(m => P.push({p: m.c, c: [28, 36, 50], mod: 1}));
return P;
}
function draw() {
if (!cv.offsetParent) return;
const W = cv.width, H = cv.height; cx.clearRect(0, 0, W, H);
const cy_ = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(pit), sp = Math.sin(pit), C = B.centre;
const pr = q => { const x = q[0] - C[0], y = q[1] - C[1], z = q[2] - C[2]; const X = x * cy_ - y * sy, Y = x * sy + y * cy_; return [X, Y * sp + z * cp, Y * cp - z * sp]; };
const s = Math.min(W, H) / 26, ox = W / 2, oy = H * 0.56, L = [-0.4, -0.5, 0.77];
const polys = build(design).map(o => { const pp = o.p.map(pr); let dep = pp.reduce((a, b) => a + b[2], 0) / pp.length; if (o.mod) dep -= 0.15; if (o.roof) dep -= 0.02; if (o.g) dep = 1e9; return Object.assign({}, o, {pp, dep}); });
polys.sort((a, b) => b.dep - a.dep);
for (const o of polys) {
const a = o.p[0], b = o.p[1], c = o.p[2], u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; const nl = Math.hypot(n[0], n[1], n[2]) || 1; n = n.map(x => x / nl);
const lam = 0.62 + 0.38 * Math.abs(n[0] * L[0] + n[1] * L[1] + n[2] * L[2]);
cx.beginPath(); o.pp.forEach((q, i) => { const X = ox + q[0] * s, Y = oy - q[1] * s; i ? cx.lineTo(X, Y) : cx.moveTo(X, Y); }); cx.closePath();
cx.fillStyle = `rgb(${o.c.map(x => Math.round(x * lam)).join(",")})`; cx.fill();
cx.strokeStyle = o.mod ? "#8d99a8" : "rgba(60,50,40,.35)"; cx.lineWidth = o.mod ? 1 : 0.7; cx.stroke();
}
const fs = Math.round(Math.min(40, 15 * W / Math.max(1, cv.clientWidth)));
cx.fillStyle = "#4a443a"; cx.font = `600 ${fs}px system-ui,sans-serif`; cx.textAlign = "center";
const st = pr(B.street_label); cx.fillText("Street", ox + st[0] * s, oy - st[1] * s);
const nx = B.ground.reduce((a, q) => Math.min(a, q[0]), 1e9) + 1.5, n1 = pr([nx, -4.5, 0]), n2 = pr([nx, -2, 0]);
cx.strokeStyle = "#24211c"; cx.lineWidth = Math.max(2, fs / 7); cx.beginPath(); cx.moveTo(ox + n1[0] * s, oy - n1[1] * s); cx.lineTo(ox + n2[0] * s, oy - n2[1] * s); cx.stroke();
cx.fillStyle = "#24211c"; cx.fillText("N", ox + n2[0] * s + (n2[0] >= n1[0] ? 10 : -10), oy - n2[1] * s - fs * 0.4);
}
let drag = null;
cv.addEventListener("pointerdown", e => { drag = [e.clientX, e.clientY, yaw, pit]; try { cv.setPointerCapture(e.pointerId); } catch (x) { /* ok */ } });
cv.addEventListener("pointermove", e => { if (!drag) return; yaw = drag[2] - (e.clientX - drag[0]) * 0.008; pit = Math.max(0.05, Math.min(1.5, drag[3] + (e.clientY - drag[1]) * 0.006)); draw(); });
["pointerup", "pointercancel", "lostpointercapture"].forEach(t => cv.addEventListener(t, () => { drag = null; }));
/* ---------- checks ---------- */
function checks() {
const Q = S.qc, ds = S.designs, by = k => ds.find(d => d.k === k);
const rows = [
["Confirmed", `Counts re-derived from each module list: ${ds.map(d => `${d.k} = ${d.n}`).join(", ")}. kW = panels × 0.43. Plans, 3D, tables and money all read the same files.`, ""],
["Confirmed", `Every module rebuilt from its centre, long-side bearing, orientation, pitch and azimuth by separate code: ${Q.overlaps} overlaps, ${Q.edges} edge-clearance misses, ${Q.strips} modules in a pathway strip, smallest gap ${Q.gap.toFixed(2)} m.`, ""],
["Confirmed", `Heights: every module corner sits on its roof plane (worst ${Q.height.toFixed(3)} m off, limit 0.05 m). Rows square to the eave (worst ${Q.square}°, limit 2°).`, ""],
["Confirmed", `Fire access (2021 IRC R324.6): array share of the ${S.roof_m2} m² plan roof: ${ds.map(d => `${d.k} ${d.pct}%`).join(", ")}. D is over 33%, so its ridge setback is 36 in. A, B, C and E keep the street hip and the north slope empty as pathways.`, ""],
["Confirmed", `Shading: spots that lose over 20% of a year's direct sun are left empty (${ds.map(d => `${d.k} ${S.dropped[d.k]}`).join(", ")} dropped). The worst kept panel loses ${Math.max(...ds.map(d => d.shade)).toFixed(0)}%, on the lower rear roof in the morning shadow of the wing.`, ""],
["Issue", `Design D covers ${by("D").vents} roof vents. It only works if a roofer reroutes or combines them under the array.`, "Price vent work in the quote, or use C."],
["Issue", `C (≈ ${by("C").ac} kW AC) and D (≈ ${by("D").ac} kW AC) are over what a 200 A panel with a 200 A main can take (≈ 7.7 kW AC, 120% rule).`, "Supply-side tap, smaller main or panel upgrade; priced at $2,150."],
["Issue", "C, D and E use 6 in at eaves, rakes, hips and valleys. The 2021 IRC asks for 18 in only at ridges plus the 36 in pathways; some reviewers still ask for 18 in along hips and valleys.", "Ask the counter; A keeps 18 in everywhere."],
["Blocker", "Pitch 5:12 and eave heights are assumed for the sample house; on a real house they are measured.", "Measure on site or get the installer's survey."],
["Blocker", "No electrical single-line, conductor sizing or structural attachment design: no city issues a permit without them.", "Installer or a Texas PE supplies them."],
["Can't verify", "The 60-minute peak demand (5 kW summer, 3.5 kW winter) drives the solar demand charge and is assumed.", "Read the real figure from the utility's interval data."]
];
const cls = {"Confirmed": "ok", "Issue": "warn", "Blocker": "bad", "Can't verify": "warn"};
$("qcTable").innerHTML = "<thead><tr><th>Result</th><th>Evidence</th><th>Fix</th></tr></thead><tbody>" + rows.map(r => `<tr><td><span class="pill ${cls[r[0]]}">${r[0]}</span></td><td>${esc(r[1])}</td><td>${esc(r[2] || "–")}</td></tr>`).join("") + "</tbody>";
$("roofM2").textContent = S.roof_m2;
const tot = S.use.reduce((a, b) => a + b, 0);
$("useRow").textContent = "Dec–Nov: " + S.use.map(x => x.toLocaleString("en-US")).join(" · ") + " = " + tot.toLocaleString("en-US") + " kWh";
}
/* ---------- tour ---------- */
const STEPS = [
{tab: "decision", el: "heroPanel", h: "The answer first", p: "This is the verdict for the cell picked below: Go, Go if you stay, or No-go, with the money behind it. It starts on design E, sized to the house's use, paid in cash."},
{tab: "decision", el: "mxPanel", h: "Every size, every way to pay", p: "Five roof layouts down the side, four ways to pay across the top. Tap any cell to open it in the verdict above. Green pays back while you live there; red never does."},
{tab: "decision", el: "asmPanel", h: "Make it yours", p: "Change the price per watt, how long you will stay, the demand you pull, or add a battery. Every cell, chart and table recalculates. Reset brings back the dated values.", open: true},
{tab: "roof", el: "planPanel", h: "Where the panels go", p: "Pick a design above the plan. Red dashes are setbacks measured on the slope, hatched areas are fire pathways, circles are vents. The 3D view and module list below follow the same pick."},
{tab: "money", el: "soldPanel", h: "Why bigger is not better here", p: "El Paso Electric buys extra power at about 1.6¢ a kWh, while a kWh used at home saves about 13¢. Panels past the house's use mostly sell cheap, so the last panels in C and D earn little."},
{tab: "checks", el: "qcPanel", h: "What a reviewer will ask", p: "Geometry checks run on every module with separate code. The blockers list what a real house still needs before filing: measured pitches and the electrical and structural sheets."}
];
let ti = -1, lit = null;
function tourGo(i) {
if (lit) lit.classList.remove("tour-lit");
if (i < 0 || i >= STEPS.length) { ti = -1; $("tour").hidden = true; lit = null; return; }
ti = i; const st = STEPS[i]; show(st.tab, false);
if (st.open) $("asm").open = true;
lit = $(st.el); lit.classList.add("tour-lit");
$("tourH").textContent = st.h; $("tourP").textContent = st.p; $("tourN").textContent = `${i + 1} of ${STEPS.length}`;
$("tourBack").disabled = i === 0; $("tourNext").textContent = i === STEPS.length - 1 ? "Done" : "Next";
$("tour").hidden = false;
const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
lit.scrollIntoView({block: "start", behavior: reduce ? "auto" : "smooth"});
requestAnimationFrame(place); setTimeout(place, 450);
}
function place() {
if (!lit) return; const r = lit.getBoundingClientRect(), t = $("tour"), vh = window.innerHeight;
t.classList.remove("up");
const tr = t.getBoundingClientRect();
if (r.top < vh * 0.4 && r.bottom > tr.top) { /* card would cover the lit part: keep it at the bottom only if the top is visible */ }
if (r.top > tr.height + 30 && r.top > vh * 0.45) t.classList.add("up");
}
$("tourBtn").addEventListener("click", () => tourGo(0));
$("tourNext").addEventListener("click", () => tourGo(ti + 1));
$("tourBack").addEventListener("click", () => tourGo(ti - 1));
$("tourEnd").addEventListener("click", () => tourGo(-1));
document.addEventListener("keydown", e => { if (ti >= 0 && e.key === "Escape") tourGo(-1); });
window.addEventListener("resize", () => { place(); draw(); });
/* ---------- start ---------- */
faceTable(); setDesign("E"); checks();
const h = (location.hash || "").slice(1);
if (h && $(h) && $(h).classList.contains("tab")) show(h, false);
if (/[?&]tour=1/.test(location.search)) tourGo(0);
window.SGOUI = {show, setDesign, tourGo, draw};
})();
sgo.css (layout)111 lines
/* Solar Go/No-Go: layout and look. Light only; plans and charts are drawn on a light background. */
:root{--ink:#24211c;--mut:#6f685b;--bg:#f7f5f0;--card:#fff;--line:#e4dfd4;--acc:#c7462f;--ok:#2f7d4f;--warn:#b7791f;--dark:#1f2a38;--soft:#faf8f3;color-scheme:light}
*{box-sizing:border-box}[hidden]{display:none!important}
html{-webkit-text-size-adjust:100%}
body{margin:0;font-family:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;color:var(--ink);background:var(--bg);line-height:1.5;font-size:15px;overflow-x:hidden}
a{color:#1f5fa8}
h1,h2{font-family:Georgia,"Times New Roman",serif;font-weight:700}
h1{font-size:clamp(26px,5vw,38px);margin:4px 0 6px;line-height:1.12}
h2{font-size:21px;margin:0 0 10px;line-height:1.25}
h3{font-size:15px;margin:16px 0 6px}
.wrap{max-width:1120px;margin:auto;padding:0 16px}
header.mast{padding:22px 0 10px}
.mrow{display:flex;gap:14px;align-items:flex-start;justify-content:space-between;flex-wrap:wrap}
.eyebrow,.kick{font-size:12px;letter-spacing:.1em;text-transform:uppercase;color:var(--acc);font-weight:700}
.sub{color:var(--mut);margin:0;max-width:760px}
.mastbtns{display:flex;gap:8px;flex-wrap:wrap}
.btn{display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--line);background:#fff;color:var(--ink);border-radius:9px;padding:8px 14px;font:600 14px system-ui,sans-serif;cursor:pointer;text-decoration:none;min-height:40px}
.btn.pri{background:var(--ink);color:#fff;border-color:var(--ink)}
.btn:focus-visible,button:focus-visible,summary:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #1f5fa8;outline-offset:2px}
.banner{background:#fff4e8;border:1px solid #f0d2b2;border-radius:10px;padding:10px 14px;margin-top:14px;font-size:13.5px}
nav.tabs{position:sticky;top:0;z-index:20;background:rgba(247,245,240,.97);border-bottom:1px solid var(--line);margin-top:14px}
nav.tabs .in{max-width:1120px;margin:auto;display:flex;gap:4px;overflow-x:auto;padding:8px 12px;scrollbar-width:none}
nav.tabs .in::-webkit-scrollbar{display:none}
nav.tabs button{border:0;background:none;padding:8px 14px;border-radius:999px;font:600 14px system-ui,sans-serif;color:var(--mut);white-space:nowrap;cursor:pointer;min-height:38px}
nav.tabs button[aria-selected=true]{background:var(--ink);color:#fff}
main{padding:16px 0 30px}
section.tab{display:none}section.tab.on{display:block}
.panel{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:16px;margin-bottom:14px;min-width:0}
.scroll{overflow-x:auto;-webkit-overflow-scrolling:touch}
.note{font-size:12.5px;color:var(--mut)}
.note.top{margin-top:0}
table{border-collapse:collapse;width:100%;font-size:13px}
th,td{border-bottom:1px solid var(--line);padding:6px 8px;text-align:left;vertical-align:top}
th{font-weight:600;color:var(--mut);font-size:12px}
tr.tot td{font-weight:700}
tr.rec td{background:#f1f7f2}
th.recc{background:#f1f7f2}
td.bestc{background:#e3f1e8;font-weight:700}
td.dh{background:#f3efe6;font-weight:700;font-size:12px;letter-spacing:.06em;text-transform:uppercase}
table.wide td,table.wide th{white-space:nowrap}
table.dt td:first-child{font-weight:600;min-width:120px}
.pill{display:inline-block;padding:1px 8px;border-radius:999px;font-size:12px;font-weight:600;white-space:nowrap}
.pill.ok{background:#e3f1e8;color:var(--ok)}.pill.bad{background:#fbe5e0;color:#a33a26}.pill.warn{background:#fbefd9;color:#7a4f12}
/* decision */
.hero{display:grid;grid-template-columns:auto 1fr;gap:16px;align-items:center}
.big{font:700 30px/1 Georgia,serif;padding:14px 18px;border-radius:14px;color:#fff;text-align:center;min-width:130px}
.big small{display:block;font:600 11px system-ui,sans-serif;letter-spacing:.06em;text-transform:uppercase;opacity:.9;margin-top:6px}
.big.g{background:#2f7d4f}.big.y{background:#9a6514}.big.r{background:#b53d28}
#ev-title{margin:0 0 4px}#ev-why{margin:0}
.kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(118px,1fr));gap:8px;margin-top:12px}
.kpi{background:var(--soft);border:1px solid var(--line);border-radius:10px;padding:8px 10px;min-width:0}
.kpi b{display:block;font-size:18px;overflow-wrap:anywhere}
.kpi span{font-size:11.5px;color:var(--mut)}
table.mx{border-collapse:separate;border-spacing:4px;font-size:12.5px;min-width:560px}
table.mx th{text-align:center;font-size:11.5px;vertical-align:bottom;border:0}
table.mx td{border:0;border-radius:8px;text-align:center;padding:7px 6px;line-height:1.3}
table.mx td.rowh{text-align:left;background:none;font-weight:600}
table.mx td[data-d]{cursor:pointer}
td.cg{background:#e3f1e8;color:#1f5a38}td.cy{background:#fbefd9;color:#7a4f12}td.cr{background:#fbe5e0;color:#8f2f1d}
td.cg b,td.cy b,td.cr b{display:block;font-size:13px}
td.sel{outline:2px solid var(--ink)}
.seg2{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0 10px}
.seg2 button,.seg button{border:1px solid var(--line);background:#fff;border-radius:999px;padding:6px 13px;font:600 13px system-ui,sans-serif;cursor:pointer;color:var(--ink);min-height:36px}
.seg2 button.on,.seg button[aria-pressed=true]{background:var(--ink);color:#fff;border-color:var(--ink)}
.seg{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px}
.ecin{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:10px;margin-top:10px}
.ecin label{display:flex;flex-direction:column;font-size:12px;color:var(--mut);gap:4px}
.ecin input[type=number]{font:600 16px system-ui,sans-serif;padding:7px 9px;border:1px solid var(--line);border-radius:8px;color:var(--ink);background:#fff;width:100%}
.ecin small{font-size:10.5px}
.ecin label.chk{flex-direction:row;align-items:center;gap:8px;font-size:14px;color:var(--ink);font-weight:600}
.ecin label.chk input{width:20px;height:20px}
details summary{cursor:pointer;font-weight:700;font-size:16px;min-height:32px}
.chart svg{width:100%;height:auto;display:block}
.leg{display:flex;flex-wrap:wrap;gap:4px 14px;margin-top:6px;font-size:12.5px}
.leg span{display:inline-flex;align-items:center;gap:6px}
.leg svg{width:18px;height:6px}
select{font:600 14px system-ui,sans-serif;padding:4px 6px;border-radius:6px;border:1px solid var(--line);background:#fff;color:var(--ink);max-width:100%}
ul.src{padding-left:18px;font-size:13px}ul.src li{margin:4px 0;overflow-wrap:anywhere}
/* roof */
.plan img{width:100%;height:auto;display:block;border-radius:8px}
.grid2{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,340px),1fr));gap:14px}
canvas{width:100%;height:auto;display:block;background:linear-gradient(#eef3f7,#f7f5f0);border-radius:10px;touch-action:none;cursor:grab}
.btns{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0}
.btns .btn{min-height:36px;padding:6px 12px;font-size:13px}
table.mods td,table.mods th{white-space:nowrap}
ul.chk{padding-left:0;list-style:none;margin:0}ul.chk li{padding:7px 0 7px 30px;border-bottom:1px solid var(--line);position:relative}
ul.chk li::before{content:"";position:absolute;left:4px;top:11px;width:14px;height:14px;border:2px solid var(--mut);border-radius:4px}
ul.steps{padding-left:20px}ul.steps li{margin:6px 0}
footer.foot{padding:6px 0 40px;font-size:12px;color:var(--mut)}
/* tour */
.tour-lit{position:relative;z-index:41;box-shadow:0 0 0 4px #f0b43c,0 0 0 9999px rgba(20,18,14,.45);border-radius:12px}
#tour{position:fixed;z-index:60;left:50%;bottom:16px;transform:translateX(-50%);width:min(440px,calc(100vw - 24px));background:#fff;border:1px solid var(--line);border-radius:14px;box-shadow:0 12px 40px rgba(0,0,0,.25);padding:14px 16px}
#tour.up{bottom:auto;top:12px}
#tour h3{margin:0 0 4px;font-size:16px}
#tour p{margin:0 0 10px;font-size:14px}
#tour .tb{display:flex;gap:8px;justify-content:space-between;align-items:center}
#tour .tb span{font-size:12px;color:var(--mut)}
#tour .tb div{display:flex;gap:6px}
@media(max-width:560px){
.hero{grid-template-columns:1fr}.big{font-size:26px}
body{font-size:14.5px}
.panel{padding:12px}
header.mast{padding-top:14px}
}
@media(max-height:460px) and (orientation:landscape){
nav.tabs{position:static}
#tour{left:auto;right:10px;transform:none;width:min(360px,46vw);bottom:10px}
#tour.up{top:10px}
}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}}
model.py (the invented roof, setbacks, packing, five designs)255 lines
"""Roof model + module layout for an INVENTED sample house in El Paso, TX (no real address).
Local grid in metres: x = east, y = north, origin = west end of the house's south eave line.
Two-storey cross-hip roof with a south gable wing, one-storey rear roof and garage roof.
Pitch and heights are ASSUMED. Street to the east.
"""
import math, json, csv
from shapely.geometry import Polygon, LineString, box, Point
from shapely import affinity
PITCH = 22.6 # deg, 5:12 ASSUMED
TANP = math.tan(math.radians(PITCH)); COSP = math.cos(math.radians(PITCH))
UPPER_EAVE_H = 5.8 # m ASSUMED (2-storey plate + overhang)
LOWER_EAVE_H = 2.9 # m ASSUMED (1-storey)
MOD_L, MOD_W, MOD_P = 1.722, 1.134, 430 # ASSUMED residential all-black module
GAP = 0.05
CLEAR = {"eave": 0.25, "rake": 0.25, "wall": 0.25, "hip": 0.46, "valley": 0.46, "ridge": 0.46}
VENT_CLEAR = 0.35; VENT_R = 0.05
# ---- roof faces (plan polygons, CCW not required). each edge typed.
# az = downhill azimuth (0 = north, 90 = east, 180 = south, 270 = west)
FACES = {
# upper roof: E-W block x 3.2..17.2, y 4.3..11.5, ridge y 7.9; south wing x 5.8..13.0 ridge x 9.4 gable at y 0
"U-S1": dict(desc="Upper roof, south slope east of wing", az=180, eave_h=UPPER_EAVE_H,
pts=[(13.0,4.3),(17.2,4.3),(13.6,7.9),(9.4,7.9)], edges=["eave","hip","ridge","valley"]),
"U-S2": dict(desc="Upper roof, south slope west of wing", az=180, eave_h=UPPER_EAVE_H,
pts=[(3.2,4.3),(5.8,4.3),(9.4,7.9),(6.8,7.9)], edges=["eave","valley","ridge","hip"]),
"U-W": dict(desc="Upper wing, west slope (faces the street)", az=270, eave_h=UPPER_EAVE_H,
pts=[(5.8,0.0),(5.8,4.3),(9.4,7.9),(9.4,0.0)], edges=["eave","valley","ridge","rake"]),
"U-E": dict(desc="Upper wing, east slope (rear)", az=90, eave_h=UPPER_EAVE_H,
pts=[(13.0,0.0),(13.0,4.3),(9.4,7.9),(9.4,0.0)], edges=["eave","valley","ridge","rake"]),
"U-EH": dict(desc="Upper roof, east hip end (rear)", az=90, eave_h=UPPER_EAVE_H,
pts=[(17.2,4.3),(17.2,11.5),(13.6,7.9)], edges=["eave","hip","hip"]),
"U-WH": dict(desc="Upper roof, west hip end (street side) - kept free as street-side pathway", az=270, eave_h=UPPER_EAVE_H,
pts=[(3.2,4.3),(3.2,11.5),(6.8,7.9)], edges=["eave","hip","hip"], keep_free=True),
"U-N": dict(desc="Upper roof, north slope - kept free (pathway, low yield)", az=0, eave_h=UPPER_EAVE_H,
pts=[(3.2,11.5),(17.2,11.5),(13.6,7.9),(6.8,7.9)], edges=["eave","hip","ridge","hip"], keep_free=True),
"L-SE": dict(desc="Lower rear roof (1-storey), slopes south from upper wall", az=180, eave_h=LOWER_EAVE_H,
pts=[(13.0,0.0),(17.2,0.0),(17.2,4.3),(13.0,4.3)], edges=["eave","rake","wall","wall"]),
# lower front roof over garage: hip, ridge E-W at y 3.5, abuts the upper storey at x 5.4
"G-S": dict(desc="Garage roof, south slope (1-storey)", az=180, eave_h=LOWER_EAVE_H,
pts=[(0.0,0.1),(5.4,0.1),(5.4,3.5),(3.4,3.5)], edges=["eave","wall","ridge","hip"]),
"G-W": dict(desc="Garage roof, west hip end (faces the street)", az=270, eave_h=LOWER_EAVE_H,
pts=[(0.0,0.1),(3.4,3.5),(0.0,6.9)], edges=["hip","hip","eave"]),
"G-N": dict(desc="Garage roof, north slope (1-storey)", az=0, eave_h=LOWER_EAVE_H,
pts=[(0.0,6.9),(3.4,3.5),(5.4,3.5),(5.4,6.9)], edges=["hip","ridge","wall","eave"]),
}
# lower front roof (garage / entry) - outline only, not used
FRONT_ROOF = [(0.3,6.9),(2.9,6.9),(2.9,11.0),(0.3,11.0)] # porch roof, outline only
CLEAR_TIGHT = {"eave": 0.15, "rake": 0.15, "wall": 0.15, "hip": 0.15, "valley": 0.15, "ridge": 0.46}
PATIO = [(17.2,5.2),(19.9,5.2),(19.9,9.6),(17.2,9.6)]
# roof vents on the sample house (plan, m), before the transform below
VENTS = [(8.9,5.3),(15.7,5.2),(11.8,3.2),(12.2,2.6),(12.5,2.0),(10.9,0.7),(11.1,9.5),(11.9,8.5),(9.2,10.9)]
# ---- the sample house is invented: the base outline is lengthened 1.2 m east of the wing and mirrored
# east-west, so the street is to the EAST. Every outline, vent and keep-out goes through T().
STRETCH, XMAX = 1.2, 18.4
def T(p):
x, y = p
if x > 13.05: x += STRETCH
return (round(XMAX - x, 3), y)
FLIP = {90: 270, 270: 90, 0: 0, 180: 180}
for _f in FACES.values():
_f["pts"] = [T(p) for p in _f["pts"]]; _f["az"] = FLIP[_f["az"]]
_f["desc"] = _f["desc"].replace("west", "WEST").replace("east", "west").replace("WEST", "east").replace("West", "East")
REN = {"U-W": "U-E", "U-E": "U-W", "U-EH": "U-WH", "U-WH": "U-EH", "G-W": "G-E"}
FACES = {REN.get(k, k): v for k, v in FACES.items()}
FRONT_ROOF = [T(p) for p in FRONT_ROOF]; PATIO = [T(p) for p in PATIO]; VENTS = [T(p) for p in VENTS]
def face_frame(f):
"""unit vectors: d = downhill (plan), e = along eave (right-hand when looking uphill)"""
a = math.radians(f["az"])
d = (math.sin(a), math.cos(a)) # downhill direction in plan (x east, y north)
e = (-d[1], d[0]) # rotate +90
return d, e
def to_face(f, p, origin):
d, e = face_frame(f)
dx, dy = p[0]-origin[0], p[1]-origin[1]
u = dx*e[0] + dy*e[1]
w = -(dx*d[0] + dy*d[1]) # uphill plan distance
return (u, w / COSP)
def from_face(f, uv, origin):
d, e = face_frame(f)
u, v = uv; w = v*COSP
x = origin[0] + u*e[0] - w*d[0]
y = origin[1] + u*e[1] - w*d[1]
return (x, y, f["eave_h"] + w*TANP)
def origin_of(f):
# lowest point = any eave vertex; use first vertex of the edge typed "eave"
i = f["edges"].index("eave"); return f["pts"][i]
def usable(f, clear=None, keepouts=(), vents=True):
clear = clear or CLEAR
o = origin_of(f)
fp = [to_face(f, p, o) for p in f["pts"]]
poly = Polygon(fp)
n = len(fp)
for i in range(n):
a, b = fp[i], fp[(i+1) % n]
c = clear[f["edges"][i]]
# extend the edge line far in both directions, cut a flat band
dx, dy = b[0]-a[0], b[1]-a[1]; L = math.hypot(dx, dy)
ux, uy = dx/L, dy/L
line = LineString([(a[0]-ux*50, a[1]-uy*50), (b[0]+ux*50, b[1]+uy*50)])
poly = poly.difference(line.buffer(c, cap_style=2))
for v in (VENTS if vents else []):
if Polygon(f["pts"]).contains(Point(v)):
vu = to_face(f, v, o)
poly = poly.difference(Point(vu).buffer(VENT_CLEAR + VENT_R, 32))
for k in keepouts:
kp = Polygon(k).intersection(Polygon(f["pts"]))
if not kp.is_empty and kp.area > 1e-6:
poly = poly.difference(Polygon([to_face(f, p, o) for p in kp.exterior.coords]))
return poly, Polygon(fp), o
def fill(poly, W, H):
g = fill_grid(poly, W, H); r = fill_greedy(poly, W, H)
return g if len(g) >= len(r) else r
def fill_grid(poly, W, H):
"""aligned columns: one u-phase for all rows (tidier arrays)"""
best = []
if poly.is_empty: return best
minx, miny, maxx, maxy = poly.bounds
for vphase in [i*0.05 for i in range(0, int(H/0.05)+1)]:
for uphase in [i*0.025 for i in range(0, int((W+GAP)/0.025)+1)]:
placed = []; v = miny + vphase
while v + H <= maxy + 1e-9:
u = minx + uphase - (W+GAP)
while u + W <= maxx + 1e-9:
if poly.contains(box(u, v, u+W, v+H)): placed.append((u, v))
u += W + GAP
v += H + GAP
if len(placed) > len(best): best = placed
return [(u, v, W, H) for (u, v) in best]
def fill_greedy(poly, W, H):
"""rows parallel to the eave, greedy left->right; try several row/column phase offsets"""
best = []
if poly.is_empty: return best
minx, miny, maxx, maxy = poly.bounds
for vphase in [i*0.05 for i in range(0, int(H/0.05)+1)]:
for uphase in [i*0.05 for i in range(0, int(W/0.05)+1)]:
placed = []
v = miny + vphase
while v + H <= maxy + 1e-9:
u = minx + uphase - W
row = []
while u + W <= maxx + 1e-9:
r = box(u, v, u+W, v+H)
if poly.contains(r):
row.append((u, v)); u += W + GAP
else:
u += 0.05
placed += row
v += H + GAP
if len(placed) > len(best):
best = placed
return [(u, v, W, H) for (u, v) in best]
def layout(face_ids, clear=None, keepouts=(), mixed=False, vents=True):
mods = []
for fid in face_ids:
f = FACES[fid]
poly, _, o = usable(f, clear, keepouts, vents)
land = fill(poly, MOD_L, MOD_W); port = fill(poly, MOD_W, MOD_L)
pick = land if len(land) >= len(port) else port
if mixed: # second pass: fill what is left with the other orientation
best = list(pick)
for first, other in ((land, (MOD_W, MOD_L)), (port, (MOD_L, MOD_W))):
rest = poly
for (u, v, W, H) in first: rest = rest.difference(box(u-GAP, v-GAP, u+W+GAP, v+H+GAP))
extra = fill(rest, *other) if not rest.is_empty else []
if len(first) + len(extra) > len(best): best = list(first) + extra
pick = best
for k, (u, v, W, H) in enumerate(pick):
orient = "landscape" if abs(W - MOD_L) < 1e-9 else "portrait"
cx, cy, cz = from_face(f, (u+W/2, v+H/2), o)
corners = [from_face(f, c, o) for c in [(u,v),(u+W,v),(u+W,v+H),(u,v+H)]]
long_bearing = (f["az"] + 90) % 180 if orient == "landscape" else f["az"] % 180
mods.append(dict(face=fid, orientation=orient, long_bearing=long_bearing,
cx=cx, cy=cy, cz=cz, u=u, v=v, W=W, H=H, corners=corners))
for i, m in enumerate(mods, 1):
m["id"] = f"M{i:02d}"
return mods
STREET_AZ = 90
# PVWatts v8, El Paso TMY, 22.6 deg tilt, 14% losses: kWh per kWdc per year by downhill azimuth
YIELD = {180: 1899.5, 90: 1626.4, 270: 1589.4, 0: 1236.9}
# sample household use, Dec..Nov (invented, shaped like a summer-peaking El Paso home)
USE = [650, 650, 550, 650, 900, 950, 1050, 1700, 2050, 1800, 1200, 900]
SIZE_TO = 0.88
def street_class(az):
diff = abs((az - STREET_AZ + 180) % 360 - 180)
return "faces street" if diff <= 45 else ("seen at an angle" if diff <= 100 else "not visible from street")
if __name__ == "__main__":
STRIPS = [[T(p) for p in k] for k in [[(5.8,0.0),(9.4,0.0),(9.4,0.92),(5.8,0.92)], [(9.4,0.0),(13.0,0.0),(13.0,0.92),(9.4,0.92)]]]
designs = {
"A": (["U-S1","U-S2","U-E","U-W","U-WH","L-SE"], None, (), False, True),
"B": (["U-S1","U-S2","U-W","U-WH","L-SE"], None, (), False, True),
"C": (["U-S1","U-S2","U-E","U-W","U-WH","L-SE","G-S","G-E"], CLEAR_TIGHT, (), True, True),
"D": (["U-S1","U-S2","U-E","U-W","U-WH","L-SE","G-S","G-E","G-N","U-N","U-EH"], CLEAR_TIGHT, STRIPS, True, False),
"E": (["U-S1","U-S2","U-E","U-W","U-WH","L-SE"], CLEAR_TIGHT, (), True, True), # C without the garage roof: sized to the bill
}
out = {}
import os
cache = json.load(open("shade_cache.json")) if os.path.exists("shade_cache.json") else {}
import os
cache = json.load(open("shade_cache.json")) if os.path.exists("shade_cache.json") else {}
from shapely.ops import unary_union
roof_plan = unary_union([Polygon(f["pts"]) for f in FACES.values()] + [Polygon(FRONT_ROOF)]).area
meta = {}
def kept(mods):
return [m for m in mods if (cache.get(f"{m['face']}|{m['cx']:.2f}|{m['cy']:.2f}") or 0) <= 20]
for name, (faces, clear, keep, mixed, vents) in designs.items():
clear = dict(clear or CLEAR)
mods = layout(faces, clear, keep, mixed, vents)
pct = 100*len(kept(mods))*MOD_L*MOD_W*COSP/roof_plan
if pct > 33: # IRC R324.6.2: over 33% of plan roof area -> 36 in ridge setback
clear["ridge"] = 0.914; mods = layout(faces, clear, keep, mixed, vents)
meta[name] = dict(faces=faces, clear=clear, keepouts=[list(map(list, k)) for k in keep], mixed=mixed, vents=vents)
for m in mods:
m["shade_pct"] = cache.get(f"{m['face']}|{m['cx']:.2f}|{m['cy']:.2f}")
dropped = [m for m in mods if (m["shade_pct"] or 0) > 20]
mods = [m for m in mods if (m["shade_pct"] or 0) <= 20]
if name == "E": # sized to use: keep the best-yielding modules until a year's output reaches SIZE_TO of the sample use
yld = lambda m: YIELD[FACES[m["face"]]["az"]]*(1-0.85*(m["shade_pct"] or 0)/100)
keep, tot = [], 0.0
for m in sorted(mods, key=lambda m: -yld(m)):
e = MOD_P/1000*yld(m)
if tot + e > SIZE_TO*sum(USE): continue
keep.append(m); tot += e
mods = [m for m in mods if m in keep]
for i, m in enumerate(mods, 1): m["id"] = f"M{i:02d}"
print(name, "dropped for shading >20%:", [(m["face"], m["shade_pct"]) for m in dropped])
out[name] = mods
per = {}
for m in mods: per[m["face"]] = per.get(m["face"], 0) + 1
print(name, len(mods), round(len(mods)*MOD_P/1000, 2), "kW", per)
json.dump({"faces": FACES, "vents": VENTS, "front": FRONT_ROOF, "patio": PATIO, "designs": out, "meta": meta,
"module": [MOD_L, MOD_W, MOD_P], "pitch": PITCH}, open("model.json", "w"), indent=1)
for name, mods in out.items():
with open(f"modules_design_{name}.csv", "w", newline="") as fh:
w = csv.writer(fh)
w.writerow(["id","face","orientation","long_side_bearing_deg","centre_east_m","centre_north_m","centre_height_m",
"pitch_deg","azimuth_deg","pitch_status","height_status","geometry_status","size_mm","watts","street_view","beam_shading_pct_indicative"])
for m in mods:
f = FACES[m["face"]]
w.writerow([m["id"], m["face"], m["orientation"], m["long_bearing"], f"{m['cx']:.3f}", f"{m['cy']:.3f}", f"{m['cz']:.3f}",
PITCH, f["az"], "ASSUMED", "ASSUMED", "INVENTED", f"{int(MOD_L*1000)} x {int(MOD_W*1000)}", MOD_P, street_class(f["az"]), m["shade_pct"]])
shade.py (shading model)101 lines
"""Indicative beam-shading check: own house (roof + walls) and the 2-storey neighbour to the south
(modelled as a copy of this sample house one lot south, 13.8 m). Clear-sky beam weighting, hourly, 1 year."""
import json, math
import numpy as np
import model as M
LAT, LON = 31.76, -106.44 # El Paso, city level
D = json.load(open("model.json"))
def sun_positions():
out = []
for doy in range(1, 366, 2):
g = 2*math.pi/365*(doy-1)
decl = 0.006918-0.399912*math.cos(g)+0.070257*math.sin(g)-0.006758*math.cos(2*g)+0.000907*math.sin(2*g)-0.002697*math.cos(3*g)+0.00148*math.sin(3*g)
for hh in np.arange(5, 20, 0.5): # apparent solar time
ha = math.radians(15*(hh-12))
la = math.radians(LAT)
cz = math.sin(la)*math.sin(decl)+math.cos(la)*math.cos(decl)*math.cos(ha)
alt = math.asin(max(-1, min(1, cz)))
if alt < math.radians(3): continue
az = math.atan2(math.sin(ha), math.cos(ha)*math.sin(la)-math.tan(decl)*math.cos(la)) + math.pi # 0 = north
am = 1/max(cz, 0.05)
dni = 1353*0.7**(am**0.678)
s = np.array([math.sin(az)*math.cos(alt), math.cos(az)*math.cos(alt), math.sin(alt)])
out.append((s, dni))
return out
def tris():
T = []
for dy in (0.0, -13.8):
for fid, f in M.FACES.items():
org = M.origin_of(f)
P = [np.array(M.from_face(f, M.to_face(f, p, org), org)) + [0, dy, 0] for p in f["pts"]]
for i in range(1, len(P)-1): T.append((P[0], P[i], P[i+1]))
# walls of the upper storey (eave line down to ground) for the wing and block
walls = [tuple(M.T(p) for p in w) for w in [((5.8,0),(13.0,0)), ((13.0,0),(13.0,4.3)), ((13.0,4.3),(17.2,4.3)), ((17.2,4.3),(17.2,11.5)), ((5.8,0),(5.8,4.3)), ((3.2,4.3),(5.8,4.3))]]
for (a, b) in walls:
p1 = np.array([a[0], a[1]+dy, 0]); p2 = np.array([b[0], b[1]+dy, 0])
p3 = np.array([b[0], b[1]+dy, M.UPPER_EAVE_H]); p4 = np.array([a[0], a[1]+dy, M.UPPER_EAVE_H])
T += [(p1, p2, p3), (p1, p3, p4)]
if dy != 0: # neighbour's own lower rear roof too
f = M.FACES["L-SE"]; org = M.origin_of(f)
P = [np.array(M.from_face(f, M.to_face(f, p, org), org)) + [0, dy, 0] for p in f["pts"]]
T += [(P[0], P[1], P[2]), (P[0], P[2], P[3])]
return T
def prep(T):
A = np.array([t[0] for t in T]); B = np.array([t[1] for t in T]); C = np.array([t[2] for t in T])
return A, B-A, C-A
def hitv(o, d, P):
A, E1, E2 = P
p = np.cross(d, E2); det = np.einsum('ij,ij->i', E1, p)
ok = np.abs(det) > 1e-9; inv = np.where(ok, 1/np.where(ok, det, 1), 0)
t = o - A; u = np.einsum('ij,ij->i', t, p)*inv
q = np.cross(t, E1); v = (q @ d)*inv; dist = np.einsum('ij,ij->i', E2, q)*inv
return bool(np.any(ok & (u >= 0) & (u <= 1) & (v >= 0) & (u+v <= 1) & (dist > 0.05)))
def hit(o, d, T):
eps = 1e-7
for a, b, c in T:
e1, e2 = b-a, c-a; p = np.cross(d, e2); det = e1 @ p
if abs(det) < eps: continue
inv = 1/det; t = o-a; u = (t @ p)*inv
if u < 0 or u > 1: continue
q = np.cross(t, e1); v = (d @ q)*inv
if v < 0 or u+v > 1: continue
if (e2 @ q)*inv > 0.05: return True
return False
def run_mods(mods):
S = sun_positions(); P = prep(tris()); res = {}
for m in mods:
f = M.FACES[m["face"]]
a = math.radians(f["az"]); p = math.radians(M.PITCH)
n = np.array([math.sin(a)*math.sin(p), math.cos(a)*math.sin(p), math.cos(p)])
C = np.array(m["corners"]); cen = C.mean(axis=0)
pts = [cen] + [cen + 0.8*(c-cen) for c in C]
pts = [q + n*0.08 for q in pts]
tot = sh = 0.0
for s, dni in S:
ci = n @ s
if ci <= 0: continue
w = dni*ci; tot += w
frac = sum(hitv(q, s, P) for q in pts)/len(pts)
sh += w*frac
res[f"{m['face']}|{m['cx']:.2f}|{m['cy']:.2f}"] = round(100*sh/tot, 1) if tot else 0
return res
if __name__ == "__main__":
import sys
# model.json holds the kept modules; recompute the full candidate layouts so dropped ones get values too
mods = {}
for name, meta in D["meta"].items():
clear = meta["clear"]; keep = [tuple(map(tuple, k)) for k in meta["keepouts"]]
for m in M.layout(meta["faces"], clear, keep, meta.get("mixed", False), meta.get("vents", True)): mods[f"{m['face']}|{m['cx']:.2f}|{m['cy']:.2f}"] = m
old = json.load(open("shade_cache.json"))
todo = [m for k, m in mods.items() if k not in old]
res = dict(old); res.update(run_mods(todo))
json.dump(res, open("shade_cache.json", "w"), indent=1); print(len(res), res)
qc.py (independent check of every module)132 lines
"""Independent QC: re-derives every module from the CSV (centre, bearing, orientation, pitch, azimuth) with its own
math - it does not use the layout code's transforms - and checks it against the face outlines and rules."""
import csv, json, math, re, sys
import numpy as np
from shapely.geometry import Polygon, Point, box
FACES = json.load(open("model.json"))["faces"]
VENTS = json.load(open("model.json"))["vents"]
L, W = 1.722, 1.134
CLR = {"eave": 0.25, "rake": 0.25, "wall": 0.25, "hip": 0.46, "valley": 0.46, "ridge": 0.46}
rows = []
def add(i, status, evidence, sev, fix=""): rows.append(dict(id=i, status=status, evidence=evidence, sev=sev, fix=fix))
def plane(f, p_deg):
az = math.radians(f["az"]); p = math.radians(p_deg)
down = np.array([math.sin(az), math.cos(az)])
i = f["edges"].index("eave"); e0 = np.array(f["pts"][i])
def z(x, y): # height from uphill plan distance to the eave line
return f["eave_h"] + (-(np.array([x, y]) - e0) @ down) * math.tan(p)
h = np.array([math.cos(az), -math.sin(az), 0.0]) # horizontal, along eave
s = np.array([-math.sin(az)*math.cos(p), -math.cos(az)*math.cos(p), math.sin(p)]) # up-slope unit
return z, h, s
def corners(r, f):
p = float(r["pitch_deg"]); z, h, s = plane(f, p)
c = np.array([float(r["centre_east_m"]), float(r["centre_north_m"]), float(r["centre_height_m"])])
bearing = float(r["long_side_bearing_deg"]); az = f["az"]
long_horizontal = abs(((bearing - (az + 90)) + 90) % 180 - 90) < 1e-6
a, b = (h, s) if long_horizontal else (s, h)
return [c + sa*L/2*a + sb*W/2*b for sa, sb in [(-1,-1),(1,-1),(1,1),(-1,1)]], a, b, h, s, z
def dist_pt_line3(p, a, b):
d = (b-a)/np.linalg.norm(b-a); v = p-a; return np.linalg.norm(v - (v@d)*d)
META = json.load(open("model.json"))["meta"]
def run(design):
global CLR
CLR = META[design]["clear"]
strips = [Polygon(k) for k in META[design]["keepouts"]]
strip_hits = 0
R = list(csv.DictReader(open(f"modules_design_{design}.csv")))
per = {}
worst_edge = []; worst_h = 0; worst_sq = 0; overlaps = 0; min_gap = 9; vent_hits = []
inplane = {}
for r in R:
f = FACES[r["face"]]; per[r["face"]] = per.get(r["face"], 0) + 1
C, a, b, h, s, z = corners(r, f)
# plane / height check
for c in C: worst_h = max(worst_h, abs(c[2] - z(c[0], c[1])))
# inside + clearances (3D in-plane distance to each 3D edge)
P3 = [np.array([x, y, z(x, y)]) for x, y in f["pts"]]
poly = Polygon(f["pts"])
for c in C:
if not poly.buffer(1e-6).contains(Point(c[0], c[1])): worst_edge.append((r["id"], "outside face", 0))
for k in range(len(P3)):
d = dist_pt_line3(c, P3[k], P3[(k+1) % len(P3)]); need = CLR[f["edges"][k]]
if d < need - 0.005: worst_edge.append((r["id"], f["edges"][k], round(d, 2)))
# squareness: long side vs eave (h) or slope (s)
ang = min(math.degrees(math.acos(min(1, abs(a @ h)))), math.degrees(math.acos(min(1, abs(a @ s)))))
worst_sq = max(worst_sq, ang)
# in-plane 2D rectangle for overlap / gaps / vents
o = P3[0]; uv = [((c-o) @ h, (c-o) @ s) for c in C]
rect = Polygon(uv); inplane.setdefault(r["face"], []).append((r["id"], rect))
plan_rect = Polygon([(c[0], c[1]) for c in C])
strip_hits += sum(1 for st in strips if plan_rect.intersection(st).area > 1e-4)
for v in VENTS:
if poly.contains(Point(v)):
vp = np.array([v[0], v[1], z(*v)]); vv = Point((vp-o) @ h, (vp-o) @ s)
d = rect.distance(vv)
if d < 0.35: vent_hits.append((r["id"], v, round(d, 2)))
for fid, lst in inplane.items():
for i in range(len(lst)):
for j in range(i+1, len(lst)):
if lst[i][1].intersection(lst[j][1]).area > 1e-6: overlaps += 1
min_gap = min(min_gap, lst[i][1].distance(lst[j][1]))
return R, per, worst_edge, worst_h, worst_sq, overlaps, min_gap, vent_hits, strip_hits
def street(R):
fs = ft = 0
for r in R:
dlt = abs((float(r["azimuth_deg"]) - 90 + 180) % 360 - 180)
if dlt <= 45: fs += 1
elif dlt <= 100: ft += 1
return fs, ft
def adjacent(fa, fb):
A = [tuple(p) for p in FACES[fa]["pts"]]; B = [tuple(p) for p in FACES[fb]["pts"]]
sa = {frozenset((A[i], A[(i+1) % len(A)])) for i in range(len(A))}
sb = {frozenset((B[i], B[(i+1) % len(B)])) for i in range(len(B))}
return bool(sa & sb) or Polygon(A).intersection(Polygon(B)).length > 0.5
if __name__ == "__main__":
res = {}
for dsg in ("A", "B", "C", "D", "E"):
R, per, we, wh, wsq, ov, mg, vh, sh = run(dsg)
n = len(R); kw = round(n*0.43, 2); fs, ft = street(R)
res[dsg] = dict(n=n, kw=kw, per=per, edge_issues=we, height_dev=round(wh, 3), square=round(wsq, 2), overlaps=ov,
min_gap=round(mg, 3), vents=vh, street=fs, angle=ft, strip_hits=sh, ridge=CLR["ridge"])
# fire: plan view share
roof_plan = Polygon()
for f in FACES.values(): roof_plan = roof_plan.union(Polygon(f["pts"]))
M = json.load(open("model.json"))
roof_plan = roof_plan.union(Polygon(M["front"]))
cosp = math.cos(math.radians(22.6))
for dsg in ("A", "B", "C", "D", "E"):
res[dsg]["array_plan_pct"] = round(100*res[dsg]["n"]*L*W*cosp/roof_plan.area, 1)
used = set(res[dsg]["per"])
lack = []
for fid in used:
if fid == "L-SE": continue
free_adj = [g for g in FACES if g not in used and g != fid and adjacent(fid, g) and not g.startswith("G-")]
if not free_adj:
# own-plane strip: gap >= 0.914 m along the eave, free of modules, eave to ridge
f = FACES[fid]; az = math.radians(f["az"]); hx = np.array([math.cos(az), -math.sin(az)])
i = f["edges"].index("eave"); e0 = np.array(f["pts"][i]); e1 = np.array(f["pts"][(i+1) % len(f["pts"])])
lo, hi = sorted([(e0-e0) @ hx, (e1-e0) @ hx])
iv = []
for r in csv.DictReader(open(f"modules_design_{dsg}.csv")):
if r["face"] != fid: continue
C, *_ = corners(r, f)
xs = [(np.array(c[:2])-e0) @ hx for c in C]; iv.append((min(xs), max(xs)))
iv.sort(); best = 0; cur = lo
for a_, b_ in iv:
best = max(best, a_-cur); cur = max(cur, b_)
best = max(best, hi-cur)
res[dsg].setdefault("own_strip", {})[fid] = round(best, 2)
if best < 0.914: lack.append(fid)
res[dsg]["no_free_neighbour"] = lack
res["roof_plan_m2"] = round(roof_plan.area, 1)
json.dump(res, open("qc.json", "w"), indent=1, default=str)
print(json.dumps(res, indent=1, default=str))
render.py (plan drawings and 3D scene)90 lines
"""Plan SVGs and 3D scene data for the invented sample house (no imagery)."""
import json
from shapely.geometry import Polygon
import model as M
D = json.load(open("model.json")); F = M.FACES
T = M.T
LOT = [T(p) for p in [(-6.0, -1.3), (26.0, -1.3), (26.0, 12.5), (-6.0, 12.5)]]
STREET_X = max(p[0] for p in LOT) # lot's east line = street edge
def plan_svg(design, w=900, h=600):
s = 24.0; ox, oy = 232, 430
P = lambda x, y: (ox + x*s, oy - y*s)
pts = lambda L: " ".join("%.1f,%.1f" % P(*p) for p in L)
o = [f'<svg viewBox="0 0 {w} {h}" xmlns="http://www.w3.org/2000/svg" font-family="Inter,Arial,sans-serif" font-size="11" role="img" aria-label="Roof plan, design {design}">',
'<defs><pattern id="hatch{0}" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><line x1="0" y1="0" x2="0" y2="8" stroke="#c7462f" stroke-opacity=".35" stroke-width="2"/></pattern></defs>'.format(design),
f'<rect width="{w}" height="{h}" fill="#fbfaf7"/>']
sx = P(STREET_X, 0)[0]
o.append(f'<rect x="{sx+8:.1f}" y="20" width="44" height="{h-150}" fill="#e6e3dc"/>')
o.append(f'<text x="{sx+34:.1f}" y="{(h-130)/2:.1f}" transform="rotate(90 {sx+34:.1f} {(h-130)/2:.1f})" text-anchor="middle" fill="#6b665c" font-size="12" letter-spacing="2">STREET</text>')
o.append(f'<polygon points="{pts(LOT)}" fill="none" stroke="#b9b2a3" stroke-dasharray="6 4"/>')
o.append('<text x="%.1f" y="%.1f" fill="#8a8373" font-size="10">Lot line (sample house, invented)</text>' % P(min(p[0] for p in LOT)+0.2, 12.8))
for L, lab in [(D["front"], "Porch"), (D["patio"], "Patio")]:
o.append(f'<polygon points="{pts(L)}" fill="#e9e4da" stroke="#9c9381"/>')
c = Polygon(L).centroid; x, y = P(c.x, c.y)
o.append(f'<text x="{x:.1f}" y="{y+4:.1f}" text-anchor="middle" fill="#7d7565" font-size="10">{lab}</text>')
used = {m["face"] for m in D["designs"][design]}; meta = D["meta"][design]
for fid, f in F.items():
free = f.get("keep_free") and fid not in used
o.append(f'<polygon points="{pts(f["pts"])}" fill="{"#ece6d8" if fid in used else "#f3efe6"}" stroke="#5d5547" stroke-width="1.2"/>')
if free: o.append(f'<polygon points="{pts(f["pts"])}" fill="url(#hatch{design})"/>')
for k in meta["keepouts"]:
o.append(f'<polygon points="{pts(k)}" fill="url(#hatch{design})" stroke="#c7462f" stroke-width=".6"/>')
for fid in used:
f = F[fid]; poly, _, org = M.usable(f, meta["clear"], [tuple(map(tuple, k)) for k in meta["keepouts"]], meta.get("vents", True))
for g in ([poly] if poly.geom_type == "Polygon" else list(poly.geoms)):
o.append(f'<polygon points="{pts([M.from_face(f, c, org)[:2] for c in g.exterior.coords])}" fill="none" stroke="#c7462f" stroke-width="0.8" stroke-dasharray="3 3"/>')
for m in D["designs"][design]:
o.append(f'<polygon class="mod" data-id="{m["id"]}" points="{pts([c[:2] for c in m["corners"]])}" fill="#1f2a38" stroke="#9aa7b6" stroke-width="0.8"/>')
x, y = P(m["cx"], m["cy"]); o.append(f'<text x="{x:.1f}" y="{y+3.5:.1f}" text-anchor="middle" fill="#e8edf3" font-size="8.5" pointer-events="none">{m["id"]}</text>')
for v in D["vents"]:
x, y = P(*v); o.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="3.2" fill="#fff" stroke="#c7462f" stroke-width="1.2"/>')
for fid, f in F.items():
c = Polygon(f["pts"]).representative_point(); x, y = P(c.x, c.y)
if f.get("keep_free") and fid not in used:
o.append(f'<text x="{x:.1f}" y="{y:.1f}" text-anchor="middle" fill="#a33a26" font-size="10" font-weight="600">{fid} · pathway</text>')
else:
o.append(f'<text x="{x:.1f}" y="{y-12:.1f}" text-anchor="middle" fill="#5d5547" font-size="9.5" font-weight="600">{fid}</text>')
o.append(f'<g transform="translate({w-40},50)"><polygon points="0,-22 8,8 0,2 -8,8" fill="#2b2b2b"/><text y="24" text-anchor="middle" font-weight="700">N</text></g>')
o.append(f'<g transform="translate({w-300},{h-20})"><rect width="{5*s}" height="6" fill="#2b2b2b"/><rect x="{5*s}" width="{5*s}" height="6" fill="#fff" stroke="#2b2b2b"/><text y="-4">0</text><text x="{5*s}" y="-4" text-anchor="middle">5 m</text><text x="{10*s}" y="-4" text-anchor="middle">10 m</text></g>')
c = meta["clear"]
lg = [("#1f2a38", "Module 1722 × 1134 mm (ASSUMED)"), ("hatch", "Kept free: 36 in fire access pathway"),
("none", f"Setback limit: eave/rake {c['eave']} m, hip/valley {c['hip']} m, ridge {c['ridge']} m"),
("#fff", "Roof vent, 0.35 m keep-out" if meta.get("vents", True) else "Roof vent, rerouted under the array")]
for i, (col, t) in enumerate(lg):
yy = h - 98 + i*17
if col == "none": o.append(f'<line x1="24" x2="40" y1="{yy+5}" y2="{yy+5}" stroke="#c7462f" stroke-dasharray="3 3"/>')
elif col == "#fff": o.append(f'<circle cx="32" cy="{yy+5}" r="4" fill="#fff" stroke="#c7462f" stroke-width="1.2"/>')
else: o.append(f'<rect x="24" y="{yy}" width="16" height="10" fill="{"url(#hatch%s)" % design if col == "hatch" else col}" stroke="#5d5547" stroke-width=".6"/>')
o.append(f'<text x="48" y="{yy+9}" fill="#3b372f">{t}</text>')
o.append('</svg>'); return "\n".join(o)
def r3(L): return [[round(a, 3) for a in p] for p in L]
def scene(design):
faces = []
for fid, f in F.items():
org = M.origin_of(f)
faces.append(dict(id=fid, pts=r3([M.from_face(f, M.to_face(f, p, org), org) for p in f["pts"]])))
mods = [dict(id=m["id"], c=r3(m["corners"])) for m in D["designs"][design]]
return dict(faces=faces, mods=mods)
UPPER = [T(p) for p in [(3.2,4.3),(3.2,11.5),(17.2,11.5),(17.2,4.3),(13,4.3),(13,0),(5.8,0),(5.8,4.3)]]
GARAGE = [T(p) for p in [(0,0.1),(5.4,0.1),(5.4,6.9),(0,6.9)]]
REAR = [T(p) for p in [(13,0),(17.2,0),(17.2,4.3)]]
H = M.UPPER_EAVE_H; h = M.LOWER_EAVE_H; ridge = H + 3.6*M.TANP
BODY = dict(
ground=r3([(x, y, 0) for x, y in LOT]),
street=r3([(STREET_X, -8, -0.01), (STREET_X+8, -8, -0.01), (STREET_X+8, 20, -0.01), (STREET_X, 20, -0.01)]),
walls=[dict(poly=UPPER, h0=0, h1=H, closed=True), dict(poly=GARAGE, h0=0, h1=h, closed=True), dict(poly=REAR, h0=0, h1=h, closed=False),
dict(poly=D["front"], h0=0, h1=h, closed=True)],
flats=[r3([(x, y, h+0.05) for x, y in D["front"]])],
tris=[r3([(*T((5.8, 0)), H), (*T((13, 0)), H), (*T((9.4, 0)), ridge)]),
r3([(*T((17.2, 0)), h), (*T((17.2, 4.3)), h + 4.3*M.TANP), (*T((17.2, 4.3)), h)])],
centre=[round(sum(p[0] for p in UPPER)/len(UPPER), 2), 5.7, 3], street_label=[STREET_X + 4, 6, 0])
if __name__ == "__main__":
for k in "ABCDE": open(f"plan_{k}.svg", "w").write(plan_svg(k))
json.dump(dict(body=BODY, designs={k: scene(k) for k in "ABCDE"}), open("scene.json", "w"))
print("ok", STREET_X)
build.py (writes data.js and the plans for the site)43 lines
"""Write the site files for Solar Go/No-Go from the model run: data.js and plan-<k>.svg.
Run after model.py, shade.py, model.py, qc.py and render.py. Usage: python3 build.py <out_dir>"""
import json, csv, sys, io, os
import model as M
OUT = sys.argv[1] if len(sys.argv) > 1 else "out"
os.makedirs(OUT, exist_ok=True)
D = json.load(open("model.json")); Q = json.load(open("qc.json")); SC = json.load(open("scene.json"))
F = M.FACES; DS = "ABCDE"
def kwh(m): return 0.43*M.YIELD[F[m["face"]]["az"]]*(1-0.85*(m["shade_pct"] or 0)/100)
NAME = {"A": "Conservative", "B": "Street-quiet", "C": "Dense", "D": "Maximum", "E": "Sized to use"}
RULES = {"A": "0.25 m at edges; 18 in each side of hips, valleys and ridges; vents kept clear",
"B": "As A, with nothing on the slope that faces the street",
"C": "Code minimum: 18 in at ridges, 6 in at edges, hips and valleys; adds the garage roof",
"D": "As C plus the north slope and the street hip; 36 in ridge setback (array over 33%); two 36 in pathway strips; vents rerouted",
"E": "C's spacing on the house roof only, cut back to the best-producing panels until a year's output is 88% of the use"}
designs = []
for k in DS:
mods = D["designs"][k]; n = len(mods); kw = round(n*0.43, 2); e = int(round(sum(kwh(m) for m in mods), -1))
ac = kw*0.81 # ~ AC rating with microinverters (DC/AC about 1.23)
vents = len({tuple(v[1]) for v in Q[k]["vents"]})
extra = (2150 if ac > 7.7 else 0) + (1500 if vents else 0)
designs.append(dict(k=k, name=NAME[k], n=n, kw=kw, kwh=e, per=Q[k]["per"], street=Q[k]["street"], angle=Q[k]["angle"],
pct=Q[k]["array_plan_pct"], ridge=Q[k]["ridge"], vents=vents, ac=round(ac, 1), extra=extra,
shade=max((m["shade_pct"] or 0) for m in mods), rule=RULES[k], gap=Q[k]["min_gap"]))
faces = {fid: dict(desc=f["desc"].split(" - ")[0], az=f["az"], free=bool(f.get("keep_free"))) for fid, f in F.items()}
csvs = {k: open(f"modules_design_{k}.csv").read() for k in DS}
dropped = {}
for k, meta in D["meta"].items():
cache = json.load(open("shade_cache.json"))
cand = M.layout(meta["faces"], meta["clear"], [tuple(map(tuple, x)) for x in meta["keepouts"]], meta.get("mixed", False), meta.get("vents", True))
dropped[k] = sum(1 for m in cand if (cache.get(f"{m['face']}|{m['cx']:.2f}|{m['cy']:.2f}") or 0) > 20)
data = dict(designs=designs, faces=faces, csv=csvs, scene=SC, dropped=dropped, roof_m2=Q["roof_plan_m2"],
use=M.USE, yields=M.YIELD, size_to=M.SIZE_TO,
qc=dict(gap=min(Q[k]["min_gap"] for k in DS), height=max(Q[k]["height_dev"] for k in DS), square=max(Q[k]["square"] for k in DS),
overlaps=sum(Q[k]["overlaps"] for k in DS), edges=sum(len(Q[k]["edge_issues"]) for k in DS),
strips=sum(Q[k]["strip_hits"] for k in DS)))
open(os.path.join(OUT, "data.js"), "w").write("/* Solar Go/No-Go: every number from the layout run on the invented sample house (docs/solar-go-no-go/). Generated by build.py; do not edit by hand. */\nwindow.SGO=" + json.dumps(data, separators=(",", ":")) + ";\n")
import render
for k in DS: open(os.path.join(OUT, f"plan-{k}.svg"), "w").write(render.plan_svg(k))
print({d["k"]: (d["n"], d["kw"], d["kwh"], d["extra"]) for d in designs}, dropped)
Want the full solar permit package for your own address?
The tool runs on an invented house. Send me your address, in any city: I read that municipality's solar rules, design your roof and prepare the full permit package for that address, checked the way the plan reviewer will before you file. Fixed price agreed up front, and the first call is free.