@wafertools/wafermap 0.38.0 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +79 -3
- package/README.md +4 -3
- package/dist/packages/canvas-adapter/cellShade.d.ts +21 -0
- package/dist/packages/canvas-adapter/cellShade.js +1 -0
- package/dist/packages/canvas-adapter/charts/chartShell.d.ts +19 -3
- package/dist/packages/canvas-adapter/charts/chartShell.js +1 -1
- package/dist/packages/canvas-adapter/charts/commonality.js +4 -1
- package/dist/packages/canvas-adapter/charts/correlation.d.ts +11 -0
- package/dist/packages/canvas-adapter/charts/correlation.js +1 -1
- package/dist/packages/canvas-adapter/charts/divergingScale.d.ts +23 -0
- package/dist/packages/canvas-adapter/charts/divergingScale.js +1 -0
- package/dist/packages/canvas-adapter/charts/groupComparison.js +1 -1
- package/dist/packages/canvas-adapter/charts/palette.d.ts +10 -3
- package/dist/packages/canvas-adapter/charts/palette.js +1 -1
- package/dist/packages/canvas-adapter/charts/plotChart.d.ts +8 -0
- package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
- package/dist/packages/canvas-adapter/charts/regionYieldDiagram.js +1 -1
- package/dist/packages/canvas-adapter/charts/sweep.js +1 -1
- package/dist/packages/canvas-adapter/dataTab.js +1 -1
- package/dist/packages/canvas-adapter/differenceMapPanel.d.ts +1 -0
- package/dist/packages/canvas-adapter/differenceMapPanel.js +1 -1
- package/dist/packages/canvas-adapter/filterJson.d.ts +25 -0
- package/dist/packages/canvas-adapter/filterJson.js +5 -0
- package/dist/packages/canvas-adapter/insightsTab.js +1 -1
- package/dist/packages/canvas-adapter/pageFilter.js +2 -2
- package/dist/packages/canvas-adapter/plotEditor.js +10 -1
- package/dist/packages/canvas-adapter/plotJsonComplete.d.ts +46 -0
- package/dist/packages/canvas-adapter/plotJsonComplete.js +4 -0
- package/dist/packages/canvas-adapter/plotJsonHistory.d.ts +12 -0
- package/dist/packages/canvas-adapter/plotJsonHistory.js +1 -0
- package/dist/packages/canvas-adapter/plotJsonSuggest.d.ts +16 -0
- package/dist/packages/canvas-adapter/plotJsonSuggest.js +1 -0
- package/dist/packages/canvas-adapter/plotModal.js +1 -1
- package/dist/packages/canvas-adapter/plotTab.js +1 -1
- package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
- package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
- package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
- package/dist/packages/canvas-adapter/sweepEditor.js +1 -1
- package/dist/packages/canvas-adapter/toCanvas.d.ts +1 -0
- package/dist/packages/canvas-adapter/toCanvas.js +1 -1
- package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
- package/dist/packages/canvas-adapter/userGuideHtml.js +81 -43
- package/dist/packages/canvas-adapter/version.d.ts +2 -2
- package/dist/packages/canvas-adapter/version.js +1 -1
- package/dist/packages/canvas-adapter/virtualTable.d.ts +2 -0
- package/dist/packages/canvas-adapter/virtualTable.js +1 -1
- package/dist/packages/core/compact.js +2 -2
- package/dist/packages/core/dieTable.js +1 -1
- package/dist/packages/core/utils.d.ts +6 -0
- package/dist/packages/core/utils.js +1 -1
- package/dist/packages/renderer/fmt.js +1 -1
- package/dist/packages/stats/chartCatalogue.js +1 -1
- package/dist/packages/stats/coFailure.d.ts +11 -0
- package/dist/packages/stats/coFailure.js +1 -0
- package/dist/packages/stats/commonality.d.ts +37 -4
- package/dist/packages/stats/commonality.js +1 -1
- package/dist/packages/stats/correlation.d.ts +7 -0
- package/dist/packages/stats/correlation.js +1 -1
- package/dist/packages/stats/dieRegions.d.ts +2 -0
- package/dist/packages/stats/dieRegions.js +1 -1
- package/dist/packages/stats/differenceMap.d.ts +2 -0
- package/dist/packages/stats/differenceMap.js +1 -1
- package/dist/packages/stats/examplePicks.d.ts +6 -0
- package/dist/packages/stats/examplePicks.js +1 -1
- package/dist/packages/stats/groupEffects.d.ts +66 -0
- package/dist/packages/stats/groupEffects.js +1 -0
- package/dist/packages/stats/plotData.d.ts +11 -2
- package/dist/packages/stats/plotData.js +1 -1
- package/dist/packages/stats/plotSpec.d.ts +31 -2
- package/dist/packages/stats/plotSpec.js +4 -4
- package/dist/packages/stats/plotTable.d.ts +18 -0
- package/dist/packages/stats/plotTable.js +1 -0
- package/dist/packages/stats/renderFindingsReport.js +1 -1
- package/dist/packages/stats/renderSummaryReport.js +7 -7
- package/dist/packages/stats/reportHtml.js +18 -13
- package/dist/packages/stats/sweep.d.ts +3 -3
- package/dist/packages/stats/sweepXFromName.js +1 -1
- package/dist/packages/stats/synthesis.d.ts +19 -0
- package/dist/packages/stats/synthesis.js +1 -1
- package/dist/packages/stats/testsByWafer.d.ts +11 -0
- package/dist/packages/stats/testsByWafer.js +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{compareTestsByGroup as
|
|
1
|
+
import{compareTestsByGroup as J,formatP as N,groupKeys as Q}from"../../stats/groupCompare.js";import{fmt as S}from"../../renderer/fmt.js";import{testLabel as G,unmarkedLabel as Y}from"../../renderer/testLabel.js";import{CLR as l,FONT as q,SPACE as C,controlStyle as R,wireControlHover as V,wireTooltip as k}from"../toolbar.js";import{exportCsv as Z}from"../tableExport.js";import{cardShell as ee,guideCite as te,makeListSelect as oe,renderEmptyState as K}from"./chartShell.js";import{GUIDE_SECTIONS as ne}from"../../stats/guideSections.js";import{cardAbout as se}from"./cardAbout.js";import{shadesAmong as re}from"../cellShade.js";const L="\0none",ae=6;export function renderGroupComparisonPanel(s){const r=s.ownerDocument??document,O=s.groupLabelText??"group",{card:b,body:$,controlsRow:B,setAbout:P}=ee(s.title??`Comparison by ${O.toLowerCase()}`,void 0,r);P(se("comparison")),b.dataset.wmapGroupComparison="1",b.style.gridColumn="1 / -1";const A=s.groups.flatMap(t=>t.items.map(e=>({dies:e.dies,group:t.key}))),p=Q(A),a=s.control!==null&&p.includes(s.control)?s.control:null,f=J(A,s.testDefs,a??void 0),E=p.length<=ae?p:[],U=oe([{value:L,label:"No control: compare all groups"},...p.map(t=>({value:t,label:`Control: ${t}`}))],a??L,t=>s.onControlChange(t===L?null:t),{ownerDocument:r,ariaLabel:"Control group",hook:"compare-control"});if(B.appendChild(U),s.onSaveText&&f.length){const t=r.createElement("button");t.type="button",t.textContent="Comparison CSV",k(t,"Save this table as a CSV file, one row per test"),Object.assign(t.style,{...R("outlined"),color:l.text}),V(t),t.addEventListener("click",()=>Z([{header:"Test",get:e=>Y(G(e.test,e.test.testNumber))},{header:"Test number",get:e=>e.test.testNumber},{header:"Unit",get:e=>e.test.unit??""},...p.flatMap(e=>[{header:`${e} wafers`,get:o=>o.comparison.groups.find(n=>n.key===e)?.n??0},{header:`${e} mean`,get:o=>c(o.comparison.groups.find(n=>n.key===e)?.mean)},...a&&e!==a?[{header:`${e} minus ${a}`,get:o=>c(o.comparison.contrasts?.find(n=>n.key===e)?.delta)},{header:`${e} vs ${a} p (Holm)`,get:o=>c(o.comparison.contrasts?.find(n=>n.key===e)?.pAdjusted)}]:[]]),{header:"Welch p",get:e=>c(e.comparison.welch?.p)},{header:"Kruskal-Wallis p",get:e=>c(e.comparison.kruskal?.p)},{header:"q (Benjamini-Hochberg)",get:e=>c(e.pAdjusted)},{header:"Largest shift (wafer SDs)",get:e=>c(e.effect)},{header:"Largest shift (share of limit window)",get:e=>c(e.windowShare)},{header:"Note",get:e=>e.comparison.issue??""}],f,"group-comparison.csv",s.onSaveText)),B.appendChild(t)}if(p.length<2)return K($,`Needs two or more ${O.toLowerCase()} groups to compare.`),{card:b,setTest:()=>{},destroy:()=>{}};if(f.length===0)return K($,"No measured test has values in these wafers."),{card:b,setTest:()=>{},destroy:()=>{}};const y=r.createElement("div"),z=p.map(t=>`${t} ${A.filter(e=>e.group===t).length}`).join(", ");y.textContent=`Each wafer is one value, the mean of its dies, so n is wafers (${z}). Welch: Welch's ANOVA (Welch's t for two groups). Rank: Kruskal\u2013Wallis${f.some(t=>t.comparison.kruskal?.approximate)?", approximate with fewer than five wafers in a group":""}. q: Benjamini\u2013Hochberg across the ${f.length} tests, which the table is ranked by.`+(a?` Each group's difference from ${a} has a Holm-adjusted p.`:"")+" ",y.append(te(r,ne.groups),"."),Object.assign(y.style,{color:l.label,fontSize:q.body,marginBottom:C.sm}),$.appendChild(y);const j=r.createElement("div");Object.assign(j.style,{overflow:"auto",maxHeight:"420px",border:`1px solid ${l.menuBorder}`});const x=r.createElement("table");Object.assign(x.style,{borderCollapse:"collapse",width:"100%",fontSize:q.body,fontVariantNumeric:"tabular-nums"});const W=r.createElement("thead"),D=r.createElement("tr"),h=(t,e,o="right")=>{const n=r.createElement("th");n.scope="col",n.textContent=t,e&&k(n,e),Object.assign(n.style,{position:"sticky",top:"0",background:l.menuBg,textAlign:o,padding:`${C.xs} ${C.sm}`,borderBottom:`1px solid ${l.menuBorder}`,color:l.label,fontWeight:"600",whiteSpace:"nowrap"}),D.appendChild(n)};h("Test",void 0,"left");for(const t of E)h(t===a?`${t} (control)`:t,a&&t!==a?`Mean of the wafer means, and the difference from ${a}`:"Mean of the wafer means");h("Welch p","Do the group means differ? Welch\u2019s ANOVA on wafer means, not assuming equal spreads"),h("Rank p","The same question on ranks (Kruskal\u2013Wallis): one odd wafer cannot drive it"),h("q","Welch p adjusted for the number of tests compared (Benjamini\u2013Hochberg); the table is ranked by it"),h("Largest shift","The largest difference between group means: in wafer-to-wafer standard deviations, and as a share of the limit window where the test has both limits"),W.appendChild(D),x.appendChild(W);const M=r.createElement("tbody"),H=new Map,g=(t,e,o={})=>{const n=r.createElement("td");typeof e=="string"?n.textContent=e:n.appendChild(e),o.title&&k(n,o.title),Object.assign(n.style,{padding:`${C.xs} ${C.sm}`,textAlign:o.align??"right",borderBottom:`1px solid ${l.menuBorder}`,whiteSpace:"nowrap",fontWeight:o.strong?"700":"400",color:o.muted?l.label:l.text}),o.shade&&(n.style.background=o.shade),t.appendChild(n)};for(const t of f){const e=r.createElement("tr"),o=t.comparison,n=t.test.unit,d=r.createElement("button");d.type="button",d.textContent=G(t.test,t.test.testNumber),d.dataset.wmapCompareTest=String(t.test.testNumber),k(d,`Show ${d.textContent} in the panels below${o.issue?`. ${o.issue}`:""}`),Object.assign(d.style,{...R("bare"),padding:"0",textAlign:"left",color:l.text,textDecoration:"underline",textDecorationColor:l.menuBorder}),V(d,"bare"),d.addEventListener("click",()=>{s.onSelectTest(t.test.testNumber),v(t.test.testNumber)}),g(e,d,{align:"left"});const _=re(E.map(w=>{const m=o.groups.find(i=>i.key===w);return m&&m.n?m.mean:NaN}),w=>S(w,n));for(const[w,m]of E.entries()){const i=o.groups.find(T=>T.key===m),u=o.contrasts?.find(T=>T.key===m),F=i&&i.n?S(i.mean,n):"\u2014",X=u&&Number.isFinite(u.delta)?`${F} (${u.delta>=0?"+":""}${S(u.delta,n)}, p ${N(u.pAdjusted)})`:F;g(e,X,{shade:_[w],title:i?`${m}: ${i.n} wafer${i.n===1?"":"s"}${i.n>=2?`, wafer-to-wafer SD ${S(i.sd,n)}`:""}`:void 0,muted:!i||i.n<2,strong:!!u&&u.pAdjusted<.05})}g(e,N(o.welch?.p??NaN),{title:o.issue}),g(e,N(o.kruskal?.p??NaN)),g(e,N(t.pAdjusted),{strong:t.pAdjusted<.05});const I=Number.isFinite(t.effect)?`${Math.abs(t.effect).toFixed(1)} SD${t.windowShare!==void 0?` \xB7 ${Math.abs(t.windowShare*100).toFixed(0)}% of limits`:""}`:"\u2014";g(e,I),H.set(t.test.testNumber,e),M.appendChild(e)}x.appendChild(M),j.appendChild(x),$.appendChild(j);function v(t){for(const[e,o]of H)o.style.background=e===t?l.bgActive:"",e===t?o.setAttribute("aria-current","true"):o.removeAttribute("aria-current")}return v(s.selectedTestNumber),{card:b,setTest:v,destroy:()=>{}}}const c=s=>s===void 0||!Number.isFinite(s)?"":String(s);
|
|
@@ -22,7 +22,14 @@ export declare function yieldFill(yieldPercent: number): string;
|
|
|
22
22
|
* same information positionally.
|
|
23
23
|
*/
|
|
24
24
|
export declare function capabilityColor(ppk: number | null): string;
|
|
25
|
-
/**
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
/**
|
|
26
|
+
* The two ends of every signed scale (a correlation, a z-score, a difference): warm is positive or above average, blue is
|
|
27
|
+
* negative or below, so one colour never means "high" on one chart and "low" on the next. Okabe-Ito blue and vermillion,
|
|
28
|
+
* which stay far apart under every common colour-vision deficiency.
|
|
29
|
+
*/
|
|
30
|
+
export declare const SIGNED_LOW = "#0072B2";
|
|
31
|
+
export declare const SIGNED_HIGH = "#D55E00";
|
|
32
|
+
/** Correlation sign hues (vermillion = positive, blue = negative); |r| sets intensity via background blend. */
|
|
33
|
+
export declare const CORRELATION_POSITIVE = "#D55E00";
|
|
34
|
+
export declare const CORRELATION_NEGATIVE = "#0072B2";
|
|
28
35
|
//# sourceMappingURL=palette.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{clamp01 as
|
|
1
|
+
import{clamp01 as f}from"../../core/utils.js";export const QUANTITY="#4e79a7";const p=["#0072B2","#E69F00","#009E73","#CC79A7","#56B4E9","#D55E00","#8C6D31","#999999"],I=["#1f1ff9","#f91ff9","#05d105","#65188b","#f91f68","#607afb","#8b1818","#1f4951"],n=[...p,...I];export function categorical(t){return n[(t%n.length+n.length)%n.length]}export const CATEGORICAL_COUNT=n.length;function i(t,e,c){const s=[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)],l=[parseInt(e.slice(1,3),16),parseInt(e.slice(3,5),16),parseInt(e.slice(5,7),16)],o=s.map((r,E)=>Math.round(r+(l[E]-r)*c));return`rgb(${o[0]},${o[1]},${o[2]})`}export function yieldFill(t){const e=f((t-50)/50);return i("#e7eef6","#2f6395",e)}export function capabilityColor(t){return t===null?"#999999":t>=1.33?"#009E73":t>=1?"#E69F00":"#D55E00"}export const SIGNED_LOW="#0072B2",SIGNED_HIGH="#D55E00",CORRELATION_POSITIVE=SIGNED_HIGH,CORRELATION_NEGATIVE=SIGNED_LOW;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type PlotPoint, type ResolvedPlot } from '../../stats/plotData.js';
|
|
2
|
+
import { type SaveTextHandler } from '../toolbar.js';
|
|
2
3
|
import { type CardMenuRow, type SaveImageHandler, type WaferContextMenuHandler } from './chartShell.js';
|
|
3
4
|
import type { BinColors } from '../../renderer/binColors.js';
|
|
4
5
|
/**
|
|
@@ -18,6 +19,8 @@ export declare function categoryLayout(present: ReadonlyArray<readonly number[]>
|
|
|
18
19
|
export interface PlotChartOptions {
|
|
19
20
|
ownerDocument?: Document;
|
|
20
21
|
onSaveImage?: SaveImageHandler;
|
|
22
|
+
/** Where the card's Save data as CSV goes (the host's save dialog); absent = the browser's download. */
|
|
23
|
+
onSaveText?: SaveTextHandler;
|
|
21
24
|
/** The label of the wafer an item index names, for tooltips. */
|
|
22
25
|
waferLabel: (item: number) => string;
|
|
23
26
|
/** The maps' bin colours: a plot coloured by hard or soft bin draws each bin in its map colour. */
|
|
@@ -57,6 +60,11 @@ export interface SelectInfo {
|
|
|
57
60
|
lo: number;
|
|
58
61
|
hi: number;
|
|
59
62
|
};
|
|
63
|
+
/** A heatmap cell: its row and column. */
|
|
64
|
+
cell?: {
|
|
65
|
+
row: string;
|
|
66
|
+
column: string;
|
|
67
|
+
};
|
|
60
68
|
}
|
|
61
69
|
export interface PlotChartHandle {
|
|
62
70
|
card: HTMLElement;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{escHtml as D,maxOf as Te,minOf as Gt}from"../../core/utils.js";import{fiveNumberSummary as Dt,normalQuantile as jt,sampleVariance as Bn}from"../../stats/math.js";import{CONTROL_RULE_TEXT as Wn}from"../../stats/control.js";import{PAT_VERDICT_LABEL as Ut}from"../../stats/pat.js";import{fmt as J}from"../../renderer/fmt.js";import{fitTicks as dt}from"../../renderer/axisTicks.js";import{binOfLabel as In,plotFootnote as qt,plotGuideSections as Yt,plotTestNumber as He,plotTitle as On,probabilityPosition as at}from"../../stats/plotData.js";import{SPACE as me,RADIUS as Nn,fontPx as te,FONT as mt,CLR as et,markNoPrint as Ht}from"../toolbar.js";import{cardShell as Fn,appendGuideCites as Rn,observeResize as zn,makeTooltip as _n,attachChartTip as Xn,chartFillHeight as Gn,applyCanvasFlow as _e,prepareCanvas as Xe,positionChartTooltip as pt,resolveChartCanvasColors as Ge,makeAxisFormat as Dn,horizontalTickSpacing as Kt,VERTICAL_TICK_SPACING_PX as jn,makeSeriesLegendItem as Un,renderEmptyState as Vt,isExpandedCard as Zt,makeLabeledSelect as qn,fillTextOnHalo as Lt,limitLines as Yn,limitExtent as Hn,stackLabelRows as Qt,placeClearOf as Jt,strokeLimitLine as en,drawOffAxisLimits as Kn,limitLabelPlacement as Vn,shouldIncludeLimitsByDefault as Zn,WAFER_MENU_HINT as At}from"./chartShell.js";import{guideCitesText as Qn}from"../../stats/guideSections.js";import{categorical as Jn}from"./palette.js";import{NO_DATA_FILL as tn}from"../../renderer/colorMap.js";import{resolveValueColorFn as gt}from"../../renderer/colorSchemes.js";import{wirePointInteractions as Et}from"./pointInteractions.js";import{plotAbout as eo}from"./cardAbout.js";const Ct=64,yt=16,Bt=12,De=52,to=16,no=92,oo=16,bt=5e3,nn=1500,rt=100,lo=[1e-4,.001,.01,.05,.1,.25,.5,.75,.9,.95,.99,.999,.9999],on=m=>`${+(m*100).toPrecision(4)}%`;export function categoryLayout(m){const B=.8/Math.max(1,...m.map(W=>W.length)),U=W=>(1-m[W].length*B)/2;return{width:B,left:(W,q)=>{const V=m[W].indexOf(q);return V<0?void 0:U(W)+V*B},groupAt:(W,q)=>{const V=Math.floor((q-U(W))/B);return V>=0&&V<m[W].length?m[W][V]:void 0}}}function so(m){if(m<=nn)return Array.from({length:m},(W,q)=>q);const R=[];for(let W=0;W<rt;W++)R.push(W);const B=nn-2*rt,U=m-2*rt;for(let W=0;W<B;W++)R.push(rt+Math.floor(W*U/B));for(let W=m-rt;W<m;W++)R.push(W);return R}function Wt(m,R,B){return B?Math.round(m).toLocaleString("en-GB"):R?J(m,R):`${m<=-.005?"\u2212":""}${Math.abs(m).toFixed(2)}`}const io=260;function ao(m){const R=[...m.querySelectorAll("[data-wmap-plot-panel]")],B=R[0]?.querySelector("canvas");if(!B)return null;const U=B.width/Math.max(1,B.getBoundingClientRect().width)||1,W=m.getBoundingClientRect(),q=m.ownerDocument.createElement("canvas");q.width=Math.ceil(W.width*U),q.height=Math.ceil(W.height*U);const V=q.getContext("2d");if(!V)return null;const we=getComputedStyle(m);V.fillStyle=we.backgroundColor&&we.backgroundColor!=="rgba(0, 0, 0, 0)"?we.backgroundColor:"#fff",V.fillRect(0,0,q.width,q.height);for(const Me of R){const Se=Me.querySelector("canvas"),ce=Me.dataset.wmapChartTitle??"",z=(Se??Me).getBoundingClientRect(),i=Me.getBoundingClientRect();V.fillStyle=getComputedStyle(Me).color||"#333",V.font=`600 ${Math.round(13*U)}px system-ui, sans-serif`,V.textBaseline="top",V.fillText(ce,(i.left-W.left+8)*U,(i.top-W.top+6)*U),Se&&V.drawImage(Se,(z.left-W.left)*U,(z.top-W.top)*U,z.width*U,z.height*U)}return q}const We=(m,R)=>R.extent?[...m,...R.extent]:m;function ue(m,R,B={}){const U=R.scale==="log";let W=m.length?Gt(m):0,q=m.length?Te(m):1;U&&(W=Math.log10(Math.max(W,Number.MIN_VALUE)),q=Math.log10(Math.max(q,Number.MIN_VALUE)));const V=(q-W)*.05||(U?.5:1);W=B.floorAtZero&&!U&&W>=0?0:W-V,q+=V;const Me=Q=>Q===void 0||!Number.isFinite(Q)?void 0:U?Q>0?Math.log10(Q):void 0:Q,Se=Me(R.min),ce=Me(R.max);Se!==void 0&&(W=Se),ce!==void 0&&(q=ce),q>W||(q=W+1);const z=q-W,i=!!R.reverse,$=Q=>{const ee=((U?Math.log10(Math.max(Q,Number.MIN_VALUE)):Q)-W)/z;return i?1-ee:ee};return{lo:U?10**W:W,hi:U?10**q:q,log:U,reverse:i,frac:$}}function It(m,R,B,U){if(R/m<10)return dt(m,R,B,U);const W=Math.floor(Math.log10(m)),q=Math.ceil(Math.log10(R)),V=Se=>{const ce=[];for(let z=W;z<=q;z++)for(const i of Se){const $=i*10**z;$>=m&&$<=R&&ce.push($)}return ce},we=V([1]);return{ticks:we.length>=4?we:V([1,2,5]),step:0}}export function renderPlotChart(m){const R=m.ownerDocument??document,{card:B,heading:U,body:W,controlsRow:q,setPngDecor:V,setPngCanvas:we,setAbout:Me,setMenuRows:Se}=Fn(m.panel?.title??"Plot",m.onSaveImage,R,{png:!m.panel});m.panel&&(B.dataset.wmapPlotPanel="1");let ce=[];B.dataset.wmapPlotCard="1";const z=_n(B);let i,$,Q,ee,Ke,Ie,ct,ft=!1;B.addEventListener("pointerenter",()=>{ft=!0,B.dataset.wmapPlotPanelsOwner&&(B.dataset.wmapPanelsHover="1")}),B.addEventListener("pointerleave",()=>{ft=!1,delete B.dataset.wmapPanelsHover});let tt=[];const I=new Set,he=new Set;let pe=null,ge=-1,se=[],Z,Ee,ne,ie=null,nt=0,$e,ut;const ln=()=>!!i?.facets;let de=[],ke=-1,xt=new Map,je=[],Ue=De,k=Ct,T=Bt;const sn={[Ut.outlier]:"#e69f00",[Ut.fails]:"#c0392b"},oe=e=>{const l=i?.groups[e]??"";if(i?.colorBins&&m.binColors){const s=In(l);return s===void 0?tn:(i.colorBins==="hard"?m.binColors.hard:m.binColors.soft).get(s)??tn}return sn[l]??Jn(e)},qe=e=>i?.groups[e]||"";function Oe(){const e=W.clientWidth,l=(m.panel?Math.max(170,Math.min(280,e*.72)):Math.max(220,Math.min(420,e*.62)))+(Ue-De),s=Gn(B,W,$,l);return{w:e,h:s,plotW:Math.max(10,e-k-yt),plotH:Math.max(10,s-T-Ue)}}const Ce=e=>{const l=(e?.references??[]).flatMap(s=>s.to===void 0?[{value:s.at,kind:"ref",end:"lo",label:s.label??""}]:[{value:s.at,kind:"ref",end:"lo",label:s.label??"",bandTo:s.to},{value:s.to,kind:"ref",end:"hi",label:s.label??""}]);return[...Yn(e?.limits,i?.spec.limits??"both"),...l].filter(s=>e?.scale!=="log"||s.value>0)},Ne=(e,l,s)=>{const r=s?.clip,a=r?[...e.filter(h=>h>=r.lo&&h<=r.hi),r.lo,r.hi]:e,u=a.filter(Number.isFinite);if(!l.length||u.length===0)return a;const{lo:n,hi:t}=Hn(l);return(s?i?.spec.axes?.[s===i?.x?"x":"y"]?.includeLimits:void 0)??Zn(Gt(u),Te(u),n,t)?[...a,...l.map(h=>h.value)]:a};let vt;function Ve(e,l,s,r=!1){return!r&&!i?.x?.clip&&!i?.y?.clip?()=>{}:(e.save(),e.beginPath(),e.rect(k,T,l,s),e.clip(),vt=e,Ot)}function Ot(){vt?.restore(),vt=void 0}function Fe(e,l,s,r,a,u,n,t,o){const h=[];if(u.length===0)return()=>{};const w=u.filter(p=>p.value>=a.lo&&p.value<=a.hi),v=u.filter(p=>!w.includes(p)).map(p=>({value:p.value,label:p.label,side:p.value<a.lo?"lo":"hi"}));e.save(),e.font=`${te(-1)}px system-ui, sans-serif`;const b=p=>`${p.label} ${J(p.value,n.unit)}`.trim(),f=te(-1)+2;for(const p of u){if(p.bandTo===void 0)continue;const L=a.frac(Math.min(p.value,p.bandTo)),M=a.frac(Math.max(p.value,p.bandTo)),g=Math.max(0,Math.min(L,M)),y=Math.min(1,Math.max(L,M));y<=g||(e.save(),e.globalAlpha=.1,e.fillStyle=l,t==="y"?e.fillRect(k,T+(1-y)*r,s,(y-g)*r):e.fillRect(k+g*s,T,(y-g)*s,r),e.restore())}if(t==="y"){const p=w.map(g=>{const y=T+(1-a.frac(g.value))*r;return{l:g,y,start:y-6-f/2,end:y-6+f/2}}),L=Qt(p,1),M=p.length?Te(p.map(g=>e.measureText(b(g.l)).width))+8:0;p.forEach(({l:g,y},d)=>{e.globalAlpha=.7,en(e,g,l,k,y,k+s,y),e.globalAlpha=1,e.fillStyle=l,e.textAlign="left",e.textBaseline="alphabetic";const c=k+3+L[d]*M,C=Jt(je,{x0:c,x1:c+e.measureText(b(g)).width,y0:y-4-f+2,y1:y-4+2},f);if(!o){e.fillText(b(g),c,C.y1-2);return}h.push(()=>{e.save(),e.font=`${te(-1)}px system-ui, sans-serif`,e.fillStyle=l,e.textAlign="left",e.textBaseline="alphabetic",Lt(e,b(g),c,C.y1-2,o.halo),e.restore()})})}else{const p=w.map(M=>{const g=k+a.frac(M.value)*s,y=b(M),d=M.label.split(/\s+/)[0],c=J(M.value,n.unit),C=d&&d!==M.label?[y,`${d} ${c}`,d]:[y],O=w.filter(A=>A!==M).map(A=>k+a.frac(A.value)*s),{text:_,side:P}=Vn(g,C,A=>e.measureText(A).width,k,k+s,M.end==="lo",O),E=e.measureText(_).width;return{l:M,x:g,side:P,shown:_,start:P<0?g-3-E:g+3,end:P<0?g-3:g+3+E}}),L=Qt(p,4);p.forEach(({l:M,x:g,side:y,shown:d,start:c,end:C},O)=>{e.globalAlpha=.7,en(e,M,l,g,T,g,T+r),e.globalAlpha=1;const _=y<0?"right":"left";e.fillStyle=l,e.textAlign=_,e.textBaseline="top";const P=T+2+L[O]*f,E=Jt(je,{x0:c,x1:C,y0:P,y1:P+f},f);if(!o){e.fillText(d,g+y*3,E.y0);return}h.push(()=>{e.save(),e.font=`${te(-1)}px system-ui, sans-serif`,e.fillStyle=l,e.textAlign=_,e.textBaseline="top",Lt(e,d,g+y*3,E.y0,o.halo),e.restore()})})}return e.restore(),Kn(e,v,{left:k,right:k+s,top:T,bottom:T+r},t==="y"?"vertical":"horizontal",l,p=>J(p,n.unit),void 0,je),()=>h.forEach(p=>p())}function Mt(e,l,s,r){return Dn(Math.max(Math.abs(l),Math.abs(s)),e.unit,r,e.label)}function ht(e,l){return l?`${e.label} (${l})`:e.label}const kt=18,Tt=(e,l,s)=>{if(e.measureText(l).width<=s)return l;for(let r=l.length-1;r>0;r--){const a=`${l.slice(0,r)}\u2026`;if(e.measureText(a).width<=s)return a}return""};function Ye(e,l,s,r,a,u,n,t,o,h,w){je=[],e.font=`${te(-1)}px system-ui, sans-serif`;const v=()=>jn,b=w?{ticks:w.map(g=>g.at),step:0}:t.log?It(t.lo,t.hi,u,v):dt(t.lo,t.hi,u,v),f=new Map(w?.map(g=>[g.at,g.label])),p=Mt(h,t.lo,t.hi,b.step||void 0),L=w?{tick:g=>f.get(g)??"",unitLabel:""}:p;e.strokeStyle=l.grid,e.lineWidth=.5,e.fillStyle=l.textMuted;let M="";if("labels"in n){const g=n.labels.length;if(n.labels.forEach((y,d)=>{const c=k+(d+.5)/g*a,C=y.length>22?`${y.slice(0,21)}\u2026`:y;n.rotate?(e.save(),e.translate(c,T+u+6),e.rotate(-Math.PI/4),e.textAlign="right",e.textBaseline="middle",e.fillText(C,0,0),e.restore()):(e.textAlign="center",e.textBaseline="top",e.fillText(C,c,T+u+4))}),n.nest){const y=n.nest[0]?.length??0,d=a/g;for(let c=y-2;c>=0;c--){const C=r-6-kt-c*kt,O=P=>n.nest[P].slice(0,c+1).join("");let _=0;for(let P=1;P<=g;P++){if(P<g&&O(P)===O(_))continue;const A=k+_*d,j=k+P*d;e.fillStyle=l.text,e.textAlign="center",e.textBaseline="bottom",e.fillText(Tt(e,n.nest[_][c],j-A-4),(A+j)/2,C),P<g&&(e.save(),e.strokeStyle=l.border,e.globalAlpha=c===0?.9:.45,e.lineWidth=1,e.beginPath(),e.moveTo(j,T),e.lineTo(j,C-2),e.stroke(),e.restore()),_=P}}e.fillStyle=l.textMuted}}else{const g=Kt(e,Math.max(Math.abs(n.lo),Math.abs(n.hi)),o.unit),y=n.log?It(n.lo,n.hi,a,g):dt(n.lo,n.hi,a,g),d=Mt(o,n.lo,n.hi,y.step||void 0);M=d.unitLabel;for(const c of y.ticks){const C=k+n.frac(c)*a;e.beginPath(),e.moveTo(C,T),e.lineTo(C,T+u),e.stroke(),e.textAlign="center",e.textBaseline="top",e.fillText(d.tick(c),C,T+u+4)}}for(const g of b.ticks){const y=T+(1-t.frac(g))*u;e.beginPath(),e.moveTo(k,y),e.lineTo(k+a,y),e.stroke(),e.textAlign="right",e.textBaseline="middle",e.fillText(L.tick(g),k-4,y)}e.font=`${te(0)}px system-ui, sans-serif`,e.fillStyle=l.text,e.textAlign="center",e.textBaseline="bottom",e.fillText(ht(o,M),k+a/2,r-6),e.save(),e.translate(14,T+u/2),e.rotate(-Math.PI/2),e.textBaseline="top",e.fillText(ht(h,L.unitLabel),0,0),e.restore(),e.strokeStyle=l.border,e.lineWidth=1,e.beginPath(),e.moveTo(k,T),e.lineTo(k,T+u),e.moveTo(k,T+u),e.lineTo(k+a,T+u),e.stroke()}function an(e,l,s,r,a,u,n,t,o,h,w,v={along:u,offset:0}){je=[],e.font=`${te(-1)}px system-ui, sans-serif`;const b=Kt(e,Math.max(Math.abs(o.lo),Math.abs(o.hi)),w.unit),f=o.log?It(o.lo,o.hi,a,b):dt(o.lo,o.hi,a,b),p=Mt(w,o.lo,o.hi,f.step||void 0);e.strokeStyle=l.grid,e.lineWidth=.5,e.fillStyle=l.textMuted;for(const c of f.ticks){const C=k+o.frac(c)*a;e.beginPath(),e.moveTo(C,T),e.lineTo(C,T+u),e.stroke(),e.textAlign="center",e.textBaseline="top",e.fillText(p.tick(c),C,T+u+4)}const L=n.labels.length,M=v.along/Math.max(1,L),g=T-v.offset;e.save(),e.beginPath(),e.rect(0,T-1,k+a+1,u+2),e.clip(),e.textAlign="right",e.textBaseline="middle";const y=Math.max(0,Math.floor(v.offset/M)),d=Math.min(L,Math.ceil((v.offset+u)/M));for(let c=y;c<d;c++)e.fillText(Tt(e,n.labels[c],t.inner),k-6,g+(c+.5)*M);if(n.nest){const c=n.nest[0]?.length??0;let C=k-6-t.inner-10;for(let O=c-2;O>=0;O--){const _=t.outer[O]??0,P=A=>n.nest[A].slice(0,O+1).join("");let E=0;for(let A=1;A<=L;A++){if(A<L&&P(A)===P(E))continue;const j=g+E*M,x=g+A*M;e.fillStyle=l.text,e.textAlign="right",e.textBaseline="middle",e.fillText(Tt(e,n.nest[E][O],_),C,(j+x)/2),A<L&&(e.save(),e.strokeStyle=l.border,e.globalAlpha=O===0?.9:.45,e.lineWidth=1,e.beginPath(),e.moveTo(C-_,x),e.lineTo(k+a,x),e.stroke(),e.restore()),E=A}C-=_+10}e.fillStyle=l.textMuted}e.restore(),e.font=`${te(0)}px system-ui, sans-serif`,e.fillStyle=l.text,e.textAlign="center",e.textBaseline="bottom",e.fillText(ht(w,p.unitLabel),k+a/2,r-6),e.save(),e.translate(14,T+u/2),e.rotate(-Math.PI/2),e.textBaseline="top",e.fillText(ht(h,""),0,0),e.restore(),e.strokeStyle=l.border,e.lineWidth=1,e.beginPath(),e.moveTo(k,T),e.lineTo(k,T+u),e.moveTo(k,T+u),e.lineTo(k+a,T+u),e.stroke()}function rn(){if(!i||!$||i.marks?.type!=="scatter"||!i.x||!i.y)return;_e($,ee??0);const e=Ge(B),{w:l,h:s,plotW:r,plotH:a}=Oe(),u=Xe($,B,l,s);if(!u)return;const{ctx:n}=u,t=i.marks.points,o=I.size===0?t:t.filter(P=>I.has(P.group)),h=i.colorScale,w=gt(),v=Ce(i.x),b=Ce(i.y),f=ue(Ne(We(t.map(P=>P.x),i.x),v,i.x),i.x),p=ue(Ne(We(t.map(P=>P.y),i.y),b,i.y),i.y);Z={x:f,y:p,plotW:r,plotH:a},Ye(n,e,l,s,r,a,f,p,i.x,i.y),Fe(n,e.limitLine,r,a,f,v,i.x,"x"),Fe(n,e.limitLine,r,a,p,b,i.y,"y"),Ve(n,r,a);const L=o.length>bt?Math.ceil(o.length/bt):1,M=[];for(let P=0;P<o.length;P+=L)M.push(o[P]);n.globalAlpha=Math.max(.15,Math.min(.7,200/M.length));let g;if(h)g=[M];else{const P=new Map;for(const E of M){const A=P.get(E.group);A?A.push(E):P.set(E.group,[E])}g=[...P.values()].sort((E,A)=>A.length-E.length)}se=[];const y=k,d=k+r,c=T,C=T+a;for(const P of g)for(const E of P){const A=k+f.frac(E.x)*r,j=T+(1-p.frac(E.y))*a;A<y||A>d||j<c||j>C||(se.push({p:E,cx:A,cy:j}),n.beginPath(),n.arc(A,j,2.5,0,Math.PI*2),n.fillStyle=h&&E.value!==void 0?w((E.value-h.lo)/(h.hi-h.lo||1)):oe(E.group),n.fill())}n.globalAlpha=1;const O=i.marks;if(O.type==="scatter"&&(O.identity||O.fits)){const P=(A,j)=>[k+f.frac(A)*r,T+(1-p.frac(j))*a],E=(A,j,x)=>{n.save(),n.beginPath(),n.rect(k,T,r,a),n.clip(),n.strokeStyle=j,n.lineWidth=2,n.setLineDash(x),n.beginPath();for(let be=0;be<=60;be++){const Be=be/60,ze=f.log?10**(Math.log10(f.lo)+(Math.log10(f.hi)-Math.log10(f.lo))*Be):f.lo+(f.hi-f.lo)*Be,[Pe,fe]=P(ze,A(ze));be===0?n.moveTo(Pe,fe):n.lineTo(Pe,fe)}n.stroke(),n.restore()};O.identity&&E(A=>A,e.textMuted,[6,4]);for(const A of O.fits??[])I.size>0&&!I.has(A.group)&&!h||E(j=>A.intercept+A.slope*j,h?e.text:oe(A.group),[])}const _=pe?se.find(P=>P.p===pe):void 0;if(_&&(n.beginPath(),n.arc(_.cx,_.cy,5,0,Math.PI*2),n.lineWidth=2,n.strokeStyle=e.text,n.stroke()),he.size>0){n.lineWidth=1.5,n.strokeStyle=e.text;let P=0;for(const E of he)if(!(I.size>0&&!I.has(E.group))){if(++P>bt)break;n.beginPath(),n.arc(k+f.frac(E.x)*r,T+(1-p.frac(E.y))*a,4,0,Math.PI*2),n.stroke()}}}function cn(){if(Ee=void 0,!i||i.marks?.type!=="histogram"||!i.x)return;const e=i.marks.values,l=e.flat();if(l.length===0)return;const s=ue(Ne(We(l,i.x),Ce(i.x),i.x),i.x),r=Math.max(1,i.spec.bins??oo),a=s.log?Math.log10(s.lo):s.lo,u=s.log?Math.log10(s.hi):s.hi,n=Array.from({length:r+1},(b,f)=>{const p=a+(u-a)*f/r;return s.log?10**p:p}),t=e.map(()=>new Array(r).fill(0));e.forEach((b,f)=>{for(const p of b){const L=s.log?p>0?Math.log10(p):NaN:p;if(!Number.isFinite(L)||L<a||L>u)continue;const M=Math.min(r-1,Math.floor((L-a)/(u-a)*r));t[f][M]++}});const o=i.spec.histNorm==="percent",h=o?t.map(b=>{const f=b.reduce((p,L)=>p+L,0);return b.map(p=>f?p/f*100:0)}):t;let w=0;const v=e.map(()=>{});if(i.spec.normalCurve&&!s.log){const b=(n[n.length-1]-n[0])/r;e.forEach((f,p)=>{const L=f.filter(Number.isFinite);if(L.length<2)return;const M=L.reduce((y,d)=>y+d,0)/L.length,g=Math.sqrt(Bn(L,M));g>0&&(v[p]={mean:M,sd:g},w=Math.max(w,(o?100:t[p].reduce((y,d)=>y+d,0))*b/(g*Math.sqrt(2*Math.PI))))})}Ee={edges:n,counts:t,heights:h,normal:v,maxCount:Math.max(o?.001:1,w,...h.map(b=>Te(b)))}}function fn(){if(!i||!$||!Ee||!i.x||!i.y)return;_e($,ee??0);const e=Ge(B),{w:l,h:s,plotW:r,plotH:a}=Oe(),u=Xe($,B,l,s);if(!u)return;const{ctx:n}=u,{edges:t,counts:o,heights:h,normal:w,maxCount:v}=Ee,b=ue([t[0],t[t.length-1]],{...i.x,min:t[0],max:t[t.length-1]}),f=ue([0,v],{label:i.y.label,scale:"linear",min:0,max:v*1.05});Z={x:b,y:f,plotW:r,plotH:a},Ye(n,e,l,s,r,a,b,f,i.x,i.y),Fe(n,e.limitLine,r,a,b,Ce(i.x),i.x,"x"),Ve(n,r,a);const p=o.map((M,g)=>g).filter(M=>I.size===0||I.has(M)),L=p.length>1;for(const M of p)n.globalAlpha=L?.55:.85,n.fillStyle=oe(M),h[M].forEach((g,y)=>{if(g===0)return;const d=k+Math.min(b.frac(t[y]),b.frac(t[y+1]))*r,c=k+Math.max(b.frac(t[y]),b.frac(t[y+1]))*r,C=T+(1-f.frac(g))*a;n.fillRect(d,C,Math.max(1,c-d-1),T+a-C)});if(n.globalAlpha=1,i.spec.normalCurve&&!b.log){const M=(t[t.length-1]-t[0])/(t.length-1);for(const g of p){const y=w[g];if(!y)continue;const{mean:d,sd:c}=y,C=(i.spec.histNorm==="percent"?100:o[g].reduce((O,_)=>O+_,0))*M;n.save(),n.beginPath(),n.rect(k,T,r,a),n.clip(),n.strokeStyle=oe(g),n.lineWidth=2,n.beginPath();for(let O=0;O<=120;O++){const _=t[0]+(t[t.length-1]-t[0])*O/120,P=Math.exp(-.5*((_-d)/c)**2)/(c*Math.sqrt(2*Math.PI)),E=k+b.frac(_)*r,A=T+(1-f.frac(C*P))*a;O===0?n.moveTo(E,A):n.lineTo(E,A)}n.stroke(),n.restore()}}if(ge>=0){const M=k+Math.min(b.frac(t[ge]),b.frac(t[ge+1]))*r,g=k+Math.max(b.frac(t[ge]),b.frac(t[ge+1]))*r;n.lineWidth=1.5,n.strokeStyle=e.text,n.strokeRect(M,T,Math.max(1,g-M),a)}}function un(){const e=i?.marks;if(!i||!$||!i.x||!i.y||!e||e.type!=="box"&&e.type!=="bar")return;_e($,ee??0);const l=Ge(B),s=i.spec.orientation==="horizontal",r=e.nest?e.nest.parts.map(S=>S[S.length-1]):e.categories,a=e.categories.length,u=i.groups.length,n=S=>I.size===0||I.has(S),t=e.type==="bar"&&!!e.stack,o=(S,F)=>e.type==="bar"?Number.isFinite(e.values[S][F]):e.cells[S][F].length>0,h=Array.from({length:a},(S,F)=>Array.from({length:u},(N,X)=>X).filter(N=>n(N)&&o(N,F))),w=categoryLayout(t?h.map(S=>S.length?[0]:[]):h),v=$.getContext("2d"),b=S=>v?v.measureText(S).width:S.length*6;v&&(v.font=`${te(-1)}px system-ui, sans-serif`);const f=(S,F)=>S.length>F?`${S.slice(0,F-1)}\u2026`:S;let p=!1,L={inner:0,outer:[]},M=0;if(s){L={inner:Math.min(200,Te(r.map(F=>b(f(F,28))))),outer:e.nest?e.nest.levels.slice(0,-1).map((F,N)=>Math.min(140,Te(e.nest.parts.map(X=>b(f(X[N],20)))))):[]},k=Math.max(Ct,30+L.inner+6+L.outer.reduce((F,N)=>F+N+10,0)),e.cumulative&&(T=Bt+18),Ue=De;const S=Math.max(1,...h.map(F=>t?Math.min(1,F.length):F.length));M=Math.max(22,S*to/.8)}else{const S=Te(r.map(X=>b(f(X,22)))),F=Math.max(10,W.clientWidth-k-yt)/Math.max(1,a);p=S+8>F;const N=e.nest?e.nest.levels.length-1:0;Ue=(p?De+Math.min(110,S*.72):De)+N*kt}const g=e.type==="bar"&&!t&&!!i.spec.valueLabels,y=i.y.unit,d=S=>J(S,y),c=g?Te(e.values.flat().filter(Number.isFinite).map(S=>b(d(S))).concat(0))+8:0,C=s?c:e.cumulative?40:0,{w:O,h:_,plotW:P,plotH:E}=Oe(),A=Math.max(10,P-C),j=Xe($,B,O,_);if(!j)return;const{ctx:x}=j,be=S=>S.filter(Number.isFinite),Be=Ce(i.y),ze=t?e.categories.map((S,F)=>e.values.reduce((N,X,Y)=>N+(n(Y)&&Number.isFinite(X[F])?X[F]:0),0)):[],Pe=e.type==="bar"?[...t?ze:be(e.values.flat()),0]:be(e.cells.flat(2));x.font=`${te(-1)}px system-ui, sans-serif`;const fe=s?c:te(-1)+6;if(g&&!s&&Pe.length){const S=Te(Pe);S>0&&Pe.push(S*(1+fe/Math.max(1,E-fe)))}const Le=ue(Ne(We(Pe,i.y),Be,i.y),i.y,{floorAtZero:e.type==="bar"});Z={x:Le,y:Le,plotW:A,plotH:E};const lt=s?E:A,Ze=s&&a*M>E+.5,st=Ze?a*M:lt,it=Ze?Math.max(0,Math.min(nt,st-lt)):0;nt=it,wn(Ze,st,it,A+C,E),s?an(x,l,O,_,A,E,{labels:r,rotate:!1,nest:e.nest?.parts},L,Le,i.x,i.y,{along:st,offset:it}):Ye(x,l,O,_,A,E,{labels:r,rotate:p,nest:e.nest?.parts},Le,i.x,i.y);const xe=st/a,Ae=w.width*xe;ne={slotW:xe,n:a,plotW:st,layout:w,across:s,offset:it,view:lt};const le=S=>s?k+Le.frac(S)*A:T+(1-Le.frac(S))*E,ve=S=>s?T+S-it:k+S,$t=Le.log?s?k:T+E:le(0),Qe=(S,F,N,X)=>s?[Math.min(N,X),ve(S),Math.max(1,Math.abs(X-N)),F-S]:[ve(S),Math.min(N,X),F-S,Math.max(1,Math.abs(X-N))],Pt=(S,F,N,X)=>{x.beginPath(),s?(x.moveTo(F,ve(S)),x.lineTo(X,ve(N))):(x.moveTo(ve(S),F),x.lineTo(ve(N),X)),x.stroke()},Je=S=>s?S>=$t:S<=$t,An=S=>s?te(-1)<=Ae+4:x.measureText(d(S)).width<=Ae+6,zt=g&&e.values.every(S=>S.every(F=>!Number.isFinite(F)||An(F)));if(zt){for(let S=0;S<u;S++)if(n(S))for(let F=0;F<a;F++){const N=w.left(F,S),X=e.values[S][F];if(N===void 0||!Number.isFinite(X))continue;const Y=ve(F*xe+N*xe+Ae/2),H=x.measureText(d(X)).width,G=le(X);s?je.push(Je(G)?{x0:G,x1:G+H+6,y0:Y-fe/2,y1:Y+fe/2}:{x0:G-H-6,x1:G,y0:Y-8,y1:Y+8}):je.push(Je(G)?{x0:Y-H/2,x1:Y+H/2,y0:G-fe,y1:G}:{x0:Y-H/2,x1:Y+H/2,y0:G,y1:G+fe})}}const En=Fe(x,l.limitLine,A,E,Le,Be,i.y,s?"x":"y",{halo:l.bg}),Cn=Ve(x,A,E,Ze);if(t){ne.stacks=[];for(let S=0;S<a;S++){const F=w.left(S,0),N=[];if(ne.stacks.push(N),F===void 0)continue;let X=0;for(let Y=0;Y<u;Y++){const H=e.values[Y][S];if(!n(Y)||!Number.isFinite(H)||H<=0)continue;const G=le(X),ae=le(X+H);x.fillStyle=oe(Y),x.globalAlpha=.9;const re=S*xe+F*xe;x.fillRect(...Qe(re+1,re+Ae-1,G,ae)),x.globalAlpha=1,N.push({g:Y,p0:Math.min(G,ae),p1:Math.max(G,ae)}),X+=H}}}for(let S=0;S<u&&!t;S++){if(I.size>0&&!I.has(S))continue;const F=oe(S);for(let N=0;N<a;N++){const X=w.left(N,S);if(X===void 0)continue;const Y=N*xe+X*xe;if(e.type==="bar"){const H=e.values[S][N];if(!Number.isFinite(H))continue;const G=le(H);if(x.fillStyle=F,x.globalAlpha=.9,x.fillRect(...Qe(Y+1,Y+Ae-1,$t,G)),x.globalAlpha=1,zt){x.fillStyle=l.text,x.font=`${te(-1)}px system-ui, sans-serif`;const ae=ve(Y+Ae/2);s?(x.textBaseline="middle",x.textAlign=Je(G)?"left":"right",x.fillText(d(H),G+(Je(G)?3:-3),ae)):(x.textAlign="center",x.textBaseline=Je(G)?"bottom":"top",x.fillText(d(H),ae,G+(Je(G)?-2:2)))}}else{const H=e.cells[S][N];if(H.length===0)continue;const G=Y+Ae/2,ae=Math.max(3,Math.min(Ae*.7,46)),re=Dt(Float64Array.from(H));if(x.strokeStyle=F,x.fillStyle=F,x.lineWidth=1.5,H.length===1){x.beginPath(),s?x.arc(le(re.median),ve(G),3,0,Math.PI*2):x.arc(ve(G),le(re.median),3,0,Math.PI*2),x.fill();continue}Pt(G,le(re.min),G,le(re.max));for(const Xt of[re.min,re.max])Pt(G-ae/4,le(Xt),G+ae/4,le(Xt));x.globalAlpha=.35,x.fillRect(...Qe(G-ae/2,G+ae/2,le(re.q1),le(re.q3))),x.globalAlpha=1,x.strokeRect(...Qe(G-ae/2,G+ae/2,le(re.q1),le(re.q3))),x.lineWidth=2.5,Pt(G-ae/2,le(re.median),G+ae/2,le(re.median))}}}Cn(),En();const _t=ie?w.left(ie.c,t?0:ie.g):void 0;if(ie&&_t!==void 0){Ze&&(x.save(),x.beginPath(),x.rect(k-1,T,A+2,E),x.clip()),x.lineWidth=1.5,x.strokeStyle=l.text;const S=ie.c*xe+_t*xe,F=t?ne.stacks?.[ie.c]?.find(N=>N.g===ie.g):void 0;t&&F?x.strokeRect(...Qe(S,S+Ae,F.p0,F.p1)):t||x.strokeRect(...Qe(S,S+Ae,s?k:T,s?k+A:T+E)),Ze&&x.restore()}if(e.cumulative){const S=N=>s?k+N/100*A:T+(1-N/100)*E,F=(N,X)=>s?[S(X),ve((N+.5)*xe)]:[ve((N+.5)*xe),S(X)];if(x.save(),x.strokeStyle=l.text,x.fillStyle=l.text,x.lineWidth=1.5,x.beginPath(),e.cumulative.forEach((N,X)=>{const[Y,H]=F(X,N);X===0?x.moveTo(Y,H):x.lineTo(Y,H)}),x.stroke(),e.cumulative.forEach((N,X)=>{const[Y,H]=F(X,N);x.beginPath(),x.arc(Y,H,2.5,0,Math.PI*2),x.fill()}),x.strokeStyle=l.border,x.lineWidth=1,x.beginPath(),s?(x.moveTo(k,T),x.lineTo(k+A,T)):(x.moveTo(k+A,T),x.lineTo(k+A,T+E)),x.stroke(),x.fillStyle=l.textMuted,x.font=`${te(-1)}px system-ui, sans-serif`,s){x.textAlign="center",x.textBaseline="bottom";for(const N of[0,25,50,75,100])x.fillText(`${N}%`,S(N),T-3)}else{x.textAlign="left",x.textBaseline="middle";for(const N of[0,25,50,75,100])x.fillText(`${N}%`,k+A+4,S(N))}x.restore()}}function hn(e){const l=i?.setTests,s=l?l.labels.indexOf(e):-1;return s>=0?{test:l.tests[s]}:{}}function wt(e){if(!ne||!$)return null;const l=$.getBoundingClientRect(),s=ne.across?e.clientY-l.top-T:e.clientX-l.left-k;if(s<0||s>ne.view)return null;const r=s+ne.offset,a=Math.min(ne.n-1,Math.floor(r/ne.slotW)),u=ne.layout.groupAt(a,(r-a*ne.slotW)/ne.slotW);if(u===void 0)return null;if(!ne.stacks)return{g:u,c:a};const n=ne.across?e.clientX-l.left:e.clientY-l.top,t=ne.stacks[a]?.find(o=>n>=o.p0&&n<=o.p1);return t?{g:t.g,c:a}:null}function dn(e,l,s){let r=0,a=0,u=0;for(const o of l)o===100&&r++;if(e.failSide)for(const o of s){const h=e.failSide[o];h<0?a++:h>0&&u++}const n=o=>o.toLocaleString("en-GB"),t=a+u>0?` (${n(a)} below the low limit \xB7 ${n(u)} above the high limit)`:"";return`${n(r)} pass \xB7 ${n(l.length-r)} fail${t} \xB7 n = ${n(l.length)}`}function mn(e){const l=i,s=l.marks,r=l.level==="die"?"dies":"wafers",a=s.cells[e.g][e.c],u=s.nest?s.nest.parts[e.c]:[s.categories[e.c]],n=l.groups.length>1&&!u.includes(qe(e.g))?` \xB7 ${D(qe(e.g))}`:"",t=`<strong>${D(s.categories[e.c])}${n}</strong><br>`,o=l.y?.unit;if(a.length===0)return`${t}no ${r}`;const h=`${a.length.toLocaleString("en-GB")} ${r}`,w=(s.categoryItems&&m.onOpenWafer?`<br><em>click to ${D(m.openActionLabel??"open this wafer")}</em>`:"")+(s.categoryItems&&m.onWaferMenu?At:"");if(s.type==="bar"){const b=s.values[e.g][e.c],f=s.cumulative?`<br>${D(`cumulative: ${s.cumulative[e.c].toFixed(1)}% of the whole`)}`:"";return`${t}${D(`${l.y.label}: ${J(b,o)}`)}<br>${D(s.passFail?dn(s.passFail,a,s.cellUnits[e.g][e.c]):h)}${f}${w}`}const v=Dt(Float64Array.from(a));return`${t}${["max","q3","median","q1","min"].map(b=>D(`${{max:"max",q3:"upper quartile",median:"median",q1:"lower quartile",min:"min"}[b]}: ${J(v[b],o)}`)).join("<br>")}<br>${D(h)}${w}`}function pn(){const e=i?.marks;if(!i||!$||!i.x||!i.y||!e||e.type!=="line")return;_e($,ee??0);const l=Ge(B),{w:s,h:r,plotW:a,plotH:u}=Oe(),n=Xe($,B,s,r);if(!n)return;const{ctx:t}=n,o=Ce(i.x),h=Ce(i.y),w=ue(Ne(We(e.xs,i.x),o,i.x),i.x),v=e.band?[...e.band.lo.flat(),...e.band.hi.flat()]:[],b=ue(Ne(We([...e.values.flat(),...v].filter(Number.isFinite),i.y),h,i.y),i.y);if(Z={x:w,y:b,plotW:a,plotH:u},Ye(t,l,s,r,a,u,w,b,i.x,i.y),Fe(t,l.limitLine,a,u,w,o,i.x,"x"),Fe(t,l.limitLine,a,u,b,h,i.y,"y"),Ve(t,a,u),de=e.xs.map(f=>k+w.frac(f)*a),e.band){const f=p=>T+(1-b.frac(p))*u;e.band.lo.forEach((p,L)=>{if(I.size>0&&!I.has(L))return;const M=e.band.hi[L];t.save(),t.fillStyle=oe(L),t.globalAlpha=.16;let g=[];const y=()=>{if(g.length===1){const d=g[0],c=de[d];t.globalAlpha=.55,t.strokeStyle=oe(L),t.lineWidth=2,t.beginPath(),t.moveTo(c,f(p[d])),t.lineTo(c,f(M[d])),t.moveTo(c-4,f(p[d])),t.lineTo(c+4,f(p[d])),t.moveTo(c-4,f(M[d])),t.lineTo(c+4,f(M[d])),t.stroke(),t.globalAlpha=.16}else if(g.length){t.beginPath(),g.forEach((d,c)=>{c===0?t.moveTo(de[d],f(M[d])):t.lineTo(de[d],f(M[d]))});for(let d=g.length-1;d>=0;d--)t.lineTo(de[g[d]],f(p[g[d]]));t.closePath(),t.fill()}g=[]};p.forEach((d,c)=>{Number.isFinite(d)&&Number.isFinite(M[c])?g.push(c):y()}),y(),t.restore()})}e.values.forEach((f,p)=>{if(I.size>0&&!I.has(p))return;t.strokeStyle=oe(p),t.fillStyle=oe(p),t.lineWidth=2;let L=!1;t.beginPath(),f.forEach((M,g)=>{if(!Number.isFinite(M)){L=!1;return}const y=de[g],d=T+(1-b.frac(M))*u;L?t.lineTo(y,d):t.moveTo(y,d),L=!0}),t.stroke(),f.forEach((M,g)=>{Number.isFinite(M)&&(t.beginPath(),t.arc(de[g],T+(1-b.frac(M))*u,ke===g?4.5:3,0,Math.PI*2),t.fill())})}),ke>=0&&(t.lineWidth=1,t.strokeStyle=l.textMuted,t.beginPath(),t.moveTo(de[ke],T),t.lineTo(de[ke],T+u),t.stroke())}function St(e){const l=i?.marks;if(!l||l.type!=="line"||!$||!i?.x||de.length===0)return null;const s=e.clientX-$.getBoundingClientRect().left;let r=-1,a=24;if(de.forEach((t,o)=>{const h=Math.abs(t-s);h<a&&(a=h,r=o)}),ke=r,r<0)return null;const u=i.level==="die"?"dies":"wafers",n=l.values.map((t,o)=>({g:o,v:t[r],n:l.counts[o][r]})).filter(t=>Number.isFinite(t.v)&&(I.size===0||I.has(t.g)));return`<strong>${D(`${i.x.label}: ${J(l.xs[r],i.x.unit)}`)}</strong><br>`+n.map(t=>{const o=l.band?.lo[t.g][r],h=l.band?.hi[t.g][r],w=o!==void 0&&h!==void 0&&Number.isFinite(o)&&Number.isFinite(h)?`, band ${J(o,i.y.unit)} to ${J(h,i.y.unit)}`:"";return D(`${i.groups.length>1?`${qe(t.g)}: `:""}${J(t.v,i.y.unit)}${w} (${t.n.toLocaleString("en-GB")} ${u})`)}).join("<br>")+(m.onWaferMenu&&Nt(r)!==void 0?At:"")}function Nt(e){const l=i?.marks;if(l?.type!=="line")return;const s=new Set(l.cellUnits.flatMap((r,a)=>I.size>0&&!I.has(a)?[]:(r[e]??[]).map(u=>l.unit(u).item)));return s.size===1?[...s][0]:void 0}function gn(){const e=i?.marks;if(!i||!$||!i.x||!i.y||e?.type!=="probability")return;_e($,ee??0);const l=Ge(B),{w:s,h:r,plotW:a,plotH:u}=Oe(),n=Xe($,B,s,r);if(!n)return;const{ctx:t}=n,o=i.spec.probabilityAxis==="linear",h=e.values.map((P,E)=>E).filter(P=>e.values[P].length>0&&(I.size===0||I.has(P))),w=Math.max(1,...h.map(P=>e.values[P].length)),v=Math.min(.01,at(0,w)),b=P=>o?P:jt(P),f=o?0:b(v),p=o?1:b(1-v),L=o?0:(p-f)*.03,M=ue([f-L,p+L],{label:i.y.label,scale:"linear",min:f-L,max:p+L}),g=o?[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1]:lo.filter(P=>P>=v&&P<=1-v),y=[],d=P=>T+(1-M.frac(P))*u,c=g.indexOf(.5);y.push({at:b(.5),label:on(.5)});for(const P of[g.slice(c+1),g.slice(0,c).reverse()]){let E=d(b(.5));for(const A of P){const j=d(b(A));Math.abs(j-E)<16||(y.push({at:b(A),label:on(A)}),E=j)}}const C=Ce(i.x),O=ue(Ne(We(h.flatMap(P=>[e.values[P][0],e.values[P][e.values[P].length-1]]),i.x),C,i.x),i.x);Z={x:O,y:M,plotW:a,plotH:u},Ye(t,l,s,r,a,u,O,M,i.x,i.y,y),Fe(t,l.limitLine,a,u,O,C,i.x,"x"),Ve(t,a,u),se=[],t.save(),t.beginPath(),t.rect(k,T,a,u),t.clip();for(const P of h){const E=e.values[P],A=E.length,j=so(A);if(t.strokeStyle=oe(P),t.fillStyle=oe(P),t.lineWidth=1.5,t.beginPath(),j.forEach((x,be)=>{const Be=k+O.frac(E[x])*a,ze=d(b(at(x,A)));be===0?t.moveTo(Be,ze):t.lineTo(Be,ze);const Pe=P*2**26+x;let fe=xt.get(Pe);if(!fe){const{item:Le,die:lt}=e.unit(e.units[P][x]);fe={x:E[x],y:at(x,A),group:P,item:Le,die:lt},xt.set(Pe,fe)}se.push({p:fe,cx:Be,cy:ze})}),t.stroke(),A<=300)for(const x of j)t.beginPath(),t.arc(k+O.frac(E[x])*a,d(b(at(x,A))),2.5,0,Math.PI*2),t.fill()}if(t.restore(),he.size>0){t.lineWidth=1.5,t.strokeStyle=l.text;let P=0;for(const E of he)if(!(I.size>0&&!I.has(E.group))){if(++P>bt)break;t.beginPath(),t.arc(k+O.frac(E.x)*a,d(b(E.y)),4,0,Math.PI*2),t.stroke()}}const _=pe?se.find(P=>P.p===pe):void 0;_&&(t.beginPath(),t.arc(_.cx,_.cy,5,0,Math.PI*2),t.lineWidth=2,t.strokeStyle=l.text,t.stroke())}function yn(e){const l=i,r=l.marks.values[e.group].length,a=Math.round(e.y*r+.5),u=m.waferLabel(e.item),n=e.die&&e.die.x!==void 0?`die (${e.die.x}, ${e.die.y})`:"",t=[u,n].filter(Boolean).join(" \xB7 ");return(t?`<strong>${D(t)}</strong><br>`:"")+D(`${l.x.label}: ${J(e.x,l.x.unit)}`)+"<br>"+D(`rank ${a.toLocaleString("en-GB")} of ${r.toLocaleString("en-GB")}, plotted at ${+(e.y*100).toPrecision(3)}%`)+(l.groups.length>1?`<br>${D(qe(e.group))}`:"")+(m.onOpenWafer?`<br><em>click to ${D(m.openActionLabel??"open this wafer")}</em>`:"")+(m.onWaferMenu&&!e.die?At:"")}let Re,ye=null;function bn(){const e=i?.marks;if(!i||!$||e?.type!=="heatmap")return;_e($,ee??0);const l=Ge(B),s=$.getContext("2d");let r=0,a=0;s&&(s.font=`${te(-1)}px system-ui, sans-serif`,r=Te(e.rows.map(d=>s.measureText(d.length>24?`${d.slice(0,23)}\u2026`:d).width)),a=Te(e.cols.map(d=>s.measureText(d.length>22?`${d.slice(0,21)}\u2026`:d).width)));const u=Math.min(180,Math.max(k,r+24)),n=Math.max(8,W.clientWidth-u-yt)/Math.max(1,e.cols.length),t=a+8>n;Ue=t?De+Math.min(110,a*.72):De;const{w:o,h}=Oe(),w=Math.max(10,o-u-yt),v=Math.max(10,h-T-Ue),b=Xe($,B,o,h);if(!b)return;const{ctx:f}=b,p=w/e.cols.length,L=v/e.rows.length;Re={left:u,cw:p,ch:L,rows:e.rows.length,cols:e.cols.length};const M=i.colorScale,g=gt(),y=M&&M.hi-M.lo||1;f.font=`${te(-1)}px system-ui, sans-serif`;for(let d=0;d<e.rows.length;d++)for(let c=0;c<e.cols.length;c++){const C=e.values[d][c],O=u+c*p,_=T+d*L;f.fillStyle=Number.isFinite(C)&&M?g((C-M.lo)/y):l.track,f.fillRect(O+.5,_+.5,Math.max(1,p-1),Math.max(1,L-1)),Number.isFinite(C)&&p>=40&&L>=16&&(f.fillStyle="#fff",f.textAlign="center",f.textBaseline="middle",Lt(f,Wt(C,i.y?.unit,M?.integer),O+p/2,_+L/2,"rgba(0,0,0,0.55)"))}ye&&(f.lineWidth=2,f.strokeStyle=l.text,f.strokeRect(u+ye.c*p,T+ye.r*L,p,L)),f.fillStyle=l.textMuted,f.textAlign="right",f.textBaseline="middle",e.rows.forEach((d,c)=>f.fillText(d.length>24?`${d.slice(0,23)}\u2026`:d,u-6,T+(c+.5)*L)),e.cols.forEach((d,c)=>{const C=d.length>22?`${d.slice(0,21)}\u2026`:d,O=u+(c+.5)*p;t?(f.save(),f.translate(O,T+v+6),f.rotate(-Math.PI/4),f.textAlign="right",f.textBaseline="middle",f.fillText(C,0,0),f.restore()):(f.textAlign="center",f.textBaseline="top",f.fillText(C,O,T+v+4))}),f.font=`${te(0)}px system-ui, sans-serif`,f.fillStyle=l.text,f.textAlign="center",f.textBaseline="bottom",f.fillText(i.x?.label??"",u+w/2,h-6)}function Ft(e){if(!Re||!$)return null;const l=$.getBoundingClientRect(),s=Math.floor((e.clientX-l.left-Re.left)/Re.cw),r=Math.floor((e.clientY-l.top-T)/Re.ch);return r>=0&&r<Re.rows&&s>=0&&s<Re.cols?{r,c:s}:null}function xn(e){const l=i,s=l.marks,r=s.values[e.r][e.c],a=s.cellUnits[e.r][e.c].length,u=l.level==="die"?"dies":"wafers";return`<strong>${D(`${s.rows[e.r]} \xB7 ${s.cols[e.c]}`)}</strong><br>`+(Number.isFinite(r)?D(`${l.y?.label??"Count"}: ${Wt(r,l.y?.unit,l.colorScale?.integer)}`)+"<br>":"")+D(`${a.toLocaleString("en-GB")} ${u}`)+(a&&m.onSelectPoints?"<br><em>click to chart or tabulate them</em>":"")}function vn(){const e=i?.marks;if(!i||!$||!i.x||!i.y||e?.type!=="control")return;_e($,ee??0);const l=Ge(B),{w:s,h:r,plotW:a,plotH:u}=Oe(),n=Xe($,B,s,r);if(!n)return;const{ctx:t}=n,o=e.limits,h=Ce(i.y),w=ue(We(e.xs,i.x),i.x),v=ue(Ne(We([...e.values,o.ucl,o.lcl],i.y),h,i.y),i.y);Z={x:w,y:v,plotW:a,plotH:u},Ye(t,l,s,r,a,u,w,v,i.x,i.y),Fe(t,l.limitLine,a,u,v,h,i.y,"y"),Ve(t,a,u);const b=y=>k+w.frac(e.xs[y])*a,f=y=>T+(1-v.frac(y))*u;t.save(),t.beginPath(),t.rect(k,T,a,u),t.clip();const p=(y,d,c,C=1)=>{t.globalAlpha=c,t.setLineDash(d),t.lineWidth=C,t.strokeStyle=l.text,t.beginPath(),t.moveTo(k,f(y)),t.lineTo(k+a,f(y)),t.stroke()};for(const y of[-2,-1,1,2])p(o.centre+y*o.sigma,[2,4],.25);p(o.centre,[],.6,1.5),p(o.ucl,[6,4],.85),p(o.lcl,[6,4],.85),t.restore(),t.fillStyle=l.textMuted,t.font=`${te(-1)}px system-ui, sans-serif`,t.textAlign="right",t.textBaseline="bottom";const L=y=>J(y,i.y.unit);if(t.fillText(`UCL ${L(o.ucl)}`,k+a-4,f(o.ucl)-2),t.textBaseline="top",t.fillText(`LCL ${L(o.lcl)}`,k+a-4,f(o.lcl)+2),t.textBaseline="bottom",t.fillText(`Centre ${L(o.centre)}`,k+a-4,f(o.centre)-2),o.baseline<e.values.length){const y=(b(o.baseline-1)+b(o.baseline))/2;t.save(),t.strokeStyle=l.textMuted,t.setLineDash([2,3]),t.beginPath(),t.moveTo(y,T),t.lineTo(y,T+u),t.stroke(),t.restore(),t.textAlign="left",t.textBaseline="top",t.fillText("limits from here \u2190",k+4,T+2)}t.strokeStyle=oe(0),t.lineWidth=1.5,t.setLineDash([]),t.beginPath(),e.values.forEach((y,d)=>{d===0?t.moveTo(b(d),f(y)):t.lineTo(b(d),f(y))}),t.stroke();const M=new Map(e.violations.map(y=>[y.index,y.rules]));se=[],e.values.forEach((y,d)=>{const c=M.get(d);t.beginPath(),t.arc(b(d),f(y),c?4.5:3,0,Math.PI*2),t.fillStyle=c?l.alert:oe(0),t.fill(),c&&(t.fillStyle=l.alert,t.textAlign="center",t.textBaseline="bottom",t.fillText(c.join(","),b(d),f(y)-6)),se.push({p:{x:e.xs[d],y,group:0,item:e.items[d]},cx:b(d),cy:f(y)})});const g=pe?se.find(y=>y.p===pe):void 0;g&&(t.beginPath(),t.arc(g.cx,g.cy,6,0,Math.PI*2),t.lineWidth=2,t.strokeStyle=l.text,t.stroke())}function Mn(e){const l=i,s=l.marks,r=s.items.indexOf(e.item),a=(e.y-s.limits.centre)/s.limits.sigma,u=s.violations.find(n=>n.index===r)?.rules;return`<strong>${D(m.waferLabel(e.item))}</strong><br>`+D(`${l.y.label}: ${J(e.y,l.y.unit)} (${a>=0?"+":"\u2212"}${Math.abs(a).toFixed(1)}\u03C3)`)+(u?`<br>${D(`breaks rule ${u.map(n=>`${n} (${Wn[n]})`).join(", ")}`)}`:"")+(m.onOpenWafer?`<br><em>click to ${D(m.openActionLabel??"open this wafer")}</em>`:"")}function kn(){const e=i?.marks;if(!i||!$||!i.x||!i.y||e?.type!=="goal")return;_e($,ee??0);const l=Ge(B),{w:s,h:r,plotW:a,plotH:u}=Oe(),n=Xe($,B,s,r);if(!n)return;const{ctx:t}=n,o=Math.max(.5,...e.points.map(c=>Math.abs(c.x))),h=ue([-o,o],{...i.x,min:i.x.min??-o*1.05,max:i.x.max??o*1.05}),w=ue([0,...e.points.map(c=>c.y),1/6],{...i.y,min:i.y.min??0},{floorAtZero:!0});Z={x:h,y:w,plotW:a,plotH:u},Ye(t,l,s,r,a,u,h,w,i.x,i.y);const v=c=>k+h.frac(c)*a,b=c=>T+(1-w.frac(c))*u;t.save(),t.beginPath(),t.rect(k,T,a,u),t.clip(),t.font=`${te(-1)}px system-ui, sans-serif`;const f=[[1,[6,4]],[1.33,[]]];for(const[c,C]of f){const O=1/(6*c);t.strokeStyle=l.textMuted,t.lineWidth=1,t.setLineDash(C),t.beginPath(),t.moveTo(v(-.5),b(0)),t.lineTo(v(0),b(O)),t.lineTo(v(.5),b(0)),t.stroke(),t.fillStyle=l.textMuted,t.textAlign="left",t.textBaseline="bottom",t.fillText(`Ppk ${c}`,v(0)+4,b(O)-2)}t.restore(),se=[];const p=e.points.filter(c=>I.size===0||I.has(c.group));for(const c of p)t.beginPath(),t.arc(v(c.x),b(c.y),4,0,Math.PI*2),t.fillStyle=oe(c.group),t.fill(),se.push({p:{x:c.x,y:c.y,group:c.group,item:-1,value:c.testNumber},cx:v(c.x),cy:b(c.y)});const L=p.map(c=>({x0:v(c.x)-5,x1:v(c.x)+5,y0:b(c.y)-5,y1:b(c.y)+5})),M={x0:k,x1:k+a,y0:T,y1:T+u},g=c=>c.x0>=M.x0&&c.x1<=M.x1&&c.y0>=M.y0&&c.y1<=M.y1&&!L.some(C=>c.x0<C.x1&&c.x1>C.x0&&c.y0<C.y1&&c.y1>C.y0),y=te(-1)+2;t.fillStyle=l.text,t.textBaseline="middle";for(const c of[...p].filter(C=>C.ppk<1.33).sort((C,O)=>C.ppk-O.ppk)){const C=v(c.x),O=b(c.y),_=t.measureText(c.label).width,P=[[C+7,O,"left"],[C-7,O,"right"],[C,O-13,"center"],[C,O+13,"center"]];for(const[E,A,j]of P){const x=j==="left"?E:j==="right"?E-_:E-_/2,be={x0:x,x1:x+_,y0:A-y/2,y1:A+y/2};if(g(be)){L.push(be),t.textAlign=j,t.fillText(c.label,E,A);break}}}const d=pe?se.find(c=>c.p===pe):void 0;d&&(t.beginPath(),t.arc(d.cx,d.cy,6,0,Math.PI*2),t.lineWidth=2,t.strokeStyle=l.text,t.stroke())}function Tn(e){const l=i,r=l.marks.points.find(a=>a.testNumber===e.value&&a.group===e.group);return r?`<strong>${D(r.label)}</strong>${l.groups.length>1?` \xB7 ${D(qe(r.group))}`:""}<br>`+D(`Ppk ${r.ppk.toFixed(2)} \xB7 ${r.n.toLocaleString("en-GB")} dies`)+"<br>"+D(`mean ${r.x>=0?"+":"\u2212"}${Math.abs(r.x*100).toFixed(1)}% of the window from its centre, \u03C3 ${(r.y*100).toFixed(1)}% of it (${r.basis==="spec"?"spec":"test"} limits)`):""}function wn(e,l,s,r,a){!$e||!$||($e.style.display=e?"block":"none",e&&(Object.assign($e.style,{top:`${$.offsetTop+T}px`,height:`${a}px`,left:`${$.offsetLeft+k+r+1}px`}),$e.firstElementChild.style.height=`${l}px`,Math.abs($e.scrollTop-s)>=1&&($e.scrollTop=s)))}function K(){$e&&($e.style.display="none"),ut&&!ln()&&(ut.style.maxHeight=Zt(B)?"":`${no}px`),Q&&m.panel&&(Q.style.display=Zt(B)?"flex":"none"),k=Ct,T=Bt;const e=i?.marks?.type;e==="scatter"?rn():e==="control"?vn():e==="heatmap"?bn():e==="goal"?kn():e==="probability"?gn():e==="histogram"?fn():e==="box"||e==="bar"?un():e==="line"&&pn(),Ot()}function Sn(e){const l=i,s=m.waferLabel(e.item),r=e.die&&e.die.x!==void 0?`die (${e.die.x}, ${e.die.y})`:"",a=[s,r].filter(Boolean).join(" \xB7 "),u=(n,t)=>`${n.label}: ${J(t,n.unit)}`;return(a?`<strong>${D(a)}</strong><br>`:"")+D(u(l.x,e.x))+"<br>"+D(u(l.y,e.y))+(l.colorScale&&e.value!==void 0?`<br>${D(`${l.colorScale.label}: ${J(e.value,l.colorScale.unit)}`)}`:"")+(l.groups.length>1?`<br>${D(qe(e.group))}`:"")+(m.onOpenWafer?`<br><em>click to ${D(m.openActionLabel??"open this wafer")}</em>`:"")}function Rt(e){if(!Ee||!Z||!i?.x)return null;const l=$.getBoundingClientRect(),r=(e.clientX-l.left-k)/Z.plotW;if(r<0||r>1)return null;const a=Z.x.reverse?1-r:r,{edges:u,counts:n}=Ee,t=u.length-1,o=Math.min(t-1,Math.max(0,Math.floor(a*t)));ge=o;const h=i.x,w=n.map((v,b)=>({g:b,n:v[o]})).filter(v=>v.n>0&&(I.size===0||I.has(v.g)));return`<strong>${D(`${J(u[o],h.unit)} to ${J(u[o+1],h.unit)}`)}</strong><br>`+(w.length?w.map(v=>{const b=i.spec.histNorm==="percent"?` (${Ee.heights[v.g][o].toFixed(1)}% of ${i.groups.length>1?"its colour":"them"})`:"";return D(`${i.groups.length>1?`${qe(v.g)}: `:""}${v.n.toLocaleString("en-GB")} ${i.level==="die"?"dies":"wafers"}${b}`)}).join("<br>"):"none")}function $n(e){const l=R.createElement("div");l.dataset.wmapPlotColorbar="1",Object.assign(l.style,{display:"flex",alignItems:"center",gap:me.md,marginTop:me.md,marginBottom:me.xl,fontSize:mt.body,color:et.label});const s=R.createElement("canvas");s.width=200,s.height=10,Object.assign(s.style,{width:"200px",height:"10px",borderRadius:Nn.control,flex:"0 0 auto"});const r=s.getContext("2d"),a=gt();if(r)for(let h=0;h<200;h++)r.fillStyle=a(h/199),r.fillRect(h,0,1,10);const u=h=>i?.marks?.type==="heatmap"?Wt(h,e.unit,e.integer):J(h,e.unit),n=R.createElement("span");n.textContent=u(e.lo);const t=R.createElement("span");t.textContent=u(e.hi);const o=R.createElement("span");return o.textContent=e.label,o.style.color=et.text,l.append(o,n,s,t),l}const ot=(e,l,s)=>l.map(r=>{const{item:a,die:u}=e(r);return{x:0,y:0,group:s,item:a,die:u}});function Pn(){Ke?.destroy(),Ke=void 0,W.innerHTML="",$=void 0,Q=void 0,ee=void 0,tt=[],pe=null,ge=-1,se=[],Z=void 0,ne=void 0,ie=null,$e=void 0,nt=0,ut=void 0,Re=void 0,ye=null,de=[],ke=-1,Ue=De,xt=new Map,I.clear(),he.clear();for(const n of ce)n.destroy();ce=[],ct?.(),ct=void 0,W.style.overflowY="",delete B.dataset.wmapPlotPanelsOwner,delete B.dataset.wmapPanelsHover,we(()=>B.querySelector("canvas"));const e=i,l=!!e?.facets&&!m.panel;if(B.style.flex=l?"0 0 auto":"1 1 0px",B.style.gridColumn=l?"1 / -1":"",!e)return;if(U.textContent=m.panel?m.panel.title:On(e),B.dataset.wmapChartTitle=U.textContent,e.issues.length||!e.marks){for(const n of e.issues)Vt(W,n);return}const s=R.createElement("div");Object.assign(s.style,{color:et.label,fontSize:mt.body,marginBottom:me.xs});const r=m.openActionLabel??"open this wafer",a=e.marks.type==="scatter"?(m.onOpenWafer?` \xB7 click a point to ${r}`:"")+(m.onSelectPoints?` \xB7 drag to select ${e.level==="die"?"dies":"wafers"}`:""):e.marks.type==="box"||e.marks.type==="bar"?(m.onOpenWafer&&e.marks.categoryItems?` \xB7 click a ${e.marks.type} to ${r}`:m.onSelectPoints?` \xB7 click to ${m.selectActionLabel??"chart or tabulate what it counts"}`:"")+(e.marks.type==="box"?" \xB7 box: quartiles; whiskers: minimum and maximum":""):e.marks.type==="histogram"&&m.onSelectPoints?" \xB7 click a bar to chart or tabulate its dies":e.marks.type==="probability"?(m.onOpenWafer?` \xB7 click a point to ${r}`:"")+(m.onSelectPoints?` \xB7 drag to select ${e.level==="die"?"dies":"wafers"}`:""):e.marks.type==="line"&&m.onSelectPoints?` \xB7 click a point to ${m.selectActionLabel??"chart or tabulate what it averages"} \xB7 drag across the plot to select ${m.selectRangeLabel??"a run of points"}`:"";s.textContent=m.panel?`${e.population.wafers.toLocaleString("en-GB")} wafer${e.population.wafers===1?"":"s"} \xB7 ${e.population.dies.toLocaleString("en-GB")} dies`:qt(e)+(e.facets?"":a),m.panel||Rn(s,Yt(e)),Ht(s),ee=R.createElement("div"),ee.style.display="flow-root",W.appendChild(ee),ee.appendChild(s);for(const n of e.fitNotes??[]){const t=R.createElement("div");t.dataset.wmapPlotFit="1",t.textContent=n,Object.assign(t.style,{color:et.text,fontSize:mt.body,marginBottom:me.xxs,fontVariantNumeric:"tabular-nums"}),ee.appendChild(t)}for(const n of e.notes){const t=R.createElement("div");Ht(t),t.textContent=n,Object.assign(t.style,{color:et.warnText,fontSize:mt.body,marginBottom:me.xs}),ee.appendChild(t)}if(e.plotted===0){Vt(W,"Nothing to plot: no mark has every value this plot needs.");return}if(e.groups.length>1&&!e.colorRepeatsX&&(Q=R.createElement("div"),Q.dataset.wmapPlotLegend="1",Object.assign(Q.style,{display:m.panel?"none":"flex",flexWrap:"wrap",gap:me.sm,marginTop:me.md,marginBottom:me.xl,overflowY:"auto"}),ut=Q,e.facets&&Object.assign(Q.style,{position:"sticky",top:"0",zIndex:"2",background:et.menuBg,paddingBottom:me.sm,marginBottom:me.md}),e.groups.forEach((n,t)=>{const o=Un(n||"(none)",oe(t),R);Xn(o.el,B,z,`${n||"(none)"} \u2014 click to filter`),o.el.addEventListener("click",()=>{if(I.has(t)?I.delete(t):I.add(t),tt.forEach((h,w)=>h.setState({selected:I.has(w),dimmed:I.size>0&&!I.has(w)})),ce.length)for(const h of ce)h.setActiveGroups(I);else K()}),tt.push(o),Q.appendChild(o.el)}),tt.forEach((n,t)=>n.setState({selected:I.has(t),dimmed:I.size>0&&!I.has(t)})),ee.appendChild(Q)),e.colorScale&&!m.panel&&(Q=$n(e.colorScale),ee.appendChild(Q)),e.facets){const n=R.createElement("div");n.dataset.wmapPlotPanels="1",n.style.isolation="isolate",Object.assign(n.style,{display:"grid",gap:me.md});const t=()=>{n.style.gridTemplateColumns=Ie?`repeat(${Ie}, minmax(0, 1fr))`:`repeat(auto-fill, minmax(${io}px, 1fr))`};t();const o=qn("Columns:",[{value:"auto",label:"Auto (0)"},...[1,2,3,4,5].map(v=>({value:String(v),label:`${v} (${v})`}))],Ie?String(Ie):"auto",v=>{Ie=v==="auto"?void 0:Number(v),t()},{hook:"panel-columns",maxWidth:"90px",ownerDocument:R});Object.assign(o.style,{justifyContent:"flex-end",marginBottom:me.sm});const h=o.querySelector("button");W.append(o,n),W.style.overflowY="auto",B.dataset.wmapPlotPanelsOwner="1",ft&&(B.dataset.wmapPanelsHover="1");const w=v=>{if(!ft||v.ctrlKey||v.metaKey||v.altKey||v.shiftKey||v.defaultPrevented||!/^[0-5]$/.test(v.key))return;const b=v.target;typeof b?.closest=="function"&&b.closest('input, textarea, select, [contenteditable="true"], [role="menu"]')||(v.preventDefault(),Ie=v.key==="0"?void 0:Number(v.key),t(),h&&(h.value=Ie?String(Ie):"auto"))};R.addEventListener("keydown",w),ct=()=>R.removeEventListener("keydown",w);for(const v of e.facets){const b=renderPlotChart({...m,panel:{title:v.label}});n.appendChild(b.card),b.setPlot(v.plot),ce.push(b)}we(()=>ao(n));return}$=R.createElement("canvas"),$.style.display="block",$.style.cursor=e.marks.type==="scatter"||e.marks.type==="probability"?"crosshair":"default",W.appendChild($);const u=m.onWaferMenu?(n,t)=>{n.die||m.onWaferMenu(n.item,He(e.spec),t)}:void 0;if(e.marks.type==="scatter"){const n=e.marks,t=!!m.onSelectPoints;Ke=Et({card:B,canvas:$,tooltip:z,drawn:()=>se,describe:Sn,clickable:()=>!!m.onOpenWafer,onOpen:o=>m.onOpenWafer?.(o.item,He(e.spec)),onContextMenu:u,onHover:o=>{pe=o,K()},select:t?{pick:({x0:o,y0:h,x1:w,y1:v})=>Z?(I.size===0?n.points:n.points.filter(f=>I.has(f.group))).filter(f=>{const p=k+Z.x.frac(f.x)*Z.plotW,L=T+(1-Z.y.frac(f.y))*Z.plotH;return p>=o&&p<=w&&L>=h&&L<=v}):[],onPicked:(o,h)=>{he.clear();for(const w of o)he.add(w);K(),o.length>0&&m.onSelectPoints(o,h,$)},onClear:()=>{he.clear(),K()},hasSelection:()=>he.size>0}:void 0})}else if(e.marks.type==="control"||e.marks.type==="goal"){const n=e.marks.type==="control";Ke=Et({card:B,canvas:$,tooltip:z,drawn:()=>se,describe:n?Mn:Tn,clickable:()=>n&&!!m.onOpenWafer,onOpen:t=>{n&&m.onOpenWafer?.(t.item,He(e.spec))},onContextMenu:n?u:void 0,onHover:t=>{pe=t,K()}})}else if(e.marks.type==="probability"){const n=e.marks,t=e.spec.probabilityAxis==="linear";Ke=Et({card:B,canvas:$,tooltip:z,drawn:()=>se,describe:yn,clickable:()=>!!m.onOpenWafer,onOpen:o=>m.onOpenWafer?.(o.item,He(e.spec)),onContextMenu:u,onHover:o=>{pe=o,K()},select:m.onSelectPoints?{pick:({x0:o,y0:h,x1:w,y1:v})=>{if(!Z)return[];const b=[];return n.values.forEach((f,p)=>{I.size>0&&!I.has(p)||f.forEach((L,M)=>{const g=at(M,f.length),y=k+Z.x.frac(L)*Z.plotW,d=T+(1-Z.y.frac(t?g:jt(g)))*Z.plotH;if(y<o||y>w||d<h||d>v)return;const{item:c,die:C}=n.unit(n.units[p][M]);b.push({x:L,y:g,group:p,item:c,die:C})})}),b},onPicked:(o,h)=>{he.clear();for(const w of o)he.add(w);K(),o.length>0&&m.onSelectPoints(o,h,$)},onClear:()=>{he.clear(),K()},hasSelection:()=>he.size>0}:void 0})}else if(e.marks.type==="histogram"){cn(),$.addEventListener("mousemove",t=>{const o=Rt(t);if(!o){z.style.display="none",ge>=0&&(ge=-1,K());return}z.innerHTML=o,z.style.display="block",pt(z,B,t.clientX,t.clientY),K()}),$.addEventListener("mouseleave",()=>{z.style.display="none",ge>=0&&(ge=-1,K())});const n=e.marks;m.onSelectPoints&&($.style.cursor="pointer",$.addEventListener("click",t=>{if(!Ee||Rt(t)===null)return;const o=ge,{edges:h}=Ee,w=Z?.x.log,v=w?Math.log10(h[0]):h[0],b=w?Math.log10(h[h.length-1]):h[h.length-1],f=h.length-1,p=[];n.values.forEach((L,M)=>{if(I.size>0&&!I.has(M))return;const g=[];L.forEach((y,d)=>{const c=w?y>0?Math.log10(y):NaN:y;!Number.isFinite(c)||c<v||c>b||Math.min(f-1,Math.floor((c-v)/(b-v)*f))===o&&g.push(n.units[M][d])});for(const y of ot(n.unit,g,M))p.push(y)}),p.length>0&&(z.style.display="none",m.onSelectPoints(p,{x:t.clientX,y:t.clientY},$,{range:{lo:h[o],hi:h[o+1]},...I.size===1?{group:e.groups[[...I][0]]}:{}}))}))}else if(e.marks.type==="heatmap"){const n=e.marks;$.addEventListener("mousemove",t=>{const o=Ft(t);if($.style.cursor=o&&m.onSelectPoints&&n.cellUnits[o.r][o.c].length?"pointer":"default",!o){z.style.display="none",ye&&(ye=null,K());return}z.innerHTML=xn(o),z.style.display="block",pt(z,B,t.clientX,t.clientY),(!ye||ye.r!==o.r||ye.c!==o.c)&&(ye=o,K())}),$.addEventListener("mouseleave",()=>{z.style.display="none",ye&&(ye=null,K())}),$.addEventListener("click",t=>{const o=Ft(t);if(!o||!m.onSelectPoints)return;const h=n.cellUnits[o.r][o.c];h.length&&(z.style.display="none",m.onSelectPoints(ot(n.unit,h,0),{x:t.clientX,y:t.clientY},$))})}else if(e.marks.type==="box"||e.marks.type==="bar"){const n=e.marks;if(e.spec.orientation==="horizontal"){const t=R.createElement("div");t.dataset.wmapRowScroll="1",t.tabIndex=0,t.setAttribute("aria-label",`Scroll the ${n.categories.length} rows`),Object.assign(t.style,{position:"absolute",display:"none",width:"12px",overflowY:"auto",overflowX:"hidden",zIndex:"1"});const o=R.createElement("div");o.style.width="1px",t.appendChild(o),t.addEventListener("scroll",()=>{Math.abs(t.scrollTop-nt)<1||(nt=t.scrollTop,z.style.display="none",K())}),$.addEventListener("wheel",h=>{if(t.style.display==="none")return;const w=t.scrollTop;t.scrollTop+=h.deltaMode===1?h.deltaY*16:h.deltaY,t.scrollTop!==w&&h.preventDefault()},{passive:!1}),W.appendChild(t),$e=t}$.addEventListener("mousemove",t=>{const o=wt(t);if($.style.cursor=o&&(n.categoryItems&&m.onOpenWafer||m.onSelectPoints&&n.cellUnits[o.g][o.c].length>0)?"pointer":"default",!o){z.style.display="none",ie&&(ie=null,K());return}z.innerHTML=mn(o),z.style.display="block",pt(z,B,t.clientX,t.clientY),(!ie||ie.g!==o.g||ie.c!==o.c)&&(ie=o,K())}),$.addEventListener("mouseleave",()=>{z.style.display="none",ie&&(ie=null,K())}),m.onWaferMenu&&n.categoryItems&&$.addEventListener("contextmenu",t=>{const o=wt(t),h=o?n.categoryItems[o.c]:void 0;h===void 0||h<0||(z.style.display="none",m.onWaferMenu(h,He(e.spec),t))}),$.addEventListener("click",t=>{const o=wt(t);if(!o)return;const h=n.categoryItems?.[o.c];if(h!==void 0&&h>=0&&m.onOpenWafer){m.onOpenWafer(h,He(e.spec));return}const w=n.cellUnits[o.g][o.c];w.length>0&&m.onSelectPoints&&(z.style.display="none",m.onSelectPoints(ot(n.unit,w,o.g),{x:t.clientX,y:t.clientY},$,{category:n.categories[o.c],...e.groups.length>1?{group:e.groups[o.g]}:{},...hn(n.categories[o.c])}))})}else if(e.marks.type==="line"){$.addEventListener("mousemove",t=>{const o=St(t);if(!o){z.style.display="none",K();return}z.innerHTML=o,z.style.display="block",pt(z,B,t.clientX,t.clientY),K()}),$.addEventListener("mouseleave",()=>{z.style.display="none",ke>=0&&(ke=-1,K())});const n=e.marks;if(m.onWaferMenu&&$.addEventListener("contextmenu",t=>{const o=St(t)===null?void 0:Nt(ke);o!==void 0&&(z.style.display="none",m.onWaferMenu(o,He(e.spec),t))}),m.onSelectPoints){$.style.cursor="pointer";let t=!1;$.addEventListener("mousedown",o=>{if(o.button!==0)return;t=!1;const h=$.getBoundingClientRect(),w=o.clientX-h.left,v=b=>{R.removeEventListener("mouseup",v);const f=b.clientX-h.left;if(Math.abs(f-w)<4)return;t=!0;const[p,L]=w<f?[w,f]:[f,w],M=de.map((y,d)=>y>=p&&y<=L?d:-1).filter(y=>y>=0),g=n.cellUnits.flatMap((y,d)=>I.size>0&&!I.has(d)?[]:M.flatMap(c=>ot(n.unit,y[c]??[],d)));g.length>0&&(z.style.display="none",m.onSelectPoints(g,{x:b.clientX,y:b.clientY},$))};R.addEventListener("mouseup",v)}),$.addEventListener("click",o=>{if(t){t=!1;return}if(St(o)===null||ke<0)return;const h=n.cellUnits.flatMap((w,v)=>I.size>0&&!I.has(v)?[]:ot(n.unit,w[ke]??[],v));h.length>0&&(z.style.display="none",m.onSelectPoints(h,{x:o.clientX,y:o.clientY},$))})}}K()}V(()=>{const e=i;if(!e||!e.marks)return;const l=gt();return{caption:[qt(e),...e.fitNotes??[],...e.notes,...Qn(Yt(e))],legend:e.groups.length>1&&!e.colorRepeatsX?e.groups.map((s,r)=>({label:s||"(none)",color:oe(r)})):void 0,colorbar:e.colorScale?{label:e.colorScale.label,lo:J(e.colorScale.lo,e.colorScale.unit),hi:J(e.colorScale.hi,e.colorScale.unit),color:l}:void 0}});const Ln=zn(B,()=>K());return{card:B,actions:q,setPlot(e){i=e,Me(eo(e.spec)),Pn()},setMenuRows:Se,setActiveGroups(e){I.clear();for(const l of e)I.add(l);tt.forEach((l,s)=>l.setState({selected:I.has(s),dimmed:I.size>0&&!I.has(s)})),K()},destroy(){ct?.(),Ln.disconnect(),Ke?.destroy();for(const e of ce)e.destroy()}}}
|
|
1
|
+
import{escHtml as X,maxOf as Te,minOf as jt}from"../../core/utils.js";import{fiveNumberSummary as Ut,normalQuantile as Yt,sampleVariance as Rn}from"../../stats/math.js";import{CONTROL_RULE_TEXT as On}from"../../stats/control.js";import{PAT_VERDICT_LABEL as qt}from"../../stats/pat.js";import{fmt as J}from"../../renderer/fmt.js";import{fitTicks as pt}from"../../renderer/axisTicks.js";import{binOfLabel as In,plotFootnote as Ht,plotGuideSections as Kt,plotTestNumber as Ve,plotTitle as Nn,probabilityPosition as ct}from"../../stats/plotData.js";import{SPACE as me,RADIUS as Fn,fontPx as Q,FONT as gt,CLR as nt,markNoPrint as Vt}from"../toolbar.js";import{exportCsv as zn}from"../tableExport.js";import{tableToTsv as _n}from"../../core/tableCsv.js";import{plotTable as Dn}from"../../stats/plotTable.js";import{cardShell as Gn,appendGuideCites as Xn,observeResize as jn,makeTooltip as Un,attachChartTip as Yn,chartFillHeight as qn,applyCanvasFlow as Ge,prepareCanvas as Xe,positionChartTooltip as yt,resolveChartCanvasColors as je,makeAxisFormat as Hn,horizontalTickSpacing as Zt,VERTICAL_TICK_SPACING_PX as Kn,makeSeriesLegendItem as Vn,renderEmptyState as Jt,isExpandedCard as Qt,makeLabeledSelect as Zn,fillTextOnHalo as Ct,limitLines as Jn,limitExtent as Qn,stackLabelRows as en,placeClearOf as tn,strokeLimitLine as nn,drawOffAxisLimits as eo,limitLabelPlacement as to,shouldIncludeLimitsByDefault as no,WAFER_MENU_HINT as Et}from"./chartShell.js";import{guideCitesText as oo}from"../../stats/guideSections.js";import{categorical as lo}from"./palette.js";import{NO_DATA_FILL as on}from"../../renderer/colorMap.js";import{darkTextOnColor as so,plotGradient as bt}from"./divergingScale.js";import{wirePointInteractions as Bt}from"./pointInteractions.js";import{plotAbout as io}from"./cardAbout.js";const Wt=64,xt=16,Rt=12,Ue=52,ao=16,ro=92,co=16,vt=5e3,ln=1500,ft=100,fo=[1e-4,.001,.01,.05,.1,.25,.5,.75,.9,.95,.99,.999,.9999],sn=m=>`${+(m*100).toPrecision(4)}%`;export function categoryLayout(m){const W=.8/Math.max(1,...m.map(R=>R.length)),U=R=>(1-m[R].length*W)/2;return{width:W,left:(R,Y)=>{const V=m[R].indexOf(Y);return V<0?void 0:U(R)+V*W},groupAt:(R,Y)=>{const V=Math.floor((Y-U(R))/W);return V>=0&&V<m[R].length?m[R][V]:void 0}}}function uo(m){if(m<=ln)return Array.from({length:m},(R,Y)=>Y);const z=[];for(let R=0;R<ft;R++)z.push(R);const W=ln-2*ft,U=m-2*ft;for(let R=0;R<W;R++)z.push(ft+Math.floor(R*U/W));for(let R=m-ft;R<m;R++)z.push(R);return z}function Ot(m,z,W){return W?Math.round(m).toLocaleString("en-GB"):z?J(m,z):`${m<=-.005?"\u2212":""}${Math.abs(m).toFixed(2)}`}const ho=260;function mo(m){const z=[...m.querySelectorAll("[data-wmap-plot-panel]")],W=z[0]?.querySelector("canvas");if(!W)return null;const U=W.width/Math.max(1,W.getBoundingClientRect().width)||1,R=m.getBoundingClientRect(),Y=m.ownerDocument.createElement("canvas");Y.width=Math.ceil(R.width*U),Y.height=Math.ceil(R.height*U);const V=Y.getContext("2d");if(!V)return null;const we=getComputedStyle(m);V.fillStyle=we.backgroundColor&&we.backgroundColor!=="rgba(0, 0, 0, 0)"?we.backgroundColor:"#fff",V.fillRect(0,0,Y.width,Y.height);for(const Me of z){const Se=Me.querySelector("canvas"),ce=Me.dataset.wmapChartTitle??"",_=(Se??Me).getBoundingClientRect(),s=Me.getBoundingClientRect();V.fillStyle=getComputedStyle(Me).color||"#333",V.font=`600 ${Math.round(13*U)}px system-ui, sans-serif`,V.textBaseline="top",V.fillText(ce,(s.left-R.left+8)*U,(s.top-R.top+6)*U),Se&&V.drawImage(Se,(_.left-R.left)*U,(_.top-R.top)*U,_.width*U,_.height*U)}return Y}const Re=(m,z)=>z.extent?[...m,...z.extent]:m;function ue(m,z,W={}){const U=z.scale==="log";let R=m.length?jt(m):0,Y=m.length?Te(m):1;U&&(R=Math.log10(Math.max(R,Number.MIN_VALUE)),Y=Math.log10(Math.max(Y,Number.MIN_VALUE)));const V=(Y-R)*.05||(U?.5:1);R=W.floorAtZero&&!U&&R>=0?0:R-V,Y+=V;const Me=Pe=>Pe===void 0||!Number.isFinite(Pe)?void 0:U?Pe>0?Math.log10(Pe):void 0:Pe,Se=Me(z.min),ce=Me(z.max);Se!==void 0&&(R=Se),ce!==void 0&&(Y=ce),Y>R||(Y=R+1);const _=Y-R,s=!!z.reverse,Oe=Pe=>{const $=((U?Math.log10(Math.max(Pe,Number.MIN_VALUE)):Pe)-R)/_;return s?1-$:$};return{lo:U?10**R:R,hi:U?10**Y:Y,log:U,reverse:s,frac:Oe}}function It(m,z,W,U){if(z/m<10)return pt(m,z,W,U);const R=Math.floor(Math.log10(m)),Y=Math.ceil(Math.log10(z)),V=Se=>{const ce=[];for(let _=R;_<=Y;_++)for(const s of Se){const Oe=s*10**_;Oe>=m&&Oe<=z&&ce.push(Oe)}return ce},we=V([1]);return{ticks:we.length>=4?we:V([1,2,5]),step:0}}export function renderPlotChart(m){const z=m.ownerDocument??document,{card:W,heading:U,body:R,controlsRow:Y,setPngDecor:V,setPngCanvas:we,setAbout:Me,setMenuRows:Se}=Gn(m.panel?.title??"Plot",m.onSaveImage,z,{png:!m.panel});m.panel&&(W.dataset.wmapPlotPanel="1");let ce=[];W.dataset.wmapPlotCard="1";const _=Un(W);let s,Oe=()=>[];const Pe=()=>{const e=s&&(s.marks||s.facets?.length)?Dn(s,m.waferLabel):void 0;return e?[{label:"Save data as CSV",onClick:()=>{zn(e.columns,e.rows,`${e.name}.csv`,m.onSaveText)}},{label:"Copy data",onClick:()=>{z.defaultView?.navigator.clipboard?.writeText(_n(e.columns,e.rows))}}]:[]};Se(()=>[...Pe(),...Oe()]);let $,pe,te,Ze,Ie,ut,ht=!1;W.addEventListener("pointerenter",()=>{ht=!0,W.dataset.wmapPlotPanelsOwner&&(W.dataset.wmapPanelsHover="1")}),W.addEventListener("pointerleave",()=>{ht=!1,delete W.dataset.wmapPanelsHover});let ot=[];const O=new Set,he=new Set;let ge=null,ye=-1,le=[],Z,Ee,ne,se=null,lt=0,$e,dt;const an=()=>!!s?.facets;let de=[],be=-1,kt=new Map,Ye=[],qe=Ue,w=Wt,M=Rt;const rn={[qt.outlier]:"#e69f00",[qt.fails]:"#c0392b"},ee=e=>{const l=s?.groups[e]??"";if(s?.colorBins&&m.binColors){const a=In(l);return a===void 0?on:(s.colorBins==="hard"?m.binColors.hard:m.binColors.soft).get(a)??on}return rn[l]??lo(e)},He=e=>s?.groups[e]||"";function Ne(){const e=R.clientWidth,l=(m.panel?Math.max(170,Math.min(280,e*.72)):Math.max(220,Math.min(420,e*.62)))+(qe-Ue),a=qn(W,R,$,l);return{w:e,h:a,plotW:Math.max(10,e-w-xt),plotH:Math.max(10,a-M-qe)}}const Be=e=>{const l=(e?.references??[]).flatMap(a=>a.to===void 0?[{value:a.at,kind:"ref",end:"lo",label:a.label??""}]:[{value:a.at,kind:"ref",end:"lo",label:a.label??"",bandTo:a.to},{value:a.to,kind:"ref",end:"hi",label:a.label??""}]);return[...Jn(e?.limits,s?.spec.limits??"both"),...l].filter(a=>e?.scale!=="log"||a.value>0)},Fe=(e,l,a)=>{const h=a?.clip,r=h?[...e.filter(c=>c>=h.lo&&c<=h.hi),h.lo,h.hi]:e,d=r.filter(Number.isFinite);if(!l.length||d.length===0)return r;const{lo:n,hi:t}=Qn(l);return(a?s?.spec.axes?.[a===s?.x?"x":"y"]?.includeLimits:void 0)??no(jt(d),Te(d),n,t)?[...r,...l.map(c=>c.value)]:r};let Mt;function Je(e,l,a,h=!1){return!h&&!s?.x?.clip&&!s?.y?.clip?()=>{}:(e.save(),e.beginPath(),e.rect(w,M,l,a),e.clip(),Mt=e,Nt)}function Nt(){Mt?.restore(),Mt=void 0}function ze(e,l,a,h,r,d,n,t,o){const c=[];if(d.length===0)return()=>{};const y=d.filter(p=>p.value>=r.lo&&p.value<=r.hi),x=d.filter(p=>!y.includes(p)).map(p=>({value:p.value,label:p.label,side:p.value<r.lo?"lo":"hi"}));e.save(),e.font=`${Q(-1)}px system-ui, sans-serif`;const g=p=>`${p.label} ${J(p.value,n.unit)}`.trim(),f=Q(-1)+2;for(const p of d){if(p.bandTo===void 0)continue;const L=r.frac(Math.min(p.value,p.bandTo)),P=r.frac(Math.max(p.value,p.bandTo)),b=Math.max(0,Math.min(L,P)),C=Math.min(1,Math.max(L,P));C<=b||(e.save(),e.globalAlpha=.1,e.fillStyle=l,t==="y"?e.fillRect(w,M+(1-C)*h,a,(C-b)*h):e.fillRect(w+b*a,M,(C-b)*a,h),e.restore())}if(t==="y"){const p=y.map(b=>{const C=M+(1-r.frac(b.value))*h;return{l:b,y:C,start:C-6-f/2,end:C-6+f/2}}),L=en(p,1),P=p.length?Te(p.map(b=>e.measureText(g(b.l)).width))+8:0;p.forEach(({l:b,y:C},u)=>{e.globalAlpha=.7,nn(e,b,l,w,C,w+a,C),e.globalAlpha=1,e.fillStyle=l,e.textAlign="left",e.textBaseline="alphabetic";const i=w+3+L[u]*P,v=tn(Ye,{x0:i,x1:i+e.measureText(g(b)).width,y0:C-4-f+2,y1:C-4+2},f);if(!o){e.fillText(g(b),i,v.y1-2);return}c.push(()=>{e.save(),e.font=`${Q(-1)}px system-ui, sans-serif`,e.fillStyle=l,e.textAlign="left",e.textBaseline="alphabetic",Ct(e,g(b),i,v.y1-2,o.halo),e.restore()})})}else{const p=y.map(P=>{const b=w+r.frac(P.value)*a,C=g(P),u=P.label.split(/\s+/)[0],i=J(P.value,n.unit),v=u&&u!==P.label?[C,`${u} ${i}`,u]:[C],B=y.filter(E=>E!==P).map(E=>w+r.frac(E.value)*a),{text:F,side:T}=to(b,v,E=>e.measureText(E).width,w,w+a,P.end==="lo",B),A=e.measureText(F).width;return{l:P,x:b,side:T,shown:F,start:T<0?b-3-A:b+3,end:T<0?b-3:b+3+A}}),L=en(p,4);p.forEach(({l:P,x:b,side:C,shown:u,start:i,end:v},B)=>{e.globalAlpha=.7,nn(e,P,l,b,M,b,M+h),e.globalAlpha=1;const F=C<0?"right":"left";e.fillStyle=l,e.textAlign=F,e.textBaseline="top";const T=M+2+L[B]*f,A=tn(Ye,{x0:i,x1:v,y0:T,y1:T+f},f);if(!o){e.fillText(u,b+C*3,A.y0);return}c.push(()=>{e.save(),e.font=`${Q(-1)}px system-ui, sans-serif`,e.fillStyle=l,e.textAlign=F,e.textBaseline="top",Ct(e,u,b+C*3,A.y0,o.halo),e.restore()})})}return e.restore(),eo(e,x,{left:w,right:w+a,top:M,bottom:M+h},t==="y"?"vertical":"horizontal",l,p=>J(p,n.unit),void 0,Ye),()=>c.forEach(p=>p())}function Tt(e,l,a,h){return Hn(Math.max(Math.abs(l),Math.abs(a)),e.unit,h,e.label)}function mt(e,l){return l?`${e.label} (${l})`:e.label}const wt=18,St=(e,l,a)=>{if(e.measureText(l).width<=a)return l;for(let h=l.length-1;h>0;h--){const r=`${l.slice(0,h)}\u2026`;if(e.measureText(r).width<=a)return r}return""};function Ke(e,l,a,h,r,d,n,t,o,c,y){Ye=[],e.font=`${Q(-1)}px system-ui, sans-serif`;const x=()=>Kn,g=y?{ticks:y.map(b=>b.at),step:0}:t.log?It(t.lo,t.hi,d,x):pt(t.lo,t.hi,d,x),f=new Map(y?.map(b=>[b.at,b.label])),p=Tt(c,t.lo,t.hi,g.step||void 0),L=y?{tick:b=>f.get(b)??"",unitLabel:""}:p;e.strokeStyle=l.grid,e.lineWidth=.5,e.fillStyle=l.textMuted;let P="";if("labels"in n){const b=n.labels.length;if(n.labels.forEach((C,u)=>{const i=w+(u+.5)/b*r,v=C.length>22?`${C.slice(0,21)}\u2026`:C;n.rotate?(e.save(),e.translate(i,M+d+6),e.rotate(-Math.PI/4),e.textAlign="right",e.textBaseline="middle",e.fillText(v,0,0),e.restore()):(e.textAlign="center",e.textBaseline="top",e.fillText(v,i,M+d+4))}),n.nest){const C=n.nest[0]?.length??0,u=r/b;for(let i=C-2;i>=0;i--){const v=h-6-wt-i*wt,B=T=>n.nest[T].slice(0,i+1).join("");let F=0;for(let T=1;T<=b;T++){if(T<b&&B(T)===B(F))continue;const E=w+F*u,j=w+T*u;e.fillStyle=l.text,e.textAlign="center",e.textBaseline="bottom",e.fillText(St(e,n.nest[F][i],j-E-4),(E+j)/2,v),T<b&&(e.save(),e.strokeStyle=l.border,e.globalAlpha=i===0?.9:.45,e.lineWidth=1,e.beginPath(),e.moveTo(j,M),e.lineTo(j,v-2),e.stroke(),e.restore()),F=T}}e.fillStyle=l.textMuted}}else{const b=Zt(e,Math.max(Math.abs(n.lo),Math.abs(n.hi)),o.unit),C=n.log?It(n.lo,n.hi,r,b):pt(n.lo,n.hi,r,b),u=Tt(o,n.lo,n.hi,C.step||void 0);P=u.unitLabel;for(const i of C.ticks){const v=w+n.frac(i)*r;e.beginPath(),e.moveTo(v,M),e.lineTo(v,M+d),e.stroke(),e.textAlign="center",e.textBaseline="top",e.fillText(u.tick(i),v,M+d+4)}}for(const b of g.ticks){const C=M+(1-t.frac(b))*d;e.beginPath(),e.moveTo(w,C),e.lineTo(w+r,C),e.stroke(),e.textAlign="right",e.textBaseline="middle",e.fillText(L.tick(b),w-4,C)}e.font=`${Q(0)}px system-ui, sans-serif`,e.fillStyle=l.text,e.textAlign="center",e.textBaseline="bottom",e.fillText(mt(o,P),w+r/2,h-6),e.save(),e.translate(14,M+d/2),e.rotate(-Math.PI/2),e.textBaseline="top",e.fillText(mt(c,L.unitLabel),0,0),e.restore(),e.strokeStyle=l.border,e.lineWidth=1,e.beginPath(),e.moveTo(w,M),e.lineTo(w,M+d),e.moveTo(w,M+d),e.lineTo(w+r,M+d),e.stroke()}function cn(e,l,a,h,r,d,n,t,o,c,y,x={along:d,offset:0}){Ye=[],e.font=`${Q(-1)}px system-ui, sans-serif`;const g=Zt(e,Math.max(Math.abs(o.lo),Math.abs(o.hi)),y.unit),f=o.log?It(o.lo,o.hi,r,g):pt(o.lo,o.hi,r,g),p=Tt(y,o.lo,o.hi,f.step||void 0);e.strokeStyle=l.grid,e.lineWidth=.5,e.fillStyle=l.textMuted;for(const i of f.ticks){const v=w+o.frac(i)*r;e.beginPath(),e.moveTo(v,M),e.lineTo(v,M+d),e.stroke(),e.textAlign="center",e.textBaseline="top",e.fillText(p.tick(i),v,M+d+4)}const L=n.labels.length,P=x.along/Math.max(1,L),b=M-x.offset;e.save(),e.beginPath(),e.rect(0,M-1,w+r+1,d+2),e.clip(),e.textAlign="right",e.textBaseline="middle";const C=Math.max(0,Math.floor(x.offset/P)),u=Math.min(L,Math.ceil((x.offset+d)/P));for(let i=C;i<u;i++)e.fillText(St(e,n.labels[i],t.inner),w-6,b+(i+.5)*P);if(n.nest){const i=n.nest[0]?.length??0;let v=w-6-t.inner-10;for(let B=i-2;B>=0;B--){const F=t.outer[B]??0,T=E=>n.nest[E].slice(0,B+1).join("");let A=0;for(let E=1;E<=L;E++){if(E<L&&T(E)===T(A))continue;const j=b+A*P,k=b+E*P;e.fillStyle=l.text,e.textAlign="right",e.textBaseline="middle",e.fillText(St(e,n.nest[A][B],F),v,(j+k)/2),E<L&&(e.save(),e.strokeStyle=l.border,e.globalAlpha=B===0?.9:.45,e.lineWidth=1,e.beginPath(),e.moveTo(v-F,k),e.lineTo(w+r,k),e.stroke(),e.restore()),A=E}v-=F+10}e.fillStyle=l.textMuted}e.restore(),e.font=`${Q(0)}px system-ui, sans-serif`,e.fillStyle=l.text,e.textAlign="center",e.textBaseline="bottom",e.fillText(mt(y,p.unitLabel),w+r/2,h-6),e.save(),e.translate(14,M+d/2),e.rotate(-Math.PI/2),e.textBaseline="top",e.fillText(mt(c,""),0,0),e.restore(),e.strokeStyle=l.border,e.lineWidth=1,e.beginPath(),e.moveTo(w,M),e.lineTo(w,M+d),e.moveTo(w,M+d),e.lineTo(w+r,M+d),e.stroke()}function fn(){if(!s||!$||s.marks?.type!=="scatter"||!s.x||!s.y)return;Ge($,te??0);const e=je(W),{w:l,h:a,plotW:h,plotH:r}=Ne(),d=Xe($,W,l,a);if(!d)return;const{ctx:n}=d,t=s.marks.points,o=O.size===0?t:t.filter(T=>O.has(T.group)),c=s.colorScale,y=bt(s.spec.colorGradient,s.spec.colorReverse,c?.diverging,c?.rating),x=Be(s.x),g=Be(s.y),f=ue(Fe(Re(t.map(T=>T.x),s.x),x,s.x),s.x),p=ue(Fe(Re(t.map(T=>T.y),s.y),g,s.y),s.y);Z={x:f,y:p,plotW:h,plotH:r},Ke(n,e,l,a,h,r,f,p,s.x,s.y),ze(n,e.limitLine,h,r,f,x,s.x,"x"),ze(n,e.limitLine,h,r,p,g,s.y,"y"),Je(n,h,r);const L=o.length>vt?Math.ceil(o.length/vt):1,P=[];for(let T=0;T<o.length;T+=L)P.push(o[T]);n.globalAlpha=Math.max(.15,Math.min(.7,200/P.length));let b;if(c)b=[P];else{const T=new Map;for(const A of P){const E=T.get(A.group);E?E.push(A):T.set(A.group,[A])}b=[...T.values()].sort((A,E)=>E.length-A.length)}le=[];const C=w,u=w+h,i=M,v=M+r;for(const T of b)for(const A of T){const E=w+f.frac(A.x)*h,j=M+(1-p.frac(A.y))*r;E<C||E>u||j<i||j>v||(le.push({p:A,cx:E,cy:j}),n.beginPath(),n.arc(E,j,2.5,0,Math.PI*2),n.fillStyle=c&&A.value!==void 0?y((A.value-c.lo)/(c.hi-c.lo||1)):ee(A.group),n.fill())}n.globalAlpha=1;const B=s.marks;if(B.type==="scatter"&&(B.identity||B.fits)){const T=(E,j)=>[w+f.frac(E)*h,M+(1-p.frac(j))*r],A=(E,j,k)=>{n.save(),n.beginPath(),n.rect(w,M,h,r),n.clip(),n.strokeStyle=j,n.lineWidth=2,n.setLineDash(k),n.beginPath();for(let ie=0;ie<=60;ie++){const We=ie/60,De=f.log?10**(Math.log10(f.lo)+(Math.log10(f.hi)-Math.log10(f.lo))*We):f.lo+(f.hi-f.lo)*We,[Le,fe]=T(De,E(De));ie===0?n.moveTo(Le,fe):n.lineTo(Le,fe)}n.stroke(),n.restore()};B.identity&&A(E=>E,e.textMuted,[6,4]);for(const E of B.fits??[])O.size>0&&!O.has(E.group)&&!c||A(j=>E.intercept+E.slope*j,c?e.text:ee(E.group),[])}const F=ge?le.find(T=>T.p===ge):void 0;if(F&&(n.beginPath(),n.arc(F.cx,F.cy,5,0,Math.PI*2),n.lineWidth=2,n.strokeStyle=e.text,n.stroke()),he.size>0){n.lineWidth=1.5,n.strokeStyle=e.text;let T=0;for(const A of he)if(!(O.size>0&&!O.has(A.group))){if(++T>vt)break;n.beginPath(),n.arc(w+f.frac(A.x)*h,M+(1-p.frac(A.y))*r,4,0,Math.PI*2),n.stroke()}}}function un(){if(Ee=void 0,!s||s.marks?.type!=="histogram"||!s.x)return;const e=s.marks.values,l=e.flat();if(l.length===0)return;const a=ue(Fe(Re(l,s.x),Be(s.x),s.x),s.x),h=Math.max(1,s.spec.bins??co),r=a.log?Math.log10(a.lo):a.lo,d=a.log?Math.log10(a.hi):a.hi,n=Array.from({length:h+1},(g,f)=>{const p=r+(d-r)*f/h;return a.log?10**p:p}),t=e.map(()=>new Array(h).fill(0));e.forEach((g,f)=>{for(const p of g){const L=a.log?p>0?Math.log10(p):NaN:p;if(!Number.isFinite(L)||L<r||L>d)continue;const P=Math.min(h-1,Math.floor((L-r)/(d-r)*h));t[f][P]++}});const o=s.spec.histNorm==="percent",c=o?t.map(g=>{const f=g.reduce((p,L)=>p+L,0);return g.map(p=>f?p/f*100:0)}):t;let y=0;const x=e.map(()=>{});if(s.spec.normalCurve&&!a.log){const g=(n[n.length-1]-n[0])/h;e.forEach((f,p)=>{const L=f.filter(Number.isFinite);if(L.length<2)return;const P=L.reduce((C,u)=>C+u,0)/L.length,b=Math.sqrt(Rn(L,P));b>0&&(x[p]={mean:P,sd:b},y=Math.max(y,(o?100:t[p].reduce((C,u)=>C+u,0))*g/(b*Math.sqrt(2*Math.PI))))})}Ee={edges:n,counts:t,heights:c,normal:x,maxCount:Math.max(o?.001:1,y,...c.map(g=>Te(g)))}}function hn(){if(!s||!$||!Ee||!s.x||!s.y)return;Ge($,te??0);const e=je(W),{w:l,h:a,plotW:h,plotH:r}=Ne(),d=Xe($,W,l,a);if(!d)return;const{ctx:n}=d,{edges:t,counts:o,heights:c,normal:y,maxCount:x}=Ee,g=ue([t[0],t[t.length-1]],{...s.x,min:t[0],max:t[t.length-1]}),f=ue([0,x],{label:s.y.label,scale:"linear",min:0,max:x*1.05});Z={x:g,y:f,plotW:h,plotH:r},Ke(n,e,l,a,h,r,g,f,s.x,s.y),ze(n,e.limitLine,h,r,g,Be(s.x),s.x,"x"),Je(n,h,r);const p=o.map((u,i)=>i).filter(u=>O.size===0||O.has(u)),L=p.length>1,P=p.length>=3,b=u=>w+Math.min(g.frac(t[u]),g.frac(t[u+1]))*h,C=u=>w+Math.max(g.frac(t[u]),g.frac(t[u+1]))*h;for(const u of p){if(P){n.fillStyle=ee(u),n.strokeStyle=ee(u),n.lineWidth=1.75,n.lineJoin="round",n.globalAlpha=.1,c[u].forEach((v,B)=>{if(v===0)return;const F=M+(1-f.frac(v))*r;n.fillRect(b(B),F,Math.max(1,C(B)-b(B)),M+r-F)}),n.globalAlpha=1,n.beginPath();let i=!1;c[u].forEach((v,B)=>{const F=M+(1-f.frac(v))*r;i||(n.moveTo(b(B),M+r),i=!0),n.lineTo(b(B),F),n.lineTo(C(B),F),B===c[u].length-1&&n.lineTo(C(B),M+r)}),n.stroke();continue}n.globalAlpha=L?.55:.85,n.fillStyle=ee(u),c[u].forEach((i,v)=>{if(i===0)return;const B=M+(1-f.frac(i))*r;n.fillRect(b(v),B,Math.max(1,C(v)-b(v)-1),M+r-B)})}if(n.globalAlpha=1,s.spec.normalCurve&&!g.log){const u=(t[t.length-1]-t[0])/(t.length-1);for(const i of p){const v=y[i];if(!v)continue;const{mean:B,sd:F}=v,T=(s.spec.histNorm==="percent"?100:o[i].reduce((A,E)=>A+E,0))*u;n.save(),n.beginPath(),n.rect(w,M,h,r),n.clip(),n.strokeStyle=ee(i),n.lineWidth=2,n.beginPath();for(let A=0;A<=120;A++){const E=t[0]+(t[t.length-1]-t[0])*A/120,j=Math.exp(-.5*((E-B)/F)**2)/(F*Math.sqrt(2*Math.PI)),k=w+g.frac(E)*h,ie=M+(1-f.frac(T*j))*r;A===0?n.moveTo(k,ie):n.lineTo(k,ie)}n.stroke(),n.restore()}}if(ye>=0){const u=w+Math.min(g.frac(t[ye]),g.frac(t[ye+1]))*h,i=w+Math.max(g.frac(t[ye]),g.frac(t[ye+1]))*h;n.lineWidth=1.5,n.strokeStyle=e.text,n.strokeRect(u,M,Math.max(1,i-u),r)}}function dn(){const e=s?.marks;if(!s||!$||!s.x||!s.y||!e||e.type!=="box"&&e.type!=="bar")return;Ge($,te??0);const l=je(W),a=s.spec.orientation==="horizontal",h=e.nest?e.nest.parts.map(S=>S[S.length-1]):e.categories,r=e.categories.length,d=s.groups.length,n=S=>O.size===0||O.has(S),t=e.type==="bar"&&!!e.stack,o=(S,N)=>e.type==="bar"?Number.isFinite(e.values[S][N]):e.cells[S][N].length>0,c=Array.from({length:r},(S,N)=>Array.from({length:d},(I,D)=>D).filter(I=>n(I)&&o(I,N))),y=categoryLayout(t?c.map(S=>S.length?[0]:[]):c),x=$.getContext("2d"),g=S=>x?x.measureText(S).width:S.length*6;x&&(x.font=`${Q(-1)}px system-ui, sans-serif`);const f=(S,N)=>S.length>N?`${S.slice(0,N-1)}\u2026`:S;let p=!1,L={inner:0,outer:[]},P=0;if(a){L={inner:Math.min(200,Te(h.map(N=>g(f(N,28))))),outer:e.nest?e.nest.levels.slice(0,-1).map((N,I)=>Math.min(140,Te(e.nest.parts.map(D=>g(f(D[I],20)))))):[]},w=Math.max(Wt,30+L.inner+6+L.outer.reduce((N,I)=>N+I+10,0)),e.cumulative&&(M=Rt+18),qe=Ue;const S=Math.max(1,...c.map(N=>t?Math.min(1,N.length):N.length));P=Math.max(22,S*ao/.8)}else{const S=Te(h.map(D=>g(f(D,22)))),N=Math.max(10,R.clientWidth-w-xt)/Math.max(1,r);p=S+8>N;const I=e.nest?e.nest.levels.length-1:0;qe=(p?Ue+Math.min(110,S*.72):Ue)+I*wt}const b=e.type==="bar"&&!t&&!!s.spec.valueLabels,C=s.y.unit,u=S=>J(S,C),i=b?Te(e.values.flat().filter(Number.isFinite).map(S=>g(u(S))).concat(0))+8:0,v=a?i:e.cumulative?40:0,{w:B,h:F,plotW:T,plotH:A}=Ne(),E=Math.max(10,T-v),j=Xe($,W,B,F);if(!j)return;const{ctx:k}=j,ie=S=>S.filter(Number.isFinite),We=Be(s.y),De=t?e.categories.map((S,N)=>e.values.reduce((I,D,q)=>I+(n(q)&&Number.isFinite(D[N])?D[N]:0),0)):[],Le=e.type==="bar"?[...t?De:ie(e.values.flat()),0]:ie(e.cells.flat(2));k.font=`${Q(-1)}px system-ui, sans-serif`;const fe=a?i:Q(-1)+6;if(b&&!a&&Le.length){const S=Te(Le);S>0&&Le.push(S*(1+fe/Math.max(1,A-fe)))}const Ae=ue(Fe(Re(Le,s.y),We,s.y),s.y,{floorAtZero:e.type==="bar"});Z={x:Ae,y:Ae,plotW:E,plotH:A};const it=a?A:E,Qe=a&&r*P>A+.5,at=Qe?r*P:it,rt=Qe?Math.max(0,Math.min(lt,at-it)):0;lt=rt,Pn(Qe,at,rt,E+v,A),a?cn(k,l,B,F,E,A,{labels:h,rotate:!1,nest:e.nest?.parts},L,Ae,s.x,s.y,{along:at,offset:rt}):Ke(k,l,B,F,E,A,{labels:h,rotate:p,nest:e.nest?.parts},Ae,s.x,s.y);const ve=at/r,Ce=y.width*ve;ne={slotW:ve,n:r,plotW:at,layout:y,across:a,offset:rt,view:it};const oe=S=>a?w+Ae.frac(S)*E:M+(1-Ae.frac(S))*A,ke=S=>a?M+S-rt:w+S,Lt=Ae.log?a?w:M+A:oe(0),et=(S,N,I,D)=>a?[Math.min(I,D),ke(S),Math.max(1,Math.abs(D-I)),N-S]:[ke(S),Math.min(I,D),N-S,Math.max(1,Math.abs(D-I))],At=(S,N,I,D)=>{k.beginPath(),a?(k.moveTo(N,ke(S)),k.lineTo(D,ke(I))):(k.moveTo(ke(S),N),k.lineTo(ke(I),D)),k.stroke()},tt=S=>a?S>=Lt:S<=Lt,En=S=>a?Q(-1)<=Ce+4:k.measureText(u(S)).width<=Ce+6,Dt=b&&e.values.every(S=>S.every(N=>!Number.isFinite(N)||En(N)));if(Dt){for(let S=0;S<d;S++)if(n(S))for(let N=0;N<r;N++){const I=y.left(N,S),D=e.values[S][N];if(I===void 0||!Number.isFinite(D))continue;const q=ke(N*ve+I*ve+Ce/2),H=k.measureText(u(D)).width,G=oe(D);a?Ye.push(tt(G)?{x0:G,x1:G+H+6,y0:q-fe/2,y1:q+fe/2}:{x0:G-H-6,x1:G,y0:q-8,y1:q+8}):Ye.push(tt(G)?{x0:q-H/2,x1:q+H/2,y0:G-fe,y1:G}:{x0:q-H/2,x1:q+H/2,y0:G,y1:G+fe})}}const Bn=ze(k,l.limitLine,E,A,Ae,We,s.y,a?"x":"y",{halo:l.bg}),Wn=Je(k,E,A,Qe);if(t){ne.stacks=[];for(let S=0;S<r;S++){const N=y.left(S,0),I=[];if(ne.stacks.push(I),N===void 0)continue;let D=0;for(let q=0;q<d;q++){const H=e.values[q][S];if(!n(q)||!Number.isFinite(H)||H<=0)continue;const G=oe(D),ae=oe(D+H);k.fillStyle=ee(q),k.globalAlpha=.9;const re=S*ve+N*ve;k.fillRect(...et(re+1,re+Ce-1,G,ae)),k.globalAlpha=1,I.push({g:q,p0:Math.min(G,ae),p1:Math.max(G,ae)}),D+=H}}}for(let S=0;S<d&&!t;S++){if(O.size>0&&!O.has(S))continue;const N=ee(S);for(let I=0;I<r;I++){const D=y.left(I,S);if(D===void 0)continue;const q=I*ve+D*ve;if(e.type==="bar"){const H=e.values[S][I];if(!Number.isFinite(H))continue;const G=oe(H);if(k.fillStyle=N,k.globalAlpha=.9,k.fillRect(...et(q+1,q+Ce-1,Lt,G)),k.globalAlpha=1,Dt){k.fillStyle=l.text,k.font=`${Q(-1)}px system-ui, sans-serif`;const ae=ke(q+Ce/2);a?(k.textBaseline="middle",k.textAlign=tt(G)?"left":"right",k.fillText(u(H),G+(tt(G)?3:-3),ae)):(k.textAlign="center",k.textBaseline=tt(G)?"bottom":"top",k.fillText(u(H),ae,G+(tt(G)?-2:2)))}}else{const H=e.cells[S][I];if(H.length===0)continue;const G=q+Ce/2,ae=Math.max(3,Math.min(Ce*.7,46)),re=Ut(Float64Array.from(H));if(k.strokeStyle=N,k.fillStyle=N,k.lineWidth=1.5,H.length===1){k.beginPath(),a?k.arc(oe(re.median),ke(G),3,0,Math.PI*2):k.arc(ke(G),oe(re.median),3,0,Math.PI*2),k.fill();continue}At(G,oe(re.min),G,oe(re.max));for(const Xt of[re.min,re.max])At(G-ae/4,oe(Xt),G+ae/4,oe(Xt));k.globalAlpha=.35,k.fillRect(...et(G-ae/2,G+ae/2,oe(re.q1),oe(re.q3))),k.globalAlpha=1,k.strokeRect(...et(G-ae/2,G+ae/2,oe(re.q1),oe(re.q3))),k.lineWidth=2.5,At(G-ae/2,oe(re.median),G+ae/2,oe(re.median))}}}Wn(),Bn();const Gt=se?y.left(se.c,t?0:se.g):void 0;if(se&&Gt!==void 0){Qe&&(k.save(),k.beginPath(),k.rect(w-1,M,E+2,A),k.clip()),k.lineWidth=1.5,k.strokeStyle=l.text;const S=se.c*ve+Gt*ve,N=t?ne.stacks?.[se.c]?.find(I=>I.g===se.g):void 0;t&&N?k.strokeRect(...et(S,S+Ce,N.p0,N.p1)):t||k.strokeRect(...et(S,S+Ce,a?w:M,a?w+E:M+A)),Qe&&k.restore()}if(e.cumulative){const S=I=>a?w+I/100*E:M+(1-I/100)*A,N=(I,D)=>a?[S(D),ke((I+.5)*ve)]:[ke((I+.5)*ve),S(D)];if(k.save(),k.strokeStyle=l.text,k.fillStyle=l.text,k.lineWidth=1.5,k.beginPath(),e.cumulative.forEach((I,D)=>{const[q,H]=N(D,I);D===0?k.moveTo(q,H):k.lineTo(q,H)}),k.stroke(),e.cumulative.forEach((I,D)=>{const[q,H]=N(D,I);k.beginPath(),k.arc(q,H,2.5,0,Math.PI*2),k.fill()}),k.strokeStyle=l.border,k.lineWidth=1,k.beginPath(),a?(k.moveTo(w,M),k.lineTo(w+E,M)):(k.moveTo(w+E,M),k.lineTo(w+E,M+A)),k.stroke(),k.fillStyle=l.textMuted,k.font=`${Q(-1)}px system-ui, sans-serif`,a){k.textAlign="center",k.textBaseline="bottom";for(const I of[0,25,50,75,100])k.fillText(`${I}%`,S(I),M-3)}else{k.textAlign="left",k.textBaseline="middle";for(const I of[0,25,50,75,100])k.fillText(`${I}%`,w+E+4,S(I))}k.restore()}}function mn(e){const l=s?.setTests,a=l?l.labels.indexOf(e):-1;return a>=0?{test:l.tests[a]}:{}}function Pt(e){if(!ne||!$)return null;const l=$.getBoundingClientRect(),a=ne.across?e.clientY-l.top-M:e.clientX-l.left-w;if(a<0||a>ne.view)return null;const h=a+ne.offset,r=Math.min(ne.n-1,Math.floor(h/ne.slotW)),d=ne.layout.groupAt(r,(h-r*ne.slotW)/ne.slotW);if(d===void 0)return null;if(!ne.stacks)return{g:d,c:r};const n=ne.across?e.clientX-l.left:e.clientY-l.top,t=ne.stacks[r]?.find(o=>n>=o.p0&&n<=o.p1);return t?{g:t.g,c:r}:null}function pn(e,l,a){let h=0,r=0,d=0;for(const o of l)o===100&&h++;if(e.failSide)for(const o of a){const c=e.failSide[o];c<0?r++:c>0&&d++}const n=o=>o.toLocaleString("en-GB"),t=r+d>0?` (${n(r)} below the low limit \xB7 ${n(d)} above the high limit)`:"";return`${n(h)} pass \xB7 ${n(l.length-h)} fail${t} \xB7 n = ${n(l.length)}`}function gn(e){const l=s,a=l.marks,h=l.level==="die"?"dies":"wafers",r=a.cells[e.g][e.c],d=a.nest?a.nest.parts[e.c]:[a.categories[e.c]],n=l.groups.length>1&&!d.includes(He(e.g))?` \xB7 ${X(He(e.g))}`:"",t=`<strong>${X(a.categories[e.c])}${n}</strong><br>`,o=l.y?.unit;if(r.length===0)return`${t}no ${h}`;const c=`${r.length.toLocaleString("en-GB")} ${h}`,y=(a.categoryItems&&m.onOpenWafer?`<br><em>click to ${X(m.openActionLabel??"open this wafer")}</em>`:"")+(a.categoryItems&&m.onWaferMenu?Et:"");if(a.type==="bar"){const g=a.values[e.g][e.c],f=a.cumulative?`<br>${X(`cumulative: ${a.cumulative[e.c].toFixed(1)}% of the whole`)}`:"";return`${t}${X(`${l.y.label}: ${J(g,o)}`)}<br>${X(a.passFail?pn(a.passFail,r,a.cellUnits[e.g][e.c]):c)}${f}${y}`}const x=Ut(Float64Array.from(r));return`${t}${["max","q3","median","q1","min"].map(g=>X(`${{max:"max",q3:"upper quartile",median:"median",q1:"lower quartile",min:"min"}[g]}: ${J(x[g],o)}`)).join("<br>")}<br>${X(c)}${y}`}function yn(){const e=s?.marks;if(!s||!$||!s.x||!s.y||!e||e.type!=="line")return;Ge($,te??0);const l=je(W),{w:a,h,plotW:r,plotH:d}=Ne(),n=Xe($,W,a,h);if(!n)return;const{ctx:t}=n,o=Be(s.x),c=Be(s.y),y=ue(Fe(Re(e.xs,s.x),o,s.x),s.x),x=e.band?[...e.band.lo.flat(),...e.band.hi.flat()]:[],g=ue(Fe(Re([...e.values.flat(),...x].filter(Number.isFinite),s.y),c,s.y),s.y);if(Z={x:y,y:g,plotW:r,plotH:d},Ke(t,l,a,h,r,d,y,g,s.x,s.y),ze(t,l.limitLine,r,d,y,o,s.x,"x"),ze(t,l.limitLine,r,d,g,c,s.y,"y"),Je(t,r,d),de=e.xs.map(f=>w+y.frac(f)*r),e.band){const f=p=>M+(1-g.frac(p))*d;e.band.lo.forEach((p,L)=>{if(O.size>0&&!O.has(L))return;const P=e.band.hi[L];t.save(),t.fillStyle=ee(L),t.globalAlpha=.16;let b=[];const C=()=>{if(b.length===1){const u=b[0],i=de[u];t.globalAlpha=.55,t.strokeStyle=ee(L),t.lineWidth=2,t.beginPath(),t.moveTo(i,f(p[u])),t.lineTo(i,f(P[u])),t.moveTo(i-4,f(p[u])),t.lineTo(i+4,f(p[u])),t.moveTo(i-4,f(P[u])),t.lineTo(i+4,f(P[u])),t.stroke(),t.globalAlpha=.16}else if(b.length){t.beginPath(),b.forEach((u,i)=>{i===0?t.moveTo(de[u],f(P[u])):t.lineTo(de[u],f(P[u]))});for(let u=b.length-1;u>=0;u--)t.lineTo(de[b[u]],f(p[b[u]]));t.closePath(),t.fill()}b=[]};p.forEach((u,i)=>{Number.isFinite(u)&&Number.isFinite(P[i])?b.push(i):C()}),C(),t.restore()})}e.values.forEach((f,p)=>{if(O.size>0&&!O.has(p))return;t.strokeStyle=ee(p),t.fillStyle=ee(p),t.lineWidth=2;let L=!1;t.beginPath(),f.forEach((P,b)=>{if(!Number.isFinite(P)){L=!1;return}const C=de[b],u=M+(1-g.frac(P))*d;L?t.lineTo(C,u):t.moveTo(C,u),L=!0}),t.stroke(),f.forEach((P,b)=>{Number.isFinite(P)&&(t.beginPath(),t.arc(de[b],M+(1-g.frac(P))*d,be===b?4.5:3,0,Math.PI*2),t.fill())})}),be>=0&&(t.lineWidth=1,t.strokeStyle=l.textMuted,t.beginPath(),t.moveTo(de[be],M),t.lineTo(de[be],M+d),t.stroke())}function $t(e){const l=s?.marks;if(!l||l.type!=="line"||!$||!s?.x||de.length===0)return null;const a=e.clientX-$.getBoundingClientRect().left;let h=-1,r=24;if(de.forEach((t,o)=>{const c=Math.abs(t-a);c<r&&(r=c,h=o)}),be=h,h<0)return null;const d=s.level==="die"?"dies":"wafers",n=l.values.map((t,o)=>({g:o,v:t[h],n:l.counts[o][h]})).filter(t=>Number.isFinite(t.v)&&(O.size===0||O.has(t.g)));return`<strong>${X(`${s.x.label}: ${J(l.xs[h],s.x.unit)}`)}</strong><br>`+n.map(t=>{const o=l.band?.lo[t.g][h],c=l.band?.hi[t.g][h],y=o!==void 0&&c!==void 0&&Number.isFinite(o)&&Number.isFinite(c)?`, band ${J(o,s.y.unit)} to ${J(c,s.y.unit)}`:"";return X(`${s.groups.length>1?`${He(t.g)}: `:""}${J(t.v,s.y.unit)}${y} (${t.n.toLocaleString("en-GB")} ${d})`)}).join("<br>")+(m.onWaferMenu&&Ft(h)!==void 0?Et:"")}function Ft(e){const l=s?.marks;if(l?.type!=="line")return;const a=new Set(l.cellUnits.flatMap((h,r)=>O.size>0&&!O.has(r)?[]:(h[e]??[]).map(d=>l.unit(d).item)));return a.size===1?[...a][0]:void 0}function bn(){const e=s?.marks;if(!s||!$||!s.x||!s.y||e?.type!=="probability")return;Ge($,te??0);const l=je(W),{w:a,h,plotW:r,plotH:d}=Ne(),n=Xe($,W,a,h);if(!n)return;const{ctx:t}=n,o=s.spec.probabilityAxis==="linear",c=e.values.map((T,A)=>A).filter(T=>e.values[T].length>0&&(O.size===0||O.has(T))),y=Math.max(1,...c.map(T=>e.values[T].length)),x=Math.min(.01,ct(0,y)),g=T=>o?T:Yt(T),f=o?0:g(x),p=o?1:g(1-x),L=o?0:(p-f)*.03,P=ue([f-L,p+L],{label:s.y.label,scale:"linear",min:f-L,max:p+L}),b=o?[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1]:fo.filter(T=>T>=x&&T<=1-x),C=[],u=T=>M+(1-P.frac(T))*d,i=b.indexOf(.5);C.push({at:g(.5),label:sn(.5)});for(const T of[b.slice(i+1),b.slice(0,i).reverse()]){let A=u(g(.5));for(const E of T){const j=u(g(E));Math.abs(j-A)<16||(C.push({at:g(E),label:sn(E)}),A=j)}}const v=Be(s.x),B=ue(Fe(Re(c.flatMap(T=>[e.values[T][0],e.values[T][e.values[T].length-1]]),s.x),v,s.x),s.x);Z={x:B,y:P,plotW:r,plotH:d},Ke(t,l,a,h,r,d,B,P,s.x,s.y,C),ze(t,l.limitLine,r,d,B,v,s.x,"x"),Je(t,r,d),le=[],t.save(),t.beginPath(),t.rect(w,M,r,d),t.clip();for(const T of c){const A=e.values[T],E=A.length,j=uo(E);if(t.strokeStyle=ee(T),t.fillStyle=ee(T),t.lineWidth=1.5,t.beginPath(),j.forEach((k,ie)=>{const We=w+B.frac(A[k])*r,De=u(g(ct(k,E)));ie===0?t.moveTo(We,De):t.lineTo(We,De);const Le=T*2**26+k;let fe=kt.get(Le);if(!fe){const{item:Ae,die:it}=e.unit(e.units[T][k]);fe={x:A[k],y:ct(k,E),group:T,item:Ae,die:it},kt.set(Le,fe)}le.push({p:fe,cx:We,cy:De})}),t.stroke(),E<=300)for(const k of j)t.beginPath(),t.arc(w+B.frac(A[k])*r,u(g(ct(k,E))),2.5,0,Math.PI*2),t.fill()}if(t.restore(),he.size>0){t.lineWidth=1.5,t.strokeStyle=l.text;let T=0;for(const A of he)if(!(O.size>0&&!O.has(A.group))){if(++T>vt)break;t.beginPath(),t.arc(w+B.frac(A.x)*r,u(g(A.y)),4,0,Math.PI*2),t.stroke()}}const F=ge?le.find(T=>T.p===ge):void 0;F&&(t.beginPath(),t.arc(F.cx,F.cy,5,0,Math.PI*2),t.lineWidth=2,t.strokeStyle=l.text,t.stroke())}function xn(e){const l=s,h=l.marks.values[e.group].length,r=Math.round(e.y*h+.5),d=m.waferLabel(e.item),n=e.die&&e.die.x!==void 0?`die (${e.die.x}, ${e.die.y})`:"",t=[d,n].filter(Boolean).join(" \xB7 ");return(t?`<strong>${X(t)}</strong><br>`:"")+X(`${l.x.label}: ${J(e.x,l.x.unit)}`)+"<br>"+X(`rank ${r.toLocaleString("en-GB")} of ${h.toLocaleString("en-GB")}, plotted at ${+(e.y*100).toPrecision(3)}%`)+(l.groups.length>1?`<br>${X(He(e.group))}`:"")+(m.onOpenWafer?`<br><em>click to ${X(m.openActionLabel??"open this wafer")}</em>`:"")+(m.onWaferMenu&&!e.die?Et:"")}let _e,xe=null;function vn(){const e=s?.marks;if(!s||!$||e?.type!=="heatmap")return;Ge($,te??0);const l=je(W),a=$.getContext("2d");let h=0,r=0;a&&(a.font=`${Q(-1)}px system-ui, sans-serif`,h=Te(e.rows.map(u=>a.measureText(u.length>24?`${u.slice(0,23)}\u2026`:u).width)),r=Te(e.cols.map(u=>a.measureText(u.length>22?`${u.slice(0,21)}\u2026`:u).width)));const d=Math.min(180,Math.max(w,h+24)),n=Math.max(8,R.clientWidth-d-xt)/Math.max(1,e.cols.length),t=r+8>n;qe=t?Ue+Math.min(110,r*.72):Ue;const{w:o,h:c}=Ne(),y=Math.max(10,o-d-xt),x=Math.max(10,c-M-qe),g=Xe($,W,o,c);if(!g)return;const{ctx:f}=g,p=y/e.cols.length,L=x/e.rows.length;_e={left:d,cw:p,ch:L,rows:e.rows.length,cols:e.cols.length};const P=s.colorScale,b=bt(s.spec.colorGradient,s.spec.colorReverse,P?.diverging,P?.rating),C=P&&P.hi-P.lo||1;f.font=`${Q(-1)}px system-ui, sans-serif`;for(let u=0;u<e.rows.length;u++)for(let i=0;i<e.cols.length;i++){const v=e.values[u][i],B=d+i*p,F=M+u*L,T=Number.isFinite(v)&&P?b((v-P.lo)/C):l.track;if(f.fillStyle=T,f.fillRect(B,F,p,L),Number.isFinite(v)&&p>=40&&L>=16){const A=so(T);f.fillStyle=A?"#1a1a1a":"#fff",f.textAlign="center",f.textBaseline="middle",Ct(f,Ot(v,s.y?.unit,P?.integer),B+p/2,F+L/2,A?"rgba(255,255,255,0.55)":"rgba(0,0,0,0.55)")}}f.lineWidth=1,f.setLineDash([]),f.strokeStyle=l.border,f.beginPath();for(let u=1;u<e.rows.length;u++){const i=Math.round(M+u*L)+.5;f.moveTo(d,i),f.lineTo(d+y,i)}for(let u=1;u<e.cols.length;u++){const i=Math.round(d+u*p)+.5;f.moveTo(i,M),f.lineTo(i,M+x)}f.stroke(),f.strokeStyle=l.textMuted,f.strokeRect(d+.5,M+.5,y-1,x-1),f.beginPath();for(let u=0;u<e.rows.length;u++){const i=Math.round(M+(u+.5)*L)+.5;f.moveTo(d-4,i),f.lineTo(d,i)}for(let u=0;u<e.cols.length;u++){const i=Math.round(d+(u+.5)*p)+.5;f.moveTo(i,M+x),f.lineTo(i,M+x+4)}f.stroke(),xe&&(f.lineWidth=2,f.strokeStyle=l.text,f.strokeRect(d+xe.c*p,M+xe.r*L,p,L)),f.fillStyle=l.textMuted,f.textAlign="right",f.textBaseline="middle",e.rows.forEach((u,i)=>f.fillText(u.length>24?`${u.slice(0,23)}\u2026`:u,d-8,M+(i+.5)*L)),e.cols.forEach((u,i)=>{const v=u.length>22?`${u.slice(0,21)}\u2026`:u,B=d+(i+.5)*p;t?(f.save(),f.translate(B,M+x+8),f.rotate(-Math.PI/4),f.textAlign="right",f.textBaseline="middle",f.fillText(v,0,0),f.restore()):(f.textAlign="center",f.textBaseline="top",f.fillText(v,B,M+x+7))}),f.font=`${Q(0)}px system-ui, sans-serif`,f.fillStyle=l.text,f.textAlign="center",f.textBaseline="bottom",f.fillText(s.x?.label??"",d+y/2,c-6)}function zt(e){if(!_e||!$)return null;const l=$.getBoundingClientRect(),a=Math.floor((e.clientX-l.left-_e.left)/_e.cw),h=Math.floor((e.clientY-l.top-M)/_e.ch);return h>=0&&h<_e.rows&&a>=0&&a<_e.cols?{r:h,c:a}:null}function kn(e){const l=s,a=l.marks,h=a.values[e.r][e.c],r=a.cellUnits[e.r][e.c].length,d=l.level==="die"?"dies":"wafers";return`<strong>${X(`${a.rows[e.r]} \xB7 ${a.cols[e.c]}`)}</strong><br>`+(Number.isFinite(h)?X(`${l.y?.label??"Count"}: ${Ot(h,l.y?.unit,l.colorScale?.integer)}`)+"<br>":"")+X(`${r.toLocaleString("en-GB")} ${d}`)+(r&&m.onSelectPoints?"<br><em>click or right-click to chart or tabulate them</em>":"")}function Mn(){const e=s?.marks;if(!s||!$||!s.x||!s.y||e?.type!=="control")return;Ge($,te??0);const l=je(W),{w:a,h,plotW:r,plotH:d}=Ne(),n=Xe($,W,a,h);if(!n)return;const{ctx:t}=n,o=e.limits,c=Be(s.y),y=ue(Re(e.xs,s.x),s.x),x=ue(Fe(Re([...e.values,o.ucl,o.lcl],s.y),c,s.y),s.y);Z={x:y,y:x,plotW:r,plotH:d},Ke(t,l,a,h,r,d,y,x,s.x,s.y),ze(t,l.limitLine,r,d,x,c,s.y,"y"),Je(t,r,d);const g=i=>w+y.frac(e.xs[i])*r,f=i=>M+(1-x.frac(i))*d;t.save(),t.beginPath(),t.rect(w,M,r,d),t.clip();const p=(i,v,B,F=1)=>{t.globalAlpha=B,t.setLineDash(v),t.lineWidth=F,t.strokeStyle=l.text,t.beginPath(),t.moveTo(w,f(i)),t.lineTo(w+r,f(i)),t.stroke()};for(const i of[-2,-1,1,2])p(o.centre+i*o.sigma,[2,4],.25);p(o.centre,[],.6,1.5),p(o.ucl,[6,4],.85),p(o.lcl,[6,4],.85),t.restore(),t.fillStyle=l.textMuted,t.font=`${Q(-1)}px system-ui, sans-serif`,t.textAlign="right",t.textBaseline="bottom";const L=i=>J(i,s.y.unit);if(t.fillText(`UCL ${L(o.ucl)}`,w+r-4,f(o.ucl)-2),t.textBaseline="top",t.fillText(`LCL ${L(o.lcl)}`,w+r-4,f(o.lcl)+2),t.textBaseline="bottom",t.fillText(`Centre ${L(o.centre)}`,w+r-4,f(o.centre)-2),o.baseline<e.values.length){const i=(g(o.baseline-1)+g(o.baseline))/2;t.save(),t.strokeStyle=l.textMuted,t.setLineDash([2,3]),t.beginPath(),t.moveTo(i,M),t.lineTo(i,M+d),t.stroke(),t.restore(),t.textAlign="left",t.textBaseline="top",t.fillText("limits from here \u2190",w+4,M+2)}t.strokeStyle=ee(0),t.lineWidth=1.5,t.setLineDash([]);const P=O.size>0,b=i=>e.group?.[i]??0;if(!P)t.beginPath(),e.values.forEach((i,v)=>{v===0?t.moveTo(g(v),f(i)):t.lineTo(g(v),f(i))}),t.stroke();else{for(const i of[!1,!0]){t.globalAlpha=i?1:.2,t.beginPath();for(let v=1;v<e.values.length;v++)(O.has(b(v-1))&&O.has(b(v)))===i&&(t.moveTo(g(v-1),f(e.values[v-1])),t.lineTo(g(v),f(e.values[v])));t.stroke()}t.globalAlpha=1}const C=new Map(e.violations.map(i=>[i.index,i.rules]));le=[],e.values.forEach((i,v)=>{const B=C.get(v),F=b(v),T=P&&O.has(F),A=P&&!T;t.globalAlpha=A?.2:1,t.beginPath(),t.arc(g(v),f(i),(B?4.5:3)+(T?1.5:0),0,Math.PI*2),t.fillStyle=B?l.alert:ee(F),t.fill(),T&&(t.lineWidth=1.5,t.strokeStyle=l.text,t.stroke()),B&&(t.fillStyle=l.alert,t.textAlign="center",t.textBaseline="bottom",t.fillText(B.join(","),g(v),f(i)-(T?8:6))),t.globalAlpha=1,le.push({p:{x:e.xs[v],y:i,group:F,item:e.items[v]},cx:g(v),cy:f(i)})});const u=ge?le.find(i=>i.p===ge):void 0;u&&(t.beginPath(),t.arc(u.cx,u.cy,6,0,Math.PI*2),t.lineWidth=2,t.strokeStyle=l.text,t.stroke())}function Tn(e){const l=s,a=l.marks,h=a.items.indexOf(e.item),r=(e.y-a.limits.centre)/a.limits.sigma,d=a.violations.find(n=>n.index===h)?.rules;return`<strong>${X(m.waferLabel(e.item))}</strong><br>`+X(`${l.y.label}: ${J(e.y,l.y.unit)} (${r>=0?"+":"\u2212"}${Math.abs(r).toFixed(1)}\u03C3)`)+(d?`<br>${X(`breaks rule ${d.map(n=>`${n} (${On[n]})`).join(", ")}`)}`:"")+(m.onOpenWafer?`<br><em>click to ${X(m.openActionLabel??"open this wafer")}</em>`:"")}function wn(){const e=s?.marks;if(!s||!$||!s.x||!s.y||e?.type!=="goal")return;Ge($,te??0);const l=je(W),{w:a,h,plotW:r,plotH:d}=Ne(),n=Xe($,W,a,h);if(!n)return;const{ctx:t}=n,o=Math.max(.5,...e.points.map(i=>Math.abs(i.x))),c=ue([-o,o],{...s.x,min:s.x.min??-o*1.05,max:s.x.max??o*1.05}),y=ue([0,...e.points.map(i=>i.y),1/6],{...s.y,min:s.y.min??0},{floorAtZero:!0});Z={x:c,y,plotW:r,plotH:d},Ke(t,l,a,h,r,d,c,y,s.x,s.y);const x=i=>w+c.frac(i)*r,g=i=>M+(1-y.frac(i))*d;t.save(),t.beginPath(),t.rect(w,M,r,d),t.clip(),t.font=`${Q(-1)}px system-ui, sans-serif`;const f=[[1,[6,4]],[1.33,[]]];for(const[i,v]of f){const B=1/(6*i);t.strokeStyle=l.textMuted,t.lineWidth=1,t.setLineDash(v),t.beginPath(),t.moveTo(x(-.5),g(0)),t.lineTo(x(0),g(B)),t.lineTo(x(.5),g(0)),t.stroke(),t.fillStyle=l.textMuted,t.textAlign="left",t.textBaseline="bottom",t.fillText(`Ppk ${i}`,x(0)+4,g(B)-2)}t.restore(),le=[];const p=e.points.filter(i=>O.size===0||O.has(i.group));for(const i of p)t.beginPath(),t.arc(x(i.x),g(i.y),4,0,Math.PI*2),t.fillStyle=ee(i.group),t.fill(),le.push({p:{x:i.x,y:i.y,group:i.group,item:-1,value:i.testNumber},cx:x(i.x),cy:g(i.y)});const L=p.map(i=>({x0:x(i.x)-5,x1:x(i.x)+5,y0:g(i.y)-5,y1:g(i.y)+5})),P={x0:w,x1:w+r,y0:M,y1:M+d},b=i=>i.x0>=P.x0&&i.x1<=P.x1&&i.y0>=P.y0&&i.y1<=P.y1&&!L.some(v=>i.x0<v.x1&&i.x1>v.x0&&i.y0<v.y1&&i.y1>v.y0),C=Q(-1)+2;t.fillStyle=l.text,t.textBaseline="middle";for(const i of[...p].filter(v=>v.ppk<1.33).sort((v,B)=>v.ppk-B.ppk)){const v=x(i.x),B=g(i.y),F=t.measureText(i.label).width,T=[[v+7,B,"left"],[v-7,B,"right"],[v,B-13,"center"],[v,B+13,"center"]];for(const[A,E,j]of T){const k=j==="left"?A:j==="right"?A-F:A-F/2,ie={x0:k,x1:k+F,y0:E-C/2,y1:E+C/2};if(b(ie)){L.push(ie),t.textAlign=j,t.fillText(i.label,A,E);break}}}const u=ge?le.find(i=>i.p===ge):void 0;u&&(t.beginPath(),t.arc(u.cx,u.cy,6,0,Math.PI*2),t.lineWidth=2,t.strokeStyle=l.text,t.stroke())}function Sn(e){const l=s,h=l.marks.points.find(r=>r.testNumber===e.value&&r.group===e.group);return h?`<strong>${X(h.label)}</strong>${l.groups.length>1?` \xB7 ${X(He(h.group))}`:""}<br>`+X(`Ppk ${h.ppk.toFixed(2)} \xB7 ${h.n.toLocaleString("en-GB")} dies`)+"<br>"+X(`mean ${h.x>=0?"+":"\u2212"}${Math.abs(h.x*100).toFixed(1)}% of the window from its centre, \u03C3 ${(h.y*100).toFixed(1)}% of it (${h.basis==="spec"?"spec":"test"} limits)`):""}function Pn(e,l,a,h,r){!$e||!$||($e.style.display=e?"block":"none",e&&(Object.assign($e.style,{top:`${$.offsetTop+M}px`,height:`${r}px`,left:`${$.offsetLeft+w+h+1}px`}),$e.firstElementChild.style.height=`${l}px`,Math.abs($e.scrollTop-a)>=1&&($e.scrollTop=a)))}function K(){$e&&($e.style.display="none"),dt&&!an()&&(dt.style.maxHeight=Qt(W)?"":`${ro}px`),pe&&m.panel&&(pe.style.display=Qt(W)?"flex":"none"),w=Wt,M=Rt;const e=s?.marks?.type;e==="scatter"?fn():e==="control"?Mn():e==="heatmap"?vn():e==="goal"?wn():e==="probability"?bn():e==="histogram"?hn():e==="box"||e==="bar"?dn():e==="line"&&yn(),Nt()}function $n(e){const l=s,a=m.waferLabel(e.item),h=e.die&&e.die.x!==void 0?`die (${e.die.x}, ${e.die.y})`:"",r=[a,h].filter(Boolean).join(" \xB7 "),d=(n,t)=>`${n.label}: ${J(t,n.unit)}`;return(r?`<strong>${X(r)}</strong><br>`:"")+X(d(l.x,e.x))+"<br>"+X(d(l.y,e.y))+(l.colorScale&&e.value!==void 0?`<br>${X(`${l.colorScale.label}: ${J(e.value,l.colorScale.unit)}`)}`:"")+(l.groups.length>1?`<br>${X(He(e.group))}`:"")+(m.onOpenWafer?`<br><em>click to ${X(m.openActionLabel??"open this wafer")}</em>`:"")}function _t(e){if(!Ee||!Z||!s?.x)return null;const l=$.getBoundingClientRect(),h=(e.clientX-l.left-w)/Z.plotW;if(h<0||h>1)return null;const r=Z.x.reverse?1-h:h,{edges:d,counts:n}=Ee,t=d.length-1,o=Math.min(t-1,Math.max(0,Math.floor(r*t)));ye=o;const c=s.x,y=n.map((x,g)=>({g,n:x[o]})).filter(x=>x.n>0&&(O.size===0||O.has(x.g)));return`<strong>${X(`${J(d[o],c.unit)} to ${J(d[o+1],c.unit)}`)}</strong><br>`+(y.length?y.map(x=>{const g=s.spec.histNorm==="percent"?` (${Ee.heights[x.g][o].toFixed(1)}% of ${s.groups.length>1?"its colour":"them"})`:"";return X(`${s.groups.length>1?`${He(x.g)}: `:""}${x.n.toLocaleString("en-GB")} ${s.level==="die"?"dies":"wafers"}${g}`)}).join("<br>"):"none")}function Ln(e){const l=z.createElement("div");l.dataset.wmapPlotColorbar="1",Object.assign(l.style,{display:"flex",alignItems:"center",gap:me.md,marginTop:me.md,marginBottom:me.xl,fontSize:gt.body,color:nt.label});const a=z.createElement("canvas");a.width=200,a.height=10,Object.assign(a.style,{width:"200px",height:"10px",borderRadius:Fn.control,flex:"0 0 auto"});const h=a.getContext("2d"),r=bt(s?.spec.colorGradient,s?.spec.colorReverse,e.diverging,e.rating);if(h)for(let c=0;c<200;c++)h.fillStyle=r(c/199),h.fillRect(c,0,1,10);const d=c=>s?.marks?.type==="heatmap"?Ot(c,e.unit,e.integer):J(c,e.unit),n=z.createElement("span");n.textContent=d(e.lo);const t=z.createElement("span");t.textContent=d(e.hi);const o=z.createElement("span");return o.textContent=e.label,o.style.color=nt.text,l.append(o,n,a,t),l}const st=(e,l,a)=>l.map(h=>{const{item:r,die:d}=e(h);return{x:0,y:0,group:a,item:r,die:d}});function An(){Ze?.destroy(),Ze=void 0,R.innerHTML="",$=void 0,pe=void 0,te=void 0,ot=[],ge=null,ye=-1,le=[],Z=void 0,ne=void 0,se=null,$e=void 0,lt=0,dt=void 0,_e=void 0,xe=null,de=[],be=-1,qe=Ue,kt=new Map,O.clear(),he.clear();for(const n of ce)n.destroy();ce=[],ut?.(),ut=void 0,R.style.overflowY="hidden",delete W.dataset.wmapPlotPanelsOwner,delete W.dataset.wmapPanelsHover,we(()=>W.querySelector("canvas"));const e=s,l=!!e?.facets&&!m.panel;if(W.style.flex=l?"0 0 auto":"1 1 0px",W.style.gridColumn=l?"1 / -1":"",!e)return;if(U.textContent=m.panel?m.panel.title:Nn(e),W.dataset.wmapChartTitle=U.textContent,e.issues.length||!e.marks){for(const n of e.issues)Jt(R,n);return}const a=z.createElement("div");Object.assign(a.style,{color:nt.label,fontSize:gt.body,marginBottom:me.xs});const h=m.openActionLabel??"open this wafer",r=e.marks.type==="scatter"?(m.onOpenWafer?` \xB7 click a point to ${h}`:"")+(m.onSelectPoints?` \xB7 drag to select ${e.level==="die"?"dies":"wafers"}`:""):e.marks.type==="box"||e.marks.type==="bar"?(m.onOpenWafer&&e.marks.categoryItems?` \xB7 click a ${e.marks.type} to ${h}`:m.onSelectPoints?` \xB7 click or right-click to ${m.selectActionLabel??"chart or tabulate what it counts"}`:"")+(e.marks.type==="box"?" \xB7 box: quartiles; whiskers: minimum and maximum":""):e.marks.type==="histogram"&&m.onSelectPoints?" \xB7 click or right-click a bar to chart or tabulate its dies":e.marks.type==="heatmap"&&m.onSelectPoints?` \xB7 click or right-click a cell to chart or tabulate its ${e.level==="die"?"dies":"wafers"}`:e.marks.type==="probability"?(m.onOpenWafer?` \xB7 click a point to ${h}`:"")+(m.onSelectPoints?` \xB7 drag to select ${e.level==="die"?"dies":"wafers"}`:""):e.marks.type==="line"&&m.onSelectPoints?` \xB7 click a point to ${m.selectActionLabel??"chart or tabulate what it averages"} \xB7 drag across the plot to select ${m.selectRangeLabel??"a run of points"}`:"";a.textContent=m.panel?`${e.population.wafers.toLocaleString("en-GB")} wafer${e.population.wafers===1?"":"s"} \xB7 ${e.population.dies.toLocaleString("en-GB")} dies`:Ht(e)+(e.facets?"":r),m.panel||Xn(a,Kt(e)),Vt(a),te=z.createElement("div"),te.style.display="flow-root",R.appendChild(te),te.appendChild(a);for(const n of e.fitNotes??[]){const t=z.createElement("div");t.dataset.wmapPlotFit="1",t.textContent=n,Object.assign(t.style,{color:nt.text,fontSize:gt.body,marginBottom:me.xxs,fontVariantNumeric:"tabular-nums"}),te.appendChild(t)}for(const n of e.notes){const t=z.createElement("div");Vt(t),t.textContent=n,Object.assign(t.style,{color:nt.warnText,fontSize:gt.body,marginBottom:me.xs}),te.appendChild(t)}if(e.plotted===0){Jt(R,"Nothing to plot: no mark has every value this plot needs.");return}if(e.groups.length>1&&!e.colorRepeatsX&&(pe=z.createElement("div"),pe.dataset.wmapPlotLegend="1",Object.assign(pe.style,{display:m.panel?"none":"flex",flexWrap:"wrap",gap:me.sm,marginTop:me.md,marginBottom:me.xl,overflowY:"auto"}),dt=pe,e.facets&&Object.assign(pe.style,{position:"sticky",top:"0",zIndex:"2",background:nt.menuBg,paddingBottom:me.sm,marginBottom:me.md}),e.groups.forEach((n,t)=>{const o=Vn(n||"(none)",ee(t),z);Yn(o.el,W,_,`${n||"(none)"} \u2014 click to filter`),o.el.addEventListener("click",()=>{if(O.has(t)?O.delete(t):O.add(t),ot.forEach((c,y)=>c.setState({selected:O.has(y),dimmed:O.size>0&&!O.has(y)})),ce.length)for(const c of ce)c.setActiveGroups(O);else K()}),ot.push(o),pe.appendChild(o.el)}),ot.forEach((n,t)=>n.setState({selected:O.has(t),dimmed:O.size>0&&!O.has(t)})),te.appendChild(pe)),e.colorScale&&!m.panel&&(pe=Ln(e.colorScale),te.appendChild(pe)),e.facets){const n=z.createElement("div");n.dataset.wmapPlotPanels="1",n.style.isolation="isolate",Object.assign(n.style,{display:"grid",gap:me.md});const t=()=>{n.style.gridTemplateColumns=Ie?`repeat(${Ie}, minmax(0, 1fr))`:`repeat(auto-fill, minmax(${ho}px, 1fr))`};t();const o=Zn("Columns:",[{value:"auto",label:"Auto (0)"},...[1,2,3,4,5].map(x=>({value:String(x),label:`${x} (${x})`}))],Ie?String(Ie):"auto",x=>{Ie=x==="auto"?void 0:Number(x),t()},{hook:"panel-columns",maxWidth:"90px",ownerDocument:z});Object.assign(o.style,{justifyContent:"flex-end",marginBottom:me.sm});const c=o.querySelector("button");R.append(o,n),R.style.overflowY="auto",W.dataset.wmapPlotPanelsOwner="1",ht&&(W.dataset.wmapPanelsHover="1");const y=x=>{if(!ht||x.ctrlKey||x.metaKey||x.altKey||x.shiftKey||x.defaultPrevented||!/^[0-5]$/.test(x.key))return;const g=x.target;typeof g?.closest=="function"&&g.closest('input, textarea, select, [contenteditable="true"], [role="menu"]')||(x.preventDefault(),Ie=x.key==="0"?void 0:Number(x.key),t(),c&&(c.value=Ie?String(Ie):"auto"))};z.addEventListener("keydown",y),ut=()=>z.removeEventListener("keydown",y);for(const x of e.facets){const g=renderPlotChart({...m,panel:{title:x.label}});n.appendChild(g.card),g.setPlot(x.plot),ce.push(g)}we(()=>mo(n));return}$=z.createElement("canvas"),$.style.display="block",$.style.cursor=e.marks.type==="scatter"||e.marks.type==="probability"?"crosshair":"default",R.appendChild($);const d=m.onWaferMenu||m.onSelectPoints?(n,t)=>{!n.die&&m.onWaferMenu?m.onWaferMenu(n.item,Ve(e.spec),t):n.die&&m.onSelectPoints&&(t.preventDefault(),m.onSelectPoints([n],{x:t.clientX,y:t.clientY},$))}:void 0;if(e.marks.type==="scatter"){const n=e.marks,t=!!m.onSelectPoints;Ze=Bt({card:W,canvas:$,tooltip:_,drawn:()=>le,describe:$n,clickable:()=>!!m.onOpenWafer,onOpen:o=>m.onOpenWafer?.(o.item,Ve(e.spec)),onContextMenu:d,onHover:o=>{ge=o,K()},select:t?{pick:({x0:o,y0:c,x1:y,y1:x})=>Z?(O.size===0?n.points:n.points.filter(f=>O.has(f.group))).filter(f=>{const p=w+Z.x.frac(f.x)*Z.plotW,L=M+(1-Z.y.frac(f.y))*Z.plotH;return p>=o&&p<=y&&L>=c&&L<=x}):[],onPicked:(o,c)=>{he.clear();for(const y of o)he.add(y);K(),o.length>0&&m.onSelectPoints(o,c,$)},onClear:()=>{he.clear(),K()},hasSelection:()=>he.size>0}:void 0})}else if(e.marks.type==="control"||e.marks.type==="goal"){const n=e.marks.type==="control";Ze=Bt({card:W,canvas:$,tooltip:_,drawn:()=>le,describe:n?Tn:Sn,clickable:()=>n&&!!m.onOpenWafer,onOpen:t=>{n&&m.onOpenWafer?.(t.item,Ve(e.spec))},onContextMenu:n?d:void 0,onHover:t=>{ge=t,K()}})}else if(e.marks.type==="probability"){const n=e.marks,t=e.spec.probabilityAxis==="linear";Ze=Bt({card:W,canvas:$,tooltip:_,drawn:()=>le,describe:xn,clickable:()=>!!m.onOpenWafer,onOpen:o=>m.onOpenWafer?.(o.item,Ve(e.spec)),onContextMenu:d,onHover:o=>{ge=o,K()},select:m.onSelectPoints?{pick:({x0:o,y0:c,x1:y,y1:x})=>{if(!Z)return[];const g=[];return n.values.forEach((f,p)=>{O.size>0&&!O.has(p)||f.forEach((L,P)=>{const b=ct(P,f.length),C=w+Z.x.frac(L)*Z.plotW,u=M+(1-Z.y.frac(t?b:Yt(b)))*Z.plotH;if(C<o||C>y||u<c||u>x)return;const{item:i,die:v}=n.unit(n.units[p][P]);g.push({x:L,y:b,group:p,item:i,die:v})})}),g},onPicked:(o,c)=>{he.clear();for(const y of o)he.add(y);K(),o.length>0&&m.onSelectPoints(o,c,$)},onClear:()=>{he.clear(),K()},hasSelection:()=>he.size>0}:void 0})}else if(e.marks.type==="histogram"){un(),$.addEventListener("mousemove",t=>{const o=_t(t);if(!o){_.style.display="none",ye>=0&&(ye=-1,K());return}_.innerHTML=o,_.style.display="block",yt(_,W,t.clientX,t.clientY),K()}),$.addEventListener("mouseleave",()=>{_.style.display="none",ye>=0&&(ye=-1,K())});const n=e.marks;if(m.onSelectPoints){$.style.cursor="pointer";const t=o=>{if(!Ee||_t(o)===null)return!1;const c=ye,{edges:y}=Ee,x=Z?.x.log,g=x?Math.log10(y[0]):y[0],f=x?Math.log10(y[y.length-1]):y[y.length-1],p=y.length-1,L=[];return n.values.forEach((P,b)=>{if(O.size>0&&!O.has(b))return;const C=[];P.forEach((u,i)=>{const v=x?u>0?Math.log10(u):NaN:u;!Number.isFinite(v)||v<g||v>f||Math.min(p-1,Math.floor((v-g)/(f-g)*p))===c&&C.push(n.units[b][i])});for(const u of st(n.unit,C,b))L.push(u)}),L.length===0?!1:(_.style.display="none",m.onSelectPoints(L,{x:o.clientX,y:o.clientY},$,{range:{lo:y[c],hi:y[c+1]},...O.size===1?{group:e.groups[[...O][0]]}:{}}),!0)};$.addEventListener("click",o=>{t(o)}),$.addEventListener("contextmenu",o=>{t(o)&&o.preventDefault()})}}else if(e.marks.type==="heatmap"){const n=e.marks;$.addEventListener("mousemove",o=>{const c=zt(o);if($.style.cursor=c&&m.onSelectPoints&&n.cellUnits[c.r][c.c].length?"pointer":"default",!c){_.style.display="none",xe&&(xe=null,K());return}_.innerHTML=kn(c),_.style.display="block",yt(_,W,o.clientX,o.clientY),(!xe||xe.r!==c.r||xe.c!==c.c)&&(xe=c,K())}),$.addEventListener("mouseleave",()=>{_.style.display="none",xe&&(xe=null,K())});const t=o=>{const c=zt(o);if(!c||!m.onSelectPoints)return!1;const y=n.cellUnits[c.r][c.c];return y.length?(_.style.display="none",m.onSelectPoints(st(n.unit,y,0),{x:o.clientX,y:o.clientY},$,{cell:{row:n.rows[c.r],column:n.cols[c.c]}}),!0):!1};$.addEventListener("click",o=>{t(o)}),$.addEventListener("contextmenu",o=>{t(o)&&o.preventDefault()})}else if(e.marks.type==="box"||e.marks.type==="bar"){const n=e.marks;if(e.spec.orientation==="horizontal"){const o=z.createElement("div");o.dataset.wmapRowScroll="1",o.tabIndex=0,o.setAttribute("aria-label",`Scroll the ${n.categories.length} rows`),Object.assign(o.style,{position:"absolute",display:"none",width:"12px",overflowY:"auto",overflowX:"hidden",zIndex:"1"});const c=z.createElement("div");c.style.width="1px",o.appendChild(c),o.addEventListener("scroll",()=>{Math.abs(o.scrollTop-lt)<1||(lt=o.scrollTop,_.style.display="none",K())}),$.addEventListener("wheel",y=>{if(o.style.display==="none")return;const x=o.scrollTop;o.scrollTop+=y.deltaMode===1?y.deltaY*16:y.deltaY,o.scrollTop!==x&&y.preventDefault()},{passive:!1}),R.appendChild(o),$e=o}$.addEventListener("mousemove",o=>{const c=Pt(o);if($.style.cursor=c&&(n.categoryItems&&m.onOpenWafer||m.onSelectPoints&&n.cellUnits[c.g][c.c].length>0)?"pointer":"default",!c){_.style.display="none",se&&(se=null,K());return}_.innerHTML=gn(c),_.style.display="block",yt(_,W,o.clientX,o.clientY),(!se||se.g!==c.g||se.c!==c.c)&&(se=c,K())}),$.addEventListener("mouseleave",()=>{_.style.display="none",se&&(se=null,K())});const t=(o,c)=>{const y=n.cellUnits[c.g][c.c];return y.length===0||!m.onSelectPoints?!1:(_.style.display="none",m.onSelectPoints(st(n.unit,y,c.g),{x:o.clientX,y:o.clientY},$,{category:n.categories[c.c],...e.groups.length>1?{group:e.groups[c.g]}:{},...mn(n.categories[c.c])}),!0)};$.addEventListener("contextmenu",o=>{const c=Pt(o);if(!c)return;const y=n.categoryItems?.[c.c];y!==void 0&&y>=0&&m.onWaferMenu?(_.style.display="none",m.onWaferMenu(y,Ve(e.spec),o)):t(o,c)&&o.preventDefault()}),$.addEventListener("click",o=>{const c=Pt(o);if(!c)return;const y=n.categoryItems?.[c.c];if(y!==void 0&&y>=0&&m.onOpenWafer){m.onOpenWafer(y,Ve(e.spec));return}t(o,c)})}else if(e.marks.type==="line"){$.addEventListener("mousemove",o=>{const c=$t(o);if(!c){_.style.display="none",K();return}_.innerHTML=c,_.style.display="block",yt(_,W,o.clientX,o.clientY),K()}),$.addEventListener("mouseleave",()=>{_.style.display="none",be>=0&&(be=-1,K())});const n=e.marks,t=()=>n.cellUnits.flatMap((o,c)=>O.size>0&&!O.has(c)?[]:st(n.unit,o[be]??[],c));if((m.onWaferMenu||m.onSelectPoints)&&$.addEventListener("contextmenu",o=>{if($t(o)===null||be<0)return;const c=Ft(be);if(c!==void 0&&m.onWaferMenu)_.style.display="none",m.onWaferMenu(c,Ve(e.spec),o);else if(m.onSelectPoints){const y=t();y.length>0&&(o.preventDefault(),_.style.display="none",m.onSelectPoints(y,{x:o.clientX,y:o.clientY},$))}}),m.onSelectPoints){$.style.cursor="pointer";let o=!1;$.addEventListener("mousedown",c=>{if(c.button!==0)return;o=!1;const y=$.getBoundingClientRect(),x=c.clientX-y.left,g=f=>{z.removeEventListener("mouseup",g);const p=f.clientX-y.left;if(Math.abs(p-x)<4)return;o=!0;const[L,P]=x<p?[x,p]:[p,x],b=de.map((u,i)=>u>=L&&u<=P?i:-1).filter(u=>u>=0),C=n.cellUnits.flatMap((u,i)=>O.size>0&&!O.has(i)?[]:b.flatMap(v=>st(n.unit,u[v]??[],i)));C.length>0&&(_.style.display="none",m.onSelectPoints(C,{x:f.clientX,y:f.clientY},$))};z.addEventListener("mouseup",g)}),$.addEventListener("click",c=>{if(o){o=!1;return}if($t(c)===null||be<0)return;const y=t();y.length>0&&(_.style.display="none",m.onSelectPoints(y,{x:c.clientX,y:c.clientY},$))})}}K()}V(()=>{const e=s;if(!e||!e.marks)return;const l=bt(e.spec.colorGradient,e.spec.colorReverse,e.colorScale?.diverging,e.colorScale?.rating);return{caption:[Ht(e),...e.fitNotes??[],...e.notes,...oo(Kt(e))],legend:e.groups.length>1&&!e.colorRepeatsX?e.groups.map((a,h)=>({label:a||"(none)",color:ee(h)})):void 0,colorbar:e.colorScale?{label:e.colorScale.label,lo:J(e.colorScale.lo,e.colorScale.unit),hi:J(e.colorScale.hi,e.colorScale.unit),color:l}:void 0}});const Cn=jn(W,()=>K());return{card:W,actions:Y,setPlot(e){s=e,Me(io(e.spec)),An()},setMenuRows(e){Oe=e},setActiveGroups(e){O.clear();for(const l of e)O.add(l);ot.forEach((l,a)=>l.setState({selected:O.has(a),dimmed:O.size>0&&!O.has(a)})),K()},destroy(){ut?.(),Cn.disconnect(),Ze?.destroy();for(const e of ce)e.destroy()}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseRegionKey as
|
|
1
|
+
import{parseRegionKey as q,parseReticleCellKey as H}from"../../stats/regions.js";import{yieldFill as _}from"./palette.js";import{fontPx as L}from"../toolbar.js";import{escHtml as K}from"../../core/utils.js";import{makeTooltip as Q,positionChartTooltip as Z,cardShell as U,resolveChartCanvasColors as z,observeResize as J,growCardToFitContent as V,setChartGrow as x,isExpandedCard as ee,bodyRoom as te,renderEmptyState as ne,prepareCanvas as oe}from"./chartShell.js";import{cardAbout as le}from"./cardAbout.js";const N=320,ie=220,Y={SE:[0,Math.PI/2],SW:[Math.PI/2,Math.PI],NW:[Math.PI,1.5*Math.PI],NE:[1.5*Math.PI,2*Math.PI]};function B(e,i,o,g,M,r){e.beginPath(),e.moveTo(i+r,o),e.arcTo(i+g,o,i+g,o+M,r),e.arcTo(i+g,o+M,i,o+M,r),e.arcTo(i,o+M,i,o,r),e.arcTo(i,o,i+g,o,r),e.closePath()}function A(e,i,o,g,M,r){e.font=`${L(-1)}px system-ui, sans-serif`;const b=e.measureText(g).width;e.font="700 11px system-ui, sans-serif";const E=e.measureText(M).width,R=Math.max(b,E)+12,y=30;e.fillStyle=r.bg,B(e,i-R/2,o-y/2,R,y,4),e.fill(),e.strokeStyle=r.border,e.lineWidth=1,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.fillStyle=r.textMuted,e.font=`${L(-1)}px system-ui, sans-serif`,e.fillText(g,i,o-7),e.fillStyle=r.text,e.font="700 11px system-ui, sans-serif",e.fillText(M,i,o+7)}function re(e,i,o,g,M){e.font="700 11px system-ui, sans-serif";const r=e.measureText(g).width+8;e.fillStyle=M.bg,B(e,i-r/2,o-8,r,16,3),e.fill(),e.textAlign="center",e.textBaseline="middle",e.fillStyle=M.text,e.fillText(g,i,o+.5)}export function renderRegionYieldDiagram(e){const{mode:i,rows:o,onSaveImage:g}=e,M=e.title??(i==="ring"?"Ring yield":i==="quadrant"?"Quadrant yield":"Reticle cell yield"),{card:r,body:b,setAbout:E}=U(M,g,e.ownerDocument);E(le(i==="ring"?"ring-yield":i==="quadrant"?"quadrant-yield":"reticle-yield")),x(r,"square");const R=o.length>0;if(!R)return ne(b,"No bin data available for regional yield."),{card:r,hasData:R,destroy:()=>{}};Object.assign(b.style,{display:"flex",justifyContent:"center",alignItems:"center"});const y=r.ownerDocument.createElement("canvas");Object.assign(y.style,{display:"block",flex:"none"}),b.appendChild(y);let C={cx:0,cy:0,R:0};const W=new Map;let S=0,p=0;if(i==="reticleCell"){for(const l of o){const n=H(l.key);n&&(W.set(`${n.column},${n.row}`,l),S=Math.max(S,n.column+1),p=Math.max(p,n.row+1))}S=Math.max(S,e.grid?.width??0),p=Math.max(p,e.grid?.height??0)}let k={x0:0,y0:0,side:0};const T=Q(r);function O(l,n,c,t){const a=Math.max(4,Math.floor(Math.min((n-40)/S,(n-40)/p))),f=Math.round((n-a*S)/2),s=Math.round((n-a*p)/2);k={x0:f,y0:s,side:a};for(let I=0;I<p;I++)for(let u=0;u<S;u++){const h=f+u*a,d=s+(p-1-I)*a,m=W.get(`${u},${I}`);l.fillStyle=m?t(m.yieldPercent):c.bg,l.fillRect(h,d,a,a),l.strokeStyle=c.border,l.lineWidth=1,l.strokeRect(h+.5,d+.5,a-1,a-1),!(!m||a<30)&&(a>=54?A(l,h+a/2,d+a/2,`(${u}, ${I})`,`${m.yieldPercent.toFixed(1)}%`,c):re(l,h+a/2,d+a/2,`${m.yieldPercent.toFixed(0)}%`,c))}l.strokeStyle=c.text,l.lineWidth=1.5,l.strokeRect(f+.5,s+.5,a*S-1,a*p-1)}function F(){const l=Math.max(ie,Math.min(b.clientWidth||N,N));V(r,b,l);const n=ee(r)?Math.max(l,Math.floor(Math.min(b.clientWidth,te(r,b,y)))):l,c=oe(y,r,n,n);if(!c)return;const{ctx:t}=c,P=z(r),a=_;if(i==="reticleCell"){O(t,n,P,a);return}const f=n/2,s=n/2,u=n/2-34;if(C={cx:f,cy:s,R:u},i==="ring"){const h=o.length;for(let d=0;d<h;d++){const m=d/h*u,w=(d+1)/h*u;t.beginPath(),t.arc(f,s,w,0,2*Math.PI),t.arc(f,s,m,0,2*Math.PI,!0),t.closePath(),t.fillStyle=a(o[d].yieldPercent),t.fill(),t.strokeStyle=P.border,t.lineWidth=1,t.stroke()}t.beginPath(),t.arc(f,s,u,0,2*Math.PI),t.strokeStyle=P.text,t.lineWidth=1.5,t.stroke();for(let d=0;d<h;d++){const m=(d+.5)/h*u,w=-Math.PI/2+d/h*2*Math.PI,$=f+Math.cos(w)*m,v=s+Math.sin(w)*m;A(t,$,v,o[d].label,`${o[d].yieldPercent.toFixed(1)}%`,P)}}else{for(const h of o){const d=q(h.key).quadrant,m=d?Y[d]:void 0;if(!m)continue;const[w,$]=m;t.beginPath(),t.moveTo(f,s),t.arc(f,s,u,w,$),t.closePath(),t.fillStyle=a(h.yieldPercent),t.fill(),t.strokeStyle=P.border,t.lineWidth=1,t.stroke();const v=(w+$)/2,j=f+Math.cos(v)*u*.6,G=s+Math.sin(v)*u*.6;A(t,j,G,h.label,`${h.yieldPercent.toFixed(1)}%`,P)}t.beginPath(),t.arc(f,s,u,0,2*Math.PI),t.strokeStyle=P.text,t.lineWidth=1.5,t.stroke()}}function D(l,n){if(i==="reticleCell"){const f=Math.floor((l-k.x0)/k.side),s=Math.floor((n-k.y0)/k.side);return k.side<=0||f<0||f>=S||s<0||s>=p?null:W.get(`${f},${p-1-s}`)??null}const c=l-C.cx,t=n-C.cy,P=Math.hypot(c,t);if(!(P<=C.R))return null;if(i==="ring")return o[Math.min(o.length-1,Math.floor(P/C.R*o.length))]??null;const a=(Math.atan2(t,c)+2*Math.PI)%(2*Math.PI);return o.find(f=>{const s=Y[q(f.key).quadrant??""];return!!s&&a>=s[0]&&a<s[1]})??null}if(y.addEventListener("mousemove",l=>{const n=y.getBoundingClientRect(),c=D(l.clientX-n.left,l.clientY-n.top);if(!c){T.style.display="none";return}T.innerHTML=`<strong>${K(c.label)}</strong><br>${c.yieldPercent.toFixed(1)}% yield (${c.passDies} of ${c.n} dies)`+(e.onSelectRegion?"<br><em>click to chart or tabulate these dies</em>":""),T.style.display="block",Z(T,r,l.clientX,l.clientY)}),y.addEventListener("mouseleave",()=>{T.style.display="none"}),e.onSelectRegion){y.style.cursor="pointer";const l=n=>{const c=y.getBoundingClientRect(),t=D(n.clientX-c.left,n.clientY-c.top);return t?(e.onSelectRegion(t,n),!0):!1};y.addEventListener("click",n=>{l(n)}),y.addEventListener("contextmenu",n=>{l(n)&&n.preventDefault()})}const X=J(r,()=>F());return F(),{card:r,hasData:R,destroy:()=>X.disconnect()}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildSweepData as ue,sweepAppliesTo as he}from"../../stats/sweep.js";import{fmt as
|
|
1
|
+
import{buildSweepData as ue,sweepAppliesTo as he}from"../../stats/sweep.js";import{fmt as D}from"../../renderer/fmt.js";import{SPACE as oe,fontPx as me,FONT as ie,CLR as Y,ALPHA as xe}from"../toolbar.js";import{categorical as ge}from"./palette.js";import{cardShell as be,observeResize as ye,makeTooltip as $e,positionChartTooltip as ve,renderEmptyState as re,chartFillHeight as Te,populationPhrase as Se,PADDING as J,prepareCanvas as Le,makeAxisFormat as Me,VERTICAL_TICK_SPACING_PX as we}from"./chartShell.js";import{fitTicks as Pe}from"../../renderer/axisTicks.js";import{escHtml as m}from"../../core/utils.js";import{unmarkedLabel as ke,derivedTestNote as Ae,DERIVED_MARK as Q,DERIVED_KEY as Ee}from"../../renderer/testLabel.js";import{plotAbout as Ce}from"./cardAbout.js";function O(p,g){return g?D(p,g).replace(/(\.\d*?)0+(?=\D|$)/,"$1").replace(/\.(?=\D|$)/,""):Number.isInteger(p)?String(p):String(Number(p.toPrecision(3)))}function Ie(p){const g=ke(p.label),C=g.length>9?`${g.slice(0,8)}\u2026`:g;return p.derived?`${Q} ${C}`:C}const le=260,De=62,Ne=56,He=3;function Be(p,g){const C=p.series[0]?.points[0]?.testNumber;return C===void 0?void 0:g?.find(j=>j.testNumber===C)?.unit}export function renderSweepPanel(p){const{testDefs:g,onSaveImage:C,population:j}=p;let $=p.spec,z=p.dies;const{card:b,body:M,heading:ae,controlsRow:ce,setAbout:fe}=be($.title,C,p.ownerDocument);fe(Ce({id:$.id,chart:"sweep"})),b.style.alignSelf="start";const V=b.ownerDocument,N=V.createElement("div");N.dataset.wmapCaption="1",Object.assign(N.style,{color:Y.label,fontSize:ie.body,marginBottom:oe.sm}),b.insertBefore(N,M);const W=V.createElement("div");Object.assign(W.style,{color:Y.label,fontSize:ie.body,marginTop:oe.sm}),b.appendChild(W);const w=$e(b);let F=null,L=null,v;const R=n=>$.series[n]?.color??ge(n);function K(){if(M.innerHTML="",W.innerHTML="",F?.disconnect(),F=null,$.series.length===0){N.textContent="",re(M,"This sweep defines no series.");return}if(L=ue(z,g,$),v=Be(L,g),L.series.filter(s=>s.points.some(l=>l.count>0)).length===0){N.textContent="",re(M,he($,g)?"No values recorded for the tests in this sweep.":"None of this sweep\u2019s tests are in this data \u2014 it may belong to another test program."),Z();return}N.textContent=`Line = median across ${Se(L.dieCount,z.length,j)}, band = p10\u2013p90`+($.series.length>2?" \xB7 crossing and separation measured between the first two series":"")+(p.onSelectPoint?" \xB7 click a level to chart or tabulate the dies measured there":"");const a=V.createElement("canvas");a.style.display="block",M.appendChild(a);let i=null;const P=()=>{const s=L;if(s===null)return;const l=Math.max(1,M.clientWidth),y=Math.max(le,Te(b,M,a,le)),T=Le(a,b,l,y);if(!T)return;const{ctx:e,theme:c}=T,x=t=>s.xScale==="log"?Math.log10(t):t;let f=1/0,o=-1/0,u=1/0,h=-1/0;for(const t of s.series)for(const r of t.points)r.count!==0&&(f=Math.min(f,r.p10),o=Math.max(o,r.p90),u=Math.min(u,x(r.x)),h=Math.max(h,x(r.x)));for(const t of s.separations)f=Math.min(f,t.y),o=Math.max(o,t.y);if(!Number.isFinite(f)||!Number.isFinite(o))return;f===o&&(f-=1,o+=1);const ee=(o-f)*.08;if(f-=ee,o+=ee,u===h&&(u-=.5,h+=.5),s.xScale==="log"){const t=(h-u)*.03;u-=t,h+=t}e.font=`${me(-1)}px system-ui, sans-serif`;const S=J+De,H=l-J-8,X=J,k=y-Ne,A=t=>k-(t-f)/(o-f)*(k-X),B=t=>S+(x(t)-u)/(h-u)*(H-S);i={left:S,right:H,xLo:u,xHi:h,yOf:A,ax:x},e.strokeStyle=c.border,e.lineWidth=1,e.beginPath(),e.moveTo(S,X),e.lineTo(S,k),e.lineTo(H,k),e.stroke(),e.fillStyle=c.text,e.textAlign="right",e.textBaseline="middle";const te=Pe(f,o,k-X,()=>we),pe=Me(Math.max(Math.abs(f),Math.abs(o)),v,te.step||void 0);for(const t of te.ticks)e.fillText(pe.tickWithUnit(t),S-6,A(t));for(const t of s.separations){const r=A(t.y);e.save(),e.strokeStyle=c.limitLine,e.globalAlpha=.55,e.setLineDash([4,3]),e.beginPath(),e.moveTo(S,r),e.lineTo(H,r),e.stroke(),e.restore()}if(s.series.forEach((t,r)=>{const E=t.points.filter(d=>d.count>0);if(!(E.length<2)){e.save(),e.fillStyle=R(r),e.globalAlpha=.14,e.beginPath(),E.forEach((d,I)=>{const _=B(d.x),se=A(d.p90);I===0?e.moveTo(_,se):e.lineTo(_,se)});for(let d=E.length-1;d>=0;d--){const I=E[d];e.lineTo(B(I.x),A(I.p10))}e.closePath(),e.fill(),e.restore()}}),s.series.forEach((t,r)=>{e.strokeStyle=R(r),e.lineWidth=1.75,e.beginPath();let E=!1;for(const d of t.points){if(d.count===0){E=!1;continue}const I=B(d.x),_=A(d.median);E?e.lineTo(I,_):e.moveTo(I,_),E=!0}e.stroke(),e.fillStyle=R(r);for(const d of t.points)d.count!==0&&(e.beginPath(),e.arc(B(d.x),A(d.median),He,0,Math.PI*2),e.fill())}),s.crossing){const t=B(s.crossing.x),r=A(s.crossing.y);e.save(),e.strokeStyle=c.text,e.globalAlpha=.45,e.setLineDash([3,3]),e.beginPath(),e.moveTo(t,r),e.lineTo(t,k),e.stroke(),e.restore(),e.save(),e.strokeStyle=c.text,e.lineWidth=2,e.beginPath(),e.arc(t,r,5.5,0,Math.PI*2),e.stroke(),e.restore()}e.fillStyle=c.text,e.textBaseline="top",e.textAlign="center";const G=s.xIsPhysical?[...new Set(s.series.flatMap(t=>t.points.map(r=>r.x)))].sort((t,r)=>t-r).map(t=>({x:t,label:O(t,s.xUnit)})):(s.series[0]?.points??[]).map(t=>({x:t.x,label:Ie(t)})),de=Math.max(1,Math.ceil(G.length*46/Math.max(1,H-S)));G.forEach((t,r)=>{r%de!==0&&r!==G.length-1||e.fillText(t.label,B(t.x),k+6)}),e.save(),e.fillStyle=c.text,e.globalAlpha=.75,e.textAlign="center",e.textBaseline="bottom",e.fillText(s.xLabel,(S+H)/2,y-4),e.restore(),e.save(),e.fillStyle=c.text,e.globalAlpha=.75,e.translate(12,(X+k)/2),e.rotate(-Math.PI/2),e.textBaseline="top",e.fillText(s.yLabel+(v?` (${v})`:""),0,0),e.restore(),e.textAlign="left",e.textBaseline="middle";let U=S+4;const ne=X+8;s.series.forEach((t,r)=>{e.fillStyle=R(r),e.fillRect(U,ne-4,10,3),U+=14,e.fillStyle=c.text,e.fillText(t.label,U,ne),U+=e.measureText(t.label).width+16})};P(),F=ye(M,P);const q=s=>{const l=L;if(l===null||i===null)return null;const y=s.clientX-a.getBoundingClientRect().left,T=i.xLo+(y-i.left)/Math.max(1,i.right-i.left)*(i.xHi-i.xLo);let e=null;for(const c of l.series)for(const x of c.points){if(x.count===0)continue;const f=Math.abs(i.ax(x.x)-T);(e===null||f<e.dist)&&(e={x:x.x,dist:f})}return e===null?null:e.x};if(a.addEventListener("mousemove",s=>{const l=L,y=q(s);if(l===null||y===null){w.style.display="none";return}const T={x:y},e=l.series.map(o=>o.points.find(u=>u.x===T.x&&u.count>0)),c=l.series.map((o,u)=>{const h=e[u];return h===void 0?"":`<span style="color:${R(u)}">\u25A0</span> ${h.derived?`${Q} `:""}${m(o.label)}: <strong>${m(D(h.median,v))}</strong><br><span style="opacity:${xe.muted}">p10 ${m(D(h.p10,v))} \u2013 p90 ${m(D(h.p90,v))} \xB7 n=${h.count.toLocaleString()}</span>`}).filter(Boolean);if(c.length===0){w.style.display="none";return}const x=l.series.flatMap(o=>o.points).find(o=>o.x===T.x&&o.count>0),f=[...new Set(e.map(o=>Ae(o)).filter(o=>o!==void 0))];w.innerHTML=`<strong>${m(x?.label??"")}</strong><br>`+c.join("<br>")+f.map(o=>`<br><em>${m(o)}</em>`).join(""),w.style.display="block",ve(w,b,s.clientX,s.clientY)}),a.addEventListener("mouseleave",()=>{w.style.display="none"}),p.onSelectPoint){a.style.cursor="pointer";const s=l=>{const y=L,T=q(l);if(y===null||T===null)return!1;const e=y.series.flatMap(c=>c.points.filter(x=>x.x===T&&x.count>0));return e.length===0?!1:(w.style.display="none",p.onSelectPoint({testNumbers:e.map(c=>c.testNumber),label:e[0].label},l),!0)};a.addEventListener("click",l=>{s(l)}),a.addEventListener("contextmenu",l=>{s(l)&&l.preventDefault()})}Z()}function Z(){const n=L;if(n===null)return;const a=[];n.notMeasured!==void 0?a.push(`<strong>Crossing and widths:</strong> not measured \u2014 ${m(n.notMeasured)}`):n.crossing?a.push(`<strong>Crossing:</strong> ${m(`${n.xLabel} = ${O(n.crossing.x,n.xUnit)}`)} \xB7 ${m(`${n.yLabel} ${D(n.crossing.y,v)}`)}`+(n.crossing.multiple?" <em>(first of several \u2014 the curves cross more than once)</em>":"")):($.crossing??!0)&&$.series.length>=2&&a.push("<strong>Crossing:</strong> the first two series do not cross over the swept range");for(const i of n.separations)if(i.distance!==null){const P=i.ratio!==void 0&&i.from!==void 0&&i.to!==void 0?`\xD7${Number(i.ratio.toPrecision(3))} on the ${n.xLabel} axis (${O(i.from,n.xUnit)} \u2192 ${O(i.to,n.xUnit)})`:`${O(i.distance,n.xUnit)} on the ${n.xLabel} axis`;a.push(`<strong>Width at ${m(D(i.y,v))}:</strong> ${m(P)}`)}else{const P=i.reason==="second-series-never-reaches"?n.series[1]?.label:n.series[0]?.label;a.push(`<strong>Width at ${m(D(i.y,v))}:</strong> not measurable \u2014 ${m(P??"a series")} never reaches this level`)}n.series.some(i=>i.points.some(P=>P.derived))&&a.push(`${Q} ${m(Ee)} \u2014 hover a point for the expression`);for(const i of n.warnings)a.push(`<span style="color:${Y.errText}">${m(i)}</span>`);W.innerHTML=a.join("<br>")}return K(),{card:b,destroy:()=>{F?.disconnect(),w.remove(),b.remove()},setDies:n=>{z=n,K()},setSpec:n=>{$=n,ae.textContent=n.title,b.dataset.wmapChartTitle=n.title,K()},actions:ce}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isYieldEligibleDie as W}from"../core/dies.js";import{testValue as A}from"../core/dieTable.js";import{metadataDisplayValue as I}from"../core/metadata.js";import{attributeLabel as H}from"../stats/facets.js";import{tableToTsv as V}from"../core/tableCsv.js";import{commonMetadata as Y}from"../stats/facets.js";import{buildYieldData as G}from"../stats/yield.js";import{isParametricTest as k}from"../renderer/buildWaferMap.js";import{fmt as U}from"../renderer/fmt.js";import{testLabel as $}from"../renderer/testLabel.js";import{resolveDieColumns as K}from"./dieList.js";import{createVirtualTable as N}from"./virtualTable.js";import{exportCsv as O}from"./tableExport.js";import{CLR as y,FONT as L,RADIUS as R,SPACE as C,controlStyle as q,wireControlHover as j,wireTooltip as S}from"./toolbar.js";import{buildTestSection as X,buildFunctionalTestSection as J}from"./summaryPanel.js";import{patTests as Q,waferPatVerdicts as Z,PAT_VERDICT_LABEL as ee}from"../stats/pat.js";export const DATA_VIEWS=[{key:"statistics",label:"Statistics",hint:"One row per test: count, spread, limits and limit yield"},{key:"wafers",label:"Wafers",hint:"One row per wafer: its attributes, die counts, yield and test means"},{key:"dies",label:"Dies",hint:"One row per die, with its position, bins and every test"}],EXCEL_ROW_LIMIT=1048576,COPY_CELL_LIMIT=2e5,WAFER_TEST_COLUMNS=50;const D=(e,l,o=l+"s")=>`${e.toLocaleString()} ${e===1?l:o}`;export function renderDataSection(e){const{doc:l}=e,o=l.createElement("div");o.dataset.wmapDataTab="1",Object.assign(o.style,{display:"flex",flexDirection:"column",gap:C.md,minWidth:"0"});const c=l.createElement("div");Object.assign(c.style,{display:"flex",alignItems:"center",gap:C.md,flexWrap:"wrap"}),o.appendChild(c);const p=l.createElement("div");Object.assign(p.style,{display:"flex",flexDirection:"column",gap:C.md,minWidth:"0"}),o.appendChild(p);const g=DATA_VIEWS.filter(f=>!e.views||e.views.includes(f.key)),s=P(l,"Table",g,e.view,"wmapDataView",f=>e.onViewChange(f));c.appendChild(s.el);let r;switch(e.view){case"dies":r=oe(e);break;case"wafers":r=se(e);break;default:r=te(e)}let u=()=>{};if(e.view==="dies"){const f=P(l,"Export format",[{key:"wide",label:"Wide",hint:"A column for each test"},{key:"long",label:"Long",hint:"A row for each die and test, the shape statistics tools prefer"}],e.diesLayout,"wmapDataLayout",t=>{f.set(t),e.onDiesLayoutChange(t),r.actions?.setLayout?.(t),u()});S(f.el,"Wide: a column per test. Long: a row per die per test, for tools that want tidy data. The table on screen is always wide.");const d=l.createElement("span");Object.assign(d.style,{display:"inline-flex",alignItems:"center",gap:C.sm});const i=l.createElement("span");i.textContent="Export format:",Object.assign(i.style,{color:y.label,fontSize:L.body}),d.append(i,f.el),c.appendChild(d)}if(r.actions){const f=r.actions,d=l.createElement("div");d.style.flex="1",c.appendChild(d);const i=M(l,"Export CSV");i.dataset.wmapDataExport="1",i.addEventListener("click",()=>{if(i.disabled)return;const m=i.textContent,h=f.exportCsv();h&&(i.disabled=!0,i.setAttribute("aria-busy","true"),h.catch(()=>{}).finally(()=>{i.disabled=!1,i.removeAttribute("aria-busy"),i.textContent=m}))});const t=M(l,"Copy");t.dataset.wmapDataCopy="1",f.copyText?(S(t,"Copy the table as tab-separated text, to paste into a spreadsheet"),t.addEventListener("click",()=>{const m=f.copyText(),h=l.defaultView?.navigator?.clipboard;if(!h)return;const v=t.textContent;h.writeText(m).then(()=>{t.textContent="Copied",l.defaultView?.setTimeout(()=>{t.textContent=v},1500)}).catch(()=>{})})):(t.disabled=!0,S(t,`Too large to copy (over ${COPY_CELL_LIMIT.toLocaleString()} cells). Use Export CSV.`)),c.append(t,i);const a=l.createElement("div");a.dataset.wmapDataNote="1",a.textContent=f.note(),u=()=>{a.textContent=f.note()},Object.assign(a.style,{color:y.label,fontSize:L.body}),o.insertBefore(a,p)}return p.appendChild(r.el),{card:o,destroy:()=>r.destroy()}}function te(e){const{doc:l}=e,o=l.createElement("div");Object.assign(o.style,{display:"flex",flexDirection:"column",gap:C.lg,minWidth:"0"});const c=[],p=e.groups&&e.groups.length>0?e.groups:void 0,g=p??[{key:"",items:e.items}];for(const s of g){if(p){const u=l.createElement("div");u.textContent=`${e.groupLabelText??"Group"}: ${s.key}`,Object.assign(u.style,{fontWeight:"700",color:y.text,fontSize:L.body}),o.appendChild(u)}const r=e.buildStatistics(s.items);c.push(r.destroy);for(const u of r.cards)o.appendChild(u)}return!o.querySelector("table")&&!o.textContent&&(o.textContent="No test statistics to show for these wafers.",Object.assign(o.style,{color:y.label,fontSize:L.body})),{el:o,destroy:()=>{for(const s of c)s()}}}function ne(e,l,o){if(Q(l).length===0)return;const c=new Map;for(const s of e){const r=s.allDies??(o?void 0:s.dies);if(!r)continue;const u=Z(r,l,s.passBins);r.forEach((f,d)=>c.set(f,u[d]))}if(c.size===0)return;const p=s=>{const r=l.find(u=>u.testNumber===s);return r?$(r,s):`Test ${s}`};let g=!1;for(const s of c.values())if(s.verdict==="outlier"){g=!0;break}return{verdict:s=>{const r=c.get(s)?.verdict;return r?ee[r]:void 0},tests:s=>{const r=c.get(s);return r?.verdict==="outlier"?r.tests.map(p).join("; "):""},anyOutlier:g}}function oe(e){const{doc:l,items:o}=e,c=new WeakMap,p=new WeakMap,g=new WeakMap,s=[];let r=!1;for(const n of o){n.wafer&&(r=!0);for(const b of n.dies)c.set(b,n.label),g.set(b,n.waferIndex),n.wafer&&p.set(b,n.wafer),s.push(b)}if(s.length===0)return B(l,"No dies to show.");const u=ne(o,e.allTestDefs,!!e.population),{columns:f,visibleColumns:d}=K(s,e.allTestDefs,{...e.dieListOptions,...u?{patColumns:u}:{},metadataFields:e.metadataFields,extraColumn:o.length>1||e.population?{label:"Wafer",get:n=>c.get(n)}:void 0,getWafer:r?(n=>p.get(n)):void 0,ringCount:e.ringCount,waferMetadata:o.some(n=>n.wafer)?Y(o.map(n=>({metadata:n.wafer?.metadata}))):void 0,attributes:e.attributes,ownerDocument:l}),i=d.map(n=>({header:n.label,get:n.get,numeric:n.test!==void 0&&k(n.test),...n.test!==void 0&&k(n.test)?{sortKey:b=>A(b,n.test.testNumber)}:{}})),t=N({columns:i,rows:s,ariaLabel:`Dies (${s.length})`,ownerDocument:l,onRowClick:e.onLocateDie?n=>e.onLocateDie(n,g.get(n)):void 0});t.el.style.maxHeight="70vh",t.el.style.minHeight="240px";const a=e.population?`-${e.population.fileTag}`:"",m=f.filter(n=>n.test!==void 0),h=f.filter(n=>n.test===void 0),v=s.length*f.length,w=s.length*m.length,x=()=>f.map(n=>({header:n.csvLabel??n.label,get:n.csvGet??n.get})),_=()=>[...h.map(n=>({header:n.csvLabel??n.label,get:b=>(n.csvGet??n.get)(b.die)})),{header:"Test",get:n=>$(n.test,n.test.testNumber)},{header:"Test number",get:n=>n.test.testNumber},{header:"Unit",get:n=>n.test.unit??""},{header:"Value",get:n=>n.value}];function*F(){for(const n of t.orderedRows())for(const b of m){const T=(b.csvGet??b.get)(n);T===""||T===void 0||T===null||(yield{die:n,test:b.test,value:T})}}let E=e.diesLayout==="long"&&m.length>0;const z=()=>E?`Long format: up to ${D(w,"row")} (a die with no result for a test has no row)`+(w>EXCEL_ROW_LIMIT?` \u2014 more than Excel opens (${EXCEL_ROW_LIMIT.toLocaleString()}).`:"."):`Wide format: ${D(s.length,"row")} \xD7 ${D(f.length,"column")}`+(s.length>EXCEL_ROW_LIMIT?` \u2014 more than Excel opens (${EXCEL_ROW_LIMIT.toLocaleString()} rows).`:".");return{el:t.el,destroy:()=>t.destroy(),actions:{note:()=>`${D(s.length,"die")} ${e.population?.phrase??`on ${D(o.length,"wafer")}`}. ${z()} Export follows the order shown.${e.onLocateDie?" Click a row to show that die on the map.":""}`,setLayout:n=>{E=n==="long"&&m.length>0},exportCsv:()=>E?O(_(),F(),`die-list-long${a}.csv`,e.onSaveText,{rowCount:w}):O(x(),t.orderedRows(),`die-list${a}.csv`,e.onSaveText,{rowCount:s.length}),copyText:v<=COPY_CELL_LIMIT?()=>V(x(),t.orderedRows()):null}}}function se(e){const{doc:l,items:o}=e;if(o.length===0)return B(l,"No wafers to show.");const c=o.map(t=>{const a=e.yieldByWaferIndex.get(t.waferIndex),m=G([{label:t.label,dies:t.dies,passBins:t.passBins,yieldPercent:a,key:t.waferIndex}])[0]?.percent;return{item:t,yieldPercent:t.dies.length?m??null:null}}),p=[];for(const{item:t}of c)for(const a of Object.keys(t.wafer?.metadata??{}))!p.includes(a)&&I((t.wafer?.metadata)[a])!==void 0&&p.push(a);const g=e.testDefs.slice(0,WAFER_TEST_COLUMNS),s=(t,a)=>{const m=t.item.statsSummary?.stats.perTestStats?.find(w=>w.testNumber===a.testNumber);if(m)return m.mean;let h=0,v=0;for(const w of t.item.dies){if(!W(w))continue;const x=A(w,a.testNumber);x!==void 0&&Number.isFinite(x)&&(h++,v+=x)}return h?v/h:void 0},r=[{header:"Wafer",cell:t=>t.item.label},...p.map(t=>({header:H(t,e.attributes),cell:a=>I(a.item.wafer?.metadata?.[t])??""})),{header:"Dies",cell:t=>t.item.dies.length,numeric:!0},{header:"Yield-eligible dies",cell:t=>t.item.dies.filter(a=>W(a)).length,numeric:!0},{header:"Yield %",cell:t=>t.yieldPercent===null?"":t.yieldPercent,show:t=>t.yieldPercent===null?"":t.yieldPercent.toFixed(1),numeric:!0},...g.map(t=>({header:`${$(t,t.testNumber)}${t.unit?` (${t.unit})`:""} mean`,cell:a=>s(a,t),show:a=>{const m=s(a,t);return m===void 0?"":U(m,t.unit)},numeric:!0}))],u=r.map(t=>({header:t.header,get:a=>t.show?t.show(a):String(t.cell(a)??""),numeric:t.numeric,...t.numeric?{sortKey:a=>{const m=t.cell(a);return typeof m=="number"?m:void 0}}:{}})),f=N({columns:u,rows:c,ariaLabel:`Wafers (${c.length})`,ownerDocument:l,onRowClick:e.onOpenWafer?t=>e.onOpenWafer(t.item.waferIndex,t.item.label):void 0});f.el.style.maxHeight="70vh",f.el.style.minHeight="120px";const d=()=>r.map(t=>({header:t.header,get:t.cell})),i=e.testDefs.length>g.length?` Mean columns cover the first ${g.length} of ${e.testDefs.length} tests.`:"";return{el:f.el,destroy:()=>f.destroy(),actions:{note:()=>`${D(c.length,"wafer")}.${i}${e.onOpenWafer?" Click a row to open that wafer.":""} Export follows the order shown.`,exportCsv:()=>O(d(),f.orderedRows(),"wafers.csv",e.onSaveText,{rowCount:c.length}),copyText:c.length*r.length<=COPY_CELL_LIMIT?()=>V(d(),f.orderedRows()):null}}}function B(e,l){const o=e.createElement("div");return o.textContent=l,Object.assign(o.style,{color:y.label,fontSize:L.body,padding:C.md}),{el:o,destroy:()=>{}}}function M(e,l){const o=e.createElement("button");return o.type="button",o.textContent=l,Object.assign(o.style,{fontSize:L.body,padding:"3px 10px",borderRadius:R.control,...q("outlined"),background:y.menuBg}),j(o),o}function P(e,l,o,c,p,g){const s=e.createElement("div");s.setAttribute("role","radiogroup"),s.setAttribute("aria-label",l),Object.assign(s.style,{display:"inline-flex",background:y.menuBg,border:`1px solid ${y.menuBorder}`,borderRadius:R.control,overflow:"hidden"});const r=[];let u=c;const f=()=>{for(const d of r){const i=d.dataset[p]===u;d.setAttribute("aria-checked",String(i)),d.tabIndex=i?0:-1,Object.assign(d.style,{background:i?y.bgActive:"transparent",color:i?y.iconActive:y.label,fontWeight:i?"600":"400"})}};for(const d of o){const i=e.createElement("button");d.hint&&S(i,d.hint),i.type="button",i.textContent=d.label,i.dataset[p]=d.key,i.setAttribute("role","radio"),Object.assign(i.style,{border:"none",cursor:"pointer",fontSize:L.body,padding:`${C.xs} ${C.md}`,whiteSpace:"nowrap"}),j(i,"bare"),i.addEventListener("click",()=>{u!==d.key&&g(d.key)}),r.push(i),s.appendChild(i)}return f(),s.addEventListener("keydown",d=>{if(d.key!=="ArrowLeft"&&d.key!=="ArrowRight")return;const i=r.indexOf(e.activeElement);if(i<0)return;d.preventDefault();const t=r[(i+(d.key==="ArrowRight"?1:-1)+r.length)%r.length];t.click(),t.focus()}),{el:s,set:d=>{u=d,f()}}}export function renderDataTables(e){const{doc:l}=e,o=l.createElement("div");Object.assign(o.style,{display:"flex",flexDirection:"column",minWidth:"0",minHeight:"0",flex:"1",padding:C.md});const c=e.items.map((a,m)=>({...a,waferIndex:a.waferIndex??m})),p=c.flatMap(a=>a.dies),g=e.testDefs??[],s=g.filter(k),r=e.views??(c.length>1?["statistics","wafers","dies"]:["statistics","dies"]),u=e.population?{populationLabel:`${D(p.length,"die")} ${e.population}`}:c.length>1?{perWaferMetadata:c.map(a=>a.wafer?.metadata??{}),populationLabel:`${D(c.length,"wafer")} pooled`}:{waferMetadata:c[0]?.wafer?.metadata};let f=r.includes(e.view)?e.view:r[0],d="wide",i=null;const t=()=>{i?.destroy(),i=renderDataSection({doc:l,items:c,testDefs:s,allTestDefs:g,ringCount:e.ringCount,yieldByWaferIndex:new Map,onSaveText:e.onSaveText,views:r,view:f,dieListOptions:e.dieListOptions,metadataFields:e.metadataFields,attributes:e.attributes,onLocateDie:e.onLocateDie,population:e.population?{phrase:e.population,fileTag:"selection"}:void 0,buildStatistics:a=>{const m=a.flatMap(x=>x.dies),h=[],v=X(m,s,void 0,void 0,e.onSaveText,u,a.map(x=>({dies:x.dies})),void 0,"full");v&&h.push(v);const w=J(m,g,void 0,e.onSaveText,u);return w&&h.push(w),{cards:h,destroy:()=>{}}},onViewChange:a=>{f=a,t()},diesLayout:d,onDiesLayoutChange:a=>{d=a}}),o.replaceChildren(i.card)};return t(),{el:o,destroy:()=>i?.destroy()}}export function renderSelectionTables(e){return renderDataTables({...e,views:e.items.length>1?["statistics","wafers","dies"]:["statistics","dies"]})}
|
|
1
|
+
import{maxOf as J}from"../core/utils.js";import{isYieldEligibleDie as z}from"../core/dies.js";import{testValue as B}from"../core/dieTable.js";import{metadataDisplayValue as _}from"../core/metadata.js";import{attributeLabel as F}from"../stats/facets.js";import{tableToTsv as H}from"../core/tableCsv.js";import{commonMetadata as Z}from"../stats/facets.js";import{buildYieldData as ee}from"../stats/yield.js";import{isParametricTest as j}from"../renderer/buildWaferMap.js";import{fmt as I}from"../renderer/fmt.js";import{testLabel as M}from"../renderer/testLabel.js";import{resolveDieColumns as te}from"./dieList.js";import{createVirtualTable as P}from"./virtualTable.js";import{exportCsv as A}from"./tableExport.js";import{CLR as S,FONT as k,RADIUS as q,SPACE as T,controlStyle as ne,wireControlHover as G,wireTooltip as V}from"./toolbar.js";import{buildTestSection as oe,buildFunctionalTestSection as se}from"./summaryPanel.js";import{pooledTestStatsSteps as ie}from"../stats/capability.js";import{runChunked as ae}from"./chunked.js";import{capabilityShade as re,outOfLimitsShade as le,shadesAmong as K,shortfallShade as U}from"./cellShade.js";import{patTests as de,waferPatVerdicts as ce,PAT_VERDICT_LABEL as ue}from"../stats/pat.js";export const DATA_VIEWS=[{key:"statistics",label:"Statistics",hint:"One row per test: count, spread, limits and limit yield"},{key:"wafers",label:"Wafers",hint:"One row per wafer: its attributes, die counts, yield and test means"},{key:"dies",label:"Dies",hint:"One row per die, with its position, bins and every test"}],EXCEL_ROW_LIMIT=1048576,COPY_CELL_LIMIT=2e5,WAFER_TEST_COLUMNS=50;const O=(t,d,s=d+"s")=>`${t.toLocaleString()} ${t===1?d:s}`;export function renderDataSection(t){const{doc:d}=t,s=d.createElement("div");s.dataset.wmapDataTab="1",Object.assign(s.style,{display:"flex",flexDirection:"column",gap:T.md,minWidth:"0"});const a=d.createElement("div");Object.assign(a.style,{display:"flex",alignItems:"center",gap:T.md,flexWrap:"wrap"}),s.appendChild(a);const h=d.createElement("div");Object.assign(h.style,{display:"flex",flexDirection:"column",gap:T.md,minWidth:"0"}),s.appendChild(h);const y=DATA_VIEWS.filter(f=>!t.views||t.views.includes(f.key)),o=X(d,"Table",y,t.view,"wmapDataView",f=>t.onViewChange(f));a.appendChild(o.el);let r;switch(t.view){case"dies":r=pe(t);break;case"wafers":r=ge(t);break;default:r=fe(t)}let p=()=>{};if(t.view==="dies"){const f=X(d,"Export format",[{key:"wide",label:"Wide",hint:"A column for each test"},{key:"long",label:"Long",hint:"A row for each die and test, the shape statistics tools prefer"}],t.diesLayout,"wmapDataLayout",u=>{f.set(u),t.onDiesLayoutChange(u),r.actions?.setLayout?.(u),p()});V(f.el,"Wide: a column per test. Long: a row per die per test, for tools that want tidy data. The table on screen is always wide.");const c=d.createElement("span");Object.assign(c.style,{display:"inline-flex",alignItems:"center",gap:T.sm});const l=d.createElement("span");l.textContent="Export format:",Object.assign(l.style,{color:S.label,fontSize:k.body}),c.append(l,f.el),a.appendChild(c)}if(r.actions){const f=r.actions,c=d.createElement("div");c.style.flex="1",a.appendChild(c);const l=Y(d,"Export CSV");l.dataset.wmapDataExport="1",l.addEventListener("click",()=>{if(l.disabled)return;const w=l.textContent,b=f.exportCsv();b&&(l.disabled=!0,l.setAttribute("aria-busy","true"),b.catch(()=>{}).finally(()=>{l.disabled=!1,l.removeAttribute("aria-busy"),l.textContent=w}))});const u=Y(d,"Copy");u.dataset.wmapDataCopy="1",f.copyText?(V(u,"Copy the table as tab-separated text, to paste into a spreadsheet"),u.addEventListener("click",()=>{const w=f.copyText(),b=d.defaultView?.navigator?.clipboard;if(!b)return;const x=u.textContent;b.writeText(w).then(()=>{u.textContent="Copied",d.defaultView?.setTimeout(()=>{u.textContent=x},1500)}).catch(()=>{})})):(u.disabled=!0,V(u,`Too large to copy (over ${COPY_CELL_LIMIT.toLocaleString()} cells). Use Export CSV.`)),a.append(u,l);const g=d.createElement("div");g.dataset.wmapDataNote="1",g.textContent=f.note(),p=()=>{g.textContent=f.note()},Object.assign(g.style,{color:S.label,fontSize:k.body}),s.insertBefore(g,h)}return h.appendChild(r.el),{card:s,destroy:()=>r.destroy()}}function fe(t){const{doc:d}=t,s=d.createElement("div");Object.assign(s.style,{display:"flex",flexDirection:"column",gap:T.lg,minWidth:"0"});const a=[],h=t.groups&&t.groups.length>0?t.groups:void 0,y=h??[{key:"",items:t.items}];if(h&&h.length>1){const o=me(t,h);o&&(s.appendChild(o.el),a.push(o.destroy))}for(const o of y){if(h){const p=d.createElement("div");p.textContent=`${t.groupLabelText??"Group"}: ${o.key}`,Object.assign(p.style,{fontWeight:"700",color:S.text,fontSize:k.body}),s.appendChild(p)}const r=t.buildStatistics(o.items);a.push(r.destroy);for(const p of r.cards)s.appendChild(p)}return!s.querySelector("table")&&!s.textContent&&(s.textContent="No test statistics to show for these wafers.",Object.assign(s.style,{color:S.label,fontSize:k.body})),{el:s,destroy:()=>{for(const o of a)o()}}}function me(t,d){const{doc:s}=t,a=t.testDefs.filter(b=>b.testNumber!==void 0&&j(b));if(a.length===0)return null;const h=t.groupLabelText??"Group",y=s.createElement("div");y.dataset.wmapGroupStats="1",Object.assign(y.style,{display:"flex",flexDirection:"column",gap:T.sm,minWidth:"0"});const o=s.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",gap:T.md,flexWrap:"wrap"});const r=s.createElement("div");r.textContent=`Compared across ${h}`,Object.assign(r.style,{fontWeight:"700",color:S.text,fontSize:k.body}),o.appendChild(r);const p=s.createElement("div");p.textContent="Computing test statistics\u2026",Object.assign(p.style,{color:S.label,fontSize:k.body}),y.append(o,p);const f=new Map;let c=d.length,l,u=!1;const g=()=>{if(u)return;const b=[];for(const e of a)for(const n of d){const m=f.get(n.key),i=m?.stats.get(e.testNumber);if(!m||!i)continue;const C=m.specTally.get(e.testNumber);b.push({def:e,group:n.key,count:i.count,min:i.min,q1:i.q1,median:i.median,mean:i.mean,q3:i.q3,max:i.max,stddev:i.stddev,ppk:m.capability.find(W=>W.testNumber===e.testNumber)?.ppk??null,limitYield:C&&C.n>0?100*(1-C.fail/C.n):void 0})}if(b.length===0){y.remove();return}const x=new Map;for(const e of b){const n=x.get(e.def.testNumber);n?n.push(e):x.set(e.def.testNumber,[e])}for(const e of x.values()){const n=K(e.map(i=>i.mean),i=>I(i,e[0].def.unit)),m=J(e.map(i=>i.limitYield??-1/0));e.forEach((i,C)=>{i.meanShade=n[C],i.yieldShade=i.limitYield===void 0||!Number.isFinite(m)?void 0:U(i.limitYield-m)})}const v=e=>({get:n=>I(e(n),n.def.unit),numeric:!0,sortKey:e}),L=(e,n)=>({get:m=>{const i=e(m);return i===void 0||!Number.isFinite(i)?"":n(i)},numeric:!0,sortKey:m=>{const i=e(m);return i===void 0||!Number.isFinite(i)?void 0:i}}),D=[{header:"Test",get:e=>`${M(e.def,e.def.testNumber)}${e.def.unit?` (${e.def.unit})`:""}`},{header:h,get:e=>e.group},{header:"N",...L(e=>e.count,e=>String(e))},{header:"Min",...v(e=>e.min)},{header:"Q1",...v(e=>e.q1)},{header:"Median",...v(e=>e.median)},{header:"Mean",...v(e=>e.mean),shade:e=>e.meanShade},{header:"Q3",...v(e=>e.q3)},{header:"Max",...v(e=>e.max)},{header:"Std dev",...v(e=>e.stddev)},{header:"Ppk",...L(e=>e.ppk??void 0,e=>e.toFixed(2)),shade:e=>re(e.ppk)},{header:"Limit yield %",...L(e=>e.limitYield,e=>e.toFixed(1)),shade:e=>e.yieldShade}],E=P({columns:D,rows:b,ariaLabel:`Statistics by ${h} (${b.length})`,ownerDocument:s});E.el.style.maxHeight="50vh",E.el.style.minHeight="120px",l=E;const N=()=>[{header:"Test number",get:e=>e.def.testNumber??null},{header:"Test",get:e=>M(e.def,e.def.testNumber)},{header:"Unit",get:e=>e.def.unit??""},{header:h,get:e=>e.group},{header:"N",get:e=>e.count},{header:"Min",get:e=>e.min},{header:"Q1",get:e=>e.q1},{header:"Median",get:e=>e.median},{header:"Mean",get:e=>e.mean},{header:"Q3",get:e=>e.q3},{header:"Max",get:e=>e.max},{header:"Std dev",get:e=>e.stddev},{header:"Ppk",get:e=>e.ppk},{header:"Limit yield %",get:e=>e.limitYield??null}],$=Y(s,"Statistics CSV");$.dataset.wmapGroupStatsCsv="1",$.addEventListener("click",()=>{A(N(),E.orderedRows(),`statistics-by-${h.toLowerCase().replace(/[^a-z0-9]+/g,"-")}.csv`,t.onSaveText,{rowCount:b.length})}),o.appendChild($),p.replaceWith(E.el)},w=[];for(const b of d)w.push(ae(ie(b.items.map(x=>({dies:x.dies})),a),{onDone:x=>{f.set(b.key,x),--c===0&&g()}}));return{el:y,destroy:()=>{u=!0;for(const b of w)b.cancel();l?.destroy()}}}function he(t,d,s){if(de(d).length===0)return;const a=new Map;for(const o of t){const r=o.allDies??(s?void 0:o.dies);if(!r)continue;const p=ce(r,d,o.passBins);r.forEach((f,c)=>a.set(f,p[c]))}if(a.size===0)return;const h=o=>{const r=d.find(p=>p.testNumber===o);return r?M(r,o):`Test ${o}`};let y=!1;for(const o of a.values())if(o.verdict==="outlier"){y=!0;break}return{verdict:o=>{const r=a.get(o)?.verdict;return r?ue[r]:void 0},tests:o=>{const r=a.get(o);return r?.verdict==="outlier"?r.tests.map(h).join("; "):""},anyOutlier:y}}function pe(t){const{doc:d,items:s}=t,a=new WeakMap,h=new WeakMap,y=new WeakMap,o=[];let r=!1;for(const e of s){e.wafer&&(r=!0);for(const n of e.dies)a.set(n,e.label),y.set(n,e.waferIndex),e.wafer&&h.set(n,e.wafer),o.push(n)}if(o.length===0)return Q(d,"No dies to show.");const p=he(s,t.allTestDefs,!!t.population),{columns:f,visibleColumns:c}=te(o,t.allTestDefs,{...t.dieListOptions,...p?{patColumns:p}:{},metadataFields:t.metadataFields,extraColumn:s.length>1||t.population?{label:"Wafer",get:e=>a.get(e)}:void 0,getWafer:r?(e=>h.get(e)):void 0,ringCount:t.ringCount,waferMetadata:s.some(e=>e.wafer)?Z(s.map(e=>({metadata:e.wafer?.metadata}))):void 0,attributes:t.attributes,ownerDocument:d}),l=c.map(e=>({header:e.label,get:e.get,numeric:e.test!==void 0&&j(e.test),...e.test!==void 0&&j(e.test)?{sortKey:n=>B(n,e.test.testNumber),shade:n=>{const m=e.test,i=B(n,m.testNumber);return i!==void 0&&Number.isFinite(i)&&(m.limitLow!==void 0&&i<m.limitLow||m.limitHigh!==void 0&&i>m.limitHigh)?le():void 0}}:{}})),u=P({columns:l,rows:o,ariaLabel:`Dies (${o.length})`,ownerDocument:d,onRowClick:t.onLocateDie?e=>t.onLocateDie(e,y.get(e)):void 0});u.el.style.maxHeight="70vh",u.el.style.minHeight="240px";const g=t.population?`-${t.population.fileTag}`:"",w=f.filter(e=>e.test!==void 0),b=f.filter(e=>e.test===void 0),x=o.length*f.length,v=o.length*w.length,L=()=>f.map(e=>({header:e.csvLabel??e.label,get:e.csvGet??e.get})),D=()=>[...b.map(e=>({header:e.csvLabel??e.label,get:n=>(e.csvGet??e.get)(n.die)})),{header:"Test",get:e=>M(e.test,e.test.testNumber)},{header:"Test number",get:e=>e.test.testNumber},{header:"Unit",get:e=>e.test.unit??""},{header:"Value",get:e=>e.value}];function*E(){for(const e of u.orderedRows())for(const n of w){const m=(n.csvGet??n.get)(e);m===""||m===void 0||m===null||(yield{die:e,test:n.test,value:m})}}let N=t.diesLayout==="long"&&w.length>0;const $=()=>N?`Long format: up to ${O(v,"row")} (a die with no result for a test has no row)`+(v>EXCEL_ROW_LIMIT?` \u2014 more than Excel opens (${EXCEL_ROW_LIMIT.toLocaleString()}).`:"."):`Wide format: ${O(o.length,"row")} \xD7 ${O(f.length,"column")}`+(o.length>EXCEL_ROW_LIMIT?` \u2014 more than Excel opens (${EXCEL_ROW_LIMIT.toLocaleString()} rows).`:".");return{el:u.el,destroy:()=>u.destroy(),actions:{note:()=>`${O(o.length,"die")} ${t.population?.phrase??`on ${O(s.length,"wafer")}`}. ${$()} Export follows the order shown.${t.onLocateDie?" Click a row to show that die on the map.":""}`,setLayout:e=>{N=e==="long"&&w.length>0},exportCsv:()=>N?A(D(),E(),`die-list-long${g}.csv`,t.onSaveText,{rowCount:v}):A(L(),u.orderedRows(),`die-list${g}.csv`,t.onSaveText,{rowCount:o.length}),copyText:x<=COPY_CELL_LIMIT?()=>H(L(),u.orderedRows()):null}}}function ge(t){const{doc:d,items:s}=t;if(s.length===0)return Q(d,"No wafers to show.");const a=s.map(e=>{const n=t.yieldByWaferIndex.get(e.waferIndex),m=ee([{label:e.label,dies:e.dies,passBins:e.passBins,yieldPercent:n,key:e.waferIndex}])[0]?.percent;return{item:e,yieldPercent:e.dies.length?m??null:null}}),h=[];for(const{item:e}of a)for(const n of Object.keys(e.wafer?.metadata??{}))!h.includes(n)&&_((e.wafer?.metadata)[n])!==void 0&&h.push(n);const y=t.testDefs.slice(0,WAFER_TEST_COLUMNS),o=(e,n)=>{const m=e.item.statsSummary?.stats.perTestStats?.find(W=>W.testNumber===n.testNumber);if(m)return m.mean;let i=0,C=0;for(const W of e.item.dies){if(!z(W))continue;const R=B(W,n.testNumber);R!==void 0&&Number.isFinite(R)&&(i++,C+=R)}return i?C/i:void 0},r=(e,n)=>_(e.item.wafer?.metadata?.[n])??"",p=e=>({header:F(e,t.attributes),cell:n=>r(n,e)}),f=e=>a.length>1&&a.every(n=>r(n,e)===r(a[0],e)),c=h.filter(f),l=h.filter(e=>!c.includes(e)),u=t.groupLabelText?l.find(e=>F(e,t.attributes)===t.groupLabelText):void 0,g=a.map(e=>e.yieldPercent).filter(e=>e!==null&&Number.isFinite(e)),w=g.length?g.reduce((e,n)=>e+n,0)/g.length:void 0,b=[{header:"Dies",cell:e=>e.item.dies.length,numeric:!0},{header:"Yield-eligible dies",cell:e=>e.item.dies.filter(n=>z(n)).length,numeric:!0},{header:"Yield %",cell:e=>e.yieldPercent===null?"":e.yieldPercent,show:e=>e.yieldPercent===null?"":e.yieldPercent.toFixed(1),numeric:!0,shade:e=>e.yieldPercent===null||w===void 0?void 0:U(e.yieldPercent-w)},...y.map(e=>{const n=new Map,m=K(a.map(i=>o(i,e)??NaN),i=>I(i,e.unit));return a.forEach((i,C)=>n.set(i,m[C])),{header:`${M(e,e.testNumber)}${e.unit?` (${e.unit})`:""} mean`,cell:i=>o(i,e),show:i=>{const C=o(i,e);return C===void 0?"":I(C,e.unit)},numeric:!0,shade:i=>n.get(i)}})],x=[{header:"Wafer",cell:e=>e.item.label},...u?[p(u)]:[],...b,...l.filter(e=>e!==u).map(p)],v=[...x,...c.map(p)],L=x.map(e=>({header:e.header,get:n=>e.show?e.show(n):String(e.cell(n)??""),numeric:e.numeric,...e.shade?{shade:e.shade}:{},...e.numeric?{sortKey:n=>{const m=e.cell(n);return typeof m=="number"?m:void 0}}:{}})),D=P({columns:L,rows:a,ariaLabel:`Wafers (${a.length})`,ownerDocument:d,onRowClick:t.onOpenWafer?e=>t.onOpenWafer(e.item.waferIndex,e.item.label):void 0});D.el.style.maxHeight="70vh",D.el.style.minHeight="120px";const E=()=>v.map(e=>({header:e.header,get:e.cell})),N=t.testDefs.length>y.length?` Mean columns cover the first ${y.length} of ${t.testDefs.length} tests.`:"";let $=D.el;if(c.length){const e=d.createElement("div");e.dataset.wmapWafersSame="1",e.textContent=`Same on every wafer: ${c.map(n=>`${F(n,t.attributes)} ${r(a[0],n)}`).join(" \xB7 ")}`,Object.assign(e.style,{color:S.label,fontSize:k.body,lineHeight:"1.5",marginBottom:T.sm}),$=d.createElement("div"),$.append(e,D.el)}return{el:$,destroy:()=>D.destroy(),actions:{note:()=>`${O(a.length,"wafer")}.${N}${t.onOpenWafer?" Click a row to open that wafer.":""} Export follows the order shown.`,exportCsv:()=>A(E(),D.orderedRows(),"wafers.csv",t.onSaveText,{rowCount:a.length}),copyText:a.length*v.length<=COPY_CELL_LIMIT?()=>H(E(),D.orderedRows()):null}}}function Q(t,d){const s=t.createElement("div");return s.textContent=d,Object.assign(s.style,{color:S.label,fontSize:k.body,padding:T.md}),{el:s,destroy:()=>{}}}function Y(t,d){const s=t.createElement("button");return s.type="button",s.textContent=d,Object.assign(s.style,{fontSize:k.body,padding:"3px 10px",borderRadius:q.control,...ne("outlined"),background:S.menuBg}),G(s),s}function X(t,d,s,a,h,y){const o=t.createElement("div");o.setAttribute("role","radiogroup"),o.setAttribute("aria-label",d),Object.assign(o.style,{display:"inline-flex",background:S.menuBg,border:`1px solid ${S.menuBorder}`,borderRadius:q.control,overflow:"hidden"});const r=[];let p=a;const f=()=>{for(const c of r){const l=c.dataset[h]===p;c.setAttribute("aria-checked",String(l)),c.tabIndex=l?0:-1,Object.assign(c.style,{background:l?S.bgActive:"transparent",color:l?S.iconActive:S.label,fontWeight:l?"600":"400"})}};for(const c of s){const l=t.createElement("button");c.hint&&V(l,c.hint),l.type="button",l.textContent=c.label,l.dataset[h]=c.key,l.setAttribute("role","radio"),Object.assign(l.style,{border:"none",cursor:"pointer",fontSize:k.body,padding:`${T.xs} ${T.md}`,whiteSpace:"nowrap"}),G(l,"bare"),l.addEventListener("click",()=>{p!==c.key&&y(c.key)}),r.push(l),o.appendChild(l)}return f(),o.addEventListener("keydown",c=>{if(c.key!=="ArrowLeft"&&c.key!=="ArrowRight")return;const l=r.indexOf(t.activeElement);if(l<0)return;c.preventDefault();const u=r[(l+(c.key==="ArrowRight"?1:-1)+r.length)%r.length];u.click(),u.focus()}),{el:o,set:c=>{p=c,f()}}}export function renderDataTables(t){const{doc:d}=t,s=d.createElement("div");Object.assign(s.style,{display:"flex",flexDirection:"column",minWidth:"0",minHeight:"0",flex:"1",padding:T.md});const a=t.items.map((g,w)=>({...g,waferIndex:g.waferIndex??w})),h=a.flatMap(g=>g.dies),y=t.testDefs??[],o=y.filter(j),r=t.views??(a.length>1?["statistics","wafers","dies"]:["statistics","dies"]),p=t.population?{populationLabel:`${O(h.length,"die")} ${t.population}`}:a.length>1?{perWaferMetadata:a.map(g=>g.wafer?.metadata??{}),populationLabel:`${O(a.length,"wafer")} pooled`}:{waferMetadata:a[0]?.wafer?.metadata};let f=r.includes(t.view)?t.view:r[0],c="wide",l=null;const u=()=>{l?.destroy(),l=renderDataSection({doc:d,items:a,testDefs:o,allTestDefs:y,ringCount:t.ringCount,yieldByWaferIndex:new Map,onSaveText:t.onSaveText,views:r,view:f,dieListOptions:t.dieListOptions,metadataFields:t.metadataFields,attributes:t.attributes,onLocateDie:t.onLocateDie,population:t.population?{phrase:t.population,fileTag:"selection"}:void 0,buildStatistics:g=>{const w=g.flatMap(L=>L.dies),b=[],x=oe(w,o,void 0,void 0,t.onSaveText,p,g.map(L=>({dies:L.dies})),void 0,"full");x&&b.push(x);const v=se(w,y,void 0,t.onSaveText,p);return v&&b.push(v),{cards:b,destroy:()=>{}}},onViewChange:g=>{f=g,u()},diesLayout:c,onDiesLayoutChange:g=>{c=g}}),s.replaceChildren(l.card)};return u(),{el:s,destroy:()=>l?.destroy()}}export function renderSelectionTables(t){return renderDataTables({...t,views:t.items.length>1?["statistics","wafers","dies"]:["statistics","dies"]})}
|