mmrech commited on
Commit
ebaf8c2
·
verified ·
1 Parent(s): 9f07919

Launch ASCEND with linked interactive 3D globe

Browse files
DELIVERY_NOTES.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Delivery and validation — 18 October 2026
2
+
3
+ The original ASCEND Decision Observatory is implemented as a portable HTML and a modular static app. Its default World Lens view contains an actual interactive WebGL globe with locally bundled geography and rendering dependencies.
4
+
5
+ ## Verified
6
+
7
+ - All 24 tests pass: 17 numerical-model tests and seven globe-geometry tests, including geographic projection, marker placement and Three.js texture alignment. Model checks cover conservation, budget constraints, unavailable options, ties, extreme inputs, and equivalence between the fast landscape calculation and the detailed simulation.
8
+ - The 10,000-cell performance test passes its 750 ms threshold. Measured timings vary by machine load; an independent run measured about 35 ms.
9
+ - Isolated Chrome rendered the portable HTML at 1440 × 1100 and 390 × 844, and the modular app at the local preview URL. The in-app browser path timed out, so it was not counted as successful validation.
10
+ - Browser checks verified meaningful SVG output; preset and reset; JSON and SVG downloads; 12 country rows; missing data in the 2024 view; 12 publication and five trial cards; keyword filtering; methods-dialog opening/closing; and no horizontal overflow at 390 px.
11
+ - Additional regressions verify that the keyboard skip link preserves the scenario and evidence-category filters are included in the view URL.
12
+ - Globe browser checks verify an actual WebGL canvas, reference-marker picking, linked country selection, pointer drag, rotation and zoom controls, metric/year changes, missing-data display, PNG export, mobile layout and reduced-motion behavior. The globe pauses while offscreen. Capital markers are geographic reference points, not health-service locations.
13
+ - No JavaScript page errors were observed in these test flows. Desktop and mobile screenshots were visually inspected. Crowded mobile terrain labels were corrected.
14
+ - The data-refresh script validates 12 countries, 60 series, 600 annual slots, 51 null values, 12 publications and five trial registrations.
15
+
16
+ ## Scope and limits
17
+
18
+ World Bank, Europe PMC, ClinicalTrials.gov, CNES and SIH data requests were actually completed. A World Bank observation retrieved through Firecrawl Alexandria matched the direct API. The scholarly set is a convenience retrieval, and registered cancer studies are broad oncology records rather than surgical efficacy evidence.
19
+
20
+ The intervention model is illustrative. No real policy effect, calibrated investment recommendation, patient waiting-time prediction, survival effect or formal value-of-information result is claimed. The app makes no live LLM call. AI supported development and discovery; the running calculation and relevance tags are transparent code.
21
+
22
+ Live Europe PMC search is implemented with a timeout and a preserved-snapshot fallback. Its success depends on the service and browser network policy. The saved snapshot and scenario model remain usable offline. Live-search results and their query/time are retained in decision exports; shared view links retain filters, not a private copy of a live response.
23
+
24
+ Safari, Firefox and assistive-technology combinations have not been independently tested. No HSIL affiliation, endorsement, integration, or proprietary-framework permission is implied. CADUCEUS was used for inspiration and was not modified.
README.md CHANGED
@@ -1,10 +1,45 @@
1
  ---
2
- title: ASCEND
3
- emoji: 📉
4
  colorFrom: green
5
- colorTo: purple
6
  sdk: static
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: ASCEND Decision Observatory
3
+ emoji: ↗
4
  colorFrom: green
5
+ colorTo: gray
6
  sdk: static
7
+ app_file: index.html
8
  pinned: false
9
  ---
10
 
11
+ # ASCEND Decision Observatory
12
+
13
+ An original interactive research prototype exploring how health-system assumptions affect intervention choices. Inspired by the user's request for an exploratory visual tool; CADUCEUS was inspected as a reference and its code, layout and simulation multipliers were not reused. No HSIL affiliation or permission to reproduce its proprietary framework is implied.
14
+
15
+ ## Open it
16
+
17
+ The accompanying `ASCEND_Observatory.html` is self-contained. Double-click it to open in a browser. Its saved data and scenario model work offline; live Europe PMC searches need internet access.
18
+
19
+ Space: [mmrech/ASCEND](https://huggingface.co/spaces/mmrech/ASCEND). The hosted `index.html` is the self-contained snapshot. The hosted `source.html` loads the modular source and `data.json`; for a local source checkout, serve this directory with a local web server. CADUCEUS remains a separate application.
20
+
21
+ ## Three views
22
+
23
+ - **Decision landscape:** click a capacity/referral combination or use the sliders. Compare four options under explicitly illustrative assumptions, inspect the binding resource, and export a decision JSON or labeled SVG.
24
+ - **World lens:** rotate and zoom an actual 3D globe, click capital reference markers, and compare 12 countries using World Bank data, 2015–2024. Choose health spending, physicians, life expectancy or out-of-pocket share as the marker color; missing observations stay gray. The globe, country selector, scatterplot and profile are linked. Each view uses one reference year, preserves missing values and exposes a numeric table. Country selection does not change model parameters.
25
+ - **Evidence atlas:** inspect 12 retrieved publications and five registered cancer studies with Brazilian locations. Search the cached titles and abstracts, filter by keyword tags, or issue a new live Europe PMC query. These are discovery leads, not appraised evidence or causal inputs.
26
+
27
+ ## Data and calculation
28
+
29
+ `data.json` contains 600 annual observation slots: 549 values and 51 nulls at the initial retrieval on 18 October 2026. It retains source URLs, dates, observation years and access status. The snapshot also records successful CNES/SIH connector checks, exposing schema names rather than individual patient records. `alexandria-verification.json` records a World Bank observation independently retrieved through Firecrawl Alexandria. Its Brazil 2023 health-spending value matched the direct API.
30
+
31
+ The scenario model is **unfitted and illustrative**. Monthly completions equal the minimum of patients available, referral throughput, staffed capacity and funded slots. Programme spending is committed, including unused purchased slots. Referral capacity is capped at new arrivals; this simplified model can slow queue growth but cannot clear an existing backlog. It cannot estimate waiting times, survival, DALYs or causal policy effects. Colors show scenario winners, not probabilities. Ties are displayed.
32
+
33
+ Run `npm test` or `node --test tests/*.mjs` inside the source directory to verify the numerical model and globe geometry (24 tests). Browser review covers desktop/mobile layout and main interactions; see the delivery note for exact results.
34
+
35
+ ## Refresh and reuse
36
+
37
+ Run `python3 refresh_data.py` inside the source directory to update its data snapshot, or `python3 refresh_data.py --validate` to validate the existing snapshot. Raw responses are saved in a local `data_raw` folder. The modular app reads the updated snapshot immediately; the portable HTML remains a frozen export until rebuilt. No credentials are embedded.
38
+
39
+ Source data retain their original attribution and terms. Publication and abstract rights remain with their respective holders. The scholarly search set is a convenience sample, not a systematic review. ClinicalTrials.gov registrations are not proof of efficacy, surgical relevance or routine-care access.
40
+
41
+ ## Technical design
42
+
43
+ Semantic HTML, responsive CSS, SVG and JavaScript modules, with a locally vendored Three.js 0.160.1 renderer for the globe. Natural Earth geometry and renderer dependencies ship with the app, so the globe makes no CDN requests. See `assets/ATTRIBUTION.md` and `vendor/THREE-LICENSE.txt`. The landscape renders roughly 1,300 cells; the scatterplot has at most 12 country points. URL state retains tab, year, country and model controls. Sliders offer a keyboard alternative to pointer-based chart selection. SVG/JSON exports carry model assumptions and provenance. Reduced-motion preferences are respected.
44
+
45
+ The globe uses one WebGL context, pauses its animation when offscreen, limits pixel density for mobile, and starts without automatic rotation when reduced motion is requested. If WebGL is unavailable, the country selector, comparison chart and data table still work. Capital markers are reference points, not service locations.
alexandria-verification.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "success": true,
3
+ "data": {
4
+ "alexandria": [
5
+ {
6
+ "provider": "data-worldbank-org",
7
+ "capability": "indicators/data",
8
+ "data": {
9
+ "last_updated": "2026-10-08",
10
+ "next_page": null,
11
+ "observed_at_ms": 1792313841863,
12
+ "page": 1,
13
+ "pages": 1,
14
+ "per_page": 1,
15
+ "records": [
16
+ {
17
+ "country_id": "BR",
18
+ "country_iso3": "BRA",
19
+ "country_name": "Brazil",
20
+ "date": "2023",
21
+ "decimal": 2,
22
+ "footnote": null,
23
+ "indicator_id": "SH.XPD.CHEX.PC.CD",
24
+ "indicator_name": "Current health expenditure per capita (current US$)",
25
+ "obs_status": null,
26
+ "unit": null,
27
+ "value": 1009.83563232
28
+ }
29
+ ],
30
+ "source_id": "2",
31
+ "source_url": "https://api.worldbank.org/v2/country/BRA/indicator/SH.XPD.CHEX.PC.CD?format=json&per_page=1&page=1&date=2023",
32
+ "total": 1,
33
+ "warnings": []
34
+ },
35
+ "workflow": {
36
+ "version": "2.0.4",
37
+ "digest": "sha256:3dc3d9944f1f9b95fd446b20f514ca4491bddf08b8d7be7f16c44e98be51f3c8"
38
+ },
39
+ "records": 1,
40
+ "upstreamStatus": 200,
41
+ "alexandriaId": "7eaf66c896953a52404406f51506f966c5012cb97aaf2917c0a4533252661e3b",
42
+ "providerRequestId": "53eaa424-175c-4717-b661-ca7263f2f229",
43
+ "workflowRunId": "53eaa424-175c-4717-b661-ca7263f2f229"
44
+ }
45
+ ],
46
+ "creditsCost": 5
47
+ },
48
+ "requestId": "aa16ff2c-276a-4bf0-86da-1bc2b9dba637",
49
+ "scrape_id": "01a14e3a-d6d5-709c-9649-e414b2039d3f",
50
+ "feedbackTool": {
51
+ "name": "firecrawl_feedback",
52
+ "when": "After task completion, within 20 minutes of your last Alexandria call. Free, optional, refunds 1 credit, No job ID needed.",
53
+ "arguments": {
54
+ "endpoint": "alexandria",
55
+ "rating": "<good | partial | bad>",
56
+ "requestedWebsite": {
57
+ "url": "<website the user needed data from>",
58
+ "requestedFunctionality": "<what they needed from it>"
59
+ },
60
+ "objective": "<underlying goal of the task>",
61
+ "rationale": "<why this rating, from observed results>",
62
+ "providerFeedback": "<optional [{name, issue, why}]: providers that were missing, thin, or unavailable>",
63
+ "capabilityFeedback": "<optional [{name, provider, issue, why, requestedFunctionality?}]: capabilities that were missing, wrong, or failed>"
64
+ }
65
+ }
66
+ }
app.mjs ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {createGlobe} from './globe.mjs';
2
+ import {DEFAULTS,STRATEGIES,evaluate,landscape,recommendation,normalizeState} from './model.mjs';
3
+
4
+ const $=id=>document.getElementById(id);
5
+ const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
6
+ const fmt=(n,d=0)=>Number.isFinite(n)?new Intl.NumberFormat('en-US',{maximumFractionDigits:d}).format(n):'Not available';
7
+ const money=n=>`R$${n>=1e6?fmt(n/1e6,2)+'m':fmt(n)}`;
8
+ const shortNames={current:'Current service',theatre:'Surgical capacity',referral:'Referral programme',combined:'Combined package'};
9
+ const colors=Object.fromEntries(STRATEGIES.map(s=>[s.id,s.color]));
10
+ const S=(tag,attrs={},text='')=>{const e=document.createElementNS('http://www.w3.org/2000/svg',tag);for(const[k,v]of Object.entries(attrs))e.setAttribute(k,v);if(text)e.textContent=text;return e;};
11
+ const draw=(svg,tag,attrs,text)=>{const e=S(tag,attrs,text);svg.append(e);return e;};
12
+ let globe=null,globeMetric='spending',globeAutoRotate=!matchMedia('(prefers-reduced-motion: reduce)').matches;
13
+ let data,params={...DEFAULTS},activeTab='world',country='BRA',year=2023,metric='life',evidenceFilter='all',livePapers=null,liveSearchMeta=null,toastTimer,searchController;
14
+
15
+ function toast(message){$('toast').textContent=message;$('toast').classList.add('show');clearTimeout(toastTimer);toastTimer=setTimeout(()=>$('toast').classList.remove('show'),3500);}
16
+ function urlState(){const p=new URLSearchParams({view:activeTab,country,year:String(year),metric,globeMetric,category:evidenceFilter,q:$('paperSearch').value.trim()});for(const k of ['budget','capacity','referralGain','arrivals','unitCost'])p.set(k,String(params[k]));return '#'+p;}
17
+ function saveState(push=false){try{history[push?'pushState':'replaceState'](null,'',urlState());}catch{}}
18
+ function readState(){const p=new URLSearchParams(location.hash.slice(1));activeTab=['world','evidence','landscape'].includes(p.get('view'))?p.get('view'):'world';country=data?.countries.some(c=>c.id===p.get('country'))?p.get('country'):'BRA';const y=Number(p.get('year'));year=Number.isInteger(y)&&y>=2015&&y<=2024?y:2023;metric=p.get('metric')==='oop'?'oop':'life';globeMetric=['spending','workforce','life','oop'].includes(p.get('globeMetric'))?p.get('globeMetric'):'spending';evidenceFilter=['capacity','access','financing'].includes(p.get('category'))?p.get('category'):'all';$('paperSearch').value=p.get('q')||'';document.querySelectorAll('[data-evidence]').forEach(b=>b.classList.toggle('active',b.dataset.evidence===evidenceFilter));let input={};for(const k of ['budget','capacity','referralGain','arrivals','unitCost'])if(p.has(k)&&Number.isFinite(Number(p.get(k))))input[k]=Number(p.get(k));params=normalizeState(input);}
19
+ function setTab(tab,push=true){activeTab=tab;document.body.dataset.view=tab;globe?.setActive(tab==='world');document.querySelectorAll('.view').forEach(v=>{v.hidden=v.id!==tab;v.classList.toggle('active',v.id===tab);});document.querySelectorAll('[data-tab]').forEach(b=>{b.classList.toggle('active',b.dataset.tab===tab);if(b.dataset.tab===tab)b.setAttribute('aria-current','page');else b.removeAttribute('aria-current');});$('viewStatus').innerHTML=tab==='landscape'?'<span class="badge amber">ILLUSTRATIVE SCENARIO</span><span>12-month planning model · not a policy forecast</span>':tab==='world'?'<span class="badge green">PUBLIC OBSERVATIONS</span><span>Fixed-year comparison · missing values preserved</span>':'<span class="badge green">RETRIEVED SOURCES</span><span>Discovery leads · not approved model parameters</span>';$('saveChart').hidden=tab!=='landscape';if(tab==='world')renderWorld();if(tab==='evidence')renderEvidence();if(tab==='landscape')renderModel();saveState(push);}
20
+ function bindControls(){for(const k of ['budget','capacity','referralGain','arrivals','unitCost'])$(k).value=params[k];$('budgetValue').textContent=money(params.budget);$('capacityValue').textContent=fmt(params.capacity);$('referralValue').textContent='+'+fmt(params.referralGain*100)+' pp';}
21
+ function renderModel(){bindControls();const results=evaluate(params),winner=recommendation(results);renderTerrain();renderFlow(winner);renderComparison(results,winner);const ties=winner.tiedIds.filter(id=>id!==winner.id);$('decisionCallout').innerHTML=`<div><div class="section-label">AT THESE ASSUMPTIONS</div><h3>${esc(shortNames[winner.id])}${ties.length?' · tied':''}</h3><p>${ties.length?'Same outcome and spending as '+ties.map(id=>esc(shortNames[id])).join(', ')+'. ':''}${winner.id==='current'?'No modeled throughput gain from the additional investment.':'Highest modeled throughput; not a policy recommendation.'}</p></div><div class="decision-value"><strong>+${fmt(winner.incremental,1)}</strong><small>expected procedures / year</small></div>`;
22
+ const capBinds=winner.bottleneck.includes('capacity'),refBinds=winner.bottleneck.includes('Referral');$('nextQuestion').textContent=capBinds?'How much staffed capacity is actually usable?':refBinds?'How much can referral throughput really improve?':'Which resource would constrain the next expansion?';$('nextReason').textContent=capBinds?'Measure staffed theatre time and cancellations. A registered facility or bed count cannot answer this question.':refBinds?'Measure referral completion and losses along the pathway. A promising study from another setting is not a local effect estimate.':'Audit operating funds, demand and implementation delays before treating this scenario as a real investment case.';}
23
+ function renderTerrain(){const svg=$('terrain');if(!svg.clientWidth)return;const W=Math.max(300,svg.clientWidth),H=svg.clientHeight||430,m={l:48,r:22,t:24,b:58},pw=W-m.l-m.r,ph=H-m.t-m.b,cols=43,rows=31;svg.replaceChildren();svg.setAttribute('viewBox',`0 0 ${W} ${H}`);draw(svg,'title',{id:'terrainTitle'},'Decision landscape: strategy with greatest modeled additional completions');draw(svg,'desc',{id:'terrainDesc'},'Horizontal axis usable monthly surgical capacity, 40 to 180 slots. Vertical axis assumed referral gain, 0 to 40 percentage points. Use the labeled sliders to select an exact point. Colors indicate strategies, not probabilities.');const cells=landscape(params,cols,rows),cw=pw/cols,ch=ph/rows;
24
+ for(const c of cells)draw(svg,'rect',{x:m.l+c.col*cw,y:m.t+(rows-1-c.row)*ch,width:cw+.2,height:ch+.2,fill:c.color,opacity:c.winnerId==='current'?'.3':'.84'});
25
+ for(let i=1;i<cols;i++)for(let j=0;j<rows;j++){const c=cells[j*cols+i],prev=cells[j*cols+i-1];if(c.winnerId!==prev.winnerId)draw(svg,'line',{x1:m.l+i*cw,y1:m.t+(rows-1-j)*ch,x2:m.l+i*cw,y2:m.t+(rows-j)*ch,stroke:'#102b31','stroke-width':1,opacity:'.65'});}
26
+ for(let j=1;j<rows;j++)for(let i=0;i<cols;i++){const c=cells[j*cols+i],prev=cells[(j-1)*cols+i];if(c.winnerId!==prev.winnerId)draw(svg,'line',{x1:m.l+i*cw,y1:m.t+(rows-j)*ch,x2:m.l+(i+1)*cw,y2:m.t+(rows-j)*ch,stroke:'#102b31','stroke-width':1,opacity:'.65'});}
27
+ const x=v=>m.l+(v-40)/140*pw,y=v=>m.t+ph-v/.4*ph;
28
+ for(const t of [40,80,120,160,180]){draw(svg,'line',{x1:x(t),x2:x(t),y1:m.t+ph,y2:m.t+ph+5,stroke:'#9fb7af'});draw(svg,'text',{x:x(t),y:m.t+ph+20,fill:'#c6d6cf','font-size':10,'text-anchor':'middle'},String(t));}
29
+ for(const t of [0,.1,.2,.3,.4]){draw(svg,'text',{x:m.l-10,y:y(t)+4,fill:'#c6d6cf','font-size':10,'text-anchor':'end'},'+'+Math.round(t*100));}
30
+ draw(svg,'text',{x:m.l+pw/2,y:H-11,fill:'#d2e5da','font-size':11,'text-anchor':'middle'},'Usable surgical capacity · slots / month');draw(svg,'text',{transform:`translate(15 ${m.t+ph/2}) rotate(-90)`,fill:'#d2e5da','font-size':10,'text-anchor':'middle'},'Referral improvement · percentage points');
31
+ // Labels describe regions, never data-derived causal mechanisms.
32
+ for(const s of STRATEGIES){const subset=cells.filter(c=>c.winnerId===s.id);if(subset.length<45)continue;let candidates=subset.filter(c=>c.col>3&&c.col<cols-4&&c.row>3&&c.row<rows-4);if(!candidates.length)continue;const med=candidates[Math.floor(candidates.length*.58)],lx=x(med.x),ly=y(med.y);let label=W<520?({current:'No gain',theatre:'Capacity',referral:'Referral',combined:'Combined'})[s.id]:shortNames[s.id];draw(svg,'text',{x:Math.max(m.l+44,Math.min(W-m.r-55,lx)),y:ly,fill:s.id==='current'?'#c6d6cf':'#173d3b','font-size':W<520?11:12,'font-weight':600,'text-anchor':'middle','paint-order':'stroke',stroke:s.id==='current'?'#243c44':s.color,'stroke-width':3},label);}
33
+ const px=x(params.capacity),py=y(params.referralGain);draw(svg,'line',{x1:px,x2:px,y1:m.t,y2:m.t+ph,stroke:'#fff','stroke-dasharray':'4 5',opacity:'.7'});draw(svg,'line',{x1:m.l,x2:m.l+pw,y1:py,y2:py,stroke:'#fff','stroke-dasharray':'4 5',opacity:'.7'});draw(svg,'circle',{cx:px,cy:py,r:9,fill:'#153438',stroke:'#fff','stroke-width':2});draw(svg,'circle',{cx:px,cy:py,r:2.5,fill:'#fff'});
34
+ svg.onclick=e=>{const r=svg.getBoundingClientRect(),xx=e.clientX-r.left,yy=e.clientY-r.top;if(xx<m.l||xx>W-m.r||yy<m.t||yy>H-m.b)return;params.capacity=Math.round(40+(xx-m.l)/pw*140);params.referralGain=Math.round((1-(yy-m.t)/ph)*40)/100;renderModel();saveState();};}
35
+ function renderFlow(winner){const m=winner.monthly[0];const stages=[['Eligible arrivals',params.arrivals,'Demand'],['Referral throughput',m.referralThroughput,'Referral flow'],['Staffed slots',m.capacity,'Staffed capacity'],['Funded slots',m.fundedSlots,'Operating funds']];$('flow').innerHTML=`<div class="flow-stages">${stages.map(([label,v,b])=>`<div class="flow-stage ${winner.bindingConstraints.includes(b)?'binding':''}"><small>${label}</small><strong>${fmt(v,1)}</strong><div class="gate"><i style="width:${Math.min(100,v/Math.max(...stages.map(s=>s[1]))*100)}%"></i></div><span class="binding-label">${winner.bindingConstraints.includes(b)?'BINDING GATE':''}</span></div>`).join('')}</div><div class="flow-note"><b>${fmt(m.completed,1)} expected completions / month</b> under the selected ${esc(shortNames[winner.id].toLowerCase())}.<br>Unresolved at 12 months: ${fmt(winner.queue,1)} cases.</div>`;}
36
+ function renderComparison(results,winner){const max=Math.max(...results.map(r=>r.incremental),1);$('comparison').innerHTML=results.map(r=>`<div class="compare-row"><div class="compare-name">${esc(shortNames[r.id])}${winner.tiedIds.includes(r.id)?' *':''}<small>${r.feasible?money(r.cost)+' committed':esc(r.reason)}</small></div><div class="compare-track"><div class="compare-bar" style="width:${r.incremental/max*100}%;background:${r.color}"></div></div><div class="compare-number">${r.feasible?'+'+fmt(r.incremental,1):'—'}</div></div>`).join('')+`<p class="fineprint">* Highest-ranked under these assumptions. End-of-horizon unresolved cases: ${fmt(winner.queue)} versus ${fmt(results[0].queue)} under current service.</p>`;}
37
+
38
+ function value(c,key,y=year){return c.indicators?.[key]?.observations?.find(o=>Number(o.year)===Number(y))?.value??null;}
39
+ function renderWorld(){if(!data)return;syncGlobe();$('year').value=year;$('worldMetric').value=metric;const c=data.countries.find(c=>c.id===country)||data.countries[0];if(!c){$('worldChart').textContent='Country data unavailable.';return;}const rows=data.countries.map(c=>({c,x:value(c,'spending'),y:value(c,metric)})),valid=rows.filter(r=>Number.isFinite(r.x)&&r.x>0&&Number.isFinite(r.y));const W=Math.max(310,$('worldChart').clientWidth),H=W<500?365:410,m={l:50,r:30,t:26,b:64},pw=W-m.l-m.r,ph=H-m.t-m.b;const svg=S('svg',{viewBox:`0 0 ${W} ${H}`,class:'world-svg',role:'img','aria-label':`Health expenditure per capita versus ${metric==='life'?'life expectancy':'out-of-pocket share'} in ${year}; correlation is not causation.`});$('worldChart').replaceChildren(svg);let xmin=valid.length?Math.floor(Math.log10(Math.min(...valid.map(r=>r.x)))):1,xmax=valid.length?Math.ceil(Math.log10(Math.max(...valid.map(r=>r.x)))):5;const ymin=metric==='life'?40:0,ymax=metric==='life'?90:80,x=v=>m.l+(Math.log10(v)-xmin)/(xmax-xmin||1)*pw,y=v=>m.t+ph-(v-ymin)/(ymax-ymin)*ph;
40
+ for(let t=ymin;t<=ymax;t+=metric==='life'?10:20){draw(svg,'line',{x1:m.l,x2:W-m.r,y1:y(t),y2:y(t),stroke:'#dce3d8','stroke-width':.7});draw(svg,'text',{x:m.l-9,y:y(t)+3,'text-anchor':'end',fill:'#657a72','font-size':10},String(t));}
41
+ for(let e=xmin;e<=xmax;e++){const v=10**e;draw(svg,'text',{x:x(v),y:H-m.b+22,'text-anchor':'middle',fill:'#657a72','font-size':10},'$'+fmt(v));}
42
+ draw(svg,'text',{x:m.l,y:13,fill:'#4b675e','font-size':10},metric==='life'?'Life expectancy at birth · years':'Out-of-pocket share of health expenditure · %');draw(svg,'text',{x:m.l+pw/2,y:H-10,'text-anchor':'middle',fill:'#4b675e','font-size':10},'Current health expenditure per person · US$ (log scale)');
43
+ const placed=[];for(const r of valid.sort((a,b)=>(a.c.id===country?1:0)-(b.c.id===country?1:0))){const cx=x(r.x),cy=y(r.y),selected=r.c.id===country,g=S('g',{role:'button',tabindex:0,'aria-label':`${r.c.name}: ${fmt(r.x)} dollars per person, ${fmt(r.y,1)} ${metric==='life'?'years':'percent'}. Select country.`});svg.append(g);draw(g,'circle',{cx,cy,r:16,fill:'transparent'});draw(g,'circle',{cx,cy,r:selected?8:5.5,fill:selected?'#147d70':'#a7bfb0',stroke:selected?'#153438':'#fff','stroke-width':selected?2:1.5});let ly=cy-12,lx=cx,anchor='middle';if(cx>W-70){lx=cx-10;anchor='end';}else if(cx<95){lx=cx+10;anchor='start';}while(placed.some(p=>Math.abs(p.y-ly)<13&&Math.abs(p.x-lx)<55))ly+=15;ly=Math.min(H-m.b-5,Math.max(28,ly));placed.push({x:lx,y:ly});draw(g,'text',{x:lx,y:ly,'text-anchor':anchor,'font-size':selected?12:10,fill:selected?'#125a4e':'#60766c','font-weight':selected?700:400},selected?r.c.name:r.c.id);const select=()=>{country=r.c.id;renderWorld();saveState();};g.onclick=select;g.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();select();}};}
44
+ $('worldMissing').textContent=`World Bank snapshot · ${year} · ${valid.length}/${rows.length} countries plotted. ${rows.filter(r=>!Number.isFinite(r.x)||r.x<=0||!Number.isFinite(r.y)).map(r=>r.c.name).join(', ')||'No countries'} missing a required value. No interpolation or carry-forward.`;
45
+ $('countryChips').innerHTML=data.countries.map(c=>`<button class="${c.id===country?'active':''}" data-country="${esc(c.id)}">${esc(c.name)}</button>`).join('');$('countryChips').querySelectorAll('button').forEach(b=>b.onclick=()=>{country=b.dataset.country;renderWorld();saveState();});
46
+ const indicators=[['spending','Health spending / person','US$'],['life','Life expectancy','years'],['workforce','Physicians','per 1,000 people'],['oop','Out-of-pocket share','% of health spending']];$('countryDetail').innerHTML=`<div class="section-label">SELECTED SYSTEM · ${year}</div><h2>${esc(c.name)}</h2><p class="fineprint">${esc(c.region)} · ${esc(c.income)}</p>${indicators.map(([key,label,unit])=>`<div class="indicator"><span>${label}</span><strong>${fmt(value(c,key),key==='workforce'?2:1)}</strong><small>${unit} · ${value(c,key)===null?'no observation':year}</small></div>`).join('')}<p class="fineprint">Country selection changes context only. It does not calibrate the illustrative scenario.</p>`;
47
+ $('observationTable').innerHTML=`<thead><tr><th>Country · ${year}</th><th>Spending / person (US$)</th><th>Life expectancy (years)</th><th>Physicians / 1,000</th><th>OOP share (%)</th></tr></thead><tbody>${data.countries.map(c=>`<tr><td>${esc(c.name)}</td><td>${fmt(value(c,'spending'),1)}</td><td>${fmt(value(c,'life'),1)}</td><td>${fmt(value(c,'workforce'),2)}</td><td>${fmt(value(c,'oop'),1)}</td></tr>`).join('')}</tbody>`;}
48
+
49
+
50
+ const globeMetrics={spending:{label:'Health spending / person',unit:'US$'},workforce:{label:'Physicians',unit:'per 1,000 people'},life:{label:'Life expectancy',unit:'years'},oop:{label:'Out-of-pocket share',unit:'% of health spending'}};
51
+ function selectSystem(id){if(!data.countries.some(c=>c.id===id))return;country=id;renderWorld();saveState();}
52
+ function syncGlobe(){
53
+ const meta=globeMetrics[globeMetric],values=data.countries.map(c=>value(c,globeMetric)).filter(Number.isFinite),c=data.countries.find(c=>c.id===country),v=c?value(c,globeMetric):null;
54
+ $('globeMetric').value=globeMetric;$('globeCountry').value=country;
55
+ $('globeSelected').textContent=`${c?.name||country} · ${fmt(v,globeMetric==='workforce'?2:1)}`;
56
+ $('globeLegend').innerHTML=`<span>${esc(meta.label)} · ${year}</span><div class="globe-scale"></div><div class="globe-scale-values"><span>${values.length?fmt(Math.min(...values),1):'—'}</span><span>${values.length?fmt(Math.max(...values),1):'—'}</span></div><span>${esc(meta.unit)} · linear scale</span>`;
57
+ $('globeCoverage').textContent=`${values.length} observed reference markers · ${data.countries.length-values.length} missing in ${year} · gold ring = selected system`;
58
+ if(!globe){globe=createGlobe($('worldGlobe'),{countries:data.countries,onSelect:selectSystem,selectedCountry:country,getValue:c=>value(c,globeMetric),metricLabel:meta.label+' ('+meta.unit+')',year});globe.setAutoRotate(globeAutoRotate);window.ASCEND_GLOBE=globe;}
59
+ globe.setMetric({getValue:c=>value(c,globeMetric),metricLabel:meta.label+' ('+meta.unit+')',year});globe.setSelection(country);globe.setActive(activeTab==='world');
60
+ $('globeRotate').textContent=globeAutoRotate?'Pause rotation':'Start rotation';$('globeRotate').setAttribute('aria-pressed',String(globeAutoRotate));
61
+ }
62
+ function wireGlobe(){
63
+ $('globeCountry').innerHTML=data.countries.map(c=>`<option value="${esc(c.id)}">${esc(c.name)}</option>`).join('');$('globeCountry').onchange=()=>selectSystem($('globeCountry').value);
64
+ $('globeMetric').onchange=()=>{globeMetric=$('globeMetric').value;syncGlobe();saveState();};
65
+ $('rotateWest').onclick=()=>{globeAutoRotate=false;globe.setAutoRotate(false);globe.rotateBy(-20,0);syncGlobe();};$('rotateEast').onclick=()=>{globeAutoRotate=false;globe.setAutoRotate(false);globe.rotateBy(20,0);syncGlobe();};
66
+ $('globeZoomIn').onclick=()=>globe?.zoomBy(.86);$('globeZoomOut').onclick=()=>globe?.zoomBy(1.16);$('globeReset').onclick=()=>{globe?.reset();};
67
+ $('globeRotate').onclick=()=>{globeAutoRotate=!globeAutoRotate;globe?.setAutoRotate(globeAutoRotate);syncGlobe();};
68
+ $('worldGlobe').addEventListener('pointerdown',()=>{globeAutoRotate=false;globe?.setAutoRotate(false);$('globeRotate').textContent='Start rotation';$('globeRotate').setAttribute('aria-pressed','false');});
69
+ $('saveGlobe').onclick=()=>{const url=globe?.capture();if(!url){toast('Globe image export is unavailable on this device.');return;}const a=document.createElement('a');a.href=url;a.download=`ASCEND-globe-${globeMetric}-${year}.png`;a.click();toast('Globe image saved. Indicator and year are shown in this view.');};
70
+ }
71
+
72
+ function plain(s){return String(s??'').replace(/<[^>]*>/g,' ').replace(/\s+/g,' ').trim();}
73
+ function topic(p){const t=(p.title+' '+(p.abstract||'')).toLowerCase();return ['capacity','access','financing'].filter(k=>({capacity:/capacity|workforce|surgeon|infrastructure|hospital/,access:/access|referral|delay|equity|inequal/,financing:/financ|cost|fund|expend|insurance|economic/})[k].test(t));}
74
+ function papers(){return livePapers||data.evidence?.publications||[];}
75
+ function renderEvidence(){if(!data)return;const q=$('paperSearch').value.trim().toLowerCase();const ps=papers().filter(p=>(evidenceFilter==='all'||topic(p).includes(evidenceFilter))&&(!q||`${p.title} ${p.abstract||''} ${p.authors||''}`.toLowerCase().includes(q)||livePapers!==null));$('evidenceCards').innerHTML=ps.length?ps.map(p=>`<article class="paper-card"><div class="paper-meta">${esc(p.year||'YEAR UNAVAILABLE')} · ${esc(p.pmid?'PUBMED '+p.pmid:'EUROPE PMC')}</div><h3>${esc(p.title)}</h3><div class="authors">${esc(Array.isArray(p.authors)?p.authors.join(', '):p.authors||'Author information unavailable')}</div><p>${topic(p).length?topic(p).map(t=>({capacity:'Capacity',access:'Access & referral',financing:'Financing'})[t]).join(' · '):'Related research'} <span class="badge amber">DISCOVERY LEAD</span></p>${p.abstract?`<details><summary>Read abstract</summary><p>${esc(plain(p.abstract))}</p></details>`:'<p>Abstract unavailable in this snapshot.</p>'}<a class="source-link" href="${esc(safeURL(p.url))}" target="_blank" rel="noopener">Open source ↗</a></article>`).join(''):'<p class="empty">No matching sources in this snapshot. Try a broader term or search Europe PMC.</p>';
76
+ const studies=data.trials?.studies||[];$('trials').innerHTML=studies.length?studies.map(t=>`<article class="trial-card"><div class="section-label">${esc(t.nctId)} · ${esc((t.status||'Status unavailable').replaceAll('_',' '))}</div><h3>${esc(t.title)}</h3><p>${esc(t.studyType||'')} ${esc(Array.isArray(t.phase)?t.phase.join(', '):t.phase||'')}</p><p>${esc((t.locations||[]).slice(0,3).map(l=>l.city||l.facility||'Brazilian site').join(' · '))}${t.locations?.length>3?' + more sites':''}</p><a href="${esc(safeURL(t.url))}" target="_blank" rel="noopener">View registration ↗</a></article>`).join(''):'<p class="empty">Trial registry snapshot unavailable. This is a data-access gap, not an absence of studies.</p>';
77
+ const registry=data.apiRegistry||[];$('sourceRegistry').innerHTML=registry.map(s=>`<article class="source-card"><div class="section-label">${esc(s.status||'RETRIEVED SNAPSHOT')}</div><h3>${esc(s.name||s.id)}</h3><p>${esc(s.description||s.purpose||s.note||'Public-source data; inspect provenance in the export.')}</p><a href="${esc(safeURL(s.documentationUrl||s.url||s.endpoint))}" target="_blank" rel="noopener">Source & documentation ↗</a></article>`).join('');$('snapshotNote').textContent=`Snapshot retrieved ${String(data.accessedAt||data.retrievedAt||data.generatedAt||'Date unavailable').slice(0,10)}. Sources can revise historical observations. Data are cached; the app is not a continuously updating monitoring service.`;}
78
+ function safeURL(u){try{const v=new URL(u);return ['https:','http:'].includes(v.protocol)?v.href:'https://europepmc.org';}catch{return'https://europepmc.org';}}
79
+ async function searchPapers(){const q=$('paperSearch').value.trim();if(!q){toast('Enter a literature search term first.');return;}searchController?.abort();searchController=new AbortController();const timer=setTimeout(()=>searchController.abort(),20000);$('liveSearch').disabled=true;$('searchStatus').textContent='Retrieving matching publications from Europe PMC…';try{const url='https://www.ebi.ac.uk/europepmc/webservices/rest/search?'+new URLSearchParams({query:q,format:'json',resultType:'core',pageSize:'12'});const r=await fetch(url,{signal:searchController.signal});if(!r.ok)throw Error('HTTP '+r.status);const j=await r.json();liveSearchMeta={query:q,url,retrievedAt:new Date().toISOString()};livePapers=(j.resultList?.result||[]).map(p=>({title:p.title,year:p.pubYear,authors:p.authorString,abstract:p.abstractText,pmid:p.pmid|| (p.source==='MED'?p.id:null),doi:p.doi,url:p.doi?'https://doi.org/'+p.doi:'https://europepmc.org/article/'+p.source+'/'+p.id}));evidenceFilter='all';document.querySelectorAll('[data-evidence]').forEach(b=>b.classList.toggle('active',b.dataset.evidence==='all'));$('searchStatus').textContent=`Retrieved ${livePapers.length} of ${fmt(j.hitCount)} matches. Search relevance is not evidence quality.`;renderEvidence();saveState();}catch(e){$('searchStatus').textContent='Live retrieval unavailable. The saved evidence snapshot is still available; no missing data were replaced.';livePapers=null;renderEvidence();}finally{clearTimeout(timer);$('liveSearch').disabled=false;}}
80
+ function download(name,content,type){const a=document.createElement('a');const u=URL.createObjectURL(new Blob([content],{type}));a.href=u;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(u),1000);}
81
+ function exportDecision(){const r=evaluate(params);download('ASCEND-decision.json',JSON.stringify({exportedAt:new Date().toISOString(),prototypeVersion:'1.1-3d',warning:'Illustrative scenario, not calibrated or a causal estimate.',view:{tab:activeTab,country,year,metric,globeMetric,globeCamera:globe?{longitude:$('worldGlobe').dataset.cameraLongitude,latitude:$('worldGlobe').dataset.cameraLatitude,distance:$('worldGlobe').dataset.cameraDistance}:null,evidenceFilter,query:$('paperSearch').value.trim()},assumptions:params,results:r,ranking:recommendation(r),dataSnapshot:data,sources:data.sources,liveSearchResults:livePapers,liveSearchMeta},null,2),'application/json');toast('Decision, assumptions, data and sources exported.');}
82
+ function exportSVG(){const svg=$('terrain').cloneNode(true);svg.setAttribute('xmlns','http://www.w3.org/2000/svg');svg.style.background='#102b31';svg.style.fontFamily='Arial, sans-serif';const W=$('terrain').clientWidth,H=$('terrain').clientHeight;svg.setAttribute('width',W);svg.setAttribute('height',H+48);svg.setAttribute('viewBox',`0 0 ${W} ${H+48}`);draw(svg,'rect',{x:0,y:H,width:W,height:48,fill:'#102b31'});draw(svg,'text',{x:15,y:H+20,fill:'#d2e5da','font-size':10},`ASCEND · ILLUSTRATIVE scenario · budget ${money(params.budget)} · not a causal estimate`);draw(svg,'text',{x:15,y:H+37,fill:'#d2e5da','font-size':9},'Legend: gray=current; green=capacity; violet=referral; amber=combined.');download('ASCEND-decision-landscape.svg',new XMLSerializer().serializeToString(svg),'image/svg+xml');toast('Labeled SVG exported.');}
83
+ function wire(){wireGlobe();document.querySelector('.skip').onclick=e=>{e.preventDefault();$('main').focus();$('main').scrollIntoView();};document.querySelectorAll('[data-tab]').forEach(b=>b.onclick=()=>setTab(b.dataset.tab));for(const k of ['budget','capacity','referralGain','arrivals','unitCost'])$(k).addEventListener('input',()=>{const n=Number($(k).value);if(!Number.isFinite(n)||$(k).value==='')return;params=normalizeState({...params,[k]:n});renderModel();saveState();});$('year').innerHTML=Array.from({length:10},(_,i)=>2024-i).map(y=>`<option>${y}</option>`).join('');$('year').onchange=()=>{year=Number($('year').value);renderWorld();saveState();};$('worldMetric').onchange=()=>{metric=$('worldMetric').value;renderWorld();saveState();};$('reset').onclick=()=>{params={...DEFAULTS};country='BRA';year=2023;metric='life';globeMetric='spending';livePapers=null;liveSearchMeta=null;$('paperSearch').value='';evidenceFilter='all';document.querySelectorAll('[data-evidence]').forEach(b=>b.classList.toggle('active',b.dataset.evidence==='all'));$('searchStatus').textContent='';setTab(activeTab,false);toast('Default view restored.');};$('export').onclick=exportDecision;$('saveChart').onclick=exportSVG;$('share').onclick=async()=>{saveState();try{await navigator.clipboard.writeText(location.href);toast('View link copied. Country, year, indicator and scenario settings are included.');}catch{download('ASCEND-view-link.txt',location.href,'text/plain');toast('View link saved.');}};$('storyPreset').onclick=()=>{params={...DEFAULTS,capacity:145,referralGain:.25};renderModel();saveState();toast('Referral bottleneck selected. Try increasing surgical capacity: it adds no benefit here.');};$('guided').onclick=e=>{e.preventDefault();setTab('landscape');$('storyPreset').click();$('landscape').scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth'});};$('toEvidence').onclick=()=>{setTab('evidence');$('evidence').scrollIntoView({behavior:'smooth'});};$('methods').onclick=$('methodsFooter').onclick=()=>$('methodDialog').showModal();$('closeMethods').onclick=()=>$('methodDialog').close();$('methodDialog').addEventListener('click',e=>{if(e.target===$('methodDialog')){const r=$('methodDialog').getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)$('methodDialog').close();}});$('paperSearch').oninput=()=>{if(livePapers){livePapers=null;liveSearchMeta=null;}renderEvidence();saveState();};$('paperSearch').onkeydown=e=>{if(e.key==='Enter')searchPapers();};$('liveSearch').onclick=searchPapers;document.querySelectorAll('[data-evidence]').forEach(b=>b.onclick=()=>{evidenceFilter=b.dataset.evidence;document.querySelectorAll('[data-evidence]').forEach(x=>x.classList.toggle('active',x===b));renderEvidence();saveState();});window.addEventListener('popstate',()=>{readState();setTab(activeTab,false);});window.addEventListener('hashchange',()=>{readState();setTab(activeTab,false);});const ro=new ResizeObserver(()=>{if(activeTab==='landscape')renderTerrain();else if(activeTab==='world')renderWorld();});ro.observe($('terrainWrap'));ro.observe($('worldChart'));}
84
+
85
+ async function init(){try{data=window.ASCEND_DATA||await fetch('./data.json').then(r=>{if(!r.ok)throw Error('Data snapshot could not be loaded');return r.json();});readState();$('terrainLegend').innerHTML=STRATEGIES.map(s=>`<span><i class="swatch" style="background:${s.color}"></i>${esc(shortNames[s.id])}</span>`).join('');wire();setTab(activeTab,false);window.ASCEND_READY=true;}catch(e){document.querySelector('main').innerHTML='<div class="fatal"><h1>Data snapshot unavailable</h1><p>The app could not load its source data. Use the supplied standalone HTML or serve the project folder. No synthetic data have been substituted.</p><p>'+esc(e.message)+'</p></div>';console.error(e);}}
86
+ init();
assets/ATTRIBUTION.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Geographic data
2
+
3
+ Natural Earth 1:110m land and country boundaries, distributed as topology by world-atlas 2.0.2 and converted to GeoJSON with topojson-client 3.1.0.
4
+
5
+ - Natural Earth data: https://www.naturalearthdata.com/about/terms-of-use/ (public domain)
6
+ - Topology package: https://github.com/topojson/world-atlas (ISC software license)
7
+ - Three.js 0.160.1: https://github.com/mrdoob/three.js/tree/r160 (MIT; full license in vendor/THREE-LICENSE.txt)
8
+
9
+ Geographic boundaries are for reference and do not express a position on disputed territories. Country markers use World Bank metadata capital-reference coordinates, not national centroids. Geometry is embedded locally: no map tiles, third-party scripts, or network calls are needed for the globe.
assets/world-110m.mjs ADDED
The diff for this file is too large to render. See raw diff
 
data.json ADDED
The diff for this file is too large to render. See raw diff
 
globe-math.mjs ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Three.js sphere UVs place Greenwich at u=.25; geographic textures at u=.5.
2
+ export const EQUIRECTANGULAR_OFFSET=.25;
3
+ const RAD=Math.PI/180;
4
+ export function normaliseLongitude(lon){return lon>=-180&&lon<180?lon:((lon+180)%360+360)%360-180;}
5
+ export function lonLatToVector(lon,lat,radius=1){
6
+ const a=lon*RAD,b=lat*RAD,c=Math.cos(b);
7
+ return {x:radius*c*Math.sin(a),y:radius*Math.sin(b),z:radius*c*Math.cos(a)};
8
+ }
9
+ export function cameraFocus(country){return {longitude:normaliseLongitude(country.lon),latitude:Math.max(-75,Math.min(75,country.lat))};}
10
+ export function isMarkerVisible(lon,lat,camera,distance=3){
11
+ const p=lonLatToVector(lon,lat),c=lonLatToVector(camera.longitude,camera.latitude);
12
+ return p.x*c.x+p.y*c.y+p.z*c.z>1/distance;
13
+ }
14
+ export function metricFraction(value,min,max){
15
+ if(value===null||value===undefined||!Number.isFinite(value))return null;
16
+ if(max===min)return .5;
17
+ return Math.max(0,Math.min(1,(value-min)/(max-min)));
18
+ }
19
+ export function makeGraticule(spacing=30,step=3,radius=1.002){
20
+ const lines=[];
21
+ for(let lon=-180;lon<180;lon+=spacing)for(let lat=-90;lat<90;lat+=step)
22
+ lines.push([lonLatToVector(lon,lat,radius),lonLatToVector(lon,Math.min(90,lat+step),radius)]);
23
+ for(let lat=-60;lat<=60;lat+=spacing)for(let lon=-180;lon<180;lon+=step)
24
+ lines.push([lonLatToVector(lon,lat,radius),lonLatToVector(Math.min(180,lon+step),lat,radius)]);
25
+ return lines;
26
+ }
globe.mjs ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as THREE from './vendor/three-0.160.1.module.js';
2
+ import geography from './assets/world-110m.mjs';
3
+ import {lonLatToVector,normaliseLongitude,cameraFocus,isMarkerVisible,metricFraction,makeGraticule,EQUIRECTANGULAR_OFFSET} from './globe-math.mjs';
4
+
5
+ /** One locally bundled WebGL globe; all reference coordinates come from the caller. */
6
+ export function createGlobe(container,{countries=[],onSelect=()=>{},selectedCountry='BRA',getValue=()=>null,metricLabel='Observed indicator',year=''}={}){
7
+ let renderer;
8
+ const inert={ready:false,setSelection(){},setMetric(){},setActive(){},reset(){},rotateBy(){},zoomBy(){},setAutoRotate(){},capture(){return null;},getMarkerPositions(){return [];},dispose(){}};
9
+ try{renderer=new THREE.WebGLRenderer({antialias:true,alpha:true,preserveDrawingBuffer:true,powerPreference:'low-power'});}
10
+ catch(error){
11
+ const notice=document.createElement('p');notice.className='globe-fallback';notice.setAttribute('role','status');
12
+ notice.textContent='3D rendering is unavailable in this browser. Use the country selector and World Lens chart below to explore the same observations.';
13
+ container.replaceChildren(notice);container.dataset.globeReady='false';container.dataset.renderer='unavailable';return inert;
14
+ }
15
+ const canvas=renderer.domElement;
16
+ canvas.dataset.renderer='webgl';canvas.tabIndex=0;canvas.setAttribute('role','application');
17
+ canvas.setAttribute('aria-roledescription','interactive 3D world globe');
18
+ canvas.setAttribute('aria-label','World health indicators. Drag to rotate; arrow keys rotate; plus and minus zoom; Space pauses or resumes rotation. Country markers are capital reference points. Use the country selector for all countries.');
19
+ Object.assign(canvas.style,{width:'100%',height:'100%',display:'block',touchAction:'pan-y',cursor:'grab',outlineOffset:'-4px'});
20
+ container.append(canvas);container.dataset.renderer='webgl';
21
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2));renderer.setClearColor(0x081b22,0);
22
+ renderer.outputColorSpace=THREE.SRGBColorSpace;
23
+ const scene=new THREE.Scene();
24
+ const camera=new THREE.PerspectiveCamera(39,1,.1,30);
25
+ const world=new THREE.Group();scene.add(world);
26
+ scene.add(new THREE.AmbientLight(0xc6efe6,1.45));
27
+ const light=new THREE.DirectionalLight(0xf2fff8,2.15);light.position.set(-3,3,5);scene.add(light);
28
+ const rim=new THREE.DirectionalLight(0x1da6a3,.8);rim.position.set(4,-1,-4);scene.add(rim);
29
+ const texture=makeLandTexture();
30
+ const earth=new THREE.Mesh(new THREE.SphereGeometry(1,96,64),new THREE.MeshPhongMaterial({map:texture,shininess:10,specular:0x31535a}));world.add(earth);
31
+ const gridPositions=[];
32
+ for(const [a,b] of makeGraticule())gridPositions.push(a.x,a.y,a.z,b.x,b.y,b.z);
33
+ const grid=new THREE.LineSegments(new THREE.BufferGeometry().setAttribute('position',new THREE.Float32BufferAttribute(gridPositions,3)),new THREE.LineBasicMaterial({color:0x8abfb6,transparent:true,opacity:.13,depthWrite:false}));world.add(grid);
34
+ const outlines=[];
35
+ for(const path of geography.boundaries.coordinates)for(let i=1;i<path.length;i++){
36
+ const a=lonLatToVector(path[i-1][0],path[i-1][1],1.004),b=lonLatToVector(path[i][0],path[i][1],1.004);
37
+ outlines.push(a.x,a.y,a.z,b.x,b.y,b.z);
38
+ }
39
+ world.add(new THREE.LineSegments(new THREE.BufferGeometry().setAttribute('position',new THREE.Float32BufferAttribute(outlines,3)),new THREE.LineBasicMaterial({color:0x85bbae,transparent:true,opacity:.34,depthWrite:false})));
40
+ const atmosphere=new THREE.Mesh(new THREE.SphereGeometry(1.025,64,48),new THREE.ShaderMaterial({
41
+ uniforms:{glowColor:{value:new THREE.Color(0x53c7bc)}},
42
+ vertexShader:'varying vec3 n; varying vec3 p; void main(){vec4 v=modelViewMatrix*vec4(position,1.0);p=v.xyz;n=normalize(normalMatrix*normal);gl_Position=projectionMatrix*v;}',
43
+ fragmentShader:'varying vec3 n;varying vec3 p;uniform vec3 glowColor;void main(){float f=pow(1.0-max(0.0,dot(normalize(n),normalize(-p))),3.4);gl_FragColor=vec4(glowColor,f*0.22);}',
44
+ transparent:true,blending:THREE.AdditiveBlending,depthWrite:false,side:THREE.FrontSide
45
+ }));world.add(atmosphere);
46
+ const markerGeometry=new THREE.SphereGeometry(.017,16,12);
47
+ const markers=countries.filter(c=>Number.isFinite(c.lat)&&Number.isFinite(c.lon)).map(country=>{
48
+ const mesh=new THREE.Mesh(markerGeometry,new THREE.MeshBasicMaterial({color:0x86dfcc}));
49
+ const p=lonLatToVector(country.lon,country.lat,1.016);mesh.position.set(p.x,p.y,p.z);mesh.userData.country=country;world.add(mesh);return mesh;
50
+ });
51
+ const halo=new THREE.Mesh(new THREE.RingGeometry(.036,.042,64),new THREE.MeshBasicMaterial({color:0xf1cc83,side:THREE.DoubleSide,transparent:true,opacity:.95,depthWrite:false}));world.add(halo);
52
+ const haloOuter=new THREE.Mesh(new THREE.RingGeometry(.057,.06,64),new THREE.MeshBasicMaterial({color:0xf1cc83,side:THREE.DoubleSide,transparent:true,opacity:.4,depthWrite:false}));world.add(haloOuter);
53
+ let selected=null, distance=3.25, longitude=-47.9292,latitude=-15.7801,target=null;
54
+ let active=true,inView=true,disposed=false,autoRotate=!window.matchMedia('(prefers-reduced-motion: reduce)').matches,raf=0,lastTime=0;
55
+ const reducedMotion=window.matchMedia('(prefers-reduced-motion: reduce)');
56
+ let metric={getValue,metricLabel,year};
57
+ const raycaster=new THREE.Raycaster(),pointer=new THREE.Vector2();
58
+ function syncCamera(){
59
+ const p=lonLatToVector(longitude,latitude,distance);camera.position.set(p.x,p.y,p.z);camera.lookAt(0,0,0);camera.updateMatrixWorld();
60
+ container.dataset.cameraLongitude=longitude.toFixed(3);container.dataset.cameraLatitude=latitude.toFixed(3);container.dataset.cameraDistance=distance.toFixed(3);
61
+ container.dataset.autoRotate=String(autoRotate);
62
+ }
63
+ function draw(){if(disposed)return;syncCamera();renderer.render(scene,camera);}
64
+ function canAnimate(){return active&&inView&&!document.hidden;}
65
+ function frame(time){
66
+ raf=0;if(disposed||!canAnimate())return;
67
+ const dt=lastTime?Math.min((time-lastTime)/1000,.05):0;lastTime=time;
68
+ if(target){
69
+ const dl=normaliseLongitude(target.longitude-longitude),da=target.latitude-latitude;
70
+ if(Math.abs(dl)+Math.abs(da)<.12||reducedMotion.matches){longitude=target.longitude;latitude=target.latitude;target=null;}
71
+ else{const t=1-Math.exp(-dt*7);longitude=normaliseLongitude(longitude+dl*t);latitude+=da*t;}
72
+ }else if(autoRotate&&!drag)longitude=normaliseLongitude(longitude+dt*2.4);
73
+ draw();if(target||autoRotate)raf=requestAnimationFrame(frame);
74
+ }
75
+ function requestFrame(){if(!raf&&canAnimate()&&!disposed){lastTime=0;raf=requestAnimationFrame(frame);}}
76
+ function pauseOrResume(){if(!canAnimate()&&raf){cancelAnimationFrame(raf);raf=0;}else requestFrame();}
77
+ function setSelection(id){
78
+ if(selected===id)return;
79
+ const country=countries.find(c=>c.id===id);if(!country)return;selected=id;container.dataset.selectedCountry=id;
80
+ const p=lonLatToVector(country.lon,country.lat,1.024),normal=new THREE.Vector3(p.x,p.y,p.z).normalize();
81
+ for(const ring of [halo,haloOuter]){ring.position.set(p.x,p.y,p.z);ring.quaternion.setFromUnitVectors(new THREE.Vector3(0,0,1),normal);}
82
+ target=cameraFocus(country);if(reducedMotion.matches){longitude=target.longitude;latitude=target.latitude;target=null;}
83
+ canvas.setAttribute('aria-label',`${country.name} selected. ${metric.metricLabel}, ${metric.year}. Country markers are capital reference points. Drag or use arrow keys to rotate; plus and minus zoom; Space toggles rotation.`);
84
+ draw();requestFrame();
85
+ }
86
+ function setMetric(next){
87
+ metric={...metric,...next};
88
+ const values=countries.map(c=>metric.getValue(c)).filter(v=>v!==null&&v!==undefined&&Number.isFinite(v));
89
+ const min=values.length?Math.min(...values):0,max=values.length?Math.max(...values):1;
90
+ for(const mesh of markers){const t=metricFraction(metric.getValue(mesh.userData.country),min,max);mesh.material.color.set(t===null?0x73858b:new THREE.Color(0x267b80).lerp(new THREE.Color(0xc0f4d2),t));}
91
+ container.dataset.metricLabel=metric.metricLabel;container.dataset.metricYear=String(metric.year);container.dataset.metricMin=String(min);container.dataset.metricMax=String(max);
92
+ draw();
93
+ }
94
+ function rotateBy(deltaLon,deltaLat){target=null;longitude=normaliseLongitude(longitude+deltaLon);latitude=Math.max(-75,Math.min(75,latitude+deltaLat));draw();requestFrame();}
95
+ function zoomBy(factor){distance=Math.max(2.05,Math.min(5,distance*factor));draw();requestFrame();}
96
+ function setAutoRotate(value){autoRotate=Boolean(value);draw();pauseOrResume();}
97
+ function reset(){distance=3.25;const country=countries.find(c=>c.id===selected)||countries[0];target=country?cameraFocus(country):{longitude:0,latitude:15};if(reducedMotion.matches){longitude=target.longitude;latitude=target.latitude;target=null;}draw();requestFrame();}
98
+ function resize(){const w=Math.max(200,container.clientWidth),h=Math.max(260,container.clientHeight||460);renderer.setSize(w,h,false);camera.aspect=w/h;camera.updateProjectionMatrix();draw();}
99
+ let drag=null,lastHover=0;
100
+ function hit(event){
101
+ const rect=canvas.getBoundingClientRect();pointer.set((event.clientX-rect.left)/rect.width*2-1,-(event.clientY-rect.top)/rect.height*2+1);
102
+ raycaster.setFromCamera(pointer,camera);
103
+ const intersections=raycaster.intersectObjects(markers);
104
+ return intersections.find(h=>isMarkerVisible(h.object.userData.country.lon,h.object.userData.country.lat,{longitude,latitude},distance))?.object;
105
+ }
106
+ function down(event){if(event.button!==0&&event.pointerType!=='touch')return;drag={x:event.clientX,y:event.clientY,startX:event.clientX,startY:event.clientY,moved:false};target=null;canvas.setPointerCapture(event.pointerId);canvas.style.cursor='grabbing';}
107
+ function move(event){
108
+ if(drag){const dx=event.clientX-drag.x,dy=event.clientY-drag.y;drag.moved ||= Math.hypot(event.clientX-drag.startX,event.clientY-drag.startY)>5;drag.x=event.clientX;drag.y=event.clientY;rotateBy(-dx*.28,dy*.22);}
109
+ else if(performance.now()-lastHover>50){lastHover=performance.now();const marker=hit(event);canvas.style.cursor=marker?'pointer':'grab';const value=marker?metric.getValue(marker.userData.country):null;const display=value===null||value===undefined||!Number.isFinite(value)?'No observation':new Intl.NumberFormat('en',{maximumFractionDigits:2}).format(value);canvas.title=marker?`${marker.userData.country.name} — ${metric.metricLabel}: ${display} (${metric.year}). Capital reference point.`:'';}
110
+ }
111
+ function up(event){if(!drag)return;const moved=drag.moved;drag=null;canvas.style.cursor='grab';if(canvas.hasPointerCapture(event.pointerId))canvas.releasePointerCapture(event.pointerId);if(!moved){const marker=hit(event);if(marker){setSelection(marker.userData.country.id);onSelect(marker.userData.country.id);}}requestFrame();}
112
+ function cancel(){drag=null;canvas.style.cursor='grab';requestFrame();}
113
+ function wheel(event){event.preventDefault();zoomBy(Math.exp(event.deltaY*.001));}
114
+ function key(event){
115
+ const map={ArrowLeft:[-10,0],ArrowRight:[10,0],ArrowUp:[0,8],ArrowDown:[0,-8]};
116
+ if(map[event.key]){event.preventDefault();rotateBy(...map[event.key]);}
117
+ else if(event.key==='+'||event.key==='='){event.preventDefault();zoomBy(.88);}
118
+ else if(event.key==='-'){event.preventDefault();zoomBy(1.14);}
119
+ else if(event.key===' '){event.preventDefault();setAutoRotate(!autoRotate);}
120
+ else if(event.key==='Home'){event.preventDefault();reset();}
121
+ }
122
+ canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointermove',move);canvas.addEventListener('pointerup',up);canvas.addEventListener('pointercancel',cancel);canvas.addEventListener('wheel',wheel,{passive:false});canvas.addEventListener('keydown',key);
123
+ const observer=typeof ResizeObserver!=='undefined'?new ResizeObserver(resize):null;observer?.observe(container);
124
+ const intersection=typeof IntersectionObserver!=='undefined'?new IntersectionObserver(entries=>{inView=entries[0].isIntersecting;pauseOrResume();},{threshold:.01}):null;intersection?.observe(container);
125
+ document.addEventListener('visibilitychange',pauseOrResume);
126
+ function motionChange(event){if(event.matches){autoRotate=false;pauseOrResume();}}
127
+ reducedMotion.addEventListener?.('change',motionChange);
128
+ resize();setMetric(metric);setSelection(selectedCountry);
129
+ if(target){longitude=target.longitude;latitude=target.latitude;target=null;draw();}
130
+ container.dataset.globeReady='true';requestFrame();
131
+ return {ready:true,setSelection,setMetric,setActive(value){active=Boolean(value);pauseOrResume();},reset,rotateBy,zoomBy,setAutoRotate,
132
+ capture(){draw();return canvas.toDataURL('image/png');},
133
+ getMarkerPositions(){syncCamera();const rect=canvas.getBoundingClientRect();return markers.map(mesh=>{const c=mesh.userData.country,p=mesh.position.clone().project(camera);return {id:c.id,x:rect.left+(p.x+1)/2*rect.width,y:rect.top+(1-p.y)/2*rect.height,visible:isMarkerVisible(c.lon,c.lat,{longitude,latitude},distance),value:metric.getValue(c)};});},
134
+ dispose(){disposed=true;if(raf)cancelAnimationFrame(raf);observer?.disconnect();intersection?.disconnect();document.removeEventListener('visibilitychange',pauseOrResume);reducedMotion.removeEventListener?.('change',motionChange);canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointermove',move);canvas.removeEventListener('pointerup',up);canvas.removeEventListener('pointercancel',cancel);canvas.removeEventListener('wheel',wheel);canvas.removeEventListener('keydown',key);scene.traverse(o=>{o.geometry?.dispose();if(o.material){for(const material of Array.isArray(o.material)?o.material:[o.material])material.dispose();}});texture.dispose();renderer.dispose();canvas.remove();container.dataset.globeReady='false';}
135
+ };
136
+ }
137
+
138
+ function makeLandTexture(){
139
+ const canvas=document.createElement('canvas');canvas.width=2048;canvas.height=1024;
140
+ const ctx=canvas.getContext('2d');ctx.fillStyle='#102b31';ctx.fillRect(0,0,canvas.width,canvas.height);
141
+ const land=geography.land;const geometries=land.type==='FeatureCollection'?land.features.map(f=>f.geometry):[land.geometry];
142
+ ctx.fillStyle='#38695f';ctx.strokeStyle='rgba(138,205,177,.55)';ctx.lineWidth=.9;
143
+ for(const geometry of geometries){const polygons=geometry.type==='Polygon'?[geometry.coordinates]:geometry.coordinates;
144
+ for(const polygon of polygons)for(const shift of [-canvas.width,0,canvas.width]){
145
+ ctx.beginPath();
146
+ for(const ring of polygon){let previousX=null;ring.forEach(([lon,lat],index)=>{
147
+ let x=(lon+180)/360*canvas.width;
148
+ if(previousX!==null){while(x-previousX>canvas.width/2)x-=canvas.width;while(x-previousX<-canvas.width/2)x+=canvas.width;}
149
+ previousX=x;const y=(90-lat)/180*canvas.height;index?ctx.lineTo(x+shift,y):ctx.moveTo(x+shift,y);
150
+ });ctx.closePath();}
151
+ ctx.fill('evenodd');ctx.stroke();
152
+ }
153
+ }
154
+ const texture=new THREE.CanvasTexture(canvas);texture.colorSpace=THREE.SRGBColorSpace;
155
+ texture.wrapS=THREE.RepeatWrapping;texture.offset.x=EQUIRECTANGULAR_OFFSET;texture.anisotropy=4;return texture;
156
+ }
index.html CHANGED
The diff for this file is too large to render. See raw diff
 
model.mjs ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ASCEND illustrative service-flow model, not a fitted clinical or causal model.
3
+ * Units: expected operations and unresolved cases; months; incremental BRL.
4
+ * Fractional counts are deliberate expected flows, not individual patient records.
5
+ *
6
+ * Each month: available = opening unresolved cases + new arrivals;
7
+ * completed = min(available, referral throughput, staffed capacity, funded slots).
8
+ * Referral throughput = arrivals * min(1, baseline referral + intervention gain).
9
+ * Therefore completions cannot exceed arrivals: this model can slow backlog growth
10
+ * but cannot clear an existing backlog or estimate waiting times. It has no exits,
11
+ * mortality, contraindications, repeat operations, or empirical effect estimates.
12
+ *
13
+ * An additional slot costs unitCost, bundling staff, theatre service, and funding.
14
+ * Theatre/combined purchase capacity and fund it; referral only funds use of
15
+ * existing capacity. All intervention budgets are committed expenditure, even
16
+ * when other constraints make some purchased slots unused. Programme fixed costs
17
+ * are paid in full. Current-service costs are excluded from incremental spending.
18
+ */
19
+
20
+ export const DEFAULTS = Object.freeze({
21
+ budget: 2400000,
22
+ capacity: 90,
23
+ referralGain: 0.15,
24
+ arrivals: 150,
25
+ initialQueue: 240,
26
+ baseReferral: 0.6,
27
+ unitCost: 12000,
28
+ referralFixedCost: 600000,
29
+ baselineFundedSlots: 100,
30
+ months: 12,
31
+ });
32
+
33
+ export const STRATEGIES = Object.freeze([
34
+ Object.freeze({ id: 'current', name: 'Current service', color: '#8493a6' }),
35
+ Object.freeze({ id: 'theatre', name: 'Expand surgical capacity', color: '#61d8bf' }),
36
+ Object.freeze({ id: 'referral', name: 'Strengthen referral', color: '#a99bff' }),
37
+ Object.freeze({ id: 'combined', name: 'Combine both', color: '#f4c56a' }),
38
+ ]);
39
+
40
+ const BOUNDS = Object.freeze({
41
+ budget: [0, 6000000], capacity: [40, 180], referralGain: [0, 0.4],
42
+ arrivals: [0, 10000], initialQueue: [0, 1000000], baseReferral: [0, 1],
43
+ unitCost: [1, 10000000], referralFixedCost: [0, 6000000],
44
+ baselineFundedSlots: [0, 10000], months: [1, 120],
45
+ });
46
+ const TOLERANCE = 1e-7;
47
+
48
+ /** Only actual finite numbers are accepted; missing fields use defaults. */
49
+ export function normalizeState(input = {}) {
50
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
51
+ throw new TypeError('Model state must be an object of finite numbers.');
52
+ }
53
+ const state = {};
54
+ for (const [key, fallback] of Object.entries(DEFAULTS)) {
55
+ const value = Object.hasOwn(input, key) ? input[key] : fallback;
56
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
57
+ throw new TypeError(`${key} must be an actual finite number.`);
58
+ }
59
+ const [lower, upper] = BOUNDS[key];
60
+ state[key] = Math.max(lower, Math.min(upper, value));
61
+ }
62
+ state.months = Math.floor(state.months);
63
+ return state;
64
+ }
65
+
66
+ function simulate(state, { additionalSlots = 0, referralGain = 0, expand = false } = {}) {
67
+ const capacity = state.capacity + (expand ? additionalSlots : 0);
68
+ const fundedSlots = state.baselineFundedSlots + additionalSlots;
69
+ const referralThroughput = state.arrivals * Math.min(1, state.baseReferral + referralGain);
70
+ const monthly = [];
71
+ let queue = state.initialQueue;
72
+ let total = 0;
73
+ for (let index = 0; index < state.months; index += 1) {
74
+ const openingQueue = queue;
75
+ const available = openingQueue + state.arrivals;
76
+ const completed = Math.min(available, referralThroughput, capacity, fundedSlots);
77
+ queue = Math.max(0, available - completed);
78
+ total += completed;
79
+ monthly.push({
80
+ month: index + 1, openingQueue, arrivals: state.arrivals, available,
81
+ referralThroughput: Math.min(available, referralThroughput), capacity,
82
+ fundedSlots, completed, closingQueue: queue, queue,
83
+ });
84
+ }
85
+ const final = monthly.at(-1);
86
+ const limits = [
87
+ ['Demand', final.available], ['Referral flow', final.referralThroughput],
88
+ ['Staffed capacity', final.capacity], ['Operating funds', final.fundedSlots],
89
+ ];
90
+ const bindingConstraints = limits.filter(([, limit]) => Math.abs(limit - final.completed) <= TOLERANCE).map(([label]) => label);
91
+ const bottleneck = bindingConstraints.includes('Demand') ? 'Demand' : bindingConstraints.join(' + ');
92
+ return { completed: total, queue, monthly, bottleneck, bindingConstraints };
93
+ }
94
+
95
+ /** Returns current, theatre, referral, combined; infeasible options are explicit. */
96
+ export function evaluate(input = {}) {
97
+ const state = normalizeState(input);
98
+ const baseline = simulate(state);
99
+ return STRATEGIES.map(strategy => {
100
+ const isCurrent = strategy.id === 'current';
101
+ const usesReferral = strategy.id === 'referral' || strategy.id === 'combined';
102
+ const expand = strategy.id === 'theatre' || strategy.id === 'combined';
103
+ const feasible = isCurrent || (state.budget > 0 && (!usesReferral || state.budget >= state.referralFixedCost));
104
+ const reason = feasible ? '' : state.budget <= 0
105
+ ? 'No incremental budget is available.'
106
+ : 'Budget is below the fixed referral programme cost.';
107
+ const programmeCost = !isCurrent && feasible && usesReferral ? state.referralFixedCost : 0;
108
+ const cost = !isCurrent && feasible ? state.budget : 0;
109
+ const slotExpenditure = Math.max(0, cost - programmeCost);
110
+ const additionalSlots = slotExpenditure / state.unitCost / state.months;
111
+ const result = isCurrent || !feasible ? baseline : simulate(state, {
112
+ additionalSlots,
113
+ referralGain: usesReferral ? state.referralGain : 0,
114
+ expand,
115
+ });
116
+ return {
117
+ ...strategy, ...result, feasible, reason,
118
+ incremental: Math.max(0, result.completed - baseline.completed),
119
+ cost, programmeCost, slotExpenditure, additionalSlots,
120
+ };
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Maximizes extra completed operations, then minimizes committed cost.
126
+ * Exact outcome/cost ties retain input order; tiedIds makes that convention visible.
127
+ * This is a scenario ranking, not a clinical recommendation or cost-effectiveness test.
128
+ */
129
+ export function recommendation(results) {
130
+ if (!Array.isArray(results)) throw new TypeError('Results must be an array.');
131
+ const feasible = results.filter(result => result.feasible !== false);
132
+ if (!feasible.length) throw new RangeError('At least one feasible result is required.');
133
+ for (const result of feasible) {
134
+ if (!Number.isFinite(result.incremental) || !Number.isFinite(result.cost)) {
135
+ throw new TypeError('Feasible results must have finite incremental outcomes and cost.');
136
+ }
137
+ }
138
+ const bestEffect = Math.max(...feasible.map(result => result.incremental));
139
+ const effectTies = feasible.filter(result => bestEffect - result.incremental <= TOLERANCE);
140
+ const lowestCost = Math.min(...effectTies.map(result => result.cost));
141
+ const ties = effectTies.filter(result => result.cost - lowestCost <= TOLERANCE);
142
+ return { ...ties[0], tiedIds: ties.map(result => result.id), effectTiedIds: effectTies.map(result => result.id) };
143
+ }
144
+
145
+ /** Row-major scenario grid. y=0 is no assumed referral improvement. */
146
+ export function landscape(input = {}, cols = 35, rows = 25) {
147
+ if (![cols, rows].every(value => Number.isInteger(value) && value >= 2 && value <= 200)) {
148
+ throw new RangeError('Landscape dimensions must be integers between 2 and 200.');
149
+ }
150
+ const state = normalizeState(input);
151
+ // Referral throughput never exceeds arrivals, so available demand cannot bind
152
+ // below it, even with an empty opening queue. All remaining limits are fixed:
153
+ // monthly completions are constant, and no monthly history is needed here.
154
+ // Keep evaluate()'s detailed simulation for monthly inspection and conservation.
155
+ const options = STRATEGIES.map(strategy => {
156
+ const isCurrent = strategy.id === 'current';
157
+ const usesReferral = strategy.id === 'referral' || strategy.id === 'combined';
158
+ const feasible = isCurrent || (state.budget > 0 && (!usesReferral || state.budget >= state.referralFixedCost));
159
+ const cost = !isCurrent && feasible ? state.budget : 0;
160
+ const programmeCost = !isCurrent && feasible && usesReferral ? state.referralFixedCost : 0;
161
+ const additionalSlots = (cost - programmeCost) / state.unitCost / state.months;
162
+ return {
163
+ ...strategy, feasible, cost, additionalSlots,
164
+ usesReferral: feasible && usesReferral,
165
+ expand: feasible && (strategy.id === 'theatre' || strategy.id === 'combined'),
166
+ };
167
+ });
168
+ const baseThroughput = state.arrivals * state.baseReferral;
169
+ const cells = [];
170
+ for (let row = 0; row < rows; row += 1) {
171
+ const y = 0.4 * row / (rows - 1);
172
+ const improvedThroughput = state.arrivals * Math.min(1, state.baseReferral + y);
173
+ for (let col = 0; col < cols; col += 1) {
174
+ const x = 40 + 140 * col / (cols - 1);
175
+ const baselineCompleted = Math.min(baseThroughput, x, state.baselineFundedSlots) * state.months;
176
+ const results = options.map(option => {
177
+ const monthlyCompleted = Math.min(
178
+ option.usesReferral ? improvedThroughput : baseThroughput,
179
+ x + (option.expand ? option.additionalSlots : 0),
180
+ state.baselineFundedSlots + option.additionalSlots,
181
+ );
182
+ const completed = monthlyCompleted * state.months;
183
+ return {
184
+ ...option, completed,
185
+ incremental: Math.max(0, completed - baselineCompleted),
186
+ queue: Math.max(0, state.initialQueue + state.months * (state.arrivals - monthlyCompleted)),
187
+ };
188
+ });
189
+ const winner = recommendation(results);
190
+ cells.push({
191
+ index: cells.length, col, row, xIndex: col, yIndex: row, x, y,
192
+ winnerId: winner.id, winnerName: winner.name, color: winner.color,
193
+ incremental: winner.incremental, completed: winner.completed,
194
+ cost: winner.cost, queue: winner.queue, tiedIds: winner.tiedIds,
195
+ effectTiedIds: winner.effectTiedIds,
196
+ });
197
+ }
198
+ }
199
+ return cells;
200
+ }
package.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "ascend-decision-observatory",
3
+ "version": "1.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "test": "node --test tests/*.mjs"
8
+ }
9
+ }
refresh_data.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reproducible public-data snapshot for ASCEND; no synthetic fallback."""
3
+ from pathlib import Path
4
+ import argparse, concurrent.futures, datetime, gzip, html, json, math, re, time
5
+ import urllib.request, urllib.parse
6
+
7
+ BASE = Path(__file__).resolve().parent
8
+ DEST = BASE / 'data.json'
9
+ RAW = BASE / 'data_raw'
10
+ COUNTRIES = ['BRA','MEX','CHL','COL','ARG','USA','GBR','DEU','IND','ZAF','KEN','THA']
11
+ INDICATORS = {
12
+ 'spending':('SH.XPD.CHEX.PC.CD','Current health expenditure per capita','current US$'),
13
+ 'life':('SP.DYN.LE00.IN','Life expectancy at birth','years'),
14
+ 'workforce':('SH.MED.PHYS.ZS','Physicians','per 1,000 people'),
15
+ 'oop':('SH.XPD.OOPC.CH.ZS','Out-of-pocket expenditure','% of current health expenditure'),
16
+ 'population':('SP.POP.TOTL','Population','people'),
17
+ }
18
+
19
+ def validate(data):
20
+ assert data['kind'] == 'observed/retrieved'
21
+ assert {c['id'] for c in data['countries']} == set(COUNTRIES)
22
+ assert len(data['countries']) == 12
23
+ for c in data['countries']:
24
+ assert c['name'] and c['region'] and c['income']
25
+ assert c['lat'] is None or -90 <= c['lat'] <= 90
26
+ assert c['lon'] is None or -180 <= c['lon'] <= 180
27
+ assert set(c['indicators']) == set(INDICATORS)
28
+ for key, m in c['indicators'].items():
29
+ assert m['id'] == INDICATORS[key][0]
30
+ assert [o['year'] for o in m['observations']] == list(range(2015,2025))
31
+ assert all(o['value'] is None or isinstance(o['value'],(int,float)) and math.isfinite(o['value']) for o in m['observations'])
32
+ observed = [o for o in m['observations'] if o['value'] is not None]
33
+ assert m['latest'] == (observed[-1] if observed else None)
34
+ for source in data['sources']:
35
+ assert source['url'].startswith('https://') and source['accessedAt'] and source['licenseNote']
36
+ assert data['evidence']['classification'] == 'related literature; not model effect estimates'
37
+ for p in data['evidence']['publications']:
38
+ assert p['title'] and p['url'].startswith('https://')
39
+ assert data['trials']['classification'] == 'registered studies; not evidence of efficacy or surgery relevance'
40
+ for p in data['trials']['studies']:
41
+ assert p['nctId'].startswith('NCT') and p['url'].startswith('https://clinicaltrials.gov/study/')
42
+ assert all(loc['country'] == 'Brazil' for loc in p['locations'])
43
+ for c in data['connectorProofs']:
44
+ assert 'schemaFields' in c and 'patientData' not in c
45
+ return {'countries':len(data['countries']),'series':60,'observations':600,
46
+ 'nullObservations':sum(o['value'] is None for c in data['countries'] for m in c['indicators'].values() for o in m['observations']),
47
+ 'publications':len(data['evidence']['publications']),'trials':len(data['trials']['studies'])}
48
+
49
+
50
+ def utcnow():
51
+ return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')
52
+
53
+ def fetch(job):
54
+ name,url,note = job
55
+ record = {'id':name,'name':name.replace('_',' ').title(),'url':url,'accessedAt':utcnow(),'licenseNote':note}
56
+ for attempt in range(2):
57
+ try:
58
+ req = urllib.request.Request(url,headers={'User-Agent':'ASCEND-research-prototype/0.1','Accept':'application/json','Accept-Encoding':'gzip'})
59
+ with urllib.request.urlopen(req,timeout=35) as response:
60
+ body=response.read()
61
+ if body[:2] == b'\x1f\x8b': body=gzip.decompress(body)
62
+ payload=json.loads(body.decode('utf-8'))
63
+ record.update(status='success',httpStatus=response.status,bytes=len(body),attempts=attempt+1)
64
+ (RAW/f'{name}.json').write_text(json.dumps(payload,ensure_ascii=False,indent=2))
65
+ return name,payload,record
66
+ except Exception as exc:
67
+ record.update(status='failed',error=str(exc),attempts=attempt+1)
68
+ if attempt == 0: time.sleep(1)
69
+ return name,None,record
70
+
71
+ def clean_text(text):
72
+ return html.unescape(re.sub('<[^>]+>', ' ', text or '')).strip()
73
+
74
+ def build():
75
+ RAW.mkdir(parents=True,exist_ok=True)
76
+ country_path=';'.join(COUNTRIES)
77
+ wb_note='World Bank open data; check indicator attribution and applicable World Bank dataset terms before redistribution. Source attribution retained.'
78
+ epmc_note='Europe PMC bibliographic service. Article and abstract rights remain with their respective holders; linked records retain identifiers and attribution.'
79
+ gov_note='Official Brazilian Ministry of Health public API. Connector proof only; schema field names retained, no individual patient records distributed.'
80
+ jobs=[('worldbank_countries',f'https://api.worldbank.org/v2/country/{country_path}?format=json&per_page=100',wb_note)]
81
+ for key,(ident,label,unit) in INDICATORS.items():
82
+ jobs.append((f'worldbank_{key}',f'https://api.worldbank.org/v2/country/{country_path}/indicator/{ident}?format=json&date=2015:2024&per_page=20000',wb_note))
83
+ queries={
84
+ 'europe_pmc_brazil':'(TITLE_ABS:"cancer surgery" OR TITLE_ABS:"surgical oncology" OR TITLE_ABS:"surgical access") AND TITLE_ABS:Brazil',
85
+ 'europe_pmc_capacity':'TITLE_ABS:"surgical capacity" AND (TITLE_ABS:financing OR TITLE_ABS:access OR TITLE_ABS:health)'
86
+ }
87
+ for key,q in queries.items():
88
+ jobs.append((key,'https://www.ebi.ac.uk/europepmc/webservices/rest/search?'+urllib.parse.urlencode({'query':q,'format':'json','pageSize':6,'resultType':'core'}),epmc_note))
89
+ jobs.extend([
90
+ ('demas_cnes','https://apidadosabertos.saude.gov.br/cnes/estabelecimentos?codigo_uf=35&limit=1&offset=0',gov_note),
91
+ ('demas_sih','https://apidadosabertos.saude.gov.br/assistencia-a-saude/sih-procedimentos-hospitalares?nu_ano=2023&limit=1&offset=0',gov_note),
92
+ ('clinical_trials','https://clinicaltrials.gov/api/v2/studies?query.cond=cancer&query.locn=Brazil&pageSize=5&format=json','ClinicalTrials.gov public registry data; sponsor submissions are not independent verification of efficacy. See ClinicalTrials.gov terms and conditions.')
93
+ ])
94
+ responses={}; sources=[]
95
+ with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
96
+ for name,payload,record in pool.map(fetch,jobs):
97
+ responses[name]=payload;sources.append(record)
98
+ print(name,record['status'],flush=True)
99
+ (RAW/'request_manifest.json').write_text(json.dumps(sources,indent=2))
100
+ metadata=responses['worldbank_countries']
101
+ if not isinstance(metadata,list) or len(metadata)<2 or not isinstance(metadata[1],list):
102
+ raise RuntimeError('Country metadata unavailable; no substitute snapshot was fabricated. Inspect raw request manifest.')
103
+ metadata={m['id']:m for m in metadata[1]}
104
+ countries=[]
105
+ for country in COUNTRIES:
106
+ meta=metadata[country]
107
+ c={'id':country,'name':meta['name'],'region':meta['region']['value'],'income':meta['incomeLevel']['value'],
108
+ 'lat':float(meta['latitude']) if meta.get('latitude') else None,'lon':float(meta['longitude']) if meta.get('longitude') else None,
109
+ 'coordinateNote':'World Bank country metadata coordinates (capital reference), not a national centroid.', 'indicators':{}}
110
+ for key,(ident,label,unit) in INDICATORS.items():
111
+ response=responses[f'worldbank_{key}']; rows=response[1] if isinstance(response,list) and len(response)>1 and isinstance(response[1],list) else []
112
+ values={int(row['date']):row['value'] for row in rows if row.get('countryiso3code')==country}
113
+ observations=[{'year':year,'value':values.get(year)} for year in range(2015,2025)]
114
+ observed=[o for o in observations if o['value'] is not None]
115
+ c['indicators'][key]={'id':ident,'label':label,'unit':unit,'observations':observations,'latest':observed[-1] if observed else None,
116
+ 'sourceId':f'worldbank_{key}','retrievalStatus':'success' if rows else 'unavailable'}
117
+ countries.append(c)
118
+ publications=[]; seen=set()
119
+ for key,q in queries.items():
120
+ response=responses[key] or {}
121
+ for p in response.get('resultList',{}).get('result',[]):
122
+ ident=p.get('doi') or p.get('pmid') or p['id']
123
+ if ident in seen: continue
124
+ seen.add(ident)
125
+ source=p.get('source','MED');id_=p['id']
126
+ publications.append({'id':id_,'title':clean_text(p.get('title')),'authors':p.get('authorString',''),'year':int(p['pubYear']) if p.get('pubYear') else None,
127
+ 'doi':p.get('doi'),'pmid':p.get('pmid'),'url':f'https://europepmc.org/article/{source}/{id_}',
128
+ 'abstract':clean_text(p.get('abstractText')),'journal':p.get('journalInfo',{}).get('journal',{}).get('title',''),
129
+ 'classification':'related literature; not model effect estimates','query':q,'sourceId':key})
130
+ studies=[]
131
+ for row in (responses['clinical_trials'] or {}).get('studies',[]):
132
+ p=row['protocolSection']; ident=p['identificationModule']; design=p.get('designModule',{}); status=p.get('statusModule',{})
133
+ locations=p.get('contactsLocationsModule',{}).get('locations',[])
134
+ studies.append({'nctId':ident['nctId'],'title':ident.get('briefTitle',''),'status':status.get('overallStatus',''),
135
+ 'phase':design.get('phases',[]),'studyType':design.get('studyType',''),'briefSummary':p.get('descriptionModule',{}).get('briefSummary',''),
136
+ 'url':'https://clinicaltrials.gov/study/'+ident['nctId'],'locations':[{k:loc[k] for k in ['facility','city','state','country'] if k in loc} for loc in locations if loc.get('country')=='Brazil'],
137
+ 'sourceId':'clinical_trials','lastUpdate':status.get('lastUpdatePostDateStruct',{}).get('date')})
138
+ proofs=[]
139
+ for name,key in [('demas_cnes','estabelecimentos'),('demas_sih','sih_procedimentos_hospitalares')]:
140
+ response=responses[name] or {}; rows=response.get(key,[])
141
+ proofs.append({'id':name,'label':'CNES establishment schema' if name=='demas_cnes' else 'SIH hospital-procedure schema',
142
+ 'status':'success' if rows else 'unavailable','schemaFields':sorted(rows[0].keys()) if rows else [],'sampleRowsRetrieved':len(rows),
143
+ 'sourceId':name,'note':'Connectivity and schema proof only. One response row does not establish data completeness, historical coverage, surgical relevance, or analytic validity.'})
144
+ data={'version':'1.0.0','kind':'observed/retrieved','accessedAt':utcnow(),'yearRange':[2015,2024],
145
+ 'description':'Twelve-country contextual health indicators and separate literature/registry discovery feeds. Observational comparisons do not establish intervention effects.',
146
+ 'countries':countries,'sources':sources,'apiRegistry':[{k:v for k,v in r.items() if k not in ['bytes']} for r in sources],
147
+ 'evidence':{'classification':'related literature; not model effect estimates','selection':'Two explicit Europe PMC queries, six results per query, deduplicated. Convenience discovery set, not a systematic review. No relevance or risk-of-bias adjudication.','status':'success' if publications else 'unavailable','publications':publications},
148
+ 'trials':{'classification':'registered studies; not evidence of efficacy or surgery relevance','selection':'First five API results for cancer and Brazil. No curated surgery filter.','status':'success' if studies else 'unavailable','studies':studies},
149
+ 'connectorProofs':proofs,
150
+ 'limitations':['Countries are a purposive demonstration selection, not a representative sample.','Latest values can refer to different years; each year must remain visible.','Expenditure uses current US dollars, not inflation-adjusted or purchasing-power-adjusted values.','Missing values remain null; no interpolation or imputation.','National ecological indicators cannot estimate effects of a surgical intervention.','Bibliographic and registry retrieval is not a systematic evidence synthesis.','No patient-level records are included in this distributable snapshot.']}
151
+ data['validation']=validate(data)
152
+ DEST.parent.mkdir(parents=True,exist_ok=True)
153
+ DEST.write_text(json.dumps(data,ensure_ascii=False,indent=2))
154
+ print(json.dumps(data['validation'],indent=2))
155
+
156
+ if __name__ == '__main__':
157
+ parser=argparse.ArgumentParser();parser.add_argument('--validate',action='store_true');args=parser.parse_args()
158
+ if args.validate: print(json.dumps(validate(json.loads(DEST.read_text())),indent=2))
159
+ else: build()
source.html ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#132d32"><title>ASCEND — Decision Observatory</title><link rel="stylesheet" href="style.css"></head>
3
+ <body data-view="world">
4
+ <a class="skip" href="#main">Skip to content</a>
5
+ <header class="masthead"><a class="brand" href="#"><span class="brandmark" aria-hidden="true">↗</span><span>ASCEND<small>DECISION OBSERVATORY</small></span></a><nav aria-label="Views"><button data-tab="world" class="active" aria-current="page">World lens</button><button data-tab="landscape">Decision landscape</button><button data-tab="evidence">Evidence atlas</button></nav><button class="icon-btn" id="methods">How it works <span aria-hidden="true">↗</span></button></header>
6
+ <main id="main" tabindex="-1">
7
+ <section class="intro"><div><div class="eyebrow"><span class="live-dot"></span> HEALTH SYSTEMS · EXPLORATORY RESEARCH</div><h1>Find the point where<br>the decision <em>changes.</em></h1><p class="lede">Explore what is known. Make assumptions visible.<br>Discover which uncertainty is worth resolving next.</p></div><div class="intro-aside"><span class="issue">FIELD NOTE 001 / SURGICAL ACCESS</span><div class="intro-line"></div><p>More funding is only useful<br>if care can move through<br>the whole system.</p><a href="#main" id="guided">Explore a bottleneck <span>↓</span></a></div></section>
8
+ <div class="utility"><div class="view-status" id="viewStatus"><span class="badge amber">ILLUSTRATIVE SCENARIO</span><span>12-month planning model · not a policy forecast</span></div><div><button id="reset" class="text-btn">Reset</button><button id="export" class="text-btn">Export decision ↗</button><button id="share" class="text-btn">Copy view link ↗</button></div></div>
9
+ <section id="landscape" class="view" aria-label="Decision landscape" hidden>
10
+ <div class="workspace"><aside class="controls"><div class="section-label">01 / SET THE CONDITIONS</div><h2>One pathway.<br>Four alternatives.</h2><p class="muted">A hypothetical surgical programme. These inputs are editable assumptions, not estimates for Brazil.</p>
11
+ <label for="budget">Additional annual budget <output id="budgetValue"></output></label><input type="range" id="budget" min="0" max="6000000" step="100000" value="2400000"><div class="range-ends"><span>R$0</span><span>R$6m</span></div>
12
+ <label for="capacity">Usable surgical slots / month <output id="capacityValue"></output></label><input type="range" id="capacity" min="40" max="180" step="1" value="90"><div class="range-ends"><span>40 slots</span><span>180 slots</span></div>
13
+ <label for="referralGain">Referral improvement <output id="referralValue"></output></label><input type="range" id="referralGain" min="0" max="0.4" step="0.01" value="0.15"><div class="range-ends"><span>+0 percentage points</span><span>+40 pp</span></div>
14
+ <details class="assumptions"><summary>Inspect all assumptions</summary><div><label for="arrivals">Eligible arrivals / month</label><input type="number" id="arrivals" min="1" max="1000" value="150"><label for="unitCost">Staffed slot bundle cost (R$)</label><input type="number" id="unitCost" min="1000" max="100000" step="1000" value="12000"><p>Baseline referral throughput: 60% of arrivals. Baseline funded slots: 100/month. Initial unresolved queue: 240. Referral programme fixed cost: R$600,000. Monthly completions can be fractional expected quantities.</p><p>Capacity purchases commit funds even if slots go unused. Referral effectiveness is hypothetical. Existing backlog cannot be cleared in this deliberately limited flow model.</p></div></details>
15
+ <button id="storyPreset" class="secondary full">Try a referral bottleneck ↗</button>
16
+ </aside><div class="landscape-panel"><div class="chart-heading"><div><div class="section-label">02 / EXPLORE THE DECISION BOUNDARY</div><h2>The landscape of possibilities</h2></div><button id="saveChart" class="text-btn">Save SVG ↓</button></div><p class="chart-deck">Each region shows the option delivering the most additional procedures. Click to change the conditions.</p><div id="terrainLegend" class="legend"></div><div id="terrainWrap" class="terrain-wrap"><svg id="terrain" role="img" aria-labelledby="terrainTitle terrainDesc"></svg></div><div class="chart-note"><span>↖ Click a point, or use the sliders</span><span>Colors indicate scenario choices, not probability.</span></div><div id="decisionCallout" class="decision-callout" aria-live="polite"></div></div></div>
17
+ <div class="results-grid"><section class="flow-panel"><div class="section-label">03 / FOLLOW THE BOTTLENECK</div><h2 id="flowTitle">How care moves through the system</h2><div id="flow"></div><p class="fineprint">Schematic monthly throughput. The narrowest gate limits completions. No patient-level waiting times or survival effects are inferred.</p></section><section class="comparison-panel"><div class="section-label">04 / COMPARE THE ALTERNATIVES</div><h2>What changes over 12 months?</h2><div id="comparison"></div><p class="fineprint">Rank by additional completions; break ties by lower committed spending, then simpler option. “Combined” can tie with a single intervention.</p></section></div>
18
+ <section class="next-question"><span class="question-icon" aria-hidden="true">?</span><div><div class="section-label">THE NEXT QUESTION</div><h2 id="nextQuestion"></h2><p id="nextReason"></p></div><button id="toEvidence" class="secondary">Inspect related evidence ↗</button></section>
19
+ </section>
20
+ <section id="world" class="view active" aria-label="World lens"><div class="world-head"><div><div class="section-label">OBSERVATIONS, NOT CAUSAL EFFECTS</div><h1>One world.<br><em>Many possible futures.</em></h1><p class="muted">A fixed-year comparison of public indicators. National averages do not measure surgical access.</p></div><div class="world-filters"><label for="year">Reference year</label><select id="year"></select><label for="worldMetric">Vertical measure</label><select id="worldMetric"><option value="life">Life expectancy</option><option value="oop">Out-of-pocket share</option></select></div></div><div class="globe-explorer"><section class="globe-panel" aria-label="Interactive world globe"><div class="globe-topbar"><div><div class="section-label">THE WORLD IN CONTEXT</div><h2>Explore the systems behind the numbers.</h2></div><button id="saveGlobe" class="globe-text" aria-label="Save globe image">Save globe image ↓</button></div><div class="globe-readout"><label for="globeMetric">Color the reference markers by</label><select id="globeMetric"><option value="spending">Health spending per person</option><option value="workforce">Physicians per 1,000</option><option value="life">Life expectancy</option><option value="oop">Out-of-pocket share</option></select><span id="globeSelected"></span></div><div id="worldGlobe" class="world-globe" aria-label="Drag to rotate the world; select a reference marker to inspect a country"></div><div class="globe-bottom"><div id="globeLegend" class="globe-legend"></div><div class="globe-controls" aria-label="Globe navigation"><button id="rotateWest" aria-label="Rotate west">←</button><button id="rotateEast" aria-label="Rotate east">→</button><button id="globeZoomOut" aria-label="Zoom out">−</button><button id="globeZoomIn" aria-label="Zoom in">+</button><button id="globeReset" aria-label="Focus selected country">◎</button><button id="globeRotate" aria-pressed="true">Pause rotation</button></div></div><p id="globeCoverage" class="globe-coverage"></p><p class="globe-guide">Drag to rotate · scroll or use + / − to zoom · click a reference marker to select. Gray means missing data. Countries outside this 12-system sample have no data markers.</p></section><aside class="country-detail" id="countryDetail"></aside></div><div class="globe-country-selector"><label for="globeCountry">Find a system</label><select id="globeCountry"></select><p>Reference markers use capital coordinates, not service locations or national centroids.</p></div><div class="world-layout"><section class="scatter-panel"><div class="section-label">COMPARE THE OBSERVATIONS</div><h2>A different perspective on the same systems</h2><div id="worldChart"></div><p id="worldMissing" class="fineprint"></p><div id="countryChips" class="chips" aria-label="Select a country"></div></section></div><section class="world-table"><h3>Inspect the observations</h3><div class="table-scroll"><table id="observationTable"></table></div></section></section>
21
+ <section id="evidence" class="view" aria-label="Evidence atlas" hidden><div class="evidence-head"><div><div class="section-label">TRACEABLE SOURCES / OPEN QUESTIONS</div><h2>Evidence has a place.<br>So does uncertainty.</h2><p class="muted">Publications and trial registrations are discovery leads. None automatically calibrates the scenario model.</p></div><div class="search-box"><label for="paperSearch">Explore publications</label><div><input id="paperSearch" type="search" placeholder="Search title, abstract, author…"><button id="liveSearch" class="secondary">Search Europe PMC ↗</button></div><p id="searchStatus" class="fineprint" aria-live="polite"></p></div></div><div class="evidence-categories"><button class="active" data-evidence="all">All sources</button><button data-evidence="capacity">Capacity</button><button data-evidence="access">Access & referral</button><button data-evidence="financing">Financing</button></div><div id="evidenceCards" class="evidence-cards"></div><section class="trial-section"><div class="section-label">RESEARCH IN PROGRESS</div><h2>Registered cancer studies with Brazilian sites</h2><p class="muted">Registrations describe research activity, not proven benefit, surgical relevance, or routine treatment capacity.</p><div id="trials" class="trial-grid"></div></section><section class="source-section"><div class="section-label">SOURCE HEALTH</div><h2>Where the data come from</h2><div id="sourceRegistry" class="source-grid"></div><p id="snapshotNote" class="fineprint"></p></section></section>
22
+ </main><footer><div class="footer-brand">ASCEND <span>Make the assumptions visible.</span></div><p>Independent research prototype. No HSIL affiliation, endorsement, or permission to reproduce its proprietary framework is implied.</p><button id="methodsFooter" class="text-btn">Model & sources ↗</button></footer>
23
+ <dialog id="methodDialog"><button id="closeMethods" class="close" aria-label="Close methods">×</button><div class="section-label">READ BEFORE INTERPRETING</div><h2>A decision laboratory,<br>with its assumptions exposed.</h2><div class="method-content"><h3>What is real?</h3><p>The World Lens uses retrieved World Bank observations, with reference year and missing values preserved. Its interactive 3D globe uses capital reference markers for the 12 included countries; marker colors encode the selected measure, not surgical capacity. Geographic boundaries are Natural Earth low-resolution reference geometry, not a statement on disputed borders. Literature comes from Europe PMC; trial registrations come from ClinicalTrials.gov. Data snapshots remain inspectable when a service is unavailable.</p><h3>What is hypothetical?</h3><p>Every number in the Decision Landscape is an illustrative input. The model compares current practice, additional staffed surgical capacity, improved referrals, and both. It is not calibrated to a country, hospital, cancer type, or real financing policy.</p><h3>The calculation</h3><p>Each month: completions = minimum of patients available, referral throughput, usable capacity, and funded slots. Unresolved cases carry forward. Added budget buys staffed and funded slots; a referral programme first incurs its fixed cost. The comparison maximizes completed procedures, with spending and simpler interventions breaking ties.</p><h3>What the colors mean</h3><p>Regions show which strategy wins under a pair of capacity and referral assumptions. This is a sensitivity map, not a causal estimate, probability surface, or formal value-of-information analysis. Changing the objective could change the preferred strategy.</p><h3>What remains unknown?</h3><p>True unmet need, usable theatre capacity, implementation response, marginal costs, and patient outcomes require local evidence. National spending and life expectancy are contextual observations and never become model inputs automatically.</p><h3>AI and evidence</h3><p>AI assisted the development and source discovery for this prototype. The running app uses a transparent calculation and literature search, not a hidden language model. Publication relevance tags are keyword-based; they do not assess study quality or confirm causality.</p><h3>Intellectual contribution</h3><p>ASCEND links uncertainty, decisions and evidence in an original interface. It does not copy the Health Systems Primer's framework or CADUCEUS's layout, code or simulation multipliers. Existing methods are credited in the concept brief.</p></div></dialog>
24
+ <div id="toast" class="toast" role="status" aria-live="polite"></div><script type="module" src="app.mjs"></script>
25
+ </body></html>
style.css CHANGED
@@ -1,28 +1,6 @@
1
- body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
4
- }
5
-
6
- h1 {
7
- font-size: 16px;
8
- margin-top: 0;
9
- }
10
-
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
16
- }
17
-
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
24
- }
25
-
26
- .card p:last-child {
27
- margin-bottom: 0;
28
- }
 
1
+ :root{--ink:#153438;--deep:#102b31;--muted:#5c706f;--paper:#f3f4ed;--white:#fffefa;--line:#d6ded6;--teal:#147d70;--mint:#bde9c8;--orange:#bd7842;--blue:#4284b8;--purple:#8876a7;--font:'Avenir Next','Segoe UI',Arial,sans-serif;--mono:'SFMono-Regular',Consolas,monospace}*{box-sizing:border-box}body{margin:0;color:var(--ink);background:var(--paper);font:15px/1.55 var(--font)}button,input,select{font:inherit}button,a,input,summary,select{-webkit-tap-highlight-color:transparent}button{cursor:pointer}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible{outline:3px solid #d49a48;outline-offset:4px}a{color:inherit}button{color:inherit}.skip{position:absolute;top:-80px}.skip:focus{top:8px;left:8px;background:white;padding:10px;z-index:10}.masthead{height:100px;max-width:1600px;margin:auto;padding:0 5%;display:flex;align-items:center;justify-content:space-between;gap:32px;border-bottom:1px solid var(--line)}.brand{display:flex;align-items:center;gap:12px;text-decoration:none;font-size:24px;font-weight:700;letter-spacing:3px;line-height:1.1}.brandmark{width:39px;height:43px;background:var(--ink);color:var(--mint);display:grid;place-items:center;font-size:29px;border-radius:14px 3px 14px 3px}.brand small{display:block;font:8px/2 var(--mono);letter-spacing:2px}nav{display:flex;gap:5px}nav button{border:0;background:none;font-size:13px;padding:12px 16px;border-radius:30px}nav .active{background:var(--ink);color:#fff}.icon-btn{border:1px solid var(--line);background:none;border-radius:24px;padding:10px 18px;font-size:12px}.icon-btn span{margin-left:10px}main{max-width:1600px;margin:auto;padding:0 5%}.intro{display:flex;justify-content:space-between;align-items:center;padding:55px 0 42px;gap:30px}.eyebrow,.section-label,.issue{font:10px/1.5 var(--mono);letter-spacing:1.5px}.eyebrow{display:flex;align-items:center;gap:8px}.live-dot{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--teal)}h1{font:normal clamp(40px,4.5vw,66px)/1.03 Georgia,serif;letter-spacing:-2px;margin:20px 0}h1 em{font-weight:normal;color:var(--teal)}.lede{color:var(--muted);font-size:15px;margin:22px 0 0}.intro-aside{min-width:240px;margin-right:35px;padding-top:16px}.issue{font-size:9px}.intro-line{height:1px;background:var(--line);margin:14px 0}.intro-aside p{font:23px/1.3 Georgia,serif}.intro-aside a{font-size:12px;text-decoration:none;display:flex;justify-content:space-between}.utility{display:flex;justify-content:space-between;align-items:center;padding:17px 0;gap:20px;border-top:1px solid var(--line)}.view-status{display:flex;align-items:center;gap:12px;font-size:11px;color:var(--muted)}.badge{font:9px var(--mono);letter-spacing:.5px;padding:5px 8px;border-radius:3px;white-space:nowrap}.amber{color:#745022;background:#f0e5cb}.green{color:#145548;background:#dcebdd}.text-btn{border:0;background:none;padding:7px 9px;font-size:11px;text-decoration:none}.text-btn:hover{color:var(--teal);text-decoration:underline}.view{padding-bottom:35px}.view[hidden]{display:none!important}.workspace{display:grid;grid-template-columns:280px minmax(0,1fr);border:1px solid var(--line);border-radius:15px;overflow:hidden;background:var(--white)}.controls{padding:27px 25px;border-right:1px solid var(--line);background:#f8f9f3}.section-label{color:var(--muted);font-size:9px}h2{font:normal 29px/1.15 Georgia,serif;letter-spacing:-.4px;margin:12px 0}h3{font-size:16px}.muted{font-size:12px;color:var(--muted);max-width:570px}.controls>label{font-size:11px;display:flex;flex-wrap:wrap;justify-content:space-between;gap:8px;margin-top:25px;font-weight:600}.controls output{font-family:var(--mono);color:var(--teal);font-size:11px}input[type=range]{width:100%;accent-color:var(--teal);margin:12px 0 0;cursor:pointer;height:18px}.range-ends{display:flex;justify-content:space-between;font:9px var(--mono);color:var(--muted);margin-top:5px}.assumptions{margin:25px 0 20px;border-top:1px solid var(--line);padding-top:15px;font-size:11px}.assumptions summary{cursor:pointer}.assumptions label{display:block;margin:14px 0 5px}.assumptions input{width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:#fff}.assumptions p{font-size:10px;color:var(--muted)}.secondary{border:1px solid var(--line);padding:10px 14px;border-radius:6px;background:transparent;font-size:11px;white-space:nowrap}.secondary:hover{background:#e6ede3}.full{width:100%}.landscape-panel{padding:27px 30px 22px;min-width:0}.chart-heading{display:flex;justify-content:space-between;gap:15px;align-items:center}.chart-heading h2{font-size:28px;margin-bottom:8px}.chart-deck{font-size:11px;color:var(--muted);margin:0 0 16px;max-width:550px}.legend{display:flex;gap:15px;flex-wrap:wrap;font-size:10px;margin-bottom:12px}.legend span{display:flex;gap:6px;align-items:center}.swatch{display:inline-block;width:9px;height:9px;border-radius:2px}.terrain-wrap{width:100%;border-radius:8px;overflow:hidden;background:var(--deep)}#terrain{display:block;width:100%;height:430px;cursor:crosshair}.chart-note{display:flex;justify-content:space-between;gap:15px;font-size:9px;color:var(--muted);margin:9px 0 17px}.decision-callout{display:flex;justify-content:space-between;align-items:center;gap:20px;padding:15px 0 0;border-top:1px solid var(--line)}.decision-callout h3{margin:0 0 4px;font:21px Georgia,serif}.decision-callout p{font-size:10px;color:var(--muted);margin:0}.decision-value{text-align:right;white-space:nowrap}.decision-value strong{display:block;font:31px Georgia,serif}.decision-value small{font-size:10px}.results-grid{display:grid;grid-template-columns:1fr 1fr;gap:35px;margin:35px 0}.flow-panel,.comparison-panel{min-width:0}.flow-panel h2,.comparison-panel h2{font-size:25px}.flow-stages{display:flex;gap:0;margin:27px 0 18px;position:relative}.flow-stage{flex:1;position:relative;min-width:0}.flow-stage:not(:last-child):after{content:'→';position:absolute;right:5px;top:31px;color:#8ea4a0}.flow-stage strong{display:block;font:29px Georgia,serif;margin:8px 0}.flow-stage small{font-size:10px;color:var(--muted)}.gate{height:5px;margin-right:22px;background:#d3e2d7;border-radius:3px}.gate i{display:block;height:5px;background:var(--teal);border-radius:3px}.flow-stage.binding .gate i{background:var(--orange)}.binding .binding-label{font:8px var(--mono);color:#875021}.flow-note{font-size:12px;padding:10px 13px;border-left:2px solid var(--orange);background:#eeeade}.fineprint{font-size:10px;color:var(--muted);line-height:1.6}.compare-row{display:grid;grid-template-columns:125px 1fr 55px;align-items:center;gap:10px;padding:10px 0;border-bottom:1px solid var(--line)}.compare-name{font-size:11px}.compare-name small{display:block;font-size:9px;color:var(--muted)}.compare-track{height:16px;position:relative;background:#e5e9e0;border-radius:2px}.compare-bar{height:100%;min-width:0;border-radius:2px}.compare-number{font:12px var(--mono);text-align:right}.next-question{display:flex;align-items:center;gap:23px;background:#e3eddf;padding:28px 32px;border-radius:12px}.question-icon{font:44px Georgia,serif;color:var(--teal);width:50px}.next-question h2{font-size:24px;margin:7px 0}.next-question p{font-size:11px;color:var(--muted);margin:0;max-width:700px}.next-question button{margin-left:auto}.world-head,.evidence-head{display:flex;justify-content:space-between;gap:25px;margin:20px 0 30px}.world-head h2,.evidence-head h2{font-size:38px}.world-filters{display:grid;grid-template-columns:auto auto;gap:8px 15px;align-content:center;align-items:center;font-size:11px}.world-filters select{padding:9px 12px;border:1px solid var(--line);border-radius:5px;background:var(--white)}.world-layout{display:grid;grid-template-columns:minmax(0,1fr) 270px;gap:30px}.scatter-panel{background:var(--white);padding:22px;border:1px solid var(--line);border-radius:12px}.world-svg{width:100%;height:410px}.country-detail{padding:25px;background:var(--deep);color:var(--white);border-radius:12px}.country-detail h2{font-size:32px}.country-detail .section-label,.country-detail .fineprint{color:#aac3bd}.indicator{border-bottom:1px solid #315055;padding:12px 0}.indicator strong{font:27px Georgia,serif;display:block}.indicator span{font-size:11px;color:#c1d1cc}.indicator small{font:9px var(--mono);color:var(--mint);display:block;margin-top:3px}.chips{display:flex;gap:6px;flex-wrap:wrap;margin-top:20px}.chips button{border:1px solid var(--line);background:transparent;padding:7px 10px;border-radius:20px;font-size:10px}.chips button.active{background:var(--ink);color:white}.world-table{margin-top:30px}.table-scroll{overflow:auto}table{border-collapse:collapse;width:100%;text-align:left;font-size:11px}th{font-weight:600;color:var(--muted);padding:10px;border-bottom:1px solid var(--ink)}td{padding:10px;border-bottom:1px solid var(--line)}.search-box{align-self:center;max-width:490px}.search-box>label{display:block;font-size:11px;margin-bottom:7px}.search-box>div{display:flex;gap:7px}.search-box input{min-width:180px;max-width:320px;width:100%;padding:11px;border:1px solid var(--line);border-radius:5px;background:var(--white)}.evidence-categories{display:flex;gap:6px;margin:25px 0}.evidence-categories button{background:none;border:1px solid var(--line);padding:10px 18px;border-radius:25px;font-size:11px}.evidence-categories button.active{background:var(--ink);color:white}.evidence-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.paper-card{padding:23px;background:var(--white);border:1px solid var(--line);border-radius:10px;display:flex;flex-direction:column}.paper-card .paper-meta{font:9px var(--mono);color:var(--teal)}.paper-card h3{font:20px/1.25 Georgia,serif;margin:15px 0}.paper-card .authors{font-size:10px;color:var(--muted)}.paper-card p{font-size:11px;color:var(--muted)}.paper-card summary{font-size:10px;cursor:pointer}.paper-card details{margin:10px 0}.paper-card .source-link{font-size:11px;color:var(--teal);margin-top:auto;padding-top:17px;text-decoration:none}.trial-section,.source-section{margin-top:45px;padding-top:25px;border-top:1px solid var(--line)}.trial-grid,.source-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:15px}.trial-card,.source-card{padding:20px;border:1px solid var(--line);border-radius:8px}.trial-card h3{font:19px/1.3 Georgia,serif}.trial-card p{font-size:11px}.trial-card a,.source-card a{font-size:11px;color:var(--teal)}.source-card h3{margin:7px 0}.source-card p{font-size:11px;color:var(--muted)}footer{max-width:1600px;padding:30px 5%;border-top:1px solid var(--line);margin:auto;display:flex;align-items:center;gap:30px}.footer-brand{font-size:15px;font-weight:700;white-space:nowrap}.footer-brand span{display:block;font-size:10px;font-weight:400;color:var(--muted)}footer p{font-size:10px;color:var(--muted);max-width:550px}footer button{margin-left:auto}dialog{max-width:660px;width:calc(100% - 32px);max-height:90vh;overflow:auto;border:1px solid var(--line);border-radius:15px;padding:38px;background:var(--white);color:var(--ink)}dialog::backdrop{background:#102b31b3;backdrop-filter:blur(3px)}dialog h2{font-size:36px}.method-content p{font-size:12px;color:var(--muted)}.close{position:absolute;right:15px;top:10px;font-size:28px;border:0;background:none}.toast{position:fixed;bottom:25px;left:50%;transform:translateX(-50%);padding:12px 20px;background:var(--ink);color:white;border-radius:8px;font-size:12px;opacity:0;pointer-events:none;transition:opacity .2s;z-index:20}.toast.show{opacity:1}.empty{padding:35px;border:1px dashed var(--line);color:var(--muted);grid-column:1/-1}.fatal{margin:40px;padding:25px;background:#ffe5dd}.loading{padding:30px;color:var(--muted)}.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0)}
2
+ @media(min-width:1500px){#terrain{height:470px}}@media(max-width:1100px){.masthead{gap:15px;padding:0 3%}main{padding:0 3%}nav button{padding:10px 12px}.workspace{grid-template-columns:240px 1fr}.controls{padding:23px 18px}.landscape-panel{padding:24px 20px}.intro-aside{margin-right:0}.world-layout{grid-template-columns:1fr 230px}.evidence-cards{grid-template-columns:repeat(2,1fr)}.chart-heading h2{font-size:24px}.evidence-head{display:block}.search-box{margin-top:20px}}@media(max-width:760px){.masthead{height:auto;min-height:116px;flex-wrap:wrap;padding:18px 5%;gap:16px}.brand{font-size:20px}.brandmark{width:33px;height:36px}.masthead>.icon-btn{margin-left:auto;font-size:10px;padding:8px 12px}nav{order:3;width:100%;justify-content:space-between}nav button{font-size:11px;padding:10px 11px;min-height:42px}main{padding:0 5%}.intro{padding:32px 0 27px}.intro-aside{display:none}h1{font-size:44px;letter-spacing:-1.5px}.lede{font-size:12px}.eyebrow{font-size:8px}.utility{display:block;padding:14px 0}.utility>div:last-child{margin-top:8px;display:flex;justify-content:flex-end}.view-status{font-size:9px;gap:8px;flex-wrap:wrap}.workspace{display:flex;flex-direction:column}.landscape-panel{order:0;padding:23px 14px}.controls{order:1;border:0;border-top:1px solid var(--line);padding:22px}.controls h2 br{display:none}.controls>p{max-width:none}.controls>label{margin-top:20px}.chart-heading h2{font-size:23px}.chart-heading>.text-btn{font-size:10px;padding:4px;white-space:nowrap}.chart-deck{font-size:10px}.legend{gap:10px;font-size:9px}#terrain{height:355px}.chart-note{font-size:8px;display:block}.chart-note span{display:block;margin-top:4px}.decision-callout{gap:12px}.decision-callout h3{font-size:19px}.decision-value strong{font-size:29px}.results-grid{grid-template-columns:1fr;gap:24px;margin:28px 0}.next-question{padding:22px;gap:12px;flex-wrap:wrap}.next-question .question-icon{display:none}.next-question button{margin:6px 0 0}.next-question h2{font-size:25px}.world-head{display:block}.world-head h2,.evidence-head h2{font-size:32px}.world-filters{justify-content:start;margin-top:20px}.world-layout{grid-template-columns:1fr}.scatter-panel{padding:12px}.world-svg{height:370px}.country-detail{display:grid;grid-template-columns:1fr 1fr;gap:0 20px}.country-detail>h2,.country-detail>.section-label,.country-detail>.fineprint{grid-column:1/-1}.evidence-categories{overflow:auto;gap:5px}.evidence-categories button{padding:9px 12px;white-space:nowrap}.search-box>div{flex-direction:column}.search-box input{max-width:none}.evidence-cards,.trial-grid,.source-grid{grid-template-columns:1fr}.paper-card{padding:22px}.trial-card{padding:20px}footer{padding:25px 5%;flex-wrap:wrap;gap:15px}footer p{width:100%;order:3;margin:0}footer button{font-size:10px}dialog{padding:28px 24px}.method-content p{font-size:12px}.flow-stage strong{font-size:26px}.section-label{font-size:8px}}
3
+ @media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important;animation:none!important}}
4
+ body[data-view="world"] .intro{display:none}body[data-view="world"] .utility{border-top:0;margin-top:12px}.world-head h1{font-size:43px;margin:8px 0 12px;line-height:1.05;letter-spacing:-1px}.world-head{margin:22px 0 26px}.world-layout{display:block}.globe-explorer{display:grid;grid-template-columns:minmax(0,1fr) 270px;gap:24px}.globe-panel{background:#102b31;border:1px solid #284a4d;border-radius:15px;color:#e2f0e5;overflow:hidden;min-width:0}.globe-topbar{padding:23px 26px 0;display:flex;align-items:center;justify-content:space-between;gap:20px}.globe-topbar .section-label{color:#90b6a6}.globe-topbar h2{font-size:24px;margin:7px 0 13px}.globe-text{border:0;background:none;color:#c3dece;font-size:10px;white-space:nowrap;padding:8px}.globe-text:hover{text-decoration:underline}.globe-readout{padding:0 26px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;font-size:10px;color:#b6cfc1}.globe-readout select{background:#1a3c40;color:#e2f0e5;border:1px solid #48635e;border-radius:5px;font-size:11px;padding:7px 9px;max-width:240px}.globe-readout span{margin-left:auto;color:#bde9c8;font:11px var(--mono)}.world-globe{height:470px;position:relative;overflow:hidden;outline:none}.world-globe canvas{display:block;width:100%;height:100%;touch-action:pan-y;cursor:grab}.world-globe canvas:active{cursor:grabbing}.globe-bottom{padding:0 26px;display:flex;justify-content:space-between;align-items:center;gap:20px}.globe-legend{font-size:10px;color:#bdd3c5;max-width:300px}.globe-scale{width:130px;height:5px;background:linear-gradient(90deg,#466b68,#bde9c8);border-radius:3px;margin:7px 0 3px}.globe-scale-values{display:flex;justify-content:space-between;width:130px;font:9px var(--mono)}.globe-controls{display:flex;gap:5px;align-items:center}.globe-controls button{background:#1a3c40;border:1px solid #48635e;border-radius:5px;color:#e2f0e5;min-width:36px;min-height:36px;font-size:14px}.globe-controls button:last-child{font-size:10px;padding:0 10px}.globe-controls button:hover{background:#31594f}.globe-coverage{padding:8px 26px 0;font:9px var(--mono);color:#b8cfc1;margin:9px 0 0}.globe-guide{padding:0 26px 20px;font-size:9px;color:#9cb8a9;margin:8px 0 0}.globe-country-selector{display:flex;gap:12px;align-items:center;margin:15px 0 30px}.globe-country-selector label{font-size:11px;font-weight:600}.globe-country-selector select{padding:8px 12px;border:1px solid var(--line);background:var(--white);border-radius:5px;min-width:150px}.globe-country-selector p{font-size:10px;color:var(--muted);margin-left:auto}.globe-explorer .country-detail{padding:25px}.world-layout .scatter-panel{margin-top:0}.globe-fallback{padding:35px;font-size:13px;color:#d9e9de}.globe-fallback strong{display:block;font:24px Georgia,serif;margin-bottom:10px}
5
+ @media(max-width:1100px){.globe-explorer{grid-template-columns:minmax(0,1fr) 230px;gap:18px}.globe-readout span{margin-left:0}.globe-topbar{padding:20px 20px 0}.globe-readout{padding:0 20px}.globe-bottom{padding:0 20px;gap:10px;flex-wrap:wrap}.world-globe{height:430px}.globe-topbar h2{font-size:22px}.globe-topbar{align-items:flex-start}.globe-text{padding:4px 0}.globe-controls{margin-top:6px}}
6
+ @media(max-width:760px){.world-head h1{font-size:38px}.world-head{margin-top:20px}.world-head .muted{font-size:11px}.globe-explorer{grid-template-columns:1fr;gap:18px}.globe-topbar{padding:20px 17px 0;gap:10px}.globe-topbar h2{font-size:22px;max-width:215px}.globe-text{font-size:9px;white-space:normal;text-align:right;max-width:70px}.globe-readout{padding:0 17px;gap:7px}.globe-readout label{width:100%;font-size:9px}.globe-readout select{font-size:10px;max-width:210px}.globe-readout span{font-size:9px;max-width:115px}.world-globe{height:360px}.globe-bottom{padding:0 17px;gap:12px}.globe-controls{width:100%;gap:6px;justify-content:space-between}.globe-controls button{min-width:37px;min-height:42px}.globe-controls button:last-child{min-width:95px}.globe-coverage{padding:10px 17px 0;font-size:8px}.globe-guide{padding:0 17px 18px;font-size:9px}.globe-country-selector{flex-wrap:wrap;gap:8px}.globe-country-selector p{width:100%;margin:3px 0 0}.globe-explorer .country-detail{padding:22px;grid-template-columns:1fr 1fr}.globe-explorer .country-detail .indicator strong{font-size:26px}.world-layout .scatter-panel h2{font-size:23px}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/globe.test.mjs ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { lonLatToVector, normaliseLongitude, cameraFocus, isMarkerVisible, metricFraction, makeGraticule, EQUIRECTANGULAR_OFFSET } from '../globe-math.mjs';
4
+ const close=(a,b)=>assert.ok(Math.abs(a-b)<1e-9,`${a} ≠ ${b}`);
5
+ test('Greenwich equator faces positive Z; eastern longitude positive X; north positive Y',()=>{
6
+ const g=lonLatToVector(0,0); close(g.x,0);close(g.y,0);close(g.z,1);
7
+ const e=lonLatToVector(90,0);close(e.x,1);close(e.z,0);
8
+ const n=lonLatToVector(0,90);close(n.y,1);close(n.z,0);
9
+ });
10
+ test('longitude latitude positions lie on requested sphere radius',()=>{
11
+ for (const [lon,lat] of [[-47.9292,-15.7801],[179.9,80],[-179.9,-80],[0,0]]){
12
+ const p=lonLatToVector(lon,lat,1.015);close(Math.hypot(p.x,p.y,p.z),1.015);
13
+ }
14
+ });
15
+ test('camera focus preserves country longitude, safely limits polar orbit, wraps longitude',()=>{
16
+ assert.deepEqual(cameraFocus({lon:-47.9292,lat:-15.7801}),{longitude:-47.9292,latitude:-15.7801});
17
+ assert.deepEqual(cameraFocus({lon:370,lat:89}),{longitude:10,latitude:75});
18
+ close(normaliseLongitude(-181),179);
19
+ });
20
+ test('backside reference points and below-horizon markers are hidden',()=>{
21
+ assert.equal(isMarkerVisible(0,0,{longitude:0,latitude:0},3),true);
22
+ assert.equal(isMarkerVisible(180,0,{longitude:0,latitude:0},3),false);
23
+ assert.equal(isMarkerVisible(80,0,{longitude:0,latitude:0},3),false);
24
+ assert.equal(isMarkerVisible(-47.9292,-15.7801,{longitude:-47.9292,latitude:-15.7801},3),true);
25
+ });
26
+ test('metric encoding preserves null, respects ordered bounds, uniform marker sizing independent of value',()=>{
27
+ assert.equal(metricFraction(null,0,100),null);assert.equal(metricFraction(undefined,0,100),null);
28
+ close(metricFraction(0,0,100),0);close(metricFraction(100,0,100),1);close(metricFraction(50,0,100),.5);
29
+ close(metricFraction(-5,0,100),0);close(metricFraction(200,0,100),1);
30
+ });
31
+ test('graticule consists of sphere surface segments, including Greenwich',()=>{
32
+ const segments=makeGraticule(30,4,1.002); assert.ok(segments.length>100);
33
+ assert.ok(segments.some(([a,b])=>Math.abs(a.x)<1e-9&&Math.abs(b.x)<1e-9&&a.z>0&&b.z>0));
34
+ for(const [a,b] of segments){close(Math.hypot(a.x,a.y,a.z),1.002);close(Math.hypot(b.x,b.y,b.z),1.002);}
35
+ });
36
+
37
+ import {SphereGeometry} from '../vendor/three-0.160.1.module.js';
38
+ test('the actual Three.js sphere UVs sample the correct Natural Earth texture longitude',()=>{
39
+ const sphere=new SphereGeometry(1,64,32),positions=sphere.getAttribute('position'),uvs=sphere.getAttribute('uv');
40
+ for(const lon of [0,90,-90,180]){
41
+ const wanted=lonLatToVector(lon,0);let index=-1;
42
+ for(let i=0;i<positions.count;i++)if(Math.abs(positions.getX(i)-wanted.x)<1e-6&&Math.abs(positions.getY(i)-wanted.y)<1e-6&&Math.abs(positions.getZ(i)-wanted.z)<1e-6){index=i;break;}
43
+ assert.ok(index>=0,'cardinal longitude exists in the real sphere geometry');
44
+ close((uvs.getX(index)+EQUIRECTANGULAR_OFFSET)%1,((lon+180)/360)%1);
45
+ close(1-uvs.getY(index),.5);
46
+ }
47
+ sphere.dispose();
48
+ });
tests/model.test.mjs ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { DEFAULTS, STRATEGIES, evaluate, landscape, recommendation, normalizeState } from '../model.mjs';
4
+
5
+ const near = (actual, expected, tolerance = 1e-7) => assert.ok(Math.abs(actual - expected) <= tolerance, `${actual} != ${expected}`);
6
+ const find = (results, id) => results.find(result => result.id === id);
7
+
8
+ test('defaults define four distinct strategies and a twelve-month illustrative baseline', () => {
9
+ assert.equal(DEFAULTS.months, 12);
10
+ assert.deepEqual(STRATEGIES.map(option => option.id), ['current', 'theatre', 'referral', 'combined']);
11
+ const results = evaluate();
12
+ assert.equal(results.length, 4);
13
+ near(find(results, 'current').completed, 1080);
14
+ near(find(results, 'current').queue, 960);
15
+ near(find(results, 'combined').incremental, 150);
16
+ assert.equal(recommendation(results).id, 'combined');
17
+ });
18
+
19
+ test('every month conserves people and respects each throughput constraint', () => {
20
+ const params = normalizeState({ budget: 2912345, capacity: 71.3, referralGain: 0.283, initialQueue: 53.7 });
21
+ for (const result of evaluate(params)) {
22
+ let queue = params.initialQueue;
23
+ let total = 0;
24
+ for (const month of result.monthly) {
25
+ near(month.openingQueue, queue);
26
+ near(month.openingQueue + month.arrivals, month.completed + month.closingQueue);
27
+ assert.ok(month.completed >= 0 && month.closingQueue >= 0);
28
+ for (const bound of [month.available, month.referralThroughput, month.capacity, month.fundedSlots]) {
29
+ assert.ok(month.completed <= bound + 1e-8);
30
+ }
31
+ queue = month.closingQueue;
32
+ total += month.completed;
33
+ }
34
+ near(total, result.completed);
35
+ near(queue, result.queue);
36
+ near(params.initialQueue + params.arrivals * params.months, result.completed + result.queue);
37
+ assert.ok(result.cost >= 0 && result.cost <= params.budget);
38
+ }
39
+ });
40
+
41
+ test('zero budget makes investment strategies infeasible and selects current service', () => {
42
+ const results = evaluate({ budget: 0 });
43
+ for (const result of results) {
44
+ near(result.cost, 0);
45
+ near(result.incremental, 0);
46
+ assert.equal(result.feasible, result.id === 'current');
47
+ }
48
+ assert.equal(recommendation(results).id, 'current');
49
+ });
50
+
51
+ test('referral programme is infeasible below fixed cost and spends its fixed cost when enabled', () => {
52
+ const below = evaluate({ budget: 599999 });
53
+ for (const id of ['referral', 'combined']) {
54
+ assert.equal(find(below, id).feasible, false);
55
+ near(find(below, id).cost, 0);
56
+ assert.match(find(below, id).reason, /fixed/i);
57
+ }
58
+ const exact = evaluate({ budget: 600000, capacity: 140 });
59
+ for (const id of ['referral', 'combined']) {
60
+ assert.equal(find(exact, id).feasible, true);
61
+ near(find(exact, id).cost, 600000);
62
+ near(find(exact, id).programmeCost, 600000);
63
+ near(find(exact, id).additionalSlots, 0);
64
+ }
65
+ });
66
+
67
+ test('investment costs remain committed even when another bottleneck prevents benefit', () => {
68
+ const results = evaluate({ capacity: 140, referralGain: 0, budget: 2400000 });
69
+ for (const id of ['theatre', 'referral', 'combined']) {
70
+ near(find(results, id).incremental, 0);
71
+ near(find(results, id).cost, 2400000);
72
+ }
73
+ assert.equal(recommendation(results).id, 'current');
74
+ });
75
+
76
+ test('baseline does not change with intervention budget or referral gain', () => {
77
+ const first = find(evaluate({ budget: 0, referralGain: 0 }), 'current');
78
+ const last = find(evaluate({ budget: 6000000, referralGain: 0.4 }), 'current');
79
+ assert.deepEqual(first, last);
80
+ });
81
+
82
+ test('theatre wins under a physical constraint and referral wins with existing spare capacity', () => {
83
+ assert.equal(recommendation(evaluate({ capacity: 40, budget: 2400000 })).id, 'theatre');
84
+ const winner = recommendation(evaluate({ capacity: 150, budget: 2400000 }));
85
+ assert.equal(winner.id, 'referral');
86
+ assert.deepEqual(winner.tiedIds, ['referral', 'combined']);
87
+ assert.equal(recommendation(evaluate({ capacity: 90, budget: 2400000 })).id, 'combined');
88
+ });
89
+
90
+ test('referral strategy cannot expand physical capacity and theatre cannot change referrals', () => {
91
+ const results = evaluate({ capacity: 75, budget: 6000000, referralGain: 0.4 });
92
+ const referral = find(results, 'referral');
93
+ const theatre = find(results, 'theatre');
94
+ assert.ok(referral.monthly.every(month => month.capacity === 75));
95
+ assert.ok(theatre.monthly.every(month => month.referralThroughput === 90));
96
+ near(theatre.additionalSlots, 6000000 / 12000 / 12);
97
+ near(referral.additionalSlots, (6000000 - 600000) / 12000 / 12);
98
+ });
99
+
100
+ test('more referral effect and more budget never reduce completions for a feasible strategy', () => {
101
+ for (const id of ['theatre', 'referral', 'combined']) {
102
+ let previous = -Infinity;
103
+ for (const budget of [600000, 1200000, 2400000, 6000000]) {
104
+ const result = find(evaluate({ budget, capacity: 80 }), id);
105
+ assert.ok(result.completed >= previous - 1e-7);
106
+ previous = result.completed;
107
+ }
108
+ previous = -Infinity;
109
+ for (const referralGain of [0, 0.1, 0.2, 0.4]) {
110
+ const result = find(evaluate({ referralGain, capacity: 120 }), id);
111
+ assert.ok(result.completed >= previous - 1e-7);
112
+ previous = result.completed;
113
+ }
114
+ }
115
+ });
116
+
117
+ test('zero demand does not create patients or outcomes', () => {
118
+ for (const result of evaluate({ arrivals: 0, initialQueue: 0 })) {
119
+ near(result.completed, 0);
120
+ near(result.queue, 0);
121
+ assert.equal(result.bottleneck, 'Demand');
122
+ }
123
+ });
124
+
125
+ test('tie tolerance uses lower cost then stable strategy order without implying strict superiority', () => {
126
+ const results = STRATEGIES.map((option, index) => ({ ...option, feasible: true, incremental: 10 + (index === 3 ? 1e-9 : 0), cost: index === 0 ? 0 : 100 }));
127
+ const chosen = recommendation(results);
128
+ assert.equal(chosen.id, 'current');
129
+ assert.deepEqual(chosen.tiedIds, ['current']);
130
+ assert.deepEqual(chosen.effectTiedIds, ['current', 'theatre', 'referral', 'combined']);
131
+ assert.throws(() => recommendation([]), /feasible/i);
132
+ });
133
+
134
+ test('normalization clamps finite numbers, preserves zero, and rejects invalid numeric inputs', () => {
135
+ assert.deepEqual(normalizeState(), { ...DEFAULTS });
136
+ const result = normalizeState({ budget: -20, capacity: 300, referralGain: 9, baseReferral: -1, months: 2.8, initialQueue: 0 });
137
+ assert.equal(result.budget, 0);
138
+ assert.equal(result.capacity, 180);
139
+ assert.equal(result.referralGain, 0.4);
140
+ assert.equal(result.baseReferral, 0);
141
+ assert.equal(result.months, 2);
142
+ assert.equal(result.initialQueue, 0);
143
+ for (const value of [NaN, Infinity, -Infinity, '90', null, undefined]) {
144
+ assert.throws(() => normalizeState({ capacity: value }), /capacity/);
145
+ }
146
+ });
147
+
148
+ test('landscape covers requested bounds and reproduces direct decisions at every cell', () => {
149
+ const cells = landscape({ budget: 2400000 }, 4, 3);
150
+ assert.equal(cells.length, 12);
151
+ assert.deepEqual([cells[0].x, cells[0].y], [40, 0]);
152
+ assert.deepEqual([cells.at(-1).x, cells.at(-1).y], [180, 0.4]);
153
+ for (const [index, cell] of cells.entries()) {
154
+ assert.equal(cell.index, index);
155
+ const winner = recommendation(evaluate({ budget: 2400000, capacity: cell.x, referralGain: cell.y }));
156
+ assert.equal(cell.winnerId, winner.id);
157
+ near(cell.incremental, winner.incremental);
158
+ }
159
+ assert.throws(() => landscape({}, 0, 2), /dimension/i);
160
+ assert.throws(() => landscape({}, 2, NaN), /dimension/i);
161
+ });
162
+
163
+ test('default landscape reveals all three active strategy regions without artificial coloring', () => {
164
+ const winners = new Set(landscape().map(cell => cell.winnerId));
165
+ for (const strategy of ['theatre', 'referral', 'combined']) assert.ok(winners.has(strategy));
166
+ });
167
+
168
+ test('all supported extremes remain finite, nonnegative, and budget-feasible', () => {
169
+ for (const budget of [0, 599999, 600000, 6000000]) {
170
+ for (const capacity of [40, 180]) {
171
+ for (const referralGain of [0, 0.4]) {
172
+ for (const result of evaluate({ budget, capacity, referralGain })) {
173
+ for (const field of ['completed', 'incremental', 'cost', 'queue']) {
174
+ assert.ok(Number.isFinite(result[field]), `${result.id}.${field} must be finite`);
175
+ assert.ok(result[field] >= 0, `${result.id}.${field} must not be negative`);
176
+ }
177
+ assert.ok(result.cost <= budget);
178
+ }
179
+ }
180
+ }
181
+ }
182
+ });
183
+
184
+ test('landscape preserves direct simulation totals and ties across extreme and fractional states', () => {
185
+ const scenarios = [
186
+ { budget: 0 }, { budget: 599999 }, { budget: 600000 }, { budget: 6000000 },
187
+ { arrivals: 0, initialQueue: 0 }, { arrivals: 0, initialQueue: 900 },
188
+ { arrivals: 10000, initialQueue: 1000000, unitCost: 1, months: 120 },
189
+ { baseReferral: 0, baselineFundedSlots: 0, months: 1 },
190
+ { baseReferral: 1, initialQueue: 0, baselineFundedSlots: 10000, months: 120 },
191
+ { budget: 1234567.89, arrivals: 157.73, unitCost: 15678.32, initialQueue: 25.87, months: 79 },
192
+ { referralFixedCost: 0, budget: 1 },
193
+ { referralFixedCost: 6000000, budget: 5999999 },
194
+ ];
195
+ for (const state of scenarios) {
196
+ for (const cell of landscape(state, 7, 5)) {
197
+ const winner = recommendation(evaluate({ ...state, capacity: cell.x, referralGain: cell.y }));
198
+ assert.equal(cell.winnerId, winner.id);
199
+ assert.deepEqual(cell.tiedIds, winner.tiedIds);
200
+ assert.deepEqual(cell.effectTiedIds, winner.effectTiedIds);
201
+ for (const field of ['incremental', 'completed', 'cost', 'queue']) near(cell[field], winner[field]);
202
+ }
203
+ }
204
+ });
205
+
206
+ test('large 120-month landscape remains interactive without constructing detailed monthly histories', () => {
207
+ const started = performance.now();
208
+ const cells = landscape({ months: 120 }, 100, 100);
209
+ const elapsed = performance.now() - started;
210
+ assert.equal(cells.length, 10000);
211
+ assert.ok(elapsed < 750, `10000-cell landscape took ${elapsed.toFixed(1)}ms; target <750ms`);
212
+ });
vendor/THREE-LICENSE.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License
2
+
3
+ Copyright © 2010-2023 three.js authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
vendor/three-0.160.1.module.js ADDED
The diff for this file is too large to render. See raw diff