@wafertools/wafermap 0.40.0 → 0.40.1
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 +14 -0
- package/dist/packages/canvas-adapter/charts/commonality.js +3 -3
- package/dist/packages/canvas-adapter/charts/plotChart.d.ts +5 -2
- package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
- package/dist/packages/canvas-adapter/charts/sweep.js +1 -1
- package/dist/packages/canvas-adapter/dataTab.d.ts +12 -6
- package/dist/packages/canvas-adapter/dataTab.js +1 -1
- package/dist/packages/canvas-adapter/drilldown.d.ts +1 -1
- package/dist/packages/canvas-adapter/drilldown.js +1 -1
- package/dist/packages/canvas-adapter/filterButton.d.ts +2 -0
- package/dist/packages/canvas-adapter/filterButton.js +1 -1
- package/dist/packages/canvas-adapter/identityHeader.js +1 -1
- package/dist/packages/canvas-adapter/insightsTab.d.ts +9 -4
- package/dist/packages/canvas-adapter/insightsTab.js +1 -1
- package/dist/packages/canvas-adapter/openWaferMode.d.ts +7 -0
- package/dist/packages/canvas-adapter/openWaferMode.js +1 -0
- package/dist/packages/canvas-adapter/plotTab.d.ts +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.d.ts +2 -2
- package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
- package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
- package/dist/packages/canvas-adapter/userGuideHtml.js +20 -13
- 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 -1
- package/dist/packages/canvas-adapter/virtualTable.js +1 -1
- package/dist/packages/renderer/buildView.js +1 -1
- package/dist/packages/renderer/fmt.d.ts +2 -0
- package/dist/packages/renderer/fmt.js +1 -1
- package/dist/packages/stats/commonality.d.ts +1 -1
- package/dist/packages/stats/commonality.js +1 -1
- package/dist/packages/stats/examplePicks.js +1 -1
- package/dist/packages/stats/groupEffects.d.ts +8 -0
- package/dist/packages/stats/groupEffects.js +1 -1
- package/dist/packages/stats/plotData.d.ts +7 -2
- package/dist/packages/stats/plotData.js +1 -1
- package/dist/packages/stats/synthesis.d.ts +8 -1
- package/dist/packages/stats/synthesis.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GUIDE_SECTIONS as Ne}from"./guideSections.js";import{hasPosition as nt,isYieldEligibleDie as Mt}from"../core/dies.js";import{DIE_REGIONS as He,DIE_REGION_KEYS as hn,dieRadialPosition as pn}from"./dieRegions.js";import{excludedBy as gn,excludedValue as bn,testValue as it,testsPresent as st}from"../core/dieTable.js";import{limitSetName as yn}from"../renderer/valueFilter.js";import{NEGLIGIBLE_SPREAD as wn,compareNatural as Rt,minOf as De,maxOf as Me}from"../core/utils.js";import{isParametricTest as be,getTestPassStatus as $n}from"../renderer/buildWaferMap.js";import{attributeLabel as gt,facetValueOf as Bt,buildFacetTable as _t,FACET_NONE_VALUE as bt}from"./facets.js";import{yieldCounts as yt}from"./yield.js";import{sameTestName as wt}from"./sweep.js";import{nearest as vn,sameField as Le,plotIssue as xn,plotConditions as Pt,isField as Re,isTestSet as ue,isBinned as Ae,isStatReference as Nn,isPassRateSet as kn,xFieldsOf as ke,PLOT_X_LEVELS as jt,PLOT_FACET_LIMIT as zt,PLOT_BINS_DEFAULT as Sn}from"./plotSpec.js";import{fmtExact as Gt,fmt as qe}from"../renderer/fmt.js";import{parseTestReference as Fn}from"../renderer/derivedTests/parser.js";import{capabilityLimits as Ut}from"./capability.js";import{mean as Ht,median as $t}from"../core/utils.js";import{sampleVariance as Wt,quantile as vt,tQuantileTwoSided as Ln,robustFence as An}from"./math.js";import{pickExamples as On}from"./examplePicks.js";import{compareGroups as Tn,formatP as Vt}from"./groupCompare.js";import{dieTestVerdict as Xt}from"./testPassRate.js";import{pearsonOfPairs as In}from"./correlation.js";import{individualsLimits as Cn,westernElectric as En,CONTROL_RULE_TEXT as Dn}from"./control.js";import{buildCapabilityFigures as Mn}from"./capability.js";import{patTests as Yt,waferPatLimits as Rn,waferPatVerdicts as Bn,PAT_VERDICT_LABEL as _n,PAT_VERDICT_ORDER as Pn,PAT_K as jn}from"./pat.js";function qt(e){if(!e)return;const t={};for(const n of["limitLow","limitHigh","specLow","specHigh"])Number.isFinite(e[n])&&(t[n]=e[n]);return Object.keys(t).length?t:void 0}export function fitLine(e,t,n){const s=e.length;if(s<3)return;let i=0,a=0;for(let p=0;p<s;p++)i+=e[p],a+=t[p];i/=s,a/=s;let l=0,f=0,c=0;for(let p=0;p<s;p++){const d=e[p]-i,u=t[p]-a;l+=d*d,f+=u*u,c+=d*u}if(!(l>0))return;const r=f>0?c*c/(l*f):1,h=n==="linear"||c===0?c/l:(f-l+Math.sqrt((f-l)**2+4*c*c))/(2*c);return{slope:h,intercept:a-h*i,r2:r,n:s}}function ye(e){let t=0;for(const a of e)t+=a.dies.length;const n=new Array(t),s=new Uint32Array(t);let i=0;return e.forEach((a,l)=>{for(const f of a.dies)n[i]=f,s[i++]=l}),{dies:n,item:s}}const Be={wafer:"Wafer",x:"Die X",y:"Die Y",ring:He.ring.label,quadrant:He.quadrant.label,reticleCell:He.reticleCell.label,reticleShot:He.reticleShot.label,hbin:"Hard bin",sbin:"Soft bin",site:"Site",yield:"Yield",dieCount:"Dies",waferOrder:"Wafer order",test:"Test",pat:"PAT",radius:"Radial position",reprobed:"Re-probed"};export function fieldLabel(e,t,n){if(Ae(e))return fieldLabel(e.binned,t,n);if(ue(e))return Un(e,t);if("passRate"in e)return`${t?.find(i=>i.testNumber===e.passRate)?.name||e.name||`Test ${e.passRate}`} pass rate${e.judge==="flag"?" (tester flag)":""}`;if("test"in e){const s=t?.find(a=>a.testNumber===e.test),i=s?.name||e.name||`Test ${e.test}`;return s!==void 0&&!be(s)?`${i} (pass/fail)`:i}return"builtin"in e?Be[e.builtin]??String(e.builtin):"meta"in e&&typeof e.meta=="string"?gt(e.meta,n):"Unknown field"}function Oe(e,t,n){if(Ae(e)){const s=Qt.get(e);return s?s.filter(i=>t.includes(i)):[...t].sort((i,a)=>parseFloat(i)-parseFloat(a))}return"builtin"in e&&(e.builtin==="wafer"||e.builtin==="test")?[...t]:"builtin"in e&&e.builtin==="pat"?Pn.filter(s=>t.includes(s)):Kt(t,n)}const Kt=(e,t)=>t?[...e].sort((n,s)=>(Number(n)||0)-(Number(s)||0)):[...e].sort(Rt);export function orderFieldValues(e){return Kt(e,e.every(t=>t===bt||xt.test(t.trim())))}const We=e=>!!e.num&&(e.kind==="numeric"||"meta"in e.field),zn=e=>`Bin ${e}`;export function binOfLabel(e){const t=/^Bin (-?\d+)$/.exec(e);return t?Number(t[1]):void 0}const fe=e=>e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`,Gn=e=>!!e&&"builtin"in e&&e.builtin==="pat",Te=e=>!!e&&"builtin"in e&&e.builtin==="test";function Un(e,t){const{tests:n}=expandTestSet(e,t??[]),s=i=>t?.find(a=>a.testNumber===i)?.name||e.names?.[String(i)]||`Test ${i}`;return e.passRate?e.judge==="flag"?"Pass rate (tester flag)":"Pass rate":n.length===0?e.tests.length===1?`Tests ${e.tests[0]}`:`${e.tests.length} test entries`:n.length>3?`${n.length} tests`:fe(n.map(s))}export function passKindOf(e,t){return be(e)?t==="flag"?"testFlag":"spec":"functional"}export function expandTestSet(e,t){const n=new Map(t.map(a=>[a.testNumber,a])),s=[],i=[];for(const a of e.tests){if(typeof a=="number"){s.includes(a)||s.push(a);continue}const l=Fn(String(a),n);if(!l.ok){i.push(`"${a}": ${l.message}`);continue}for(const f of l.tests)s.includes(f)||s.push(f)}return{tests:s,problems:i}}export function withTestSetNames(e,t){const n={};for(const a of expandTestSet(e,t).tests){const l=t.find(f=>f.testNumber===a)?.name;l&&(n[String(a)]=l)}const{names:s,...i}=e;return Object.keys(n).length?{...i,names:n}:i}export const TEST_SET_VALUE_LIMIT=4e6;const xt=/^[+-]?(?:\d+\.?\d*|\.\d+)$/;export function binEdges(e,t,n){const s=Array.from(e).filter(Number.isFinite).sort((f,c)=>f-c);if(s.length===0)return[];const i=s[0],a=s[s.length-1],l=[];for(let f=1;f<t;f++)l.push(n==="width"?i+(a-i)*f/t:vt(s,f/t));return l.filter((f,c)=>f>i&&f<=a&&(c===0||f>l[c-1]))}const Zt=(e,t)=>{let n=0,s=t.length;for(;n<s;){const i=n+s>>1;e>=t[i]?n=i+1:s=i}return n};function Hn(e,t,n,s){const i=[t,...e,n],a=f=>f.every((c,r)=>r===0||c!==f[r-1]);let l=s?i.map(f=>qe(f,s)):[];if(!a(l)||l.length===0){const f=s==="%"?"%":s?` ${s}`:"";for(let c=3;c<=15&&(l=i.map(r=>`${Number(r.toPrecision(c))}${f}`),!a(l));c++);}return i.slice(0,-1).map((f,c)=>`${l[c]} to ${l[c+1]}`)}const Qt=new WeakMap;function Wn(e,t,n){const{ctx:s}=t,i=J(e.binned,t),a=i.label;if(i.issue)return{...i,...n,label:a,kind:"categorical",num:void 0,issue:i.issue};if(!i.num)return{...i,...n,label:a,kind:"categorical",issue:`${i.label} is already a category: only a measured value or a number can be put into ranges`};const l=e.bins??Sn,f=e.by??"count",c=`${JSON.stringify(e)}`;let r=s.binEdges?.get(c),h=i.num;if(!r){if(s.wholeItems&&s.wholeItems!==t.items){const k=J(e.binned,{items:s.wholeItems,rows:ye(s.wholeItems),ctx:{...s,wholeItems:void 0}});k.num&&(h=k.num)}r=binEdges(h,l,f),s.binEdges?.set(c,r)}let p=1/0,d=-1/0;for(let k=0;k<h.length;k++){const w=h[k];Number.isFinite(w)&&(w<p&&(p=w),w>d&&(d=w))}if(p===1/0)return{...i,...n,label:a,kind:"categorical",num:void 0,issue:`${i.label} has no values to put into ranges`};const u=Hn(r,p,d,i.unit);Qt.set(e,u);const g=Array.from(i.num,k=>Number.isFinite(k)?u[Zt(k,r)]:void 0),v=u.map((k,w)=>((w===0?p:r[w-1])+(w===u.length-1?d:r[w]))/2),b=Float64Array.from(i.num,k=>Number.isFinite(k)?v[Zt(k,r)]:NaN);return{...n,label:a,unit:void 0,level:i.level,kind:"categorical",cat:g,mid:b,midUnit:i.unit}}function Jt(e,t){const n=new Float64Array(e),s=new Float64Array(e),i=new Int8Array(e);for(let a=0;a<e;a++){const l=t(a);n[a]=l===void 0?NaN:l==="pass"?100:0,s[a]=l===void 0?0:1,i[a]=l==="failLow"?-1:l==="failHigh"?1:0}return{num:n,weights:s,failSide:i}}function J(e,t){const{items:n,rows:s,ctx:i}=t,a=fieldLabel(e,i.testDefs,i.curation),l={field:e,label:a},f=s.dies.length,c=n.length;if(Ae(e))return Wn(e,t,l);if(ue(e)){const r=t.melt;if(!r)return{...l,level:"die",kind:"numeric",issue:"A set of tests can only be the values of a box, bar, line or histogram"};if(e.passRate){const d=r.tests.map(b=>i.testDefs?.find(k=>k.testNumber===b)),{num:u,weights:g,failSide:v}=Jt(f,b=>{const k=d[r.testOf[s.item[b]]];return Xt(s.dies[b],k,passKindOf(k,e.judge))});return{...l,level:"die",kind:"numeric",unit:"%",num:u,weights:g,failSide:v,perDie:!0,labelOf:b=>r.labels[r.testOf[b]]}}const h=new Float64Array(f);for(let d=0;d<f;d++)h[d]=it(s.dies[d],r.tests[r.testOf[s.item[d]]])??NaN;const p=new Set(r.tests.map(d=>i.testDefs?.find(u=>u.testNumber===d)?.unit).filter(d=>!!d));return{...l,level:"die",kind:"numeric",unit:p.size===1?[...p][0]:void 0,num:h,labelOf:d=>r.labels[r.testOf[d]]}}if("passRate"in e){const r=e.passRate,h=i.testDefs?.find(v=>v.testNumber===r);if(!h)return{...l,level:"die",kind:"numeric",issue:`Needs test ${r}${e.name?` (${e.name})`:""}, which is not in these dies`};if(e.name&&h.name&&!wt(e.name,h.name))return{...l,level:"die",kind:"numeric",issue:kt(r,e.name,h.name)};const p=passKindOf(h,e.judge);if(p==="spec"&&h.limitLow===void 0&&h.limitHigh===void 0)return{...l,level:"die",kind:"numeric",issue:`${h.name||`Test ${r}`} has no test limits to judge a pass by`};const{num:d,weights:u,failSide:g}=Jt(f,v=>Xt(s.dies[v],h,p));return{...l,level:"die",kind:"numeric",unit:"%",num:d,weights:u,failSide:g,perDie:!0}}if("test"in e){const r=i.testDefs?.find(d=>d.testNumber===e.test);if(r===void 0){if(t.present??=new Set(s.dies.length?st(s.dies,"values"):[]),!t.present.has(e.test))return{...l,level:"die",kind:"numeric",issue:`Needs test ${e.test}${e.name?` (${e.name})`:""}, which is not in these dies`}}else if(e.name&&r.name&&!wt(e.name,r.name))return{...l,level:"die",kind:"numeric",unit:r.unit,issue:kt(e.test,e.name,r.name)};if(r!==void 0&&!be(r)){const d=s.dies.map(u=>{const g=$n(u,e.test,r);return g===void 0?void 0:g?"Pass":"Fail"});return{...l,level:"die",kind:"categorical",cat:d}}const h=new Float64Array(f);for(let d=0;d<f;d++)h[d]=it(s.dies[d],e.test)??NaN;let p=qt(r);if(n.length===1&&!t.melt&&r){const d=n[0],u=Rn(d.allDies??d.dies,i.testDefs??[],d.passBins).limits.get(e.test);u&&(p={...p,patLow:u.lo,patHigh:u.hi})}return{...l,level:"die",kind:"numeric",unit:r?.unit,num:h,limits:p}}if("meta"in e){const r=n.map(d=>Bt(d.metadata,e.meta,i.curation));if(r.every(d=>d===void 0)){const d=[...new Set(n.flatMap(v=>Object.keys(v.metadata??{})))].sort(),u=vn(e.meta,d),g=d.length?` Wafer fields in these dies: ${d.slice(0,12).join(", ")}${d.length>12?`, and ${d.length-12} more`:""}.`:" These dies have no wafer fields.";return{...l,level:"wafer",kind:"categorical",cat:r,issue:`No wafer has a "${a}" value.${u?` Did you mean "${u}"?`:""}${g}`}}const h=r.map(d=>d===void 0||!xt.test(d.trim())?NaN:Number(d)),p=r.every((d,u)=>d===void 0||Number.isFinite(h[u]));return{...l,level:"wafer",kind:p?"numeric":"categorical",cat:r,num:p?Float64Array.from(h):void 0}}switch(e.builtin){case"wafer":return{...l,level:"wafer",kind:"categorical",cat:n.map(r=>r.label)};case"waferOrder":return{...l,level:"wafer",kind:"numeric",num:Float64Array.from(n,(r,h)=>(t.melt?t.melt.realOf[h]:h)+1)};case"test":return t.melt?{...l,level:"wafer",kind:"categorical",cat:n.map((r,h)=>t.melt.labels[t.melt.testOf[h]])}:{...l,level:"wafer",kind:"categorical",issue:"Test divides a set of tests: choose several tests as the values"};case"dieCount":return{...l,level:"wafer",kind:"numeric",num:Float64Array.from(n,r=>r.dies.length)};case"yield":{const r=new Float64Array(c),h=new Float64Array(c);return n.forEach((p,d)=>{const{pass:u,total:g}=yt(p.dies,p.passBins);r[d]=g>0?u/g*100:NaN,h[d]=g}),{...l,level:"wafer",kind:"numeric",unit:"%",num:r,weights:h}}case"x":case"y":{const r=new Float64Array(f);for(let h=0;h<f;h++){const p=s.dies[h];r[h]=nt(p)?e.builtin==="x"?p.x:p.y:NaN}return{...l,level:"die",kind:"numeric",num:r}}case"hbin":case"sbin":{const r=s.dies.map(h=>{const p=e.builtin==="hbin"?h.hbin:h.sbin;return p===void 0?void 0:zn(p)});return{...l,level:"die",kind:"categorical",cat:r}}case"site":return{...l,level:"die",kind:"categorical",cat:s.dies.map(r=>r.siteNum===void 0?void 0:`Site ${r.siteNum}`)};case"reprobed":return{...l,level:"die",kind:"numeric",unit:"%",num:Float64Array.from(s.dies,r=>r.retestCount!==void 0?100:0)};case"radius":{const r=new Float64Array(f);for(let h=0;h<f;h++){const p=pn(s.dies[h],{wafer:n[s.item[h]].wafer});r[h]=p===void 0?NaN:p*100}return{...l,level:"die",kind:"numeric",unit:"%",num:r}}case"pat":{const r=i.testDefs??[];if(Yt(r).length===0)return{...l,level:"die",kind:"categorical",issue:"PAT needs tests with both a low and a high limit"};const h=new Map,p=s.dies.map((d,u)=>{const g=n[s.item[u]];let v=h.get(g);if(!v){const b=g.allDies??g.dies,k=Bn(b,r,g.passBins);v=new Map(b.map((w,S)=>[w,k[S].verdict?_n[k[S].verdict]:void 0])),h.set(g,v)}return v.get(d)});return{...l,level:"die",kind:"categorical",cat:p}}case"ring":case"quadrant":case"reticleCell":case"reticleShot":{const r=He[e.builtin],h=s.dies.map((p,d)=>{const u=n[s.item[d]];return r.valueOf(p,{wafer:u.wafer,ringCount:u.ringCount})});return{...l,level:"die",kind:"categorical",cat:h}}default:return{...l,level:"die",kind:"categorical",issue:"Needs a newer version of this tool"}}}function Vn(e,t){const n=e.rows.dies.length,s=new Float64Array(n),i=new Float64Array(n);for(let a=0;a<n;a++){const l=e.items[e.rows.item[a]],{pass:f,total:c}=yt([e.rows.dies[a]],l.passBins);s[a]=c>0?f*100:NaN,i[a]=c}return{...t,level:"die",num:s,weights:i,perDie:!0}}export const probabilityPosition=(e,t)=>(e+.5)/t;export function combine(e,t){const n=e.filter(Number.isFinite);if(t==="count")return n.length;if(n.length===0)return NaN;switch(t){case"sum":return n.reduce((s,i)=>s+i,0);case"min":return De(n);case"max":return Me(n);case"median":{const s=[...n].sort((a,l)=>a-l),i=s.length>>1;return s.length%2?s[i]:(s[i-1]+s[i])/2}default:return n.reduce((s,i)=>s+i,0)/n.length}}const Nt={mean:"a mean",median:"a median",min:"a minimum",max:"a maximum",sum:"a sum",count:"a count",yield:"a pooled yield"},Ke={mean:"Mean",median:"Median",min:"Min",max:"Max",sum:"Sum",count:"Count",yield:"Pooled yield"};function ce(e,t,n,s,i,a){const l=s.axes?.[e]??{};let f=l.scale??"linear";if(f==="log"){for(const c of i)if(Number.isFinite(c)&&c<=0){f="linear",a.push(`The ${e.toUpperCase()} axis stays linear: a log axis needs every value above zero`);break}}return{label:l.label??t,unit:n,scale:f,min:l.min,max:l.max,reverse:l.reverse}}const en=e=>/^[A-Z][a-z]*(?: [a-z]+)*$/.test(e)?e.toLowerCase():e,tn=(e,t,n)=>n?`${e} by range of ${t}`:`${e} over ${t}`;function Xn(e,t){const{chart:n}=e,s=e.fields??{},i=ke(s.x),a=i.filter(c=>!Te(c)),l=i.length?a.length?fe(a.map(c=>fieldLabel(c,t.testDefs,t.curation))):void 0:(n==="box"||n==="bar")&&!ue(s.y)?"Wafer":void 0,f=s.y?fieldLabel(s.y,t.testDefs,t.curation):void 0;if((n==="box"||n==="bar")&&f&&!l)return f;switch(n){case"scatter":return l&&f?`${f} vs ${l}`:"Scatter";case"histogram":return f??(i[0]?fieldLabel(i[0],t.testDefs,t.curation):void 0)??"Histogram";case"probability":return f?`${f}, cumulative`:"Probability plot";case"control":return f?`${f} control chart`:"Control chart";case"goal":return"Capability goal plot";case"line":return l&&f?tn(f,l,i.length===1&&Ae(i[0])):"Line";case"box":return f&&l?`${f} by ${l}`:"Box";case"bar":return l?f?`${f} by ${l}`:`Dies by ${l}`:"Bar";default:return""}}function _e(e,t,n,s={}){return{spec:e,issues:n,notes:[],level:"die",autoTitle:Xn(e,s),groups:[""],population:{wafers:t.length,dies:t.reduce((i,a)=>i+a.dies.length,0)},plotted:0,omitted:[]}}export function combinationIssue(e,t,n={}){const s=[t.x,n.continuousColor?void 0:t.color].filter(c=>!!c&&c.level==="die"),i=!!t.y&&t.y.yield&&t.y.level==="wafer",a=(e==="bar"||e==="line")&&(n.aggregate===void 0||n.aggregate==="yield"||n.aggregate==="mean");if(i&&s.length&&!a)return{long:`${t.y.label} is one figure per wafer, and ${s[0].label} belongs to dies, so a ${e} of it cannot be split by ${s[0].label}. A bar chart of yield can (pooled yield per ${s[0].label.toLowerCase()}), or plot a measured value instead`,short:`${t.y.label} is per wafer: use a bar or line chart`};const l=[t.x,t.y].filter(c=>!!c);let f=n.level??(l.some(c=>c.level==="die")?"die":"wafer");if(e==="bar"&&!t.y&&s.length&&(f="die"),t.color?.level==="die"&&f==="wafer"&&!n.continuousColor&&!(i&&(e==="bar"||e==="line")))return{long:`${t.color.label} is per die, so it cannot colour a plot with one mark per wafer. Plot a measured value (one mark per die), or make a bar chart of yield, which can be split by ${t.color.label.toLowerCase()}`,short:`${t.color.label} is per die: this plot has one mark per wafer`}}function kt(e,t,n){return`Test ${e} was "${t}" when this plot was saved; in these dies it is "${n}". Choose the test again to plot "${n}"`}const Yn={limits:"position in limits",zscore:"z-score",robust:"robust z-score"};function qn(e,t){return e==="limits"?`rescaled to ${t.size===1?t.has("spec")?"spec limits":"test limits":"spec limits, or test limits where a test has no spec"}: 0 is the low limit, 1 the high`:e==="zscore"?"rescaled per test: standard deviations from the mean of the values in view":"rescaled per test: robust standard deviations (1.4826 \xD7 median absolute deviation) from the median of the values in view"}function nn(e,t,n,s,i){const a=new Map,l=[],f=new Set;for(const c of e){if(s==="limits"){const d=n.find(g=>g.testNumber===c),u=d&&Ut(d);if(!u){l.push(`${i(c)} has no low and high limit to place it by`);continue}f.add(u.basis),a.set(c,{offset:u.lsl,scale:u.usl-u.lsl});continue}const r=[];for(const d of t){const u=it(d,c);u!==void 0&&Number.isFinite(u)&&r.push(u)}if(r.length<2){l.push(`${i(c)} has fewer than two values to measure a spread in`);continue}let h,p;if(s==="zscore"?(h=Ht(r),p=Math.sqrt(Wt(r,h))):(h=$t(r),p=1.4826*$t(r.map(d=>Math.abs(d-h)))),!(p>0)||!Number.isFinite(p)){l.push(`${i(c)} has no spread: its values ${s==="robust"?"are mostly":"are all"} the same`);continue}a.set(c,{offset:h,scale:p})}return{scales:a,dropped:l,bases:f}}function Kn(e,t,n){const s={};for(const i of["limitLow","limitHigh","specLow","specHigh","patLow","patHigh"]){let a,l=!0;for(const f of e){const c=t(f)?.[i],r=n.get(f);if(c===void 0||!Number.isFinite(c)||!r){l=!1;break}const h=(c-r.offset)/r.scale;if(a===void 0)a=h;else if(Math.abs(h-a)>1e-9*Math.max(1,Math.abs(a))){l=!1;break}}l&&a!==void 0&&(s[i]=a)}return Object.keys(s).length?s:void 0}function sn(e,t){let n;switch(e.type){case"scatter":n=e.points.map(i=>t==="x"?i.x:i.y);break;case"histogram":case"probability":n=t==="x"?e.values.flat():[];break;case"box":n=t==="y"?e.cells.flat(2):[];break;case"bar":n=t==="y"?e.values.flat():[];break;case"line":n=t==="x"?e.xs:[...e.values.flat(),...e.band?[...e.band.lo.flat(),...e.band.hi.flat()]:[]];break;case"control":n=t==="x"?e.xs:[...e.values,e.limits.ucl,e.limits.lcl];break;case"goal":n=e.points.map(i=>t==="x"?i.x:i.y);break;case"heatmap":n=[];break}const s=n.filter(Number.isFinite);return s.length?[De(s),Me(s)]:void 0}function Zn(e,t,n){if(e.issues.length||!e.marks)return e;const s=e.groups.map(f=>n.groups.indexOf(f));if(s.some(f=>f<0))return e;const i=an(e.marks,t,s,n.groups.length),a=n.marks&&sn(n.marks,"x"),l=n.marks&&sn(n.marks,"y");return{...e,marks:i,groups:n.groups,colorScale:n.colorScale??e.colorScale,x:e.x&&a?{...e.x,extent:a}:e.x,y:e.y&&l?{...e.y,extent:l}:e.y}}function Qn(e,t){return e.issues.length||!e.marks?e:{...e,marks:an(e.marks,t,e.groups.map((n,s)=>s),e.groups.length)}}function an(e,t,n,s){const i=(c,r)=>{const h=Array.from({length:s},r);return c.forEach((p,d)=>{h[n[d]]=p}),h},a=c=>t[c],l=c=>r=>{const h=c(r);return{...h,item:a(h.item)}};let f;switch(e.type){case"scatter":f={type:"scatter",points:e.points.map(c=>({...c,item:a(c.item),group:n[c.group]}))};break;case"histogram":f={type:"histogram",values:i(e.values,()=>[]),units:i(e.units,()=>[]),unit:l(e.unit)};break;case"probability":f={type:"probability",values:i(e.values,()=>[]),units:i(e.units,()=>[]),unit:l(e.unit)};break;case"box":case"bar":f={...e,cells:i(e.cells,()=>e.categories.map(()=>[])),cellUnits:i(e.cellUnits,()=>e.categories.map(()=>[])),values:i(e.values,()=>e.categories.map(()=>NaN)),categoryItems:e.categoryItems?.map(c=>c>=0?a(c):c),unit:l(e.unit)};break;case"line":f={...e,values:i(e.values,()=>e.xs.map(()=>NaN)),counts:i(e.counts,()=>e.xs.map(()=>0)),cellUnits:i(e.cellUnits,()=>e.xs.map(()=>[])),unit:l(e.unit),...e.band?{band:{lo:i(e.band.lo,()=>e.xs.map(()=>NaN)),hi:i(e.band.hi,()=>e.xs.map(()=>NaN))}}:{}};break;case"control":f={...e,items:e.items.map(a)};break;case"goal":f={type:"goal",points:e.points.map(c=>({...c,group:n[c.group]}))};break;case"heatmap":f={...e,unit:l(e.unit)};break}return f}function Jn(e,t,n){let s=0,i=0;const a=t.map(f=>{let c;for(let r=0;r<f.dies.length;r++){const h=f.dies[r];if(Mt(h)){c?.push(h);continue}c??=f.dies.slice(0,r),h.partial?s++:i++}return c?{...f,dies:c,allDies:f.allDies??f.dies}:f}),l=ei(resolvePlot(e,a,{...n,eligibleOnly:!0}));return s+i>0?{...l,leftOut:{partial:s,edge:i}}:l}export const axisValues=(e,t)=>e.marks?St(e.marks,t).filter(Number.isFinite):[];function St(e,t){switch(e.type){case"bar":return t==="y"?e.values.flat():[];case"box":return t==="y"?e.cells.flat(2):[];case"scatter":return e.points.map(n=>t==="x"?n.x:n.y);case"line":return t==="y"?e.values.flat():e.xs;case"control":return t==="y"?e.values:e.xs;case"histogram":case"probability":return t==="x"?e.values.flat():[];default:return[]}}function ei(e){const t=[],n=p=>{const d=e.spec.axes?.[p]?.references;if(!d?.length||!e[p])return;let u;return d.flatMap(g=>Nn(g)?(u??=e.marks?St(e.marks,p).filter(Number.isFinite):[],u.length===0?(t.push(`No ${g.stat} line: nothing is drawn along that axis`),[]):[{at:g.stat==="median"?$t(u):Ht(u),label:g.label??g.stat}]):[g])},s=p=>{if(!e.spec.axes?.[p]?.clip||!e[p]||!e.marks)return;const d=St(e.marks,p).filter(Number.isFinite),u=An(d);if(!u||d.length===0)return;const g=Math.max(De(d),u.lo),v=Math.min(Me(d),u.hi);if(!(v>g))return;const b=d.reduce((k,w)=>k+(w<g||w>v?1:0),0);return{lo:g,hi:v,outside:b}},i=n("x"),a=n("y"),l=s("x"),f=s("y");if(!i&&!a&&!l&&!f)return e;const c=(p,d,u)=>p&&(d||u)?{...p,...d?{references:d}:{},...u?{clip:u}:{}}:p,r=p=>({...p,x:c(p.x,i,l),y:c(p.y,a,f)}),h=r(e);h.facets&&(h.facets=h.facets.map(p=>({...p,plot:r(p.plot)})));for(const p of[l,f])p?.outside&&t.push(`Axis clipped to the robust range: ${p.outside.toLocaleString("en-GB")} value${p.outside===1?"":"s"} outside it, still counted in every statistic`);return t.length?{...h,notes:[...h.notes,...t]}:h}export function conditionUnit(e,t){if(Re(e)&&"test"in e)return t?.find(n=>n.testNumber===e.test)?.unit;if(Re(e)&&"builtin"in e&&(e.builtin==="yield"||e.builtin==="radius"))return"%"}const on=(e,t)=>{const n=String(Number(e.toPrecision(6)));return t==="%"?`${n}%`:t?qe(e,t):n};export function conditionText(e,t,n){const s=fieldLabel(e.field,t,n);if(e.values){const f=e.values.length<2?e.values.join(""):`${e.values.slice(0,-1).join(", ")} or ${e.values[e.values.length-1]}`;return`${s} is ${e.not?"not ":""}${f}`}const i=conditionUnit(e.field,t),a=e.min!==void 0?on(e.min,i):void 0,l=e.max!==void 0?on(e.max,i):void 0;return a!==void 0&&l!==void 0?`${s} ${e.not?"outside":"from"} ${a} to ${l}`:a!==void 0?`${s} ${e.not?"below":"at least"} ${a}`:`${s} ${e.not?"above":"at most"} ${l}`}export function applyConditions(e,t,n={}){const s=ye(t),i=s.dies.length,a={items:[...t],index:t.map((v,b)=>b),said:"",dies:{kept:i,total:i},wafers:{kept:t.length,total:t.length}};if(e.length===0)return a;const l=new Uint8Array(t.length).fill(1),f=new Uint8Array(i).fill(1),c=[],r=[];for(const v of e){const b=J(v.field,{items:t,rows:s,ctx:n});if(b.issue)return{...a,issue:b.issue};let k;if(v.values){if(!b.cat)return{...a,issue:`${b.label} is a number: keep a range of it, not values`};const S=new Set(v.values),_=b.cat;k=M=>_[M]!==void 0&&S.has(_[M])!==!!v.not}else{if(!b.num)return{...a,issue:`${b.label} is a category: keep some of its values, not a range`};const S=b.num,_=v.min??-1/0,M=v.max??1/0;k=z=>Number.isFinite(S[z])&&(S[z]>=_&&S[z]<=M)!=!!v.not}const w=b.level==="wafer"?l:f;for(let S=0;S<w.length;S++)w[S]&&!k(S)&&(w[S]=0);(b.level==="wafer"?c:r).push(conditionText(v,n.testDefs,n.curation))}const h=t.map(()=>[]);let p=0;for(let v=0;v<i;v++)f[v]&&l[s.item[v]]&&(h[s.item[v]].push(s.dies[v]),p++);const d=[],u=[];t.forEach((v,b)=>{if(l[b]){if(r.length===0){d.push(v),u.push(b);return}h[b].length&&(d.push({...v,dies:h[b],allDies:v.allDies??v.dies}),u.push(b))}});const g=[c.length?`only wafers where ${fe(c)}`:"",r.length?`only dies where ${fe(r)}`:""].filter(Boolean).join("; ");return{items:d,index:u,said:g,dies:{kept:p,total:i},wafers:{kept:d.length,total:t.length}}}function ti(e,t,n){const s=(...l)=>_e(e,t,l,n),i=applyConditions(Pt(e),t,n);return i.issue?s(i.issue):i.items.length===0?s(`Nothing is left: no ${i.said.replace(/^only /,"").replace(/; only /," and ")}`):{...Qn(resolvePlot(e,i.items,{...n,whereApplied:!0}),i.index),filterNote:i.said}}function ni(e,t,n){const s=e.fields.facet,{facet:i,...a}=e.fields,l={...e,fields:a},f=(...w)=>_e(e,t,w,n),c=fieldLabel(s,n.testDefs,n.curation),r=t.flatMap(w=>w.dies),h={...n,inFacet:!0,scaleDies:n.scaleDies??r,wholeWafers:n.wholeWafers??t.length,wholeItems:n.wholeItems??t,binEdges:n.binEdges??new Map},p=Te(s);if(p&&!ue(e.fields?.y))return f("Test panels need several tests as the values");if(p&&(ke(e.fields?.x).some(Te)||Te(e.fields?.color)))return f("Test already divides the panels, so it cannot also be on the X axis or the colour");if(ke(e.fields?.x).some(w=>Le(w,s))||e.fields?.color&&Re(e.fields.color)&&Le(e.fields.color,s))return f(`${c} divides the panels, so on the X axis or the colour as well it would have one value per panel`);const d=resolvePlot(l,t,p?{...h,facetByTest:!0}:h),u=w=>({...w,autoTitle:`${w.autoTitle} \xB7 panels by ${c}`});if(d.issues.length||!d.marks)return u(d);let g=[];const v=[];if(p){const w=d.setTests;if(!w)return f("Test panels need several tests as the values");const S=t.map((_,M)=>M);g=w.tests.map((_,M)=>({label:w.labels[M],items:[...t],index:S,spec:{...l,fields:{...a,y:{test:_,...n.testDefs?.find(z=>z.testNumber===_)?.name?{name:n.testDefs.find(z=>z.testNumber===_).name}:{}}}}}))}else{const w=ye(t),S=J(s,{items:t,rows:w,ctx:n});if(S.issue)return f(S.issue);if(!S.cat)return f(`${c} is continuous: panels need a category, such as split, ring or site`);if(S.level==="die"&&d.level==="wafer")return f(`${c} is per die, so it cannot divide a plot with one mark per wafer into panels`);const _=[];for(const P of S.cat)P!==void 0&&!_.includes(P)&&_.push(P);const M=Oe(s,_,We(S));if(M.length>zt)return f(`${c} has ${M.length} values, and a plot draws at most ${zt} panels: choose a field with fewer, or narrow Show`);const z=S.cat.filter(P=>P===void 0).length;z&&v.push(`${z.toLocaleString("en-GB")} ${S.level==="die"?"dies":"wafers"} with no ${c} value are in no panel`),g=M.map(P=>{const Z=[],ee=[];if(S.level==="wafer")t.forEach((B,O)=>{S.cat[O]===P&&(Z.push(B),ee.push(O))});else{const B=t.map(()=>[]);for(let O=0;O<w.dies.length;O++)S.cat[O]===P&&B[w.item[O]].push(w.dies[O]);t.forEach((O,o)=>{B[o].length&&(Z.push({...O,dies:B[o],allDies:O.allDies??O.dies}),ee.push(o))})}return{label:P,items:Z,index:ee,spec:l}})}const b=g.map(w=>({label:w.label,plot:Zn(resolvePlot(w.spec,w.items,h),w.index,d)})),k=d.usesPat||Gn(s)||b.some(w=>w.plot.usesPat);return{...u(d),notes:[...d.notes,...v],facets:b,facetLabel:c,...k?{usesPat:!0}:{}}}function ii(e,t,n,s){if(s.normalize==="zscore"||s.normalize==="robust"){const c=Math.max(Math.abs(De(n)),Math.abs(Me(n)));if(c>0)return{label:e,unit:t,lo:-c,hi:c,diverging:!0}}if(ai(s))return{label:e,unit:t,lo:si,hi:100,rating:!0};let i=De(n),a=Me(n);const l=(i+a)/2,f=Math.abs(l)*wn;return l!==0&&a-i<f&&(i=l-f/2,a=l+f/2),{label:e,unit:t,lo:i,hi:a,...n.every(Number.isInteger)?{integer:!0}:{}}}const si=50;function ai(e){const t=e.fields?.y;return e.aggregate==="yield"?!0:t?"builtin"in t&&t.builtin==="yield"||"passRate"in t:!1}function oi(e,t,n){const s=e.fields??{},i=(...M)=>_e(e,t,M,n),a=ke(s.x)[0]??{builtin:"wafer"},l=s.rows??(ue(s.y)?{builtin:"test"}:void 0);if(!l)return i("Choose a field for the rows: a heatmap has one row per value of it");if(Le(l,a))return i("The rows and the columns need two different fields");const{rows:f,...c}=s,r={...e,chart:"bar",fields:{...c,x:[l,a],color:{none:!0}}};delete r.stack,delete r.sort,delete r.top,delete r.cumulative;const h=resolvePlot(r,t,{...n,asHeatmap:!0,inFacet:!0,whereApplied:n.whereApplied});if(h.issues.length||!h.marks||h.marks.type!=="bar")return{...h,spec:e};const p=h.marks,d=p.nest?.parts??[],u=[...new Set(d.map(M=>M[0]))],g=[...new Set(d.map(M=>M[1]))];let v=Oe(a,g,g.every(M=>xt.test(M)));if("builtin"in a&&a.builtin==="wafer"&&n.groupBy){const M=new Map(t.map(P=>[P.label,Bt(P.metadata,n.groupBy,n.curation)??""])),z=Oe({meta:n.groupBy},[...new Set(v.map(P=>M.get(P)??""))],!1);v=[...v].sort((P,Z)=>z.indexOf(M.get(P)??"")-z.indexOf(M.get(Z)??""))}const b=u.map(()=>v.map(()=>NaN)),k=u.map(()=>v.map(()=>[]));d.forEach((M,z)=>{const P=u.indexOf(M[0]),Z=v.indexOf(M[1]);b[P][Z]=p.values[0][z],k[P][Z]=p.cellUnits[0][z]});const w=b.flat().filter(Number.isFinite),S=fieldLabel(l,n.testDefs,n.curation),_=fieldLabel(a,n.testDefs,n.curation);return{...h,spec:e,marks:{type:"heatmap",rows:u,cols:v,values:b,cellUnits:k,unit:p.unit},autoTitle:`${h.y?.label??"Dies"} by ${S} and ${_}`,x:{label:e.axes?.x?.label??_,scale:"linear"},y:{label:e.axes?.y?.label??S,scale:"linear"},colorScale:w.length?ii(h.y?.label??"Count",h.y?.unit,w,e):void 0,groups:[""]}}function ri(e,t,n){const s=(...o)=>_e(e,t,o,n),i=e.fields??{};if(!i.y)return s("Choose a field for the values");if(ue(i.y))return s("A control chart follows one value: choose one test");const a=ke(i.x)[0]??{builtin:"waferOrder"},l=ye(t),f={items:t,rows:l,ctx:n},c=J(a,f),r=J(i.y,f),h=c.issue??r.issue;if(h)return s(h);if(c.level!=="wafer"||!c.num)return s(`A control chart runs along a wafer field with a number per wafer, such as wafer order or slot, not ${c.label}`);if(!r.num)return s(`${r.label} is a category, not a number, so it cannot be charted`);const p=e.aggregate&&e.aggregate!=="yield"&&e.aggregate!=="count"?e.aggregate:"mean",d=t.map(()=>[]);if(r.level==="die")for(let o=0;o<l.dies.length;o++)d[l.item[o]].push(r.num[o]);const u=o=>r.level==="wafer"?r.num[o]:combine(d[o],r.perDie?"mean":p),g=t.map((o,G)=>G).filter(o=>Number.isFinite(c.num[o])&&Number.isFinite(u(o))).sort((o,G)=>c.num[o]-c.num[G]||o-G),v=t.length-g.length;if(g.length<3)return s("A control chart needs at least three wafers with a value");const b=g.map(u),k=g.map(o=>c.num[o]),w=Cn(b,e.baseline),S=En(b,w),_=r.perDie||r.level==="wafer"?r.label:`${Ke[p]} ${r.label}`,M=[];let z=[""],P,Z;const ee=i.color,B=ee===void 0||"none"in ee?void 0:"follow"in ee?n.groupBy?{meta:n.groupBy}:void 0:ee;if(B){const o=J(B,f);if(o.issue)M.push(o.issue);else if(o.level!=="wafer"||!o.cat)M.push(`The points are coloured by a wafer field: ${o.label} is not one, so they are not coloured`);else{const G=[];for(const te of g){const D=o.cat[te];D!==void 0&&!G.includes(D)&&G.push(D)}z=Oe(B,G,We(o)),P=g.map(te=>o.cat[te]===void 0?-1:z.indexOf(o.cat[te])),Z=o.label}}const O=S.length?`${S.length} point${S.length===1?"":"s"} break${S.length===1?"s":""} a Western Electric rule (${[...new Set(S.flatMap(o=>o.rules))].sort().map(o=>`${o}: ${Dn[o]}`).join("; ")})`:"no point breaks a Western Electric rule";return{spec:e,issues:[],notes:M,level:"wafer",marks:{type:"control",xs:k,values:b,items:g,limits:w,violations:S,...P?{group:P}:{}},autoTitle:`${_} control chart`,x:ce("x",c.label,c.unit,e,k,M),y:{...ce("y",_,r.unit,e,b,M),limits:!r.perDie&&r.level==="die"&&(p==="mean"||p==="median")?r.limits:void 0},groups:z,colorLabel:Z,aggregation:`individuals chart: centre the mean of ${w.baseline===b.length?"all":`the first ${w.baseline}`} wafers, limits \xB13\u03C3 with \u03C3 the average moving range / 1.128; ${O}`,population:{wafers:t.length,dies:l.dies.length},plotted:b.length,omitted:v?[{field:r.label,count:v}]:[]}}function li(e,t,n){const s=(...b)=>_e(e,t,b,n),i=n.testDefs??[],a=e.fields??{};let l;if(!a.y)l=i.filter(be);else if(ue(a.y)){const b=new Set(expandTestSet(a.y,i).tests);l=i.filter(k=>b.has(k.testNumber))}else if("test"in a.y)l=i.filter(b=>b.testNumber===a.y.test);else return s("A goal plot shows tests: choose tests, or leave the values empty for every test with both limits");if(l=l.filter(b=>be(b)&&Ut(b)!==void 0),l.length===0)return s("No test here has both a low and a high limit to set a goal by");const f=ye(t),c={items:t,rows:f,ctx:n},r=a.color,h=r===void 0||"follow"in r?n.groupBy?{meta:n.groupBy}:void 0:"none"in r?void 0:r;let p=[""],d=()=>0;if(h){const b=J(h,c);if(b.issue)return s(b.issue);if(!b.cat)return s(`${b.label} is continuous: colour a goal plot by a category such as split`);const k=S=>b.level==="die"?b.cat[S]:b.cat[f.item[S]],w=[];for(let S=0;S<f.dies.length;S++){const _=k(S);_!==void 0&&!w.includes(_)&&w.push(_)}p=Oe(h,w,We(b)),d=S=>{const _=k(S);return _===void 0?-1:p.indexOf(_)}}const u=p.map(()=>[]);for(let b=0;b<f.dies.length;b++){const k=d(b);k>=0&&u[k].push(f.dies[b])}const g=[];if(u.forEach((b,k)=>{for(const w of Mn([{dies:b}],l)){if(!w.hasSpec||w.lsl===void 0||w.usl===void 0||!(w.stdOverall>0)||w.ppk===null)continue;const S=w.usl-w.lsl;g.push({x:(w.mean-(w.lsl+w.usl)/2)/S,y:w.stdOverall/S,group:k,testNumber:w.testNumber,label:w.label,ppk:w.ppk,n:w.n,basis:w.limitBasis??"test"})}}),g.length===0)return s("No test has values with a spread to place");const v=[];return{spec:e,issues:[],notes:v,level:"die",marks:{type:"goal",points:g},autoTitle:h?`Capability goal plot \xB7 by ${fieldLabel(h,i,n.curation)}`:"Capability goal plot",x:ce("x","Mean offset from the centre of the limits",void 0,e,g.map(b=>b.x),v),y:ce("y","Standard deviation",void 0,e,g.map(b=>b.y),v),groups:p,colorLabel:h?fieldLabel(h,i,n.curation):void 0,aggregation:"each test's mean offset and standard deviation over its dies, as shares of its limit window (spec limits where it has both, else test limits); triangles: Ppk 1 and 1.33",population:{wafers:t.length,dies:f.dies.length},plotted:g.length,omitted:[]}}export function resolvePlot(e,t,n={}){const s=ui(e,t,n);return n.populationLabel&&!n.inFacet?{...s,populationLabel:n.populationLabel}:s}function ui(e,t,n={}){const s=xn(e);if(s)return _e(e,t,[s],n);const i=(...m)=>_e(e,t,m,n);if(e.chart==="sweep")return i("A sweep is drawn by the sweep panel");if(!n.eligibleOnly)return Jn(e,t,n);if(!n.whereApplied&&Pt(e).length)return ti(e,t,n);if(e.fields?.facet&&!n.inFacet)return ni(e,t,n);if(e.chart==="control")return ri(e,t,n);if(e.chart==="goal")return li(e,t,n);if(e.chart==="heatmap"&&!n.asHeatmap)return oi(e,t,n);const a=e.chart,l=e.fields??{},f=n.testDefs??[],c=t.flatMap(m=>m.dies),r=[],h=ue(l.y)?l.y:void 0;if(ue(l.x)||ue(l.color))return i("A set of tests can only be the values (Y) of a plot");if(e.normalize&&a==="scatter")return i("Rescaling applies to the values of a box, bar, line or histogram, not to a scatter");if(h&&a==="scatter")return i("A scatter plots one value against another: choose one test for each axis, or a box, bar, line or histogram to show several tests");const p=m=>f.find(x=>x.testNumber===m)?.name||h?.names?.[String(m)]||`Test ${m}`;let d,u,g=new Set,v=t;if(h){const{tests:m,problems:x}=expandTestSet(h,f);if(x.length)return i(...x);const N=new Set(c.length?st(c,"values"):[]),I=[];let $=[];for(const C of m){const R=f.find(X=>X.testNumber===C),U=h.names?.[String(C)];if(R&&U&&R.name&&!wt(U,R.name))return i(kt(C,U,R.name));if(h.passRate){if(!R){I.push(U?`${U} (test ${C})`:`test ${C}`);continue}if(passKindOf(R,h.judge)==="spec"&&R.limitLow===void 0&&R.limitHigh===void 0){I.push(`${p(C)} (no test limits)`);continue}$.push(C);continue}if(R&&!be(R)){I.push(`${p(C)} (pass/fail, no value)`);continue}if(!N.has(C)){I.push(U?`${U} (test ${C})`:`test ${C}`);continue}$.push(C)}if($.length===0)return i(`None of these tests has ${h.passRate?"a verdict to judge":"values"} in these dies${I.length?`: ${I.join(", ")}`:""}`);if(h.passRate&&e.normalize)return i("A pass rate is a share of dies, not a measured value: it cannot be rescaled");if($.length*c.length>TEST_SET_VALUE_LIMIT){const C=Math.max(1,Math.floor(TEST_SET_VALUE_LIMIT/Math.max(1,c.length)));return i(`${$.length} tests over ${c.length.toLocaleString("en-GB")} dies is ${($.length*c.length).toLocaleString("en-GB")} values, more than one plot draws (${TEST_SET_VALUE_LIMIT.toLocaleString("en-GB")}): choose at most ${C} tests, or show fewer wafers`)}if(I.length&&r.push(`Left out, with no values here: ${I.join(", ")}`),e.normalize){const C=nn($,n.scaleDies??c,f,e.normalize,p);if(C.scales.size===0)return i(...C.dropped);C.dropped.length&&r.push(`Left out: ${C.dropped.join("; ")}`),$=$.filter(R=>C.scales.has(R)),u=C.scales,g=C.bases}else if(!h.passRate){const C=[...new Set($.map(R=>f.find(U=>U.testNumber===R)?.unit).filter(R=>!!R))];if(C.length>1)return i(`These tests are measured in different units (${C.join(", ")}): rescale them to compare them on one axis`)}const L=$.map(p),A=L.map((C,R)=>L.indexOf(C)!==L.lastIndexOf(C)?`${C} \xB7 ${$[R]}`:C),F=[],W=[],j=[];$.forEach((C,R)=>t.forEach((U,X)=>{F.push(U),W.push(X),j.push(R)})),d={realOf:Int32Array.from(W),testOf:Int32Array.from(j),tests:$,labels:A},v=F}const b=m=>d?d.realOf[m]:m,k=ye(v),w={items:v,rows:k,ctx:n,melt:d},S=ke(l.x);if(S.length>1&&a!=="box"&&a!=="bar")return i("Nested categories need a box or bar chart: choose one field for X");if(S.length>jt)return i(`At most ${jt} fields can be nested on X`);if(S.some((m,x)=>S.findIndex(N=>Le(m,N))!==x))return i("A field can be only one level of the categories");const _=S.length?S:a==="box"||a==="bar"?[{builtin:h?"test":"wafer"}]:[],M=_[0],z=_.some(Te),P=l.y,Z=a==="histogram"||a==="probability",ee=Z?P??M:P;if(a==="scatter"||a==="line"){if(!M)return i("Choose a field for X");if(!P)return i("Choose a field for Y")}if(a==="box"&&!P)return i("Choose a field for Y");if(a==="histogram"&&!ee)return i("Choose a field to count");if(a==="probability"&&!ee)return i("Choose the values to plot");const B=Z?[]:_.map(m=>J(m,w)).map(m=>a==="line"&&m.mid&&!m.issue?{...m,kind:"numeric",num:m.mid,unit:m.midUnit,cat:void 0}:m),O=B[0];let o=ee?J(ee,w):void 0;if(e.normalize&&o&&!o.issue){if(!d){if(!("test"in o.field)||!o.num)return i("Rescaling applies to a measured test: choose a test for the values");const A=o.field.test,F=nn([A],n.scaleDies??k.dies,f,e.normalize,()=>o.label);if(F.scales.size===0)return i(...F.dropped);u=F.scales,g=F.bases}const m=A=>d?d.tests[d.testOf[k.item[A]]]:o.field.test,x=new Float64Array(o.num.length);for(let A=0;A<x.length;A++){const F=u.get(m(A));x[A]=(o.num[A]-F.offset)/F.scale}const N=d?d.tests:[m(0)],I=d?N.length>3?`${N.length} tests`:fe(d.labels):o.label,$=o.limits;o={...o,num:x,unit:void 0,limits:Kn(N,d?A=>qt(f.find(F=>F.testNumber===A)):()=>$,u),label:`${I} (${Yn[e.normalize]})`}}else d&&o&&!o.issue&&!kn(o.field)&&(o={...o,label:d.tests.length>3?`${d.tests.length} tests`:fe(d.labels)});const G=a==="scatter"||a==="line"?[["X",O],["Y",o]]:a==="histogram"?[["to count",o]]:a==="probability"?[["values",o]]:a==="box"||a==="bar"?[["Y",o]]:[];for(const[m,x]of G)if(x&&!x.issue&&x.kind==="categorical"&&!x.num)return i(`${x.label} is a category, not a number, so it cannot be ${m==="to count"?"the field a histogram counts":m==="values"?"the values of a probability plot":`the ${m} of a ${a}`}. Use it as the X of a bar or box chart (one bar per ${x.label.toLowerCase()}), or as the colour`);const te=h&&!z&&!n.facetByTest&&(l.color===void 0||"follow"in l.color)?{builtin:"test"}:l.color;if(h&&!z&&!n.facetByTest&&!Te(te))return i("Put Test on the X axis or the colour, so each test is drawn on its own");let D,At=!1,at;te===void 0||"follow"in te?n.groupBy?at=n.groupBy:(n.wholeWafers??t.length)>1&&(At=!0):"none"in te||(D=J(te,w)),at&&(D=J({meta:at},w)),At&&(D=J({builtin:"wafer"},w)),D?.issue&&(te===void 0||"follow"in te)&&(D=void 0);const ot=[...B.map(m=>m.issue),o?.issue,D?.issue].filter(m=>!!m),Pe=!!D&&D.kind==="numeric"&&!("meta"in D.field);if(Pe&&a!=="scatter"&&ot.push(`${D.label} is continuous, so it can colour a scatter but not a ${a}: colour by a category such as wafer, split or bin`),ot.length)return i(...ot);const ln=[...B,o].filter(m=>!!m);let q=e.level??(ln.some(m=>m.level==="die")?"die":"wafer");const rt=[...B,Pe?void 0:D].filter(m=>!!m&&m.level==="die"),lt=m=>m&&{label:m.label,level:m.level,kind:m.kind,yield:!!m.weights},Ot=combinationIssue(a,{x:lt(B.find(m=>m.level==="die")??O),y:lt(o),color:lt(D)},{aggregate:e.aggregate,level:e.level,continuousColor:Pe});if(Ot)return i(Ot.long);if(a==="bar"&&!o&&rt.length&&(q="die"),o&&o.level==="wafer"&&o.weights&&rt.length&&(o=Vn(w,o),q="die"),q==="die"&&o?.weights&&!o.perDie&&!rt.length&&(q="wafer"),o&&"passRate"in o.field&&q==="die"&&a!=="bar"&&a!=="line")return i(`${o.label} is a share of dies: draw it as a bar or a line, or with one mark per wafer (each wafer's pass rate)`);const re=q==="die"?k.dies.length:v.length,Ze=m=>q==="die"?k.item[m]:m,Qe=m=>({item:b(Ze(m)),die:q==="die"?k.dies[m]:void 0}),Tt=e.aggregate&&e.aggregate!=="yield"?e.aggregate:"mean",we=m=>{if(!m.num)throw new Error("numeric field expected");if(m.level===q)return m.num;if(m.level==="wafer"){const N=new Float64Array(re);for(let I=0;I<re;I++)N[I]=m.num[Ze(I)];return N}const x=v.map(()=>[]);for(let N=0;N<m.num.length;N++)x[k.item[N]].push(m.num[N]);return Float64Array.from(x,N=>combine(N,Tt))},It=m=>{if(!m.cat)throw new Error("category field expected");if(m.level===q)return m.cat;if(m.level==="wafer")return Array.from({length:re},(x,N)=>m.cat[Ze(N)]);throw new Error("a per-die category cannot be used at wafer level")},un=m=>m.weights&&m.level===q?m.weights:void 0;let Je=[""],$e=new Int32Array(re),Ie,ve;if(D&&Pe)Ie=D.label,ve=we(D);else if(D){Ie=D.label;const m=It(D),x=new Map,N=[];for(let $=0;$<re;$++){const L=m[$]??bt;x.has(L)||(x.set(L,0),N.push(L))}const I=Oe(D.field,N,We(D));I.forEach(($,L)=>x.set($,L)),Je=I;for(let $=0;$<re;$++)$e[$]=x.get(m[$]??bt)}const ut=new Map,xe=m=>ut.set(m,(ut.get(m)??0)+1),Ve=(m,x)=>m.labelOf?m.labelOf(q==="die"?k.item[x]:x):m.label,et=q==="die"?"dies":"wafers";let je,ie,me,Ce,ft,Ct,ct,ze=0;const Y=Je.length,Xe=m=>m.level==="die"&&q==="wafer"?`${Ke[Tt].toLowerCase()} of ${m.label} per wafer`:void 0;if(a==="scatter"){const m=we(O),x=we(o),N=[];for(let L=0;L<re;L++){if(!Number.isFinite(m[L])){xe(O.label);continue}if(!Number.isFinite(x[L])){xe(Ve(o,L));continue}if(ve&&!Number.isFinite(ve[L])){xe(D.label);continue}N.push({x:m[L],y:x[L],group:$e[L],item:Ze(L),die:q==="die"?k.dies[L]:void 0,...ve?{value:ve[L]}:{}})}if(ze=N.length,ve&&N.length){const L=N.map(A=>A.value);Ct={label:D.label,unit:D.unit,lo:De(L),hi:Me(L)}}let I;if(e.fit){I=(ve?[N]:Array.from({length:Y},(F,W)=>N.filter(j=>j.group===W))).flatMap((F,W)=>{const j=fitLine(F.map(C=>C.x),F.map(C=>C.y),e.fit);return j?[{group:W,...j}]:[]});const A=(O.unit??"")===(o.unit??"");ct=I.map(F=>{const W=Y>1&&!ve?`${Je[F.group]||"(none)"}: `:"",j=+F.slope.toPrecision(4),C=`${j<0?"\u2212":""}${Gt(Math.abs(j))}`,R=A?C:`${C} ${o.unit??""}/${O.unit??""}`.trim(),U=F.intercept<0?"\u2212":"+";return`${W}y = ${R} x ${U} ${qe(Math.abs(F.intercept),o.unit)}, R\xB2 ${F.r2.toFixed(3)}, n ${F.n.toLocaleString("en-GB")}`})}let $=!1;if(e.identity&&((O.unit??"")!==(o.unit??"")?r.push(`y = x is left off: ${O.label} and ${o.label} are in different units`):$=!0),je={type:"scatter",points:N,...I?.length?{fits:I}:{},...$?{identity:!0}:{}},ft=In(N),ie=ce("x",O.label,O.unit,e,N.map(L=>L.x),r),me=ce("y",o.label,o.unit,e,N.map(L=>L.y),r),!n.inFacet){const L=[D?.field,e.fields?.facet].flatMap(F=>F&&"meta"in F?[F.meta]:[]),A=_t(t.map(F=>({metadata:F.metadata,dieCount:F.dies.length})),{facetableOnly:!0,curation:n.curation}).filter(F=>F.splittable&&!L.includes(F.key)).map(F=>F.label);A.length&&r.push(`Mixed ${fe(A)} across these points: a trend here may come from the groups' offset rather than the relationship (Simpson's paradox). Colour or panel by it, or keep one value with Only dies where`)}Ce=[Xe(O),Xe(o),I?.length?`${e.fit==="orthogonal"?"orthogonal (Deming) fit":"least-squares fit of Y on X"} per ${Y>1&&!ve?"colour":"plot"}`:void 0].filter(Boolean).join("; ")||void 0}else if(a==="histogram"){const m=we(o),x=Array.from({length:Y},()=>[]),N=Array.from({length:Y},()=>[]);for(let $=0;$<re;$++){if(!Number.isFinite(m[$])){xe(Ve(o,$));continue}x[$e[$]].push(m[$]),N[$e[$]].push($),ze++}je={type:"histogram",values:x,units:N,unit:Qe},ie=ce("x",o.label,o.unit,e,x.flat(),r);const I=e.histNorm==="percent";me={label:I?Y>1?`Share of each colour's ${et}`:`Share of ${et}`:"Count",scale:"linear",...I?{unit:"%"}:{},...e.axes?.y?.label?{label:e.axes.y.label}:{}},e.normalCurve&&ie.scale==="log"&&r.push("The normal curve is left off a log axis, where a normal distribution is not the shape its bars would follow"),Ce=[Xe(o),e.normalCurve&&ie.scale!=="log"?`curve: the normal distribution with ${Y>1?"each colour's":"the"} mean and standard deviation`:void 0].filter(Boolean).join("; ")||void 0}else if(a==="probability"){const m=we(o),x=Array.from({length:Y},()=>[]);for(let $=0;$<re;$++){if(!Number.isFinite(m[$])){xe(Ve(o,$));continue}x[$e[$]].push($),ze++}for(const $ of x)$.sort((L,A)=>m[L]-m[A]);const N=x.map($=>$.map(L=>m[L]));je={type:"probability",values:N,units:x,unit:Qe},ie=ce("x",o.label,o.unit,e,N.flat(),r);const I=e.probabilityAxis==="linear";me={label:e.axes?.y?.label??"Cumulative share",scale:"linear"},Ce=[Xe(o),`each ${q==="die"?"die":"wafer"} at (rank \u2212 \xBD) / n of its ${Y>1?"group":"population"}${I?"":", on a normal-probability scale"}`].filter(Boolean).join("; ")}else if(a==="line"){const m=we(O),x=we(o),N=new Set,I=new Map,$=new Map;for(let K=0;K<re;K++){if(!Number.isFinite(m[K])){xe(O.label);continue}if(!Number.isFinite(x[K])){xe(Ve(o,K));continue}N.add(m[K]);const H=`${$e[K]}|${m[K]}`;(I.get(H)??I.set(H,[]).get(H)).push(x[K]),ze++,($.get(H)??$.set(H,[]).get(H)).push(K)}const L=[...N].sort((K,H)=>K-H),A=e.aggregate??"mean",F=Array.from({length:Y},(K,H)=>L.map(se=>{const Fe=I.get(`${H}|${se}`);return Fe?combine(Fe,A==="yield"?"mean":A):NaN})),W=Array.from({length:Y},(K,H)=>L.map(se=>I.get(`${H}|${se}`)?.length??0)),j=Array.from({length:Y},(K,H)=>L.map(se=>$.get(`${H}|${se}`)??[]));let C;const R=e.spread;if(R){if(o.perDie)return i(`A band shows how values spread, and ${o.label} is a share of passing dies, not a value: leave the band off`);if(A!=="mean"&&A!=="median")return i(`A band goes round a mean or a median, not ${Nt[A]}`);const K=new Map,H=(de,he,Ee)=>{const ne=(I.get(`${de}|${he}`)??[]).filter(Number.isFinite);if(ne.length===0)return[NaN,NaN];if(R==="minmax")return[De(ne),Me(ne)];if(R==="iqr"){const y=ne.sort((T,E)=>T-E);return[vt(y,.25),vt(y,.75)]}if(ne.length<2)return[NaN,NaN];const tt=ne.reduce((y,T)=>y+T,0)/ne.length,Ge=Math.sqrt(Wt(ne,tt));let Ue=1;R==="ci95"&&(Ue=K.get(ne.length-1)??Ln(.05,ne.length-1),K.set(ne.length-1,Ue));const Ye=R==="sd"?Ge:Ue*Ge/Math.sqrt(ne.length);return[F[de][Ee]-Ye,F[de][Ee]+Ye]},se=F.map(()=>[]),Fe=F.map(()=>[]);F.forEach((de,he)=>L.forEach((Ee,ne)=>{const[tt,Ge]=H(he,Ee,ne);se[he].push(tt),Fe[he].push(Ge)})),C={lo:se,hi:Fe}}je={type:"line",xs:L,values:F,counts:W,cellUnits:j,unit:Qe,...C?{band:C}:{}},ie=ce("x",O.label,O.unit,e,L,r);const U=A==="yield"?"mean":A;me=ce("y",o.perDie?o.label:`${Ke[U]} ${o.label}`,o.unit,e,F.flat(),r);const X=q==="die"?"dies":"wafers",le={sd:`\xB1 1 standard deviation of the ${X}`,ci95:`the mean's 95% confidence interval (Student's t, n = ${X})`,iqr:`the quartiles of the ${X}`,minmax:`the range of the ${X}`},oe=Ae(O.field)?O.field:void 0,Se=oe?`in each of ${L.length} ranges of ${O.label} (${(oe.by??"count")==="width"?"equal widths":`about the same number of ${X} in each`}), drawn at the middle of the range`:`per ${o.perDie?en(O.label):O.label}`;Ce=(o.perDie?`passing dies over judged dies, ${Se}`:`${Ke[U].toLowerCase()} of ${o.label} ${Se}`)+(R?`; band: ${le[R]} ${oe?"in each range":`at each ${en(O.label)}`}`:"")}else{const m=[],x=[];for(const y of B){const T="builtin"in y.field&&(y.field.builtin==="x"||y.field.builtin==="y");if(y.kind==="numeric"&&y.level==="die"&&!T)return i(`${y.label} is continuous, so a ${a} cannot have one ${a==="bar"?"bar":"box"} per value; use a scatter or line, or choose a categorical X such as wafer, ring or bin`);const E=y.cat?It(y):Array.from(we(y),ae=>Number.isFinite(ae)?Gt(ae):void 0),V=new Set,Q=[];for(let ae=0;ae<re;ae++){const ge=E[ae];ge!==void 0&&!V.has(ge)&&(V.add(ge),Q.push(ge))}const pe=Oe(y.field,Q,We(y));m.push(E),x.push(new Map(pe.map((ae,ge)=>[ae,ge])))}const N="",I=new Map,$=[],L=y=>{const T=[];for(let E=0;E<m.length;E++){const V=m[E][y];if(V===void 0)return{missing:E};T.push(V)}return T.join(N)};for(let y=0;y<re;y++){const T=L(y);typeof T=="string"&&!I.has(T)&&(I.set(T,0),$.push(T.split(N)))}$.sort((y,T)=>{for(let E=0;E<y.length;E++){const V=x[E].get(y[E])-x[E].get(T[E]);if(V)return V}return 0});const A=$.map(y=>y.join(" \xB7 "));$.forEach((y,T)=>I.set(y.join(N),T));const F=m.length===1?m[0]:void 0,W=a==="bar"&&!o,j=e.aggregate??(W?"count":o?.weights?"yield":"mean");if(j==="yield"&&!o?.weights)return i("Pooled yield needs Yield as the Y field");if(a==="box"&&j==="count")return i("A box plot needs a measured field for Y");const C=o?we(o):void 0,R=o?un(o):void 0,U=Array.from({length:Y},()=>A.map(()=>[])),X=Array.from({length:Y},()=>A.map(()=>[])),le=Array.from({length:Y},()=>A.map(()=>[]));for(let y=0;y<re;y++){const T=L(y);if(typeof T!="string"){xe(B[T.missing].label);continue}const E=I.get(T);if(C&&!Number.isFinite(C[y])){xe(Ve(o,y));continue}U[$e[y]][E].push(C?C[y]:1),X[$e[y]][E].push(y),R&&le[$e[y]][E].push(R[y]),ze++}const oe=U.map((y,T)=>y.map((E,V)=>{if(E.length===0)return NaN;if(j==="yield"){const Q=le[T][V],pe=Q.reduce((ae,ge)=>ae+ge,0);return pe>0?E.reduce((ae,ge,mn)=>ae+ge*Q[mn],0)/pe:NaN}return combine(E,j)})),Se=a==="bar"&&(j==="count"||j==="sum");if(e.stack&&a!=="bar")return i("Only a bar chart stacks its colours");if(e.stack&&!Se)return i(`Stacking adds the colours' values, which means something for a count or a sum, not ${Nt[j]}: combine by count or sum, or draw the colours side by side`);if(e.cumulative&&!(Se&&e.sort==="value"))return i("A cumulative line needs a bar of counts or sums sorted by value, largest first");if(e.barNorm==="percent"&&!Se)return i(`A share of each colour's total means something for a count or a sum, not ${Nt[j]}: combine by count or sum`);if(e.barNorm==="percent"&&e.stack)return i("Bars are either stacked or each colour's share of its own total, not both");if(e.barNorm==="percent"&&Se)for(let y=0;y<Y;y++){const T=oe[y].reduce((E,V)=>E+(Number.isFinite(V)?V:0),0);oe[y]=oe[y].map(E=>Number.isFinite(E)&&T>0?E/T*100:NaN)}if((e.sort||e.top)&&B.length>1)return i("Sorting by value and keeping the top categories need one category field on X");const K=y=>{if(a==="box"){const E=U.flatMap(V=>V[y]);return E.length?combine(E,"median"):NaN}if(Se||e.barNorm==="percent"){let E=0,V=!1;for(const Q of oe)Number.isFinite(Q[y])&&(E+=Q[y],V=!0);return V?E:NaN}const T=U.flatMap(E=>E[y]);if(T.length===0)return NaN;if(j==="yield"){const E=le.flatMap(Q=>Q[y]),V=E.reduce((Q,pe)=>Q+pe,0);return V>0?T.reduce((Q,pe,ae)=>Q+pe*E[ae],0)/V:NaN}return combine(T,j)},H=A.map((y,T)=>K(T));let se=A.map((y,T)=>T);e.sort==="value"&&se.sort((y,T)=>(Number.isFinite(H[T])?H[T]:-1/0)-(Number.isFinite(H[y])?H[y]:-1/0)),e.sort==="ascending"&&se.sort((y,T)=>(Number.isFinite(H[y])?H[y]:1/0)-(Number.isFinite(H[T])?H[T]:1/0));const Fe=H.reduce((y,T)=>y+(Number.isFinite(T)?T:0),0);e.top&&e.top<se.length&&(r.push(`Showing the first ${e.top} of ${se.length} ${B[0].label.toLowerCase()} values${e.sort==="value"?", largest first":e.sort==="ascending"?", smallest first":""}`),se=se.slice(0,e.top));const de=y=>se.map(T=>y[T]);A.splice(0,A.length,...de(A));for(let y=0;y<Y;y++)U[y]=de(U[y]),X[y]=de(X[y]),oe[y]=de(oe[y]);const he=de(H);if($.length&&$.splice(0,$.length,...de($)),e.stack==="percent")for(let y=0;y<Y;y++)oe[y]=oe[y].map((T,E)=>Number.isFinite(T)&&he[E]>0?T/he[E]*100:NaN);let Ee=0;const ne=e.cumulative&&Fe>0?he.map(y=>(Ee+=Number.isFinite(y)?y:0,Ee/Fe*100)):void 0,Ge=!!F&&"builtin"in B[0].field&&B[0].field.builtin==="wafer"?A.map(y=>F.findIndex((T,E)=>T===y&&E>=0)):void 0,Ue=B.length>1?{levels:B.map(y=>y.label),parts:$}:void 0;je={type:a==="box"?"box":"bar",categories:A,cells:U,cellUnits:X,unit:Qe,values:oe,categoryItems:Ge?.map(y=>b(q==="die"?k.item[y]:y)),...Ue?{nest:Ue}:{},...e.stack&&Y>1?{stack:e.stack}:{},...ne?{cumulative:ne}:{},...a==="bar"&&q==="die"&&o?.perDie?{passFail:o.failSide?.some(y=>y!==0)?{failSide:o.failSide}:{}}:{}};const Ye=fe(B.map(y=>y.label.toLowerCase()));if(ie={label:e.axes?.x?.label??B.map(y=>y.label).join(" \u203A "),scale:"linear"},a==="bar"){const y=j==="count"?"Count":Ke[j],T=W?`Count of ${et}`:j==="yield"?"passRate"in o.field?o.label:"Pooled yield":`${y} ${o.label}`,E=e.stack==="percent"&&Y>1,V=e.barNorm==="percent",Q=W?et:T.toLowerCase(),pe=E?`Share of each ${B[0].label.toLowerCase()}'s ${Q}`:V?Y>1?`Share of each ${Ie?Ie.toLowerCase():"colour"}'s ${Q}`:`Share of ${Q}`:T,ae=E?[0,100]:e.stack&&Y>1?he.filter(Number.isFinite):oe.flat();me=ce("y",pe,E||V||j==="yield"?"%":j==="count"?void 0:o?.unit,e,ae,r),Ce=W?void 0:j==="yield"?`passing dies over judged dies, pooled per ${Ye}`:`${y.toLowerCase()} of ${o.label}${o.level==="die"&&q==="wafer"?" per wafer":""} per ${Ye}`}else me=ce("y",o.label,o.unit,e,U.flat(2),r),Ce=Xe(o)}const dt=(m,x)=>m&&!m.perDie&&(x===void 0||x==="mean"||x==="median"||x==="min"||x==="max")?m.limits:void 0,fn=e.aggregate??"mean";ie&&(a==="scatter"||a==="line")&&(ie.limits=dt(O)),me&&a!=="histogram"&&(me.limits=dt(o,a==="scatter"||a==="box"?void 0:fn)),Z&&ie&&(ie.limits=dt(o));const cn=()=>{const m=o?.label,x=B.filter($=>!Te($.field)),N=a==="box"||a==="bar"?x.length?fe(x.map($=>$.label)):void 0:O?.label,I=a==="scatter"?`${m} vs ${N}`:a==="histogram"?`${m}`:a==="probability"?`${m}, cumulative`:a==="line"?tn(m,N,!!O&&Ae(O.field)):N?a==="box"?`${m} by ${N}`:m?`${m} by ${N}`:`Dies by ${N}`:`${m}`;return Ie&&D&&!_.some($=>Le(D.field,$))&&!Te(D.field)?`${I} \xB7 by ${Ie}`:I},Et=[];let mt;const Dt=d?d.tests.map((m,x)=>({field:d.labels[x],test:m})):[];for(const m of new Set([...B,d?void 0:o,D]))m&&"test"in m.field&&Dt.push({field:m.label,test:m.field.test});for(const{field:m,test:x}of Dt){let N=0;for(const I of c)bn(I,x)!==void 0&&(N++,mt??=yn(gn(I)));N>0&&Et.push({field:m,count:N})}let ht;if((a==="box"||a==="bar")&&!d&&o&&"test"in o.field&&o.level==="die"&&o.num&&!o.perDie){const m=N=>!!N&&N.level==="wafer"&&N.kind==="categorical"&&!!N.cat&&!("builtin"in N.field&&(N.field.builtin==="wafer"||N.field.builtin==="test")),x=B.length===1&&m(B[0])?B[0]:!Pe&&m(D)?D:void 0;if(x){const N=new Float64Array(t.length),I=new Uint32Array(t.length);for(let A=0;A<k.dies.length;A++){const F=o.num[A];Number.isFinite(F)&&(N[k.item[A]]+=F,I[k.item[A]]++)}const $=new Map;t.forEach((A,F)=>{const W=x.cat[F];W===void 0||I[F]===0||($.get(W)??$.set(W,[]).get(W)).push(N[F]/I[F])});const L=[...$.keys()].sort(Rt);L.length>=2&&(ht={by:x.label,result:Tn(L.map(A=>({key:A,values:$.get(A)})))})}}let pt;if(e.whatIf){if(!(a==="histogram"||a==="probability"))return i("What-if limits go on a histogram or a probability plot of one test");if(d||!o||!("test"in o.field))return i("What-if limits need one measured test as the values");if(e.normalize)return i("What-if limits are in the test's own unit: turn rescaling off to set them");const m=o.field.test,x=f.find(X=>X.testNumber===m),N=x?.limitLow??-1/0,I=x?.limitHigh??1/0,$=e.whatIf.lo??x?.limitLow??-1/0,L=e.whatIf.hi??x?.limitHigh??1/0;let A=0,F=0,W=0;for(let X=0;X<k.dies.length;X++){const le=it(k.dies[X],m);le===void 0||!Number.isFinite(le)||!Mt(k.dies[X])||(A++,le>=N&&le<=I&&F++,le>=$&&le<=L&&W++)}const j=X=>A?`${(X/A*100).toFixed(1)}%`:"\u2014",C=`${Number.isFinite($)?qe($,o.unit):"\u2212\u221E"} to ${Number.isFinite(L)?qe(L,o.unit):"\u221E"}`,R=W-F,U=`what-if: ${o.label} passes ${j(F)} of ${A.toLocaleString("en-GB")} dies by its test limits, ${j(W)} from ${C} (${R===0?"no die changes":`${R>0?"+":"\u2212"}${Math.abs(R).toLocaleString("en-GB")} dies`})`;pt={...Number.isFinite($)?{lo:$}:{},...Number.isFinite(L)?{hi:L}:{},judged:A,passNow:F,passThen:W,sentence:U},ie&&(ie.limits={...ie.limits,...e.whatIf.lo!==void 0?{whatIfLow:e.whatIf.lo}:{},...e.whatIf.hi!==void 0?{whatIfHigh:e.whatIf.hi}:{}})}const dn=[...B,o,D].some(m=>!!m&&"builtin"in m.field&&m.field.builtin==="pat")||[ie,me].some(m=>m?.limits?.patLow!==void 0||m?.limits?.patHigh!==void 0);return{spec:e,issues:[],notes:r,marks:je,level:q,...ht?{comparison:ht}:{},...dn?{usesPat:!0}:{},...ct?.length?{fitNotes:ct}:{},...pt?{whatIf:pt}:{},...mt?{excluded:{limitSet:mt,fields:Et}}:{},autoTitle:cn(),x:ie,y:me,groups:Je,colorScale:Ct,colorLabel:Ie,aggregation:Ce,...ft?{correlation:ft}:{},...D&&!Pe&&"builtin"in D.field&&(D.field.builtin==="hbin"||D.field.builtin==="sbin")?{colorBins:D.field.builtin==="hbin"?"hard":"soft"}:{},...D&&_.some(m=>Le(D.field,m))?{colorRepeatsX:!0}:{},...e.normalize&&u?{normalization:qn(e.normalize,g)}:{},population:{wafers:t.length,dies:c.length},...d?{setTests:{tests:d.tests,labels:d.labels}}:{},plotted:ze,omitted:[...ut].map(([m,x])=>({field:m,count:x}))}}export function plotTitle(e){return e.spec.title?.trim()?e.spec.title:e.autoTitle}function fi(e,t){const n=t.groups.map(l=>`${l.key} ${l.n}`).join(", "),s=`by ${e.toLowerCase()}, wafer means (wafers: ${n})`;if(!t.welch&&!t.kruskal)return`${s}: ${t.issue?.toLowerCase()??"not comparable"}`;const i=t.welch?`${t.welch.method==="welch-t"?"Welch t":"Welch ANOVA"} p ${Vt(t.welch.p)}`:void 0,a=t.kruskal?`rank p ${Vt(t.kruskal.p)}${t.kruskal.approximate?" (approximate)":""}`:void 0;return`${s}: ${[i,a].filter(Boolean).join(", ")}`}export function plotFootnote(e){const{wafers:t,dies:n}=e.population,s=[e.populationLabel?`${n.toLocaleString("en-GB")} dies \xB7 ${e.populationLabel}`:`${t.toLocaleString("en-GB")} wafer${t===1?"":"s"} \xB7 ${n.toLocaleString("en-GB")} dies`];if(e.leftOut){const{partial:i,edge:a}=e.leftOut,l=(f,c)=>`${f.toLocaleString("en-GB")} ${c} di${f===1?"e":"es"}`;s.push(`${fe([...a?[l(a,"edge-excluded")]:[],...i?[l(i,"partial")]:[]])} left out, as a yield leaves them out`)}e.filterNote&&s.push(e.filterNote),e.whatIf&&s.push(e.whatIf.sentence),e.aggregation&&s.push(e.aggregation),e.correlation&&s.push(`${e.correlation.r===null?"":`r = ${e.correlation.r.toFixed(3)} \xB7 `}n = ${e.correlation.n.toLocaleString("en-GB")}`),e.normalization&&s.push(e.normalization),e.comparison&&s.push(fi(e.comparison.by,e.comparison.result)),e.usesPat&&s.push(`PAT per wafer: median \xB1 ${jn} \xD7 (Q3 \u2212 Q1) / 1.35 of its passing dies, within the test's limits`),e.facets&&s.push(`${e.facets.length} panels by ${e.facetLabel.toLowerCase()}, on shared axes`);for(const i of e.omitted)s.push(`${i.count.toLocaleString("en-GB")} ${e.level==="die"?"dies":"wafers"} without ${i.field} not plotted`);if(e.excluded)for(const i of e.excluded.fields)s.push(`${i.count.toLocaleString("en-GB")} ${i.field} value${i.count===1?"":"s"} outside ${e.excluded.limitSet} excluded`);return s.join(" \xB7 ")}export function plotGuideSections(e){const{spec:t}=e,n=t.fields??{},s=[...ke(n.x),n.y,n.color,n.rows,n.facet],i=[ci[t.chart],e.comparison&&Ne.groups,(e.fitNotes?.length||t.identity&&e.marks?.type==="scatter")&&Ne.fit,e.marks?.type==="line"&&e.marks.band&&Ne.bands,e.normalization&&Ne.rescaling,(s.some(Ae)||e.facets||e.whatIf)&&Ne.ranges];return[...new Set(i.filter(a=>!!a))]}const ci={probability:Ne.probability,control:Ne.control,goal:Ne.goal,heatmap:Ne.heatmap};export function fieldKey(e){return Ae(e)?`binned:${fieldKey(e.binned)}`:ue(e)?`${e.passRate?`passRates:${e.judge??"limits"}`:"tests"}:${e.tests.join(",")}`:"passRate"in e?`passRate:${e.passRate}${e.judge==="flag"?":flag":""}`:"test"in e?`test:${e.test}`:"builtin"in e?`builtin:${e.builtin}`:`meta:${e.meta}`}export function fieldCatalogue(e,t={}){const n=[],s=e.flatMap(u=>u.dies),i=new Set(s.length?st(s,"values"):[]),a=t.testDefs??[],l=new Map;for(const u of a)u.testType!=="F"&&(i.has(u.testNumber)||!s.length)&&l.set(u.testNumber,u.name);for(const u of i)!l.has(u)&&!a.some(g=>g.testNumber===u&&g.testType==="F")&&l.set(u,void 0);for(const[u,g]of[...l].sort((v,b)=>v[0]-b[0]))n.push({field:{test:u,...g?{name:g}:{}},label:g?`${g} \xB7 ${u}`:`Test ${u}`,name:g||`Test ${u}`,group:"Tests",kind:"numeric",level:"die",categorical:!1});l.size>=2&&n.push({field:{builtin:"test"},label:Be.test,name:Be.test,group:"Tests",kind:"categorical",level:"wafer",categorical:!0});const f=new Set(s.length?st(s,"all"):[]);for(const u of a){if(be(u)||!(f.has(u.testNumber)||!s.length))continue;const g=u.name||`Test ${u.testNumber}`;n.push({field:{test:u.testNumber,...u.name?{name:u.name}:{}},label:`${g} \xB7 ${u.testNumber} (pass/fail)`,name:g,group:"Verdicts",kind:"categorical",level:"die",categorical:!0})}for(const u of a){if(!(be(u)?(u.limitLow!==void 0||u.limitHigh!==void 0)&&(i.has(u.testNumber)||!s.length):f.has(u.testNumber)||!s.length))continue;const v=u.name||`Test ${u.testNumber}`;n.push({field:{passRate:u.testNumber,...u.name?{name:u.name}:{}},label:`${v} \xB7 ${u.testNumber} pass rate`,name:`${v} pass rate`,group:"Pass rates",kind:"numeric",level:"die",categorical:!1})}const c=u=>s.some(u),r=(u,g,v)=>n.push({field:{builtin:u},label:Be[u],name:Be[u],group:"Die",kind:g,level:"die",categorical:v});c(u=>nt(u))&&(r("x","numeric",!1),r("y","numeric",!1)),e.some(u=>u.wafer)&&c(u=>nt(u)&&u.physX!==void 0)&&r("radius","numeric",!1);const h=c(u=>nt(u));for(const u of hn)e.some(g=>He[u].available({wafer:g.wafer,ringCount:g.ringCount},h))&&r(u,"categorical",!0);c(u=>u.hbin!==void 0)&&r("hbin","categorical",!0),c(u=>u.sbin!==void 0)&&r("sbin","categorical",!0),c(u=>u.siteNum!==void 0)&&r("site","categorical",!0),c(u=>u.retestCount!==void 0)&&r("reprobed","numeric",!1),s.length&&Yt(a.filter(u=>i.has(u.testNumber))).length&&r("pat","categorical",!0);const p=(u,g,v)=>n.push({field:{builtin:u},label:Be[u],name:Be[u],group:"Wafer",kind:g,level:"wafer",categorical:v});p("wafer","categorical",!0),e.length>1&&p("waferOrder","numeric",!1),p("yield","numeric",!1),p("dieCount","numeric",!1);const d={items:e,rows:{dies:[],item:new Uint32Array(0)},ctx:t};for(const u of _t(e.map(g=>({metadata:g.metadata,dieCount:g.dies.length})),{facetableOnly:!0,curation:t.curation})){if(u.values.length===0)continue;const g=J({meta:u.key},d);n.push({field:{meta:u.key},label:u.label||gt(u.key,t.curation),name:u.label||gt(u.key,t.curation),group:"Wafer",kind:g.kind,level:"wafer",categorical:!0,distinct:u.values.length})}return n}export function fieldExtent(e,t,n={}){const s=J(e,{items:t,rows:ye(t),ctx:n});if(s.issue||!s.num)return;let i=1/0,a=-1/0;for(let l=0;l<s.num.length;l++){const f=s.num[l];Number.isFinite(f)&&(f<i&&(i=f),f>a&&(a=f))}return i===1/0?void 0:[i,a]}export function fieldValues(e,t,n={}){const s=J(e,{items:t,rows:ye(t),ctx:n});if(s.issue||!s.cat)return[];const i=[];for(const a of s.cat)a!==void 0&&!i.includes(a)&&i.push(a);return Oe(e,i,We(s))}export function fieldsForRole(e,t,n){if(t==="control"&&n==="x")return e.filter(i=>i.kind==="numeric"&&i.level==="wafer");const s=n==="y"||n==="x"&&(t==="scatter"||t==="line"||t==="histogram");return n==="color"?e.filter(i=>i.categorical||t==="scatter"&&i.kind==="numeric"):s?e.filter(i=>i.kind==="numeric"&&(n==="y"||i.group!=="Pass rates")):e.filter(i=>i.categorical)}export function defaultPlot(e,t){const n=e.filter(s=>s.group==="Tests"&&"test"in s.field);return n.length>=2?{id:t,chart:"scatter",fields:{x:n[0].field,y:n[1].field}}:n.length===1?{id:t,chart:"histogram",fields:{y:n[0].field}}:{id:t,chart:"scatter",fields:{x:{builtin:"waferOrder"},y:{builtin:"yield"}}}}const Ft=new Set(["wafer","dies","die x","die y","wafer order"]),di=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Lt=(e,t)=>t.length>=3&&new RegExp(`(^|[^A-Za-z0-9_])${di(t)}($|[^A-Za-z0-9_])`,"i").test(e);export function titleDrift(e,t){const n=e.title?.trim(),s={names:[],omits:[]};if(!n)return s;const i=e.fields?.color,a=[...ke(e.fields?.x),e.fields?.y,i,e.fields?.facet].filter(u=>Re(u)),l=u=>a.some(g=>Le(g,u)),f=t.filter(u=>!Ft.has(u.name.toLowerCase())&&!("meta"in u.field)&&!l(u.field)&&Lt(n,u.name)).map(u=>u.name),c=[...ke(e.fields?.x),e.fields?.y].filter(u=>Re(u)),r=u=>t.find(g=>Le(g.field,u))?.name??fieldLabel(u),h=c.filter(u=>!Ft.has(r(u).toLowerCase())&&Lt(n,r(u))),p=c.filter(u=>!Ft.has(r(u).toLowerCase())&&!Lt(n,r(u))),d=h.length>0||f.length>0?p.map(r):[];return{names:f,omits:d}}export function describeTitleDrift(e){const t=[];return e.names.length&&t.push(`The title names ${fe(e.names)}, which this plot does not show.`),e.omits.length&&t.push(`It does not name ${fe(e.omits)}, which this plot shows.`),t.length?t.join(" "):null}function mi(e,t={}){const n=ye(e),s=J({builtin:"ring"},{items:e,rows:n,ctx:t});if(s.issue||!s.cat)return;const i=new Map;let a=0,l=0;for(let r=0;r<n.dies.length;r++){const h=s.cat[r];if(h===void 0)continue;const p=yt([n.dies[r]],e[n.item[r]].passBins),d=i.get(h)??{pass:0,total:0};d.pass+=p.pass,d.total+=p.total,a+=p.pass,l+=p.total,i.set(h,d)}let f,c=l?a/l*100-1:-1/0;for(const[r,h]of i)h.total&&h.pass/h.total*100<c&&(c=h.pass/h.total*100,f=r);return f}function hi(e,t){if(!t||e.length<2)return e[0];const n=ye(t.items);let s=e[0],i=1/0;for(const a of e){const l=J({passRate:a.d.testNumber},{items:t.items,rows:n,ctx:t.ctx??{}});if(!l.num||!l.weights)continue;let f=0,c=0;for(let r=0;r<l.num.length;r++)l.weights[r]&&(c++,f+=l.num[r]/100);c&&f/c<i&&(i=f/c,s=a)}return s}const pi=4;export function examplePlots(e,t,n,s){const i=e.filter(o=>o.group==="Tests"&&"test"in o.field),a=e.flatMap(o=>"meta"in o.field?[o.field.meta]:[]),l=s?On(s.items,i.map(o=>o.field.test),a,s.ctx?.curation):void 0,f=new Map(i.map(o=>[o.field.test,o])),c=l?[...l.ranked.map(o=>f.get(o)).filter(Boolean).filter(o=>o.field.test!==l.partner)]:i;l?.partner!==void 0&&c.length&&c.splice(1,0,f.get(l.partner));const r=c.map(o=>o.field),h=[],p=t>1,d=o=>e.some(G=>"builtin"in G.field&&G.field.builtin===o),u=(l?.splitKey?e.find(o=>"meta"in o.field&&o.field.meta===l.splitKey):void 0)??e.find(o=>"meta"in o.field&&o.distinct!==void 0&&o.distinct>=2&&o.distinct<=Math.max(2,Math.floor(t/2))),g=o=>h.push({id:n(),...o}),v=c.length>=2?{tests:c.slice(0,8).map(o=>o.field.test),names:Object.fromEntries(c.slice(0,8).map(o=>[String(o.field.test),o.name]))}:void 0,b=u?.field,k=b??(d("ring")?{builtin:"ring"}:void 0),w={color:k??{none:!0}},S={color:b??{none:!0}};if(r.length>=2&&g({chart:"scatter",fields:{x:r[0],y:r[1],...b?{color:b}:{}},fit:"linear"}),r.length>=1&&g({chart:"histogram",fields:{y:r[0],...w},normalCurve:!0,...k?{histNorm:"percent"}:{}}),r.length>=1&&p&&g({chart:"box",fields:{x:{builtin:"wafer"},y:r[0],...S},axes:{y:{references:[{stat:"median"}]}}}),p&&g({chart:"bar",fields:{x:b??{builtin:"wafer"},y:{builtin:"yield"},color:b??{none:!0}},valueLabels:!0,axes:{y:{references:[{stat:"median"}]}}}),p)for(const o of(l?.yieldKeys??[]).filter(G=>!(b&&"meta"in b&&b.meta===G)).slice(0,pi)){const G=e.find(te=>"meta"in te.field&&te.field.meta===o)?.field;G&&g({chart:"bar",fields:{x:G,y:{builtin:"yield"},color:G},valueLabels:!0,axes:{y:{references:[{stat:"median"}]}}})}const _=p&&d("ring")&&s?mi(s.items,s.ctx):void 0;_&&g({chart:"bar",fields:{x:{builtin:"wafer"},y:{builtin:"yield"},color:{none:!0}},where:{conditions:[{field:{builtin:"ring"},values:[_]}]}}),r.length>=1&&p&&t<5&&g({chart:"line",fields:{x:{builtin:"waferOrder"},y:r[0],color:{none:!0}},aggregate:"mean",spread:"sd"}),r.length>=1&&g({chart:"probability",fields:{y:r[0],...S}});const M=s?.ctx?.testDefs??[],z=r.flatMap(o=>{const G="test"in o?M.find(te=>te.testNumber===o.test):void 0;return G&&be(G)?[{f:o,d:G}]:[]}),P=z.filter(({d:o})=>o.limitLow!==void 0&&o.limitHigh!==void 0).slice(0,8),Z=P.length>=2?{tests:P.map(({f:o})=>o.test),names:Object.fromEntries(P.filter(({d:o})=>o.name).map(({f:o,d:G})=>[String(o.test),G.name]))}:void 0;Z?g(b?{chart:"heatmap",fields:{x:b,y:Z},aggregate:"mean",normalize:"limits"}:{chart:"box",fields:{x:{builtin:"test"},y:Z},normalize:"limits"}):v&&g(b?{chart:"heatmap",fields:{x:b,y:v},aggregate:"mean",normalize:"zscore"}:{chart:"box",fields:{x:{builtin:"test"},y:v},normalize:"zscore"}),v&&p&&g({chart:"heatmap",fields:{x:{builtin:"wafer"},y:v},aggregate:"mean",normalize:"zscore"}),r.length>=1&&b&&g({chart:"box",fields:{x:b,y:r[0],color:b}}),r.length>=1&&b&&g({chart:"box",fields:{x:[b,{builtin:"wafer"}],y:r[0],color:b}}),r.length>=1&&d("ring")&&g({chart:"histogram",fields:{y:r[0],...S,facet:{builtin:"ring"}}}),r.length>=2&&g(b?{chart:"line",fields:{x:{binned:r[1],bins:5},y:r[0],color:b},aggregate:"median",spread:"sd"}:{chart:"box",fields:{x:{binned:r[1],bins:5},y:r[0],...w}}),r.length>=1&&d("radius")&&g(b?{chart:"line",fields:{x:{binned:{builtin:"radius"},bins:6,by:"width"},y:r[0],color:b},aggregate:"median",spread:"sd"}:{chart:"box",fields:{x:{binned:{builtin:"radius"},bins:6,by:"width"},y:r[0],...S}}),d("hbin")&&g({chart:"bar",fields:{x:{builtin:"hbin"},color:{none:!0}},sort:"value",cumulative:!0}),d("hbin")&&p&&g({chart:"bar",fields:{x:{builtin:"wafer"},color:{builtin:"hbin"}},stack:"percent"}),r.length>=1&&d("pat")&&g({chart:"box",fields:{x:{builtin:"pat"},y:r[0],color:{builtin:"pat"}}});const ee=e.find(o=>o.group==="Verdicts");r.length>=1&&ee&&g({chart:"box",fields:{x:ee.field,y:r[0],color:ee.field}}),r.length>=1&&t>=5&&g({chart:"control",fields:{x:{builtin:"waferOrder"},y:r[0]}}),z.some(({d:o})=>o.limitLow!==void 0&&o.limitHigh!==void 0)&&g({chart:"goal",fields:u?{color:u.field}:{}});const B=z.filter(({d:o})=>o.limitLow!==void 0||o.limitHigh!==void 0).slice(0,8);B.length>=2&&p&&g({chart:"heatmap",fields:{x:u?u.field:{builtin:"wafer"},y:{tests:B.map(({f:o})=>o.test),passRate:!0,names:Object.fromEntries(B.filter(({d:o})=>o.name).map(({f:o,d:G})=>[String(o.test),G.name]))}},aggregate:"mean"});const O=hi(z.filter(({d:o})=>o.limitLow!==void 0||o.limitHigh!==void 0).slice(0,8),s);if(O&&p&&g({chart:"bar",fields:{x:u?u.field:{builtin:"wafer"},y:{passRate:O.f.test,...O.d.name?{name:O.d.name}:{}},color:{none:!0}}}),O&&O.d.limitLow!==void 0&&O.d.limitHigh!==void 0){const o=(O.d.limitHigh-O.d.limitLow)*.1;g({chart:"histogram",fields:{y:O.f,color:{none:!0}},whatIf:{lo:O.d.limitLow-o,hi:O.d.limitHigh+o}})}return r.length>=2&&h.push({...rn(i.map(o=>o.field).flatMap(o=>"test"in o?[o]:[]),n()),title:"Example sweep"}),h}export function plotTestNumber(e){const{x:t,y:n,color:s}=e.fields??{},i=e.chart==="scatter"?[t,n,s]:e.chart==="histogram"||e.chart==="probability"?[n,t]:[n];for(const a of i){if(Re(a)&&"test"in a)return a.test;if(ue(a)){const l=a.tests[0],f=typeof l=="number"?l:parseInt(String(l),10);if(Number.isInteger(f))return f;continue}if(Re(a)&&"passRate"in a)return a.passRate}}export function defaultSweep(e,t){return rn(e.filter(be).map(n=>({test:n.testNumber,name:n.name})),t)}function rn(e,t){const n=[...e].sort((i,a)=>i.test-a.test).slice(0,5),s=Object.fromEntries(n.flatMap(i=>i.name?[[String(i.test),i.name]]:[]));return{id:t,chart:"sweep",sweep:{series:[{label:"Series 1",tests:n.map(i=>i.test),...Object.keys(s).length?{testNames:s}:{}}]}}}
|
|
1
|
+
import{GUIDE_SECTIONS as Ne}from"./guideSections.js";import{hasPosition as nt,isYieldEligibleDie as Mt}from"../core/dies.js";import{DIE_REGIONS as He,DIE_REGION_KEYS as pn,dieRadialPosition as gn}from"./dieRegions.js";import{excludedBy as bn,excludedValue as yn,testValue as it,testsPresent as st}from"../core/dieTable.js";import{limitSetName as wn}from"../renderer/valueFilter.js";import{NEGLIGIBLE_SPREAD as $n,compareNatural as Rt,minOf as Me,maxOf as Re}from"../core/utils.js";import{isParametricTest as be,getTestPassStatus as vn}from"../renderer/buildWaferMap.js";import{attributeLabel as gt,facetValueOf as Bt,buildFacetTable as _t,FACET_NONE_VALUE as bt}from"./facets.js";import{yieldCounts as yt}from"./yield.js";import{sameTestName as wt}from"./sweep.js";import{nearest as xn,sameField as Le,plotIssue as Nn,plotConditions as Pt,isField as Ae,isTestSet as ue,isBinned as Oe,isStatReference as kn,isPassRateSet as Sn,xFieldsOf as ke,PLOT_X_LEVELS as jt,PLOT_FACET_LIMIT as zt,PLOT_BINS_DEFAULT as Fn}from"./plotSpec.js";import{fmtExact as Gt,fmt as qe}from"../renderer/fmt.js";import{parseTestReference as Ln}from"../renderer/derivedTests/parser.js";import{capabilityLimits as Ut}from"./capability.js";import{mean as Ht,median as $t}from"../core/utils.js";import{sampleVariance as Wt,quantile as vt,tQuantileTwoSided as An,robustFence as On}from"./math.js";import{pickExamples as Tn}from"./examplePicks.js";import{compareGroups as In,formatP as Vt}from"./groupCompare.js";import{dieTestVerdict as Xt}from"./testPassRate.js";import{pearsonOfPairs as Cn}from"./correlation.js";import{individualsLimits as En,westernElectric as Dn,CONTROL_RULE_TEXT as Mn}from"./control.js";import{buildCapabilityFigures as Rn}from"./capability.js";import{patTests as Yt,waferPatLimits as Bn,waferPatVerdicts as _n,PAT_VERDICT_LABEL as Pn,PAT_VERDICT_ORDER as jn,PAT_K as zn}from"./pat.js";function qt(e){if(!e)return;const t={};for(const n of["limitLow","limitHigh","specLow","specHigh"])Number.isFinite(e[n])&&(t[n]=e[n]);return Object.keys(t).length?t:void 0}export function fitLine(e,t,n){const s=e.length;if(s<3)return;let i=0,o=0;for(let p=0;p<s;p++)i+=e[p],o+=t[p];i/=s,o/=s;let l=0,f=0,c=0;for(let p=0;p<s;p++){const d=e[p]-i,u=t[p]-o;l+=d*d,f+=u*u,c+=d*u}if(!(l>0))return;const r=f>0?c*c/(l*f):1,h=n==="linear"||c===0?c/l:(f-l+Math.sqrt((f-l)**2+4*c*c))/(2*c);return{slope:h,intercept:o-h*i,r2:r,n:s}}function ye(e){let t=0;for(const o of e)t+=o.dies.length;const n=new Array(t),s=new Uint32Array(t);let i=0;return e.forEach((o,l)=>{for(const f of o.dies)n[i]=f,s[i++]=l}),{dies:n,item:s}}const Be={wafer:"Wafer",x:"Die X",y:"Die Y",ring:He.ring.label,quadrant:He.quadrant.label,reticleCell:He.reticleCell.label,reticleShot:He.reticleShot.label,hbin:"Hard bin",sbin:"Soft bin",site:"Site",yield:"Yield",dieCount:"Dies",waferOrder:"Wafer order",test:"Test",pat:"PAT",radius:"Radial position",reprobed:"Re-probed"};export function fieldLabel(e,t,n){if(Oe(e))return fieldLabel(e.binned,t,n);if(ue(e))return Hn(e,t);if("passRate"in e)return`${t?.find(i=>i.testNumber===e.passRate)?.name||e.name||`Test ${e.passRate}`} pass rate${e.judge==="flag"?" (tester flag)":""}`;if("test"in e){const s=t?.find(o=>o.testNumber===e.test),i=s?.name||e.name||`Test ${e.test}`;return s!==void 0&&!be(s)?`${i} (pass/fail)`:i}return"builtin"in e?Be[e.builtin]??String(e.builtin):"meta"in e&&typeof e.meta=="string"?gt(e.meta,n):"Unknown field"}function Te(e,t,n){if(Oe(e)){const s=Qt.get(e);return s?s.filter(i=>t.includes(i)):[...t].sort((i,o)=>parseFloat(i)-parseFloat(o))}return"builtin"in e&&(e.builtin==="wafer"||e.builtin==="test")?[...t]:"builtin"in e&&e.builtin==="pat"?jn.filter(s=>t.includes(s)):Kt(t,n)}const Kt=(e,t)=>t?[...e].sort((n,s)=>(Number(n)||0)-(Number(s)||0)):[...e].sort(Rt);export function orderFieldValues(e){return Kt(e,e.every(t=>t===bt||xt.test(t.trim())))}const We=e=>!!e.num&&(e.kind==="numeric"||"meta"in e.field),Gn=e=>`Bin ${e}`;export function binOfLabel(e){const t=/^Bin (-?\d+)$/.exec(e);return t?Number(t[1]):void 0}const fe=e=>e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`,Un=e=>!!e&&"builtin"in e&&e.builtin==="pat",Ie=e=>!!e&&"builtin"in e&&e.builtin==="test";function Hn(e,t){const{tests:n}=expandTestSet(e,t??[]),s=i=>t?.find(o=>o.testNumber===i)?.name||e.names?.[String(i)]||`Test ${i}`;return e.passRate?e.judge==="flag"?"Pass rate (tester flag)":"Pass rate":n.length===0?e.tests.length===1?`Tests ${e.tests[0]}`:`${e.tests.length} test entries`:n.length>3?`${n.length} tests`:fe(n.map(s))}export function passKindOf(e,t){return be(e)?t==="flag"?"testFlag":"spec":"functional"}export function expandTestSet(e,t){const n=new Map(t.map(o=>[o.testNumber,o])),s=[],i=[];for(const o of e.tests){if(typeof o=="number"){s.includes(o)||s.push(o);continue}const l=Ln(String(o),n);if(!l.ok){i.push(`"${o}": ${l.message}`);continue}for(const f of l.tests)s.includes(f)||s.push(f)}return{tests:s,problems:i}}export function withTestSetNames(e,t){const n={};for(const o of expandTestSet(e,t).tests){const l=t.find(f=>f.testNumber===o)?.name;l&&(n[String(o)]=l)}const{names:s,...i}=e;return Object.keys(n).length?{...i,names:n}:i}export const TEST_SET_VALUE_LIMIT=4e6;const xt=/^[+-]?(?:\d+\.?\d*|\.\d+)$/;export function binEdges(e,t,n){const s=Array.from(e).filter(Number.isFinite).sort((f,c)=>f-c);if(s.length===0)return[];const i=s[0],o=s[s.length-1],l=[];for(let f=1;f<t;f++)l.push(n==="width"?i+(o-i)*f/t:vt(s,f/t));return l.filter((f,c)=>f>i&&f<=o&&(c===0||f>l[c-1]))}const Zt=(e,t)=>{let n=0,s=t.length;for(;n<s;){const i=n+s>>1;e>=t[i]?n=i+1:s=i}return n};function Wn(e,t,n,s){const i=[t,...e,n],o=f=>f.every((c,r)=>r===0||c!==f[r-1]);let l=s?i.map(f=>qe(f,s)):[];if(!o(l)||l.length===0){const f=s==="%"?"%":s?` ${s}`:"";for(let c=3;c<=15&&(l=i.map(r=>`${Number(r.toPrecision(c))}${f}`),!o(l));c++);}return i.slice(0,-1).map((f,c)=>`${l[c]} to ${l[c+1]}`)}const Qt=new WeakMap;function Vn(e,t,n){const{ctx:s}=t,i=J(e.binned,t),o=i.label;if(i.issue)return{...i,...n,label:o,kind:"categorical",num:void 0,issue:i.issue};if(!i.num)return{...i,...n,label:o,kind:"categorical",issue:`${i.label} is already a category: only a measured value or a number can be put into ranges`};const l=e.bins??Fn,f=e.by??"count",c=`${JSON.stringify(e)}`;let r=s.binEdges?.get(c),h=i.num;if(!r){if(s.wholeItems&&s.wholeItems!==t.items){const k=J(e.binned,{items:s.wholeItems,rows:ye(s.wholeItems),ctx:{...s,wholeItems:void 0}});k.num&&(h=k.num)}r=binEdges(h,l,f),s.binEdges?.set(c,r)}let p=1/0,d=-1/0;for(let k=0;k<h.length;k++){const w=h[k];Number.isFinite(w)&&(w<p&&(p=w),w>d&&(d=w))}if(p===1/0)return{...i,...n,label:o,kind:"categorical",num:void 0,issue:`${i.label} has no values to put into ranges`};const u=Wn(r,p,d,i.unit);Qt.set(e,u);const g=Array.from(i.num,k=>Number.isFinite(k)?u[Zt(k,r)]:void 0),v=u.map((k,w)=>((w===0?p:r[w-1])+(w===u.length-1?d:r[w]))/2),b=Float64Array.from(i.num,k=>Number.isFinite(k)?v[Zt(k,r)]:NaN);return{...n,label:o,unit:void 0,level:i.level,kind:"categorical",cat:g,mid:b,midUnit:i.unit}}function Jt(e,t){const n=new Float64Array(e),s=new Float64Array(e),i=new Int8Array(e);for(let o=0;o<e;o++){const l=t(o);n[o]=l===void 0?NaN:l==="pass"?100:0,s[o]=l===void 0?0:1,i[o]=l==="failLow"?-1:l==="failHigh"?1:0}return{num:n,weights:s,failSide:i}}function J(e,t){const{items:n,rows:s,ctx:i}=t,o=fieldLabel(e,i.testDefs,i.curation),l={field:e,label:o},f=s.dies.length,c=n.length;if(Oe(e))return Vn(e,t,l);if(ue(e)){const r=t.melt;if(!r)return{...l,level:"die",kind:"numeric",issue:"A set of tests can only be the values of a box, bar, line or histogram"};if(e.passRate){const d=r.tests.map(b=>i.testDefs?.find(k=>k.testNumber===b)),{num:u,weights:g,failSide:v}=Jt(f,b=>{const k=d[r.testOf[s.item[b]]];return Xt(s.dies[b],k,passKindOf(k,e.judge))});return{...l,level:"die",kind:"numeric",unit:"%",num:u,weights:g,failSide:v,perDie:!0,labelOf:b=>r.labels[r.testOf[b]]}}const h=new Float64Array(f);for(let d=0;d<f;d++)h[d]=it(s.dies[d],r.tests[r.testOf[s.item[d]]])??NaN;const p=new Set(r.tests.map(d=>i.testDefs?.find(u=>u.testNumber===d)?.unit).filter(d=>!!d));return{...l,level:"die",kind:"numeric",unit:p.size===1?[...p][0]:void 0,num:h,labelOf:d=>r.labels[r.testOf[d]]}}if("passRate"in e){const r=e.passRate,h=i.testDefs?.find(v=>v.testNumber===r);if(!h)return{...l,level:"die",kind:"numeric",issue:`Needs test ${r}${e.name?` (${e.name})`:""}, which is not in these dies`};if(e.name&&h.name&&!wt(e.name,h.name))return{...l,level:"die",kind:"numeric",issue:kt(r,e.name,h.name)};const p=passKindOf(h,e.judge);if(p==="spec"&&h.limitLow===void 0&&h.limitHigh===void 0)return{...l,level:"die",kind:"numeric",issue:`${h.name||`Test ${r}`} has no test limits to judge a pass by`};const{num:d,weights:u,failSide:g}=Jt(f,v=>Xt(s.dies[v],h,p));return{...l,level:"die",kind:"numeric",unit:"%",num:d,weights:u,failSide:g,perDie:!0}}if("test"in e){const r=i.testDefs?.find(d=>d.testNumber===e.test);if(r===void 0){if(t.present??=new Set(s.dies.length?st(s.dies,"values"):[]),!t.present.has(e.test))return{...l,level:"die",kind:"numeric",issue:`Needs test ${e.test}${e.name?` (${e.name})`:""}, which is not in these dies`}}else if(e.name&&r.name&&!wt(e.name,r.name))return{...l,level:"die",kind:"numeric",unit:r.unit,issue:kt(e.test,e.name,r.name)};if(r!==void 0&&!be(r)){const d=s.dies.map(u=>{const g=vn(u,e.test,r);return g===void 0?void 0:g?"Pass":"Fail"});return{...l,level:"die",kind:"categorical",cat:d}}const h=new Float64Array(f);for(let d=0;d<f;d++)h[d]=it(s.dies[d],e.test)??NaN;let p=qt(r);if(n.length===1&&!t.melt&&r){const d=n[0],u=Bn(d.allDies??d.dies,i.testDefs??[],d.passBins).limits.get(e.test);u&&(p={...p,patLow:u.lo,patHigh:u.hi})}return{...l,level:"die",kind:"numeric",unit:r?.unit,num:h,limits:p}}if("meta"in e){const r=n.map(d=>Bt(d.metadata,e.meta,i.curation));if(r.every(d=>d===void 0)){const d=[...new Set(n.flatMap(v=>Object.keys(v.metadata??{})))].sort(),u=xn(e.meta,d),g=d.length?` Wafer fields in these dies: ${d.slice(0,12).join(", ")}${d.length>12?`, and ${d.length-12} more`:""}.`:" These dies have no wafer fields.";return{...l,level:"wafer",kind:"categorical",cat:r,issue:`No wafer has a "${o}" value.${u?` Did you mean "${u}"?`:""}${g}`}}const h=r.map(d=>d===void 0||!xt.test(d.trim())?NaN:Number(d)),p=r.every((d,u)=>d===void 0||Number.isFinite(h[u]));return{...l,level:"wafer",kind:p?"numeric":"categorical",cat:r,num:p?Float64Array.from(h):void 0}}switch(e.builtin){case"wafer":return{...l,level:"wafer",kind:"categorical",cat:n.map(r=>r.label)};case"waferOrder":return{...l,level:"wafer",kind:"numeric",num:Float64Array.from(n,(r,h)=>(t.melt?t.melt.realOf[h]:h)+1)};case"test":return t.melt?{...l,level:"wafer",kind:"categorical",cat:n.map((r,h)=>t.melt.labels[t.melt.testOf[h]])}:{...l,level:"wafer",kind:"categorical",issue:"Test divides a set of tests: choose several tests as the values"};case"dieCount":return{...l,level:"wafer",kind:"numeric",num:Float64Array.from(n,r=>r.dies.length)};case"yield":{const r=new Float64Array(c),h=new Float64Array(c);return n.forEach((p,d)=>{const{pass:u,total:g}=yt(p.dies,p.passBins);r[d]=g>0?u/g*100:NaN,h[d]=g}),{...l,level:"wafer",kind:"numeric",unit:"%",num:r,weights:h}}case"x":case"y":{const r=new Float64Array(f);for(let h=0;h<f;h++){const p=s.dies[h];r[h]=nt(p)?e.builtin==="x"?p.x:p.y:NaN}return{...l,level:"die",kind:"numeric",num:r}}case"hbin":case"sbin":{const r=s.dies.map(h=>{const p=e.builtin==="hbin"?h.hbin:h.sbin;return p===void 0?void 0:Gn(p)});return{...l,level:"die",kind:"categorical",cat:r}}case"site":return{...l,level:"die",kind:"categorical",cat:s.dies.map(r=>r.siteNum===void 0?void 0:`Site ${r.siteNum}`)};case"reprobed":return{...l,level:"die",kind:"numeric",unit:"%",num:Float64Array.from(s.dies,r=>r.retestCount!==void 0?100:0)};case"radius":{const r=new Float64Array(f);for(let h=0;h<f;h++){const p=gn(s.dies[h],{wafer:n[s.item[h]].wafer});r[h]=p===void 0?NaN:p*100}return{...l,level:"die",kind:"numeric",unit:"%",num:r}}case"pat":{const r=i.testDefs??[];if(Yt(r).length===0)return{...l,level:"die",kind:"categorical",issue:"PAT needs tests with both a low and a high limit"};const h=new Map,p=s.dies.map((d,u)=>{const g=n[s.item[u]];let v=h.get(g);if(!v){const b=g.allDies??g.dies,k=_n(b,r,g.passBins);v=new Map(b.map((w,S)=>[w,k[S].verdict?Pn[k[S].verdict]:void 0])),h.set(g,v)}return v.get(d)});return{...l,level:"die",kind:"categorical",cat:p}}case"ring":case"quadrant":case"reticleCell":case"reticleShot":{const r=He[e.builtin],h=s.dies.map((p,d)=>{const u=n[s.item[d]];return r.valueOf(p,{wafer:u.wafer,ringCount:u.ringCount})});return{...l,level:"die",kind:"categorical",cat:h}}default:return{...l,level:"die",kind:"categorical",issue:"Needs a newer version of this tool"}}}function Xn(e,t){const n=e.rows.dies.length,s=new Float64Array(n),i=new Float64Array(n);for(let o=0;o<n;o++){const l=e.items[e.rows.item[o]],{pass:f,total:c}=yt([e.rows.dies[o]],l.passBins);s[o]=c>0?f*100:NaN,i[o]=c}return{...t,level:"die",num:s,weights:i,perDie:!0}}export const probabilityPosition=(e,t)=>(e+.5)/t;export function combine(e,t){const n=e.filter(Number.isFinite);if(t==="count")return n.length;if(n.length===0)return NaN;switch(t){case"sum":return n.reduce((s,i)=>s+i,0);case"min":return Me(n);case"max":return Re(n);case"median":{const s=[...n].sort((o,l)=>o-l),i=s.length>>1;return s.length%2?s[i]:(s[i-1]+s[i])/2}default:return n.reduce((s,i)=>s+i,0)/n.length}}const Nt={mean:"a mean",median:"a median",min:"a minimum",max:"a maximum",sum:"a sum",count:"a count",yield:"a pooled yield"},Ke={mean:"Mean",median:"Median",min:"Min",max:"Max",sum:"Sum",count:"Count",yield:"Pooled yield"};function ce(e,t,n,s,i,o){const l=s.axes?.[e]??{};let f=l.scale??"linear";if(f==="log"){for(const c of i)if(Number.isFinite(c)&&c<=0){f="linear",o.push(`The ${e.toUpperCase()} axis stays linear: a log axis needs every value above zero`);break}}return{label:l.label??t,unit:n,scale:f,min:l.min,max:l.max,reverse:l.reverse}}const en=e=>/^[A-Z][a-z]*(?: [a-z]+)*$/.test(e)?e.toLowerCase():e,tn=(e,t,n)=>n?`${e} by range of ${t}`:`${e} over ${t}`;function Yn(e,t){const{chart:n}=e,s=e.fields??{},i=ke(s.x),o=i.filter(c=>!Ie(c)),l=i.length?o.length?fe(o.map(c=>fieldLabel(c,t.testDefs,t.curation))):void 0:(n==="box"||n==="bar")&&!ue(s.y)?"Wafer":void 0,f=s.y?fieldLabel(s.y,t.testDefs,t.curation):void 0;if((n==="box"||n==="bar")&&f&&!l)return f;switch(n){case"scatter":return l&&f?`${f} vs ${l}`:"Scatter";case"histogram":return f??(i[0]?fieldLabel(i[0],t.testDefs,t.curation):void 0)??"Histogram";case"probability":return f?`${f}, cumulative`:"Probability plot";case"control":return f?`${f} control chart`:"Control chart";case"goal":return"Capability goal plot";case"line":return l&&f?tn(f,l,i.length===1&&Oe(i[0])):"Line";case"box":return f&&l?`${f} by ${l}`:"Box";case"bar":return l?f?`${f} by ${l}`:`Dies by ${l}`:"Bar";default:return""}}function _e(e,t,n,s={}){return{spec:e,issues:n,notes:[],level:"die",autoTitle:Yn(e,s),groups:[""],population:{wafers:t.length,dies:t.reduce((i,o)=>i+o.dies.length,0)},plotted:0,omitted:[]}}export function combinationIssue(e,t,n={}){const s=[t.x,n.continuousColor?void 0:t.color].filter(c=>!!c&&c.level==="die"),i=!!t.y&&t.y.yield&&t.y.level==="wafer",o=(e==="bar"||e==="line")&&(n.aggregate===void 0||n.aggregate==="yield"||n.aggregate==="mean");if(i&&s.length&&!o)return{long:`${t.y.label} is one figure per wafer, and ${s[0].label} belongs to dies, so a ${e} of it cannot be split by ${s[0].label}. A bar chart of yield can (pooled yield per ${s[0].label.toLowerCase()}), or plot a measured value instead`,short:`${t.y.label} is per wafer: use a bar or line chart`};const l=[t.x,t.y].filter(c=>!!c);let f=n.level??(l.some(c=>c.level==="die")?"die":"wafer");if(e==="bar"&&!t.y&&s.length&&(f="die"),t.color?.level==="die"&&f==="wafer"&&!n.continuousColor&&!(i&&(e==="bar"||e==="line")))return{long:`${t.color.label} is per die, so it cannot colour a plot with one mark per wafer. Plot a measured value (one mark per die), or make a bar chart of yield, which can be split by ${t.color.label.toLowerCase()}`,short:`${t.color.label} is per die: this plot has one mark per wafer`}}function kt(e,t,n){return`Test ${e} was "${t}" when this plot was saved; in these dies it is "${n}". Choose the test again to plot "${n}"`}const qn={limits:"position in limits",zscore:"z-score",robust:"robust z-score"};function Kn(e,t){return e==="limits"?`rescaled to ${t.size===1?t.has("spec")?"spec limits":"test limits":"spec limits, or test limits where a test has no spec"}: 0 is the low limit, 1 the high`:e==="zscore"?"rescaled per test: standard deviations from the mean of the values in view":"rescaled per test: robust standard deviations (1.4826 \xD7 median absolute deviation) from the median of the values in view"}function nn(e,t,n,s,i){const o=new Map,l=[],f=new Set;for(const c of e){if(s==="limits"){const d=n.find(g=>g.testNumber===c),u=d&&Ut(d);if(!u){l.push(`${i(c)} has no low and high limit to place it by`);continue}f.add(u.basis),o.set(c,{offset:u.lsl,scale:u.usl-u.lsl});continue}const r=[];for(const d of t){const u=it(d,c);u!==void 0&&Number.isFinite(u)&&r.push(u)}if(r.length<2){l.push(`${i(c)} has fewer than two values to measure a spread in`);continue}let h,p;if(s==="zscore"?(h=Ht(r),p=Math.sqrt(Wt(r,h))):(h=$t(r),p=1.4826*$t(r.map(d=>Math.abs(d-h)))),!(p>0)||!Number.isFinite(p)){l.push(`${i(c)} has no spread: its values ${s==="robust"?"are mostly":"are all"} the same`);continue}o.set(c,{offset:h,scale:p})}return{scales:o,dropped:l,bases:f}}function Zn(e,t,n){const s={};for(const i of["limitLow","limitHigh","specLow","specHigh","patLow","patHigh"]){let o,l=!0;for(const f of e){const c=t(f)?.[i],r=n.get(f);if(c===void 0||!Number.isFinite(c)||!r){l=!1;break}const h=(c-r.offset)/r.scale;if(o===void 0)o=h;else if(Math.abs(h-o)>1e-9*Math.max(1,Math.abs(o))){l=!1;break}}l&&o!==void 0&&(s[i]=o)}return Object.keys(s).length?s:void 0}function sn(e,t){let n;switch(e.type){case"scatter":n=e.points.map(i=>t==="x"?i.x:i.y);break;case"histogram":case"probability":n=t==="x"?e.values.flat():[];break;case"box":n=t==="y"?e.cells.flat(2):[];break;case"bar":n=t==="y"?e.values.flat():[];break;case"line":n=t==="x"?e.xs:[...e.values.flat(),...e.band?[...e.band.lo.flat(),...e.band.hi.flat()]:[]];break;case"control":n=t==="x"?e.xs:[...e.values,e.limits.ucl,e.limits.lcl];break;case"goal":n=e.points.map(i=>t==="x"?i.x:i.y);break;case"heatmap":n=[];break}const s=n.filter(Number.isFinite);return s.length?[Me(s),Re(s)]:void 0}function Qn(e,t,n){if(e.issues.length||!e.marks)return e;const s=e.groups.map(f=>n.groups.indexOf(f));if(s.some(f=>f<0))return e;const i=an(e.marks,t,s,n.groups.length),o=n.marks&&sn(n.marks,"x"),l=n.marks&&sn(n.marks,"y");return{...e,marks:i,groups:n.groups,colorScale:n.colorScale??e.colorScale,x:e.x&&o?{...e.x,extent:o}:e.x,y:e.y&&l?{...e.y,extent:l}:e.y}}function Jn(e,t){return e.issues.length||!e.marks?e:{...e,marks:an(e.marks,t,e.groups.map((n,s)=>s),e.groups.length)}}function an(e,t,n,s){const i=(c,r)=>{const h=Array.from({length:s},r);return c.forEach((p,d)=>{h[n[d]]=p}),h},o=c=>t[c],l=c=>r=>{const h=c(r);return{...h,item:o(h.item)}};let f;switch(e.type){case"scatter":f={type:"scatter",points:e.points.map(c=>({...c,item:o(c.item),group:n[c.group]}))};break;case"histogram":f={type:"histogram",values:i(e.values,()=>[]),units:i(e.units,()=>[]),unit:l(e.unit)};break;case"probability":f={type:"probability",values:i(e.values,()=>[]),units:i(e.units,()=>[]),unit:l(e.unit)};break;case"box":case"bar":f={...e,cells:i(e.cells,()=>e.categories.map(()=>[])),cellUnits:i(e.cellUnits,()=>e.categories.map(()=>[])),values:i(e.values,()=>e.categories.map(()=>NaN)),categoryItems:e.categoryItems?.map(c=>c>=0?o(c):c),unit:l(e.unit)};break;case"line":f={...e,values:i(e.values,()=>e.xs.map(()=>NaN)),counts:i(e.counts,()=>e.xs.map(()=>0)),cellUnits:i(e.cellUnits,()=>e.xs.map(()=>[])),unit:l(e.unit),...e.band?{band:{lo:i(e.band.lo,()=>e.xs.map(()=>NaN)),hi:i(e.band.hi,()=>e.xs.map(()=>NaN))}}:{}};break;case"control":f={...e,items:e.items.map(o)};break;case"goal":f={type:"goal",points:e.points.map(c=>({...c,group:n[c.group]}))};break;case"heatmap":f={...e,unit:l(e.unit)};break}return f}function ei(e,t,n){let s=0,i=0;const o=t.map(f=>{let c;for(let r=0;r<f.dies.length;r++){const h=f.dies[r];if(Mt(h)){c?.push(h);continue}c??=f.dies.slice(0,r),h.partial?s++:i++}return c?{...f,dies:c,allDies:f.allDies??f.dies}:f}),l=ti(resolvePlot(e,o,{...n,eligibleOnly:!0}));return s+i>0?{...l,leftOut:{partial:s,edge:i}}:l}export const axisValues=(e,t)=>e.marks?St(e.marks,t).filter(Number.isFinite):[];function St(e,t){switch(e.type){case"bar":return t==="y"?e.values.flat():[];case"box":return t==="y"?e.cells.flat(2):[];case"scatter":return e.points.map(n=>t==="x"?n.x:n.y);case"line":return t==="y"?e.values.flat():e.xs;case"control":return t==="y"?e.values:e.xs;case"histogram":case"probability":return t==="x"?e.values.flat():[];default:return[]}}function ti(e){const t=[],n=p=>{const d=e.spec.axes?.[p]?.references;if(!d?.length||!e[p])return;let u;return d.flatMap(g=>kn(g)?(u??=e.marks?St(e.marks,p).filter(Number.isFinite):[],u.length===0?(t.push(`No ${g.stat} line: nothing is drawn along that axis`),[]):[{at:g.stat==="median"?$t(u):Ht(u),label:g.label??g.stat}]):[g])},s=p=>{if(!e.spec.axes?.[p]?.clip||!e[p]||!e.marks)return;const d=St(e.marks,p).filter(Number.isFinite),u=On(d);if(!u||d.length===0)return;const g=Math.max(Me(d),u.lo),v=Math.min(Re(d),u.hi);if(!(v>g))return;const b=d.reduce((k,w)=>k+(w<g||w>v?1:0),0);return{lo:g,hi:v,outside:b}},i=n("x"),o=n("y"),l=s("x"),f=s("y");if(!i&&!o&&!l&&!f)return e;const c=(p,d,u)=>p&&(d||u)?{...p,...d?{references:d}:{},...u?{clip:u}:{}}:p,r=p=>({...p,x:c(p.x,i,l),y:c(p.y,o,f)}),h=r(e);h.facets&&(h.facets=h.facets.map(p=>({...p,plot:r(p.plot)})));for(const p of[l,f])p?.outside&&t.push(`Axis clipped to the robust range: ${p.outside.toLocaleString("en-GB")} value${p.outside===1?"":"s"} outside it, still counted in every statistic`);return t.length?{...h,notes:[...h.notes,...t]}:h}export function conditionUnit(e,t){if(Ae(e)&&"test"in e)return t?.find(n=>n.testNumber===e.test)?.unit;if(Ae(e)&&"builtin"in e&&(e.builtin==="yield"||e.builtin==="radius"))return"%"}const on=(e,t)=>{const n=String(Number(e.toPrecision(6)));return t==="%"?`${n}%`:t?qe(e,t):n};export function conditionText(e,t,n){const s=fieldLabel(e.field,t,n);if(e.values){const f=e.values.length<2?e.values.join(""):`${e.values.slice(0,-1).join(", ")} or ${e.values[e.values.length-1]}`;return`${s} is ${e.not?"not ":""}${f}`}const i=conditionUnit(e.field,t),o=e.min!==void 0?on(e.min,i):void 0,l=e.max!==void 0?on(e.max,i):void 0;return o!==void 0&&l!==void 0?`${s} ${e.not?"outside":"from"} ${o} to ${l}`:o!==void 0?`${s} ${e.not?"below":"at least"} ${o}`:`${s} ${e.not?"above":"at most"} ${l}`}export function applyConditions(e,t,n={}){const s=ye(t),i=s.dies.length,o={items:[...t],index:t.map((v,b)=>b),said:"",dies:{kept:i,total:i},wafers:{kept:t.length,total:t.length}};if(e.length===0)return o;const l=new Uint8Array(t.length).fill(1),f=new Uint8Array(i).fill(1),c=[],r=[];for(const v of e){const b=J(v.field,{items:t,rows:s,ctx:n});if(b.issue)return{...o,issue:b.issue};let k;if(v.values){if(!b.cat)return{...o,issue:`${b.label} is a number: keep a range of it, not values`};const S=new Set(v.values),_=b.cat;k=M=>_[M]!==void 0&&S.has(_[M])!==!!v.not}else{if(!b.num)return{...o,issue:`${b.label} is a category: keep some of its values, not a range`};const S=b.num,_=v.min??-1/0,M=v.max??1/0;k=z=>Number.isFinite(S[z])&&(S[z]>=_&&S[z]<=M)!=!!v.not}const w=b.level==="wafer"?l:f;for(let S=0;S<w.length;S++)w[S]&&!k(S)&&(w[S]=0);(b.level==="wafer"?c:r).push(conditionText(v,n.testDefs,n.curation))}const h=t.map(()=>[]);let p=0;for(let v=0;v<i;v++)f[v]&&l[s.item[v]]&&(h[s.item[v]].push(s.dies[v]),p++);const d=[],u=[];t.forEach((v,b)=>{if(l[b]){if(r.length===0){d.push(v),u.push(b);return}h[b].length&&(d.push({...v,dies:h[b],allDies:v.allDies??v.dies}),u.push(b))}});const g=[c.length?`only wafers where ${fe(c)}`:"",r.length?`only dies where ${fe(r)}`:""].filter(Boolean).join("; ");return{items:d,index:u,said:g,dies:{kept:p,total:i},wafers:{kept:d.length,total:t.length}}}function ni(e,t,n){const s=(...l)=>_e(e,t,l,n),i=applyConditions(Pt(e),t,n);return i.issue?s(i.issue):i.items.length===0?s(`Nothing is left: no ${i.said.replace(/^only /,"").replace(/; only /," and ")}`):{...Jn(resolvePlot(e,i.items,{...n,whereApplied:!0}),i.index),filterNote:i.said}}function ii(e,t,n){const s=e.fields.facet,{facet:i,...o}=e.fields,l={...e,fields:o},f=(...w)=>_e(e,t,w,n),c=fieldLabel(s,n.testDefs,n.curation),r=t.flatMap(w=>w.dies),h={...n,inFacet:!0,scaleDies:n.scaleDies??r,wholeWafers:n.wholeWafers??t.length,wholeItems:n.wholeItems??t,binEdges:n.binEdges??new Map},p=Ie(s);if(p&&!ue(e.fields?.y))return f("Test panels need several tests as the values");if(p&&(ke(e.fields?.x).some(Ie)||Ie(e.fields?.color)))return f("Test already divides the panels, so it cannot also be on the X axis or the colour");if(ke(e.fields?.x).some(w=>Le(w,s))||e.fields?.color&&Ae(e.fields.color)&&Le(e.fields.color,s))return f(`${c} divides the panels, so on the X axis or the colour as well it would have one value per panel`);const d=resolvePlot(l,t,p?{...h,facetByTest:!0}:h),u=w=>({...w,autoTitle:`${w.autoTitle} \xB7 panels by ${c}`});if(d.issues.length||!d.marks)return u(d);let g=[];const v=[];if(p){const w=d.setTests;if(!w)return f("Test panels need several tests as the values");const S=t.map((_,M)=>M);g=w.tests.map((_,M)=>({label:w.labels[M],items:[...t],index:S,spec:{...l,fields:{...o,y:{test:_,...n.testDefs?.find(z=>z.testNumber===_)?.name?{name:n.testDefs.find(z=>z.testNumber===_).name}:{}}}}}))}else{const w=ye(t),S=J(s,{items:t,rows:w,ctx:n});if(S.issue)return f(S.issue);if(!S.cat)return f(`${c} is continuous: panels need a category, such as split, ring or site`);if(S.level==="die"&&d.level==="wafer")return f(`${c} is per die, so it cannot divide a plot with one mark per wafer into panels`);const _=[];for(const P of S.cat)P!==void 0&&!_.includes(P)&&_.push(P);const M=Te(s,_,We(S));if(M.length>zt)return f(`${c} has ${M.length} values, and a plot draws at most ${zt} panels: choose a field with fewer, or narrow Show`);const z=S.cat.filter(P=>P===void 0).length;z&&v.push(`${z.toLocaleString("en-GB")} ${S.level==="die"?"dies":"wafers"} with no ${c} value are in no panel`),g=M.map(P=>{const Z=[],ee=[];if(S.level==="wafer")t.forEach((B,O)=>{S.cat[O]===P&&(Z.push(B),ee.push(O))});else{const B=t.map(()=>[]);for(let O=0;O<w.dies.length;O++)S.cat[O]===P&&B[w.item[O]].push(w.dies[O]);t.forEach((O,a)=>{B[a].length&&(Z.push({...O,dies:B[a],allDies:O.allDies??O.dies}),ee.push(a))})}return{label:P,items:Z,index:ee,spec:l}})}const b=g.map(w=>({label:w.label,plot:Qn(resolvePlot(w.spec,w.items,h),w.index,d)})),k=d.usesPat||Un(s)||b.some(w=>w.plot.usesPat);return{...u(d),notes:[...d.notes,...v],facets:b,facetLabel:c,...k?{usesPat:!0}:{}}}function si(e,t,n,s){if(s.normalize==="zscore"||s.normalize==="robust"){const c=Math.max(Math.abs(Me(n)),Math.abs(Re(n)));if(c>0)return{label:e,unit:t,lo:-c,hi:c,diverging:!0}}if(oi(s))return{label:e,unit:t,lo:ai,hi:100,rating:!0};let i=Me(n),o=Re(n);const l=(i+o)/2,f=Math.abs(l)*$n;return l!==0&&o-i<f&&(i=l-f/2,o=l+f/2),{label:e,unit:t,lo:i,hi:o,...n.every(Number.isInteger)?{integer:!0}:{}}}const ai=50;function oi(e){const t=e.fields?.y;return e.aggregate==="yield"?!0:t?"builtin"in t&&t.builtin==="yield"||"passRate"in t:!1}function ri(e,t,n){const s=e.fields??{},i=(...M)=>_e(e,t,M,n),o=ke(s.x)[0]??{builtin:"wafer"},l=s.rows??(ue(s.y)?{builtin:"test"}:void 0);if(!l)return i("Choose a field for the rows: a heatmap has one row per value of it");if(Le(l,o))return i("The rows and the columns need two different fields");const{rows:f,...c}=s,r={...e,chart:"bar",fields:{...c,x:[l,o],color:{none:!0}}};delete r.stack,delete r.sort,delete r.top,delete r.cumulative;const h=resolvePlot(r,t,{...n,asHeatmap:!0,inFacet:!0,whereApplied:n.whereApplied});if(h.issues.length||!h.marks||h.marks.type!=="bar")return{...h,spec:e};const p=h.marks,d=p.nest?.parts??[],u=[...new Set(d.map(M=>M[0]))],g=[...new Set(d.map(M=>M[1]))];let v=Te(o,g,g.every(M=>xt.test(M)));if("builtin"in o&&o.builtin==="wafer"&&n.groupBy){const M=new Map(t.map(P=>[P.label,Bt(P.metadata,n.groupBy,n.curation)??""])),z=Te({meta:n.groupBy},[...new Set(v.map(P=>M.get(P)??""))],!1);v=[...v].sort((P,Z)=>z.indexOf(M.get(P)??"")-z.indexOf(M.get(Z)??""))}const b=u.map(()=>v.map(()=>NaN)),k=u.map(()=>v.map(()=>[]));d.forEach((M,z)=>{const P=u.indexOf(M[0]),Z=v.indexOf(M[1]);b[P][Z]=p.values[0][z],k[P][Z]=p.cellUnits[0][z]});const w=b.flat().filter(Number.isFinite),S=fieldLabel(l,n.testDefs,n.curation),_=fieldLabel(o,n.testDefs,n.curation);return{...h,spec:e,marks:{type:"heatmap",rows:u,cols:v,values:b,cellUnits:k,unit:p.unit},autoTitle:`${h.y?.label??"Dies"} by ${S} and ${_}`,x:{label:e.axes?.x?.label??_,scale:"linear"},y:{label:e.axes?.y?.label??S,scale:"linear"},colorScale:w.length?si(h.y?.label??"Count",h.y?.unit,w,e):void 0,groups:[""]}}function li(e,t,n){const s=(...a)=>_e(e,t,a,n),i=e.fields??{};if(!i.y)return s("Choose a field for the values");if(ue(i.y))return s("A control chart follows one value: choose one test");const o=ke(i.x)[0]??{builtin:"waferOrder"},l=ye(t),f={items:t,rows:l,ctx:n},c=J(o,f),r=J(i.y,f),h=c.issue??r.issue;if(h)return s(h);if(c.level!=="wafer"||!c.num)return s(`A control chart runs along a wafer field with a number per wafer, such as wafer order or slot, not ${c.label}`);if(!r.num)return s(`${r.label} is a category, not a number, so it cannot be charted`);const p=e.aggregate&&e.aggregate!=="yield"&&e.aggregate!=="count"?e.aggregate:"mean",d=t.map(()=>[]);if(r.level==="die")for(let a=0;a<l.dies.length;a++)d[l.item[a]].push(r.num[a]);const u=a=>r.level==="wafer"?r.num[a]:combine(d[a],r.perDie?"mean":p),g=t.map((a,G)=>G).filter(a=>Number.isFinite(c.num[a])&&Number.isFinite(u(a))).sort((a,G)=>c.num[a]-c.num[G]||a-G),v=t.length-g.length;if(g.length<3)return s("A control chart needs at least three wafers with a value");const b=g.map(u),k=g.map(a=>c.num[a]),w=En(b,e.baseline),S=Dn(b,w),_=r.perDie||r.level==="wafer"?r.label:`${Ke[p]} ${r.label}`,M=[];let z=[""],P,Z;const ee=i.color,B=ee===void 0||"none"in ee?void 0:"follow"in ee?n.groupBy?{meta:n.groupBy}:void 0:ee;if(B){const a=J(B,f);if(a.issue)M.push(a.issue);else if(a.level!=="wafer"||!a.cat)M.push(`The points are coloured by a wafer field: ${a.label} is not one, so they are not coloured`);else{const G=[];for(const te of g){const D=a.cat[te];D!==void 0&&!G.includes(D)&&G.push(D)}z=Te(B,G,We(a)),P=g.map(te=>a.cat[te]===void 0?-1:z.indexOf(a.cat[te])),Z=a.label}}const O=S.length?`${S.length} point${S.length===1?"":"s"} break${S.length===1?"s":""} a Western Electric rule (${[...new Set(S.flatMap(a=>a.rules))].sort().map(a=>`${a}: ${Mn[a]}`).join("; ")})`:"no point breaks a Western Electric rule";return{spec:e,issues:[],notes:M,level:"wafer",marks:{type:"control",xs:k,values:b,items:g,limits:w,violations:S,...P?{group:P}:{}},autoTitle:`${_} control chart`,x:ce("x",c.label,c.unit,e,k,M),y:{...ce("y",_,r.unit,e,b,M),limits:!r.perDie&&r.level==="die"&&(p==="mean"||p==="median")?r.limits:void 0},groups:z,colorLabel:Z,aggregation:`individuals chart: centre the mean of ${w.baseline===b.length?"all":`the first ${w.baseline}`} wafers, limits \xB13\u03C3 with \u03C3 the average moving range / 1.128; ${O}`,population:{wafers:t.length,dies:l.dies.length},plotted:b.length,omitted:v?[{field:r.label,count:v}]:[]}}function ui(e,t,n){const s=(...b)=>_e(e,t,b,n),i=n.testDefs??[],o=e.fields??{};let l;if(!o.y)l=i.filter(be);else if(ue(o.y)){const b=new Set(expandTestSet(o.y,i).tests);l=i.filter(k=>b.has(k.testNumber))}else if("test"in o.y)l=i.filter(b=>b.testNumber===o.y.test);else return s("A goal plot shows tests: choose tests, or leave the values empty for every test with both limits");if(l=l.filter(b=>be(b)&&Ut(b)!==void 0),l.length===0)return s("No test here has both a low and a high limit to set a goal by");const f=ye(t),c={items:t,rows:f,ctx:n},r=o.color,h=r===void 0||"follow"in r?n.groupBy?{meta:n.groupBy}:void 0:"none"in r?void 0:r;let p=[""],d=()=>0;if(h){const b=J(h,c);if(b.issue)return s(b.issue);if(!b.cat)return s(`${b.label} is continuous: colour a goal plot by a category such as split`);const k=S=>b.level==="die"?b.cat[S]:b.cat[f.item[S]],w=[];for(let S=0;S<f.dies.length;S++){const _=k(S);_!==void 0&&!w.includes(_)&&w.push(_)}p=Te(h,w,We(b)),d=S=>{const _=k(S);return _===void 0?-1:p.indexOf(_)}}const u=p.map(()=>[]);for(let b=0;b<f.dies.length;b++){const k=d(b);k>=0&&u[k].push(f.dies[b])}const g=[];if(u.forEach((b,k)=>{for(const w of Rn([{dies:b}],l)){if(!w.hasSpec||w.lsl===void 0||w.usl===void 0||!(w.stdOverall>0)||w.ppk===null)continue;const S=w.usl-w.lsl;g.push({x:(w.mean-(w.lsl+w.usl)/2)/S,y:w.stdOverall/S,group:k,testNumber:w.testNumber,label:w.label,ppk:w.ppk,n:w.n,basis:w.limitBasis??"test"})}}),g.length===0)return s("No test has values with a spread to place");const v=[];return{spec:e,issues:[],notes:v,level:"die",marks:{type:"goal",points:g},autoTitle:h?`Capability goal plot \xB7 by ${fieldLabel(h,i,n.curation)}`:"Capability goal plot",x:ce("x","Mean offset from the centre of the limits",void 0,e,g.map(b=>b.x),v),y:ce("y","Standard deviation",void 0,e,g.map(b=>b.y),v),groups:p,colorLabel:h?fieldLabel(h,i,n.curation):void 0,aggregation:"each test's mean offset and standard deviation over its dies, as shares of its limit window (spec limits where it has both, else test limits); triangles: Ppk 1 and 1.33",population:{wafers:t.length,dies:f.dies.length},plotted:g.length,omitted:[]}}export function resolvePlot(e,t,n={}){const s=fi(e,t,n);return n.populationLabel&&!n.inFacet?{...s,populationLabel:n.populationLabel}:s}function fi(e,t,n={}){const s=Nn(e);if(s)return _e(e,t,[s],n);const i=(...m)=>_e(e,t,m,n);if(e.chart==="sweep")return i("A sweep is drawn by the sweep panel");if(!n.eligibleOnly)return ei(e,t,n);if(!n.whereApplied&&Pt(e).length)return ni(e,t,n);if(e.fields?.facet&&!n.inFacet)return ii(e,t,n);if(e.chart==="control")return li(e,t,n);if(e.chart==="goal")return ui(e,t,n);if(e.chart==="heatmap"&&!n.asHeatmap)return ri(e,t,n);const o=e.chart,l=e.fields??{},f=n.testDefs??[],c=t.flatMap(m=>m.dies),r=[],h=ue(l.y)?l.y:void 0;if(ue(l.x)||ue(l.color))return i("A set of tests can only be the values (Y) of a plot");if(e.normalize&&o==="scatter")return i("Rescaling applies to the values of a box, bar, line or histogram, not to a scatter");if(h&&o==="scatter")return i("A scatter plots one value against another: choose one test for each axis, or a box, bar, line or histogram to show several tests");const p=m=>f.find(x=>x.testNumber===m)?.name||h?.names?.[String(m)]||`Test ${m}`;let d,u,g=new Set,v=t;if(h){const{tests:m,problems:x}=expandTestSet(h,f);if(x.length)return i(...x);const N=new Set(c.length?st(c,"values"):[]),I=[];let $=[];for(const C of m){const R=f.find(X=>X.testNumber===C),U=h.names?.[String(C)];if(R&&U&&R.name&&!wt(U,R.name))return i(kt(C,U,R.name));if(h.passRate){if(!R){I.push(U?`${U} (test ${C})`:`test ${C}`);continue}if(passKindOf(R,h.judge)==="spec"&&R.limitLow===void 0&&R.limitHigh===void 0){I.push(`${p(C)} (no test limits)`);continue}$.push(C);continue}if(R&&!be(R)){I.push(`${p(C)} (pass/fail, no value)`);continue}if(!N.has(C)){I.push(U?`${U} (test ${C})`:`test ${C}`);continue}$.push(C)}if($.length===0)return i(`None of these tests has ${h.passRate?"a verdict to judge":"values"} in these dies${I.length?`: ${I.join(", ")}`:""}`);if(h.passRate&&e.normalize)return i("A pass rate is a share of dies, not a measured value: it cannot be rescaled");if($.length*c.length>TEST_SET_VALUE_LIMIT){const C=Math.max(1,Math.floor(TEST_SET_VALUE_LIMIT/Math.max(1,c.length)));return i(`${$.length} tests over ${c.length.toLocaleString("en-GB")} dies is ${($.length*c.length).toLocaleString("en-GB")} values, more than one plot draws (${TEST_SET_VALUE_LIMIT.toLocaleString("en-GB")}): choose at most ${C} tests, or show fewer wafers`)}if(I.length&&r.push(`Left out, with no values here: ${I.join(", ")}`),e.normalize){const C=nn($,n.scaleDies??c,f,e.normalize,p);if(C.scales.size===0)return i(...C.dropped);C.dropped.length&&r.push(`Left out: ${C.dropped.join("; ")}`),$=$.filter(R=>C.scales.has(R)),u=C.scales,g=C.bases}else if(!h.passRate){const C=[...new Set($.map(R=>f.find(U=>U.testNumber===R)?.unit).filter(R=>!!R))];if(C.length>1)return i(`These tests are measured in different units (${C.join(", ")}): rescale them to compare them on one axis`)}const L=$.map(p),A=L.map((C,R)=>L.indexOf(C)!==L.lastIndexOf(C)?`${C} \xB7 ${$[R]}`:C),F=[],W=[],j=[];$.forEach((C,R)=>t.forEach((U,X)=>{F.push(U),W.push(X),j.push(R)})),d={realOf:Int32Array.from(W),testOf:Int32Array.from(j),tests:$,labels:A},v=F}const b=m=>d?d.realOf[m]:m,k=ye(v),w={items:v,rows:k,ctx:n,melt:d},S=ke(l.x);if(S.length>1&&o!=="box"&&o!=="bar")return i("Nested categories need a box or bar chart: choose one field for X");if(S.length>jt)return i(`At most ${jt} fields can be nested on X`);if(S.some((m,x)=>S.findIndex(N=>Le(m,N))!==x))return i("A field can be only one level of the categories");const _=S.length?S:o==="box"||o==="bar"?[{builtin:h?"test":"wafer"}]:[],M=_[0],z=_.some(Ie),P=l.y,Z=o==="histogram"||o==="probability",ee=Z?P??M:P;if(o==="scatter"||o==="line"){if(!M)return i("Choose a field for X");if(!P)return i("Choose a field for Y")}if(o==="box"&&!P)return i("Choose a field for Y");if(o==="histogram"&&!ee)return i("Choose a field to count");if(o==="probability"&&!ee)return i("Choose the values to plot");const B=Z?[]:_.map(m=>J(m,w)).map(m=>o==="line"&&m.mid&&!m.issue?{...m,kind:"numeric",num:m.mid,unit:m.midUnit,cat:void 0}:m),O=B[0];let a=ee?J(ee,w):void 0;if(e.normalize&&a&&!a.issue){if(!d){if(!("test"in a.field)||!a.num)return i("Rescaling applies to a measured test: choose a test for the values");const A=a.field.test,F=nn([A],n.scaleDies??k.dies,f,e.normalize,()=>a.label);if(F.scales.size===0)return i(...F.dropped);u=F.scales,g=F.bases}const m=A=>d?d.tests[d.testOf[k.item[A]]]:a.field.test,x=new Float64Array(a.num.length);for(let A=0;A<x.length;A++){const F=u.get(m(A));x[A]=(a.num[A]-F.offset)/F.scale}const N=d?d.tests:[m(0)],I=d?N.length>3?`${N.length} tests`:fe(d.labels):a.label,$=a.limits;a={...a,num:x,unit:void 0,limits:Zn(N,d?A=>qt(f.find(F=>F.testNumber===A)):()=>$,u),label:`${I} (${qn[e.normalize]})`}}else d&&a&&!a.issue&&!Sn(a.field)&&(a={...a,label:d.tests.length>3?`${d.tests.length} tests`:fe(d.labels)});const G=o==="scatter"||o==="line"?[["X",O],["Y",a]]:o==="histogram"?[["to count",a]]:o==="probability"?[["values",a]]:o==="box"||o==="bar"?[["Y",a]]:[];for(const[m,x]of G)if(x&&!x.issue&&x.kind==="categorical"&&!x.num)return i(`${x.label} is a category, not a number, so it cannot be ${m==="to count"?"the field a histogram counts":m==="values"?"the values of a probability plot":`the ${m} of a ${o}`}. Use it as the X of a bar or box chart (one bar per ${x.label.toLowerCase()}), or as the colour`);const te=h&&!z&&!n.facetByTest&&(l.color===void 0||"follow"in l.color)?{builtin:"test"}:l.color;if(h&&!z&&!n.facetByTest&&!Ie(te))return i("Put Test on the X axis or the colour, so each test is drawn on its own");let D,At=!1,at;te===void 0||"follow"in te?n.groupBy?at=n.groupBy:(n.wholeWafers??t.length)>1&&(At=!0):"none"in te||(D=J(te,w)),at&&(D=J({meta:at},w)),At&&(D=J({builtin:"wafer"},w)),D?.issue&&(te===void 0||"follow"in te)&&(D=void 0);const ot=[...B.map(m=>m.issue),a?.issue,D?.issue].filter(m=>!!m),Pe=!!D&&D.kind==="numeric"&&!("meta"in D.field);if(Pe&&o!=="scatter"&&ot.push(`${D.label} is continuous, so it can colour a scatter but not a ${o}: colour by a category such as wafer, split or bin`),ot.length)return i(...ot);const un=[...B,a].filter(m=>!!m);let q=e.level??(un.some(m=>m.level==="die")?"die":"wafer");const rt=[...B,Pe?void 0:D].filter(m=>!!m&&m.level==="die"),lt=m=>m&&{label:m.label,level:m.level,kind:m.kind,yield:!!m.weights},Ot=combinationIssue(o,{x:lt(B.find(m=>m.level==="die")??O),y:lt(a),color:lt(D)},{aggregate:e.aggregate,level:e.level,continuousColor:Pe});if(Ot)return i(Ot.long);if(o==="bar"&&!a&&rt.length&&(q="die"),a&&a.level==="wafer"&&a.weights&&rt.length&&(a=Xn(w,a),q="die"),q==="die"&&a?.weights&&!a.perDie&&!rt.length&&(q="wafer"),a&&"passRate"in a.field&&q==="die"&&o!=="bar"&&o!=="line")return i(`${a.label} is a share of dies: draw it as a bar or a line, or with one mark per wafer (each wafer's pass rate)`);const re=q==="die"?k.dies.length:v.length,Ze=m=>q==="die"?k.item[m]:m,Qe=m=>({item:b(Ze(m)),die:q==="die"?k.dies[m]:void 0}),Tt=e.aggregate&&e.aggregate!=="yield"?e.aggregate:"mean",we=m=>{if(!m.num)throw new Error("numeric field expected");if(m.level===q)return m.num;if(m.level==="wafer"){const N=new Float64Array(re);for(let I=0;I<re;I++)N[I]=m.num[Ze(I)];return N}const x=v.map(()=>[]);for(let N=0;N<m.num.length;N++)x[k.item[N]].push(m.num[N]);return Float64Array.from(x,N=>combine(N,Tt))},It=m=>{if(!m.cat)throw new Error("category field expected");if(m.level===q)return m.cat;if(m.level==="wafer")return Array.from({length:re},(x,N)=>m.cat[Ze(N)]);throw new Error("a per-die category cannot be used at wafer level")},fn=m=>m.weights&&m.level===q?m.weights:void 0;let Je=[""],$e=new Int32Array(re),Ce,ve;if(D&&Pe)Ce=D.label,ve=we(D);else if(D){Ce=D.label;const m=It(D),x=new Map,N=[];for(let $=0;$<re;$++){const L=m[$]??bt;x.has(L)||(x.set(L,0),N.push(L))}const I=Te(D.field,N,We(D));I.forEach(($,L)=>x.set($,L)),Je=I;for(let $=0;$<re;$++)$e[$]=x.get(m[$]??bt)}const ut=new Map,xe=m=>ut.set(m,(ut.get(m)??0)+1),Ve=(m,x)=>m.labelOf?m.labelOf(q==="die"?k.item[x]:x):m.label,et=q==="die"?"dies":"wafers";let je,ie,me,Ee,ft,Ct,ct,ze=0;const Y=Je.length,Xe=m=>m.level==="die"&&q==="wafer"?`${Ke[Tt].toLowerCase()} of ${m.label} per wafer`:void 0;if(o==="scatter"){const m=we(O),x=we(a),N=[];for(let L=0;L<re;L++){if(!Number.isFinite(m[L])){xe(O.label);continue}if(!Number.isFinite(x[L])){xe(Ve(a,L));continue}if(ve&&!Number.isFinite(ve[L])){xe(D.label);continue}N.push({x:m[L],y:x[L],group:$e[L],item:Ze(L),die:q==="die"?k.dies[L]:void 0,...ve?{value:ve[L]}:{}})}if(ze=N.length,ve&&N.length){const L=N.map(A=>A.value);Ct={label:D.label,unit:D.unit,lo:Me(L),hi:Re(L)}}let I;if(e.fit){I=(ve?[N]:Array.from({length:Y},(F,W)=>N.filter(j=>j.group===W))).flatMap((F,W)=>{const j=fitLine(F.map(C=>C.x),F.map(C=>C.y),e.fit);return j?[{group:W,...j}]:[]});const A=(O.unit??"")===(a.unit??"");ct=I.map(F=>{const W=Y>1&&!ve?`${Je[F.group]||"(none)"}: `:"",j=+F.slope.toPrecision(4),C=`${j<0?"\u2212":""}${Gt(Math.abs(j))}`,R=A?C:`${C} ${a.unit??""}/${O.unit??""}`.trim(),U=F.intercept<0?"\u2212":"+";return`${W}y = ${R} x ${U} ${qe(Math.abs(F.intercept),a.unit)}, R\xB2 ${F.r2.toFixed(3)}, n ${F.n.toLocaleString("en-GB")}`})}let $=!1;if(e.identity&&((O.unit??"")!==(a.unit??"")?r.push(`y = x is left off: ${O.label} and ${a.label} are in different units`):$=!0),je={type:"scatter",points:N,...I?.length?{fits:I}:{},...$?{identity:!0}:{}},ft=Cn(N),ie=ce("x",O.label,O.unit,e,N.map(L=>L.x),r),me=ce("y",a.label,a.unit,e,N.map(L=>L.y),r),!n.inFacet){const L=[D?.field,e.fields?.facet].flatMap(F=>F&&"meta"in F?[F.meta]:[]),A=_t(t.map(F=>({metadata:F.metadata,dieCount:F.dies.length})),{facetableOnly:!0,curation:n.curation}).filter(F=>F.splittable&&!L.includes(F.key)).map(F=>F.label);A.length&&r.push(`Mixed ${fe(A)} across these points: a trend here may come from the groups' offset rather than the relationship (Simpson's paradox). Colour or panel by it, or keep one value with Only dies where`)}Ee=[Xe(O),Xe(a),I?.length?`${e.fit==="orthogonal"?"orthogonal (Deming) fit":"least-squares fit of Y on X"} per ${Y>1&&!ve?"colour":"plot"}`:void 0].filter(Boolean).join("; ")||void 0}else if(o==="histogram"){const m=we(a),x=Array.from({length:Y},()=>[]),N=Array.from({length:Y},()=>[]);for(let $=0;$<re;$++){if(!Number.isFinite(m[$])){xe(Ve(a,$));continue}x[$e[$]].push(m[$]),N[$e[$]].push($),ze++}je={type:"histogram",values:x,units:N,unit:Qe},ie=ce("x",a.label,a.unit,e,x.flat(),r);const I=e.histNorm==="percent";me={label:I?Y>1?`Share of each colour's ${et}`:`Share of ${et}`:"Count",scale:"linear",...I?{unit:"%"}:{},...e.axes?.y?.label?{label:e.axes.y.label}:{}},e.normalCurve&&ie.scale==="log"&&r.push("The normal curve is left off a log axis, where a normal distribution is not the shape its bars would follow"),Ee=[Xe(a),e.normalCurve&&ie.scale!=="log"?`curve: the normal distribution with ${Y>1?"each colour's":"the"} mean and standard deviation`:void 0].filter(Boolean).join("; ")||void 0}else if(o==="probability"){const m=we(a),x=Array.from({length:Y},()=>[]);for(let $=0;$<re;$++){if(!Number.isFinite(m[$])){xe(Ve(a,$));continue}x[$e[$]].push($),ze++}for(const $ of x)$.sort((L,A)=>m[L]-m[A]);const N=x.map($=>$.map(L=>m[L]));je={type:"probability",values:N,units:x,unit:Qe},ie=ce("x",a.label,a.unit,e,N.flat(),r);const I=e.probabilityAxis==="linear";me={label:e.axes?.y?.label??"Cumulative share",scale:"linear"},Ee=[Xe(a),`each ${q==="die"?"die":"wafer"} at (rank \u2212 \xBD) / n of its ${Y>1?"group":"population"}${I?"":", on a normal-probability scale"}`].filter(Boolean).join("; ")}else if(o==="line"){const m=we(O),x=we(a),N=new Set,I=new Map,$=new Map;for(let K=0;K<re;K++){if(!Number.isFinite(m[K])){xe(O.label);continue}if(!Number.isFinite(x[K])){xe(Ve(a,K));continue}N.add(m[K]);const H=`${$e[K]}|${m[K]}`;(I.get(H)??I.set(H,[]).get(H)).push(x[K]),ze++,($.get(H)??$.set(H,[]).get(H)).push(K)}const L=[...N].sort((K,H)=>K-H),A=e.aggregate??"mean",F=Array.from({length:Y},(K,H)=>L.map(se=>{const Fe=I.get(`${H}|${se}`);return Fe?combine(Fe,A==="yield"?"mean":A):NaN})),W=Array.from({length:Y},(K,H)=>L.map(se=>I.get(`${H}|${se}`)?.length??0)),j=Array.from({length:Y},(K,H)=>L.map(se=>$.get(`${H}|${se}`)??[]));let C;const R=e.spread;if(R){if(a.perDie)return i(`A band shows how values spread, and ${a.label} is a share of passing dies, not a value: leave the band off`);if(A!=="mean"&&A!=="median")return i(`A band goes round a mean or a median, not ${Nt[A]}`);const K=new Map,H=(de,he,De)=>{const ne=(I.get(`${de}|${he}`)??[]).filter(Number.isFinite);if(ne.length===0)return[NaN,NaN];if(R==="minmax")return[Me(ne),Re(ne)];if(R==="iqr"){const y=ne.sort((T,E)=>T-E);return[vt(y,.25),vt(y,.75)]}if(ne.length<2)return[NaN,NaN];const tt=ne.reduce((y,T)=>y+T,0)/ne.length,Ge=Math.sqrt(Wt(ne,tt));let Ue=1;R==="ci95"&&(Ue=K.get(ne.length-1)??An(.05,ne.length-1),K.set(ne.length-1,Ue));const Ye=R==="sd"?Ge:Ue*Ge/Math.sqrt(ne.length);return[F[de][De]-Ye,F[de][De]+Ye]},se=F.map(()=>[]),Fe=F.map(()=>[]);F.forEach((de,he)=>L.forEach((De,ne)=>{const[tt,Ge]=H(he,De,ne);se[he].push(tt),Fe[he].push(Ge)})),C={lo:se,hi:Fe}}je={type:"line",xs:L,values:F,counts:W,cellUnits:j,unit:Qe,...C?{band:C}:{}},ie=ce("x",O.label,O.unit,e,L,r);const U=A==="yield"?"mean":A;me=ce("y",a.perDie?a.label:`${Ke[U]} ${a.label}`,a.unit,e,F.flat(),r);const X=q==="die"?"dies":"wafers",le={sd:`\xB1 1 standard deviation of the ${X}`,ci95:`the mean's 95% confidence interval (Student's t, n = ${X})`,iqr:`the quartiles of the ${X}`,minmax:`the range of the ${X}`},oe=Oe(O.field)?O.field:void 0,Se=oe?`in each of ${L.length} ranges of ${O.label} (${(oe.by??"count")==="width"?"equal widths":`about the same number of ${X} in each`}), drawn at the middle of the range`:`per ${a.perDie?en(O.label):O.label}`;Ee=(a.perDie?`passing dies over judged dies, ${Se}`:`${Ke[U].toLowerCase()} of ${a.label} ${Se}`)+(R?`; band: ${le[R]} ${oe?"in each range":`at each ${en(O.label)}`}`:"")}else{const m=[],x=[];for(const y of B){const T="builtin"in y.field&&(y.field.builtin==="x"||y.field.builtin==="y");if(y.kind==="numeric"&&y.level==="die"&&!T)return i(`${y.label} is continuous, so a ${o} cannot have one ${o==="bar"?"bar":"box"} per value; use a scatter or line, or choose a categorical X such as wafer, ring or bin`);const E=y.cat?It(y):Array.from(we(y),ae=>Number.isFinite(ae)?Gt(ae):void 0),V=new Set,Q=[];for(let ae=0;ae<re;ae++){const ge=E[ae];ge!==void 0&&!V.has(ge)&&(V.add(ge),Q.push(ge))}const pe=Te(y.field,Q,We(y));m.push(E),x.push(new Map(pe.map((ae,ge)=>[ae,ge])))}const N="",I=new Map,$=[],L=y=>{const T=[];for(let E=0;E<m.length;E++){const V=m[E][y];if(V===void 0)return{missing:E};T.push(V)}return T.join(N)};for(let y=0;y<re;y++){const T=L(y);typeof T=="string"&&!I.has(T)&&(I.set(T,0),$.push(T.split(N)))}$.sort((y,T)=>{for(let E=0;E<y.length;E++){const V=x[E].get(y[E])-x[E].get(T[E]);if(V)return V}return 0});const A=$.map(y=>y.join(" \xB7 "));$.forEach((y,T)=>I.set(y.join(N),T));const F=m.length===1?m[0]:void 0,W=o==="bar"&&!a,j=e.aggregate??(W?"count":a?.weights?"yield":"mean");if(j==="yield"&&!a?.weights)return i("Pooled yield needs Yield as the Y field");if(o==="box"&&j==="count")return i("A box plot needs a measured field for Y");const C=a?we(a):void 0,R=a?fn(a):void 0,U=Array.from({length:Y},()=>A.map(()=>[])),X=Array.from({length:Y},()=>A.map(()=>[])),le=Array.from({length:Y},()=>A.map(()=>[]));for(let y=0;y<re;y++){const T=L(y);if(typeof T!="string"){xe(B[T.missing].label);continue}const E=I.get(T);if(C&&!Number.isFinite(C[y])){xe(Ve(a,y));continue}U[$e[y]][E].push(C?C[y]:1),X[$e[y]][E].push(y),R&&le[$e[y]][E].push(R[y]),ze++}const oe=U.map((y,T)=>y.map((E,V)=>{if(E.length===0)return NaN;if(j==="yield"){const Q=le[T][V],pe=Q.reduce((ae,ge)=>ae+ge,0);return pe>0?E.reduce((ae,ge,hn)=>ae+ge*Q[hn],0)/pe:NaN}return combine(E,j)})),Se=o==="bar"&&(j==="count"||j==="sum");if(e.stack&&o!=="bar")return i("Only a bar chart stacks its colours");if(e.stack&&!Se)return i(`Stacking adds the colours' values, which means something for a count or a sum, not ${Nt[j]}: combine by count or sum, or draw the colours side by side`);if(e.cumulative&&!(Se&&e.sort==="value"))return i("A cumulative line needs a bar of counts or sums sorted by value, largest first");if(e.barNorm==="percent"&&!Se)return i(`A share of each colour's total means something for a count or a sum, not ${Nt[j]}: combine by count or sum`);if(e.barNorm==="percent"&&e.stack)return i("Bars are either stacked or each colour's share of its own total, not both");if(e.barNorm==="percent"&&Se)for(let y=0;y<Y;y++){const T=oe[y].reduce((E,V)=>E+(Number.isFinite(V)?V:0),0);oe[y]=oe[y].map(E=>Number.isFinite(E)&&T>0?E/T*100:NaN)}if((e.sort||e.top)&&B.length>1)return i("Sorting by value and keeping the top categories need one category field on X");const K=y=>{if(o==="box"){const E=U.flatMap(V=>V[y]);return E.length?combine(E,"median"):NaN}if(Se||e.barNorm==="percent"){let E=0,V=!1;for(const Q of oe)Number.isFinite(Q[y])&&(E+=Q[y],V=!0);return V?E:NaN}const T=U.flatMap(E=>E[y]);if(T.length===0)return NaN;if(j==="yield"){const E=le.flatMap(Q=>Q[y]),V=E.reduce((Q,pe)=>Q+pe,0);return V>0?T.reduce((Q,pe,ae)=>Q+pe*E[ae],0)/V:NaN}return combine(T,j)},H=A.map((y,T)=>K(T));let se=A.map((y,T)=>T);e.sort==="value"&&se.sort((y,T)=>(Number.isFinite(H[T])?H[T]:-1/0)-(Number.isFinite(H[y])?H[y]:-1/0)),e.sort==="ascending"&&se.sort((y,T)=>(Number.isFinite(H[y])?H[y]:1/0)-(Number.isFinite(H[T])?H[T]:1/0));const Fe=H.reduce((y,T)=>y+(Number.isFinite(T)?T:0),0);e.top&&e.top<se.length&&(r.push(`Showing the first ${e.top} of ${se.length} ${B[0].label.toLowerCase()} values${e.sort==="value"?", largest first":e.sort==="ascending"?", smallest first":""}`),se=se.slice(0,e.top));const de=y=>se.map(T=>y[T]);A.splice(0,A.length,...de(A));for(let y=0;y<Y;y++)U[y]=de(U[y]),X[y]=de(X[y]),oe[y]=de(oe[y]);const he=de(H);if($.length&&$.splice(0,$.length,...de($)),e.stack==="percent")for(let y=0;y<Y;y++)oe[y]=oe[y].map((T,E)=>Number.isFinite(T)&&he[E]>0?T/he[E]*100:NaN);let De=0;const ne=e.cumulative&&Fe>0?he.map(y=>(De+=Number.isFinite(y)?y:0,De/Fe*100)):void 0,Ge=!!F&&"builtin"in B[0].field&&B[0].field.builtin==="wafer"?A.map(y=>F.findIndex((T,E)=>T===y&&E>=0)):void 0,Ue=B.length>1?{levels:B.map(y=>y.label),parts:$}:void 0;je={type:o==="box"?"box":"bar",categories:A,cells:U,cellUnits:X,unit:Qe,values:oe,categoryItems:Ge?.map(y=>b(q==="die"?k.item[y]:y)),...Ue?{nest:Ue}:{},...e.stack&&Y>1?{stack:e.stack}:{},...ne?{cumulative:ne}:{},...o==="bar"&&q==="die"&&a?.perDie?{passFail:a.failSide?.some(y=>y!==0)?{failSide:a.failSide}:{}}:{}};const Ye=fe(B.map(y=>y.label.toLowerCase()));if(ie={label:e.axes?.x?.label??B.map(y=>y.label).join(" \u203A "),scale:"linear"},o==="bar"){const y=j==="count"?"Count":Ke[j],T=W?`Count of ${et}`:j==="yield"?"passRate"in a.field?a.label:"Pooled yield":`${y} ${a.label}`,E=e.stack==="percent"&&Y>1,V=e.barNorm==="percent",Q=W?et:T.toLowerCase(),pe=E?`Share of each ${B[0].label.toLowerCase()}'s ${Q}`:V?Y>1?`Share of each ${Ce?Ce.toLowerCase():"colour"}'s ${Q}`:`Share of ${Q}`:T,ae=E?[0,100]:e.stack&&Y>1?he.filter(Number.isFinite):oe.flat();me=ce("y",pe,E||V||j==="yield"?"%":j==="count"?void 0:a?.unit,e,ae,r),Ee=W?void 0:j==="yield"?`passing dies over judged dies, pooled per ${Ye}`:`${y.toLowerCase()} of ${a.label}${a.level==="die"&&q==="wafer"?" per wafer":""} per ${Ye}`}else me=ce("y",a.label,a.unit,e,U.flat(2),r),Ee=Xe(a)}const dt=(m,x)=>m&&!m.perDie&&(x===void 0||x==="mean"||x==="median"||x==="min"||x==="max")?m.limits:void 0,cn=e.aggregate??"mean";ie&&(o==="scatter"||o==="line")&&(ie.limits=dt(O)),me&&o!=="histogram"&&(me.limits=dt(a,o==="scatter"||o==="box"?void 0:cn)),Z&&ie&&(ie.limits=dt(a));const dn=()=>{const m=a?.label,x=B.filter($=>!Ie($.field)),N=o==="box"||o==="bar"?x.length?fe(x.map($=>$.label)):void 0:O?.label,I=o==="scatter"?`${m} vs ${N}`:o==="histogram"?`${m}`:o==="probability"?`${m}, cumulative`:o==="line"?tn(m,N,!!O&&Oe(O.field)):N?o==="box"?`${m} by ${N}`:m?`${m} by ${N}`:`Dies by ${N}`:`${m}`;return Ce&&D&&!_.some($=>Le(D.field,$))&&!Ie(D.field)?`${I} \xB7 by ${Ce}`:I},Et=[];let mt;const Dt=d?d.tests.map((m,x)=>({field:d.labels[x],test:m})):[];for(const m of new Set([...B,d?void 0:a,D]))m&&"test"in m.field&&Dt.push({field:m.label,test:m.field.test});for(const{field:m,test:x}of Dt){let N=0;for(const I of c)yn(I,x)!==void 0&&(N++,mt??=wn(bn(I)));N>0&&Et.push({field:m,count:N})}let ht;if((o==="box"||o==="bar")&&!d&&a&&"test"in a.field&&a.level==="die"&&a.num&&!a.perDie){const m=N=>!!N&&N.level==="wafer"&&N.kind==="categorical"&&!!N.cat&&!("builtin"in N.field&&(N.field.builtin==="wafer"||N.field.builtin==="test")),x=B.length===1&&m(B[0])?B[0]:!Pe&&m(D)?D:void 0;if(x){const N=new Float64Array(t.length),I=new Uint32Array(t.length);for(let A=0;A<k.dies.length;A++){const F=a.num[A];Number.isFinite(F)&&(N[k.item[A]]+=F,I[k.item[A]]++)}const $=new Map;t.forEach((A,F)=>{const W=x.cat[F];W===void 0||I[F]===0||($.get(W)??$.set(W,[]).get(W)).push(N[F]/I[F])});const L=[...$.keys()].sort(Rt);L.length>=2&&(ht={by:x.label,result:In(L.map(A=>({key:A,values:$.get(A)})))})}}let pt;if(e.whatIf){if(!(o==="histogram"||o==="probability"))return i("What-if limits go on a histogram or a probability plot of one test");if(d||!a||!("test"in a.field))return i("What-if limits need one measured test as the values");if(e.normalize)return i("What-if limits are in the test's own unit: turn rescaling off to set them");const m=a.field.test,x=f.find(X=>X.testNumber===m),N=x?.limitLow??-1/0,I=x?.limitHigh??1/0,$=e.whatIf.lo??x?.limitLow??-1/0,L=e.whatIf.hi??x?.limitHigh??1/0;let A=0,F=0,W=0;for(let X=0;X<k.dies.length;X++){const le=it(k.dies[X],m);le===void 0||!Number.isFinite(le)||!Mt(k.dies[X])||(A++,le>=N&&le<=I&&F++,le>=$&&le<=L&&W++)}const j=X=>A?`${(X/A*100).toFixed(1)}%`:"\u2014",C=`${Number.isFinite($)?qe($,a.unit):"\u2212\u221E"} to ${Number.isFinite(L)?qe(L,a.unit):"\u221E"}`,R=W-F,U=`what-if: ${a.label} passes ${j(F)} of ${A.toLocaleString("en-GB")} dies by its test limits, ${j(W)} from ${C} (${R===0?"no die changes":`${R>0?"+":"\u2212"}${Math.abs(R).toLocaleString("en-GB")} dies`})`;pt={...Number.isFinite($)?{lo:$}:{},...Number.isFinite(L)?{hi:L}:{},judged:A,passNow:F,passThen:W,sentence:U},ie&&(ie.limits={...ie.limits,...e.whatIf.lo!==void 0?{whatIfLow:e.whatIf.lo}:{},...e.whatIf.hi!==void 0?{whatIfHigh:e.whatIf.hi}:{}})}const mn=[...B,a,D].some(m=>!!m&&"builtin"in m.field&&m.field.builtin==="pat")||[ie,me].some(m=>m?.limits?.patLow!==void 0||m?.limits?.patHigh!==void 0);return{spec:e,issues:[],notes:r,marks:je,level:q,...ht?{comparison:ht}:{},...mn?{usesPat:!0}:{},...ct?.length?{fitNotes:ct}:{},...pt?{whatIf:pt}:{},...mt?{excluded:{limitSet:mt,fields:Et}}:{},autoTitle:dn(),x:ie,y:me,groups:Je,colorScale:Ct,colorLabel:Ce,aggregation:Ee,...ft?{correlation:ft}:{},...D&&!Pe&&"builtin"in D.field&&(D.field.builtin==="hbin"||D.field.builtin==="sbin")?{colorBins:D.field.builtin==="hbin"?"hard":"soft"}:{},...D&&_.some(m=>Le(D.field,m))?{colorRepeatsX:!0}:{},...e.normalize&&u?{normalization:Kn(e.normalize,g)}:{},population:{wafers:t.length,dies:c.length},...d?{setTests:{tests:d.tests,labels:d.labels}}:{},plotted:ze,omitted:[...ut].map(([m,x])=>({field:m,count:x}))}}export function plotTitle(e){return e.spec.title?.trim()?e.spec.title:e.autoTitle}function ci(e,t){const n=t.groups.map(l=>`${l.key} ${l.n}`).join(", "),s=`by ${e.toLowerCase()}, wafer means (wafers: ${n})`;if(!t.welch&&!t.kruskal)return`${s}: ${t.issue?.toLowerCase()??"not comparable"}`;const i=t.welch?`${t.welch.method==="welch-t"?"Welch t":"Welch ANOVA"} p ${Vt(t.welch.p)}`:void 0,o=t.kruskal?`rank p ${Vt(t.kruskal.p)}${t.kruskal.approximate?" (approximate)":""}`:void 0;return`${s}: ${[i,o].filter(Boolean).join(", ")}`}export function plotFootnote(e){const{wafers:t,dies:n}=e.population,s=[e.populationLabel?`${n.toLocaleString("en-GB")} dies \xB7 ${e.populationLabel}`:`${t.toLocaleString("en-GB")} wafer${t===1?"":"s"} \xB7 ${n.toLocaleString("en-GB")} dies`];if(e.leftOut){const{partial:i,edge:o}=e.leftOut,l=(f,c)=>`${f.toLocaleString("en-GB")} ${c} di${f===1?"e":"es"}`;s.push(`${fe([...o?[l(o,"edge-excluded")]:[],...i?[l(i,"partial")]:[]])} left out, as a yield leaves them out`)}e.filterNote&&s.push(e.filterNote),e.whatIf&&s.push(e.whatIf.sentence),e.aggregation&&s.push(e.aggregation),e.correlation&&s.push(`${e.correlation.r===null?"":`r = ${e.correlation.r.toFixed(3)} \xB7 `}n = ${e.correlation.n.toLocaleString("en-GB")}`),e.normalization&&s.push(e.normalization),e.comparison&&s.push(ci(e.comparison.by,e.comparison.result)),e.usesPat&&s.push(`PAT per wafer: median \xB1 ${zn} \xD7 (Q3 \u2212 Q1) / 1.35 of its passing dies, within the test's limits`),e.facets&&s.push(`${e.facets.length} panels by ${e.facetLabel.toLowerCase()}, on shared axes`);for(const i of e.omitted)s.push(`${i.count.toLocaleString("en-GB")} ${e.level==="die"?"dies":"wafers"} without ${i.field} not plotted`);if(e.excluded)for(const i of e.excluded.fields)s.push(`${i.count.toLocaleString("en-GB")} ${i.field} value${i.count===1?"":"s"} outside ${e.excluded.limitSet} excluded`);return s.join(" \xB7 ")}export function plotGuideSections(e){const{spec:t}=e,n=t.fields??{},s=[...ke(n.x),n.y,n.color,n.rows,n.facet],i=[di[t.chart],e.comparison&&Ne.groups,(e.fitNotes?.length||t.identity&&e.marks?.type==="scatter")&&Ne.fit,e.marks?.type==="line"&&e.marks.band&&Ne.bands,e.normalization&&Ne.rescaling,(s.some(Oe)||e.facets||e.whatIf)&&Ne.ranges];return[...new Set(i.filter(o=>!!o))]}const di={probability:Ne.probability,control:Ne.control,goal:Ne.goal,heatmap:Ne.heatmap};export function fieldKey(e){return Oe(e)?`binned:${fieldKey(e.binned)}`:ue(e)?`${e.passRate?`passRates:${e.judge??"limits"}`:"tests"}:${e.tests.join(",")}`:"passRate"in e?`passRate:${e.passRate}${e.judge==="flag"?":flag":""}`:"test"in e?`test:${e.test}`:"builtin"in e?`builtin:${e.builtin}`:`meta:${e.meta}`}export function fieldCatalogue(e,t={}){const n=[],s=e.flatMap(u=>u.dies),i=new Set(s.length?st(s,"values"):[]),o=t.testDefs??[],l=new Map;for(const u of o)u.testType!=="F"&&(i.has(u.testNumber)||!s.length)&&l.set(u.testNumber,u.name);for(const u of i)!l.has(u)&&!o.some(g=>g.testNumber===u&&g.testType==="F")&&l.set(u,void 0);for(const[u,g]of[...l].sort((v,b)=>v[0]-b[0]))n.push({field:{test:u,...g?{name:g}:{}},label:g?`${g} \xB7 ${u}`:`Test ${u}`,name:g||`Test ${u}`,group:"Tests",kind:"numeric",level:"die",categorical:!1});l.size>=2&&n.push({field:{builtin:"test"},label:Be.test,name:Be.test,group:"Tests",kind:"categorical",level:"wafer",categorical:!0});const f=new Set(s.length?st(s,"all"):[]);for(const u of o){if(be(u)||!(f.has(u.testNumber)||!s.length))continue;const g=u.name||`Test ${u.testNumber}`;n.push({field:{test:u.testNumber,...u.name?{name:u.name}:{}},label:`${g} \xB7 ${u.testNumber} (pass/fail)`,name:g,group:"Verdicts",kind:"categorical",level:"die",categorical:!0})}for(const u of o){if(!(be(u)?(u.limitLow!==void 0||u.limitHigh!==void 0)&&(i.has(u.testNumber)||!s.length):f.has(u.testNumber)||!s.length))continue;const v=u.name||`Test ${u.testNumber}`;n.push({field:{passRate:u.testNumber,...u.name?{name:u.name}:{}},label:`${v} \xB7 ${u.testNumber} pass rate`,name:`${v} pass rate`,group:"Pass rates",kind:"numeric",level:"die",categorical:!1})}const c=u=>s.some(u),r=(u,g,v)=>n.push({field:{builtin:u},label:Be[u],name:Be[u],group:"Die",kind:g,level:"die",categorical:v});c(u=>nt(u))&&(r("x","numeric",!1),r("y","numeric",!1)),e.some(u=>u.wafer)&&c(u=>nt(u)&&u.physX!==void 0)&&r("radius","numeric",!1);const h=c(u=>nt(u));for(const u of pn)e.some(g=>He[u].available({wafer:g.wafer,ringCount:g.ringCount},h))&&r(u,"categorical",!0);c(u=>u.hbin!==void 0)&&r("hbin","categorical",!0),c(u=>u.sbin!==void 0)&&r("sbin","categorical",!0),c(u=>u.siteNum!==void 0)&&r("site","categorical",!0),c(u=>u.retestCount!==void 0)&&r("reprobed","numeric",!1),s.length&&Yt(o.filter(u=>i.has(u.testNumber))).length&&r("pat","categorical",!0);const p=(u,g,v)=>n.push({field:{builtin:u},label:Be[u],name:Be[u],group:"Wafer",kind:g,level:"wafer",categorical:v});p("wafer","categorical",!0),e.length>1&&p("waferOrder","numeric",!1),p("yield","numeric",!1),p("dieCount","numeric",!1);const d={items:e,rows:{dies:[],item:new Uint32Array(0)},ctx:t};for(const u of _t(e.map(g=>({metadata:g.metadata,dieCount:g.dies.length})),{facetableOnly:!0,curation:t.curation})){if(u.values.length===0)continue;const g=J({meta:u.key},d);n.push({field:{meta:u.key},label:u.label||gt(u.key,t.curation),name:u.label||gt(u.key,t.curation),group:"Wafer",kind:g.kind,level:"wafer",categorical:!0,distinct:u.values.length})}return n}export function fieldExtent(e,t,n={}){const s=J(e,{items:t,rows:ye(t),ctx:n});if(s.issue||!s.num)return;let i=1/0,o=-1/0;for(let l=0;l<s.num.length;l++){const f=s.num[l];Number.isFinite(f)&&(f<i&&(i=f),f>o&&(o=f))}return i===1/0?void 0:[i,o]}export function fieldValues(e,t,n={}){const s=J(e,{items:t,rows:ye(t),ctx:n});if(s.issue||!s.cat)return[];const i=[];for(const o of s.cat)o!==void 0&&!i.includes(o)&&i.push(o);return Te(e,i,We(s))}export function fieldsForRole(e,t,n){if(t==="control"&&n==="x")return e.filter(i=>i.kind==="numeric"&&i.level==="wafer");const s=n==="y"||n==="x"&&(t==="scatter"||t==="line"||t==="histogram");return n==="color"?e.filter(i=>i.categorical||t==="scatter"&&i.kind==="numeric"):s?e.filter(i=>i.kind==="numeric"&&(n==="y"||i.group!=="Pass rates")):e.filter(i=>i.categorical)}export function defaultPlot(e,t){const n=e.filter(s=>s.group==="Tests"&&"test"in s.field);return n.length>=2?{id:t,chart:"scatter",fields:{x:n[0].field,y:n[1].field}}:n.length===1?{id:t,chart:"histogram",fields:{y:n[0].field}}:{id:t,chart:"scatter",fields:{x:{builtin:"waferOrder"},y:{builtin:"yield"}}}}const Ft=new Set(["wafer","dies","die x","die y","wafer order"]),mi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Lt=(e,t)=>t.length>=3&&new RegExp(`(^|[^A-Za-z0-9_])${mi(t)}($|[^A-Za-z0-9_])`,"i").test(e);export function titleDrift(e,t){const n=e.title?.trim(),s={names:[],omits:[]};if(!n)return s;const i=e.fields?.color,o=[...ke(e.fields?.x),e.fields?.y,i,e.fields?.facet].filter(u=>Ae(u)),l=u=>o.some(g=>Le(g,u)),f=t.filter(u=>!Ft.has(u.name.toLowerCase())&&!("meta"in u.field)&&!l(u.field)&&Lt(n,u.name)).map(u=>u.name),c=[...ke(e.fields?.x),e.fields?.y].filter(u=>Ae(u)),r=u=>t.find(g=>Le(g.field,u))?.name??fieldLabel(u),h=c.filter(u=>!Ft.has(r(u).toLowerCase())&&Lt(n,r(u))),p=c.filter(u=>!Ft.has(r(u).toLowerCase())&&!Lt(n,r(u))),d=h.length>0||f.length>0?p.map(r):[];return{names:f,omits:d}}export function describeTitleDrift(e){const t=[];return e.names.length&&t.push(`The title names ${fe(e.names)}, which this plot does not show.`),e.omits.length&&t.push(`It does not name ${fe(e.omits)}, which this plot shows.`),t.length?t.join(" "):null}function hi(e,t={}){const n=ye(e),s=J({builtin:"ring"},{items:e,rows:n,ctx:t});if(s.issue||!s.cat)return;const i=new Map;let o=0,l=0;for(let r=0;r<n.dies.length;r++){const h=s.cat[r];if(h===void 0)continue;const p=yt([n.dies[r]],e[n.item[r]].passBins),d=i.get(h)??{pass:0,total:0};d.pass+=p.pass,d.total+=p.total,o+=p.pass,l+=p.total,i.set(h,d)}let f,c=l?o/l*100-1:-1/0;for(const[r,h]of i)h.total&&h.pass/h.total*100<c&&(c=h.pass/h.total*100,f=r);return f}function pi(e,t){if(!t||e.length<2)return e[0];const n=ye(t.items);let s=e[0],i=1/0;for(const o of e){const l=J({passRate:o.d.testNumber},{items:t.items,rows:n,ctx:t.ctx??{}});if(!l.num||!l.weights)continue;let f=0,c=0;for(let r=0;r<l.num.length;r++)l.weights[r]&&(c++,f+=l.num[r]/100);c&&f/c<i&&(i=f/c,s=o)}return s}const gi=4;export function examplePlots(e,t,n,s){const i=e.filter(a=>a.group==="Tests"&&"test"in a.field),o=e.flatMap(a=>"meta"in a.field?[a.field.meta]:[]),l=s?Tn(s.items,i.map(a=>a.field.test),o,s.ctx?.curation):void 0,f=new Map(i.map(a=>[a.field.test,a])),c=l?[...l.ranked.map(a=>f.get(a)).filter(Boolean).filter(a=>a.field.test!==l.partner)]:i;l?.partner!==void 0&&c.length&&c.splice(1,0,f.get(l.partner));const r=c.map(a=>a.field),h=[],p=t>1,d=a=>e.some(G=>"builtin"in G.field&&G.field.builtin===a),u=(l?.splitKey?e.find(a=>"meta"in a.field&&a.field.meta===l.splitKey):void 0)??e.find(a=>"meta"in a.field&&a.distinct!==void 0&&a.distinct>=2&&a.distinct<=Math.max(2,Math.floor(t/2))),g=a=>h.push({id:n(),...a}),v=c.length>=2?{tests:c.slice(0,8).map(a=>a.field.test),names:Object.fromEntries(c.slice(0,8).map(a=>[String(a.field.test),a.name]))}:void 0,b=u?.field,k=b??(d("ring")?{builtin:"ring"}:void 0),w={color:k??{none:!0}},S={color:b??{none:!0}};if(r.length>=2&&g({chart:"scatter",fields:{x:r[0],y:r[1],...b?{color:b}:{}},fit:"linear"}),r.length>=1&&g({chart:"histogram",fields:{y:r[0],...w},normalCurve:!0,...k?{histNorm:"percent"}:{}}),r.length>=1&&p&&g({chart:"box",fields:{x:{builtin:"wafer"},y:r[0],...S},axes:{y:{references:[{stat:"median"}]}}}),p&&g({chart:"bar",fields:{x:b??{builtin:"wafer"},y:{builtin:"yield"},color:b??{none:!0}},valueLabels:!0,axes:{y:{references:[{stat:"median"}]}}}),p)for(const a of(l?.yieldKeys??[]).filter(G=>!(b&&"meta"in b&&b.meta===G)).slice(0,gi)){const G=e.find(te=>"meta"in te.field&&te.field.meta===a)?.field;G&&g({chart:"bar",fields:{x:G,y:{builtin:"yield"},color:G},valueLabels:!0,axes:{y:{references:[{stat:"median"}]}}})}const _=p&&d("ring")&&s?hi(s.items,s.ctx):void 0;_&&g({chart:"bar",fields:{x:{builtin:"wafer"},y:{builtin:"yield"},color:{none:!0}},where:{conditions:[{field:{builtin:"ring"},values:[_]}]}}),r.length>=1&&p&&t<5&&g({chart:"line",fields:{x:{builtin:"waferOrder"},y:r[0],color:{none:!0}},aggregate:"mean",spread:"sd"}),r.length>=1&&g({chart:"probability",fields:{y:r[0],...S}});const M=s?.ctx?.testDefs??[],z=r.flatMap(a=>{const G="test"in a?M.find(te=>te.testNumber===a.test):void 0;return G&&be(G)?[{f:a,d:G}]:[]}),P=z.filter(({d:a})=>a.limitLow!==void 0&&a.limitHigh!==void 0).slice(0,8),Z=P.length>=2?{tests:P.map(({f:a})=>a.test),names:Object.fromEntries(P.filter(({d:a})=>a.name).map(({f:a,d:G})=>[String(a.test),G.name]))}:void 0;Z?g(b?{chart:"heatmap",fields:{x:b,y:Z},aggregate:"mean",normalize:"limits"}:{chart:"box",fields:{x:{builtin:"test"},y:Z},normalize:"limits"}):v&&g(b?{chart:"heatmap",fields:{x:b,y:v},aggregate:"mean",normalize:"zscore"}:{chart:"box",fields:{x:{builtin:"test"},y:v},normalize:"zscore"}),v&&p&&g({chart:"heatmap",fields:{x:{builtin:"wafer"},y:v},aggregate:"mean",normalize:"zscore"}),r.length>=1&&b&&g({chart:"box",fields:{x:b,y:r[0],color:b}}),r.length>=1&&b&&g({chart:"box",fields:{x:[b,{builtin:"wafer"}],y:r[0],color:b}}),r.length>=1&&d("ring")&&g({chart:"histogram",fields:{y:r[0],...S,facet:{builtin:"ring"}}}),r.length>=2&&g(b?{chart:"line",fields:{x:{binned:r[1],bins:5},y:r[0],color:b},aggregate:"median",spread:"sd"}:{chart:"box",fields:{x:{binned:r[1],bins:5},y:r[0],...w}}),r.length>=1&&d("radius")&&g(b?{chart:"line",fields:{x:{binned:{builtin:"radius"},bins:6,by:"width"},y:r[0],color:b},aggregate:"median",spread:"sd"}:{chart:"box",fields:{x:{binned:{builtin:"radius"},bins:6,by:"width"},y:r[0],...S}}),d("hbin")&&g({chart:"bar",fields:{x:{builtin:"hbin"},color:{none:!0}},sort:"value",cumulative:!0}),d("hbin")&&p&&g({chart:"bar",fields:{x:{builtin:"wafer"},color:{builtin:"hbin"}},stack:"percent"}),r.length>=1&&d("pat")&&g({chart:"box",fields:{x:{builtin:"pat"},y:r[0],color:{builtin:"pat"}}});const ee=e.find(a=>a.group==="Verdicts");r.length>=1&&ee&&g({chart:"box",fields:{x:ee.field,y:r[0],color:ee.field}}),r.length>=1&&t>=5&&g({chart:"control",fields:{x:{builtin:"waferOrder"},y:r[0]}}),z.some(({d:a})=>a.limitLow!==void 0&&a.limitHigh!==void 0)&&g({chart:"goal",fields:u?{color:u.field}:{}});const B=z.filter(({d:a})=>a.limitLow!==void 0||a.limitHigh!==void 0).slice(0,8);B.length>=2&&p&&g({chart:"heatmap",fields:{x:u?u.field:{builtin:"wafer"},y:{tests:B.map(({f:a})=>a.test),passRate:!0,names:Object.fromEntries(B.filter(({d:a})=>a.name).map(({f:a,d:G})=>[String(a.test),G.name]))}},aggregate:"mean"});const O=pi(z.filter(({d:a})=>a.limitLow!==void 0||a.limitHigh!==void 0).slice(0,8),s);if(O&&p&&g({chart:"bar",fields:{x:u?u.field:{builtin:"wafer"},y:{passRate:O.f.test,...O.d.name?{name:O.d.name}:{}},color:{none:!0}}}),O&&O.d.limitLow!==void 0&&O.d.limitHigh!==void 0){const a=(O.d.limitHigh-O.d.limitLow)*.1;g({chart:"histogram",fields:{y:O.f,color:{none:!0}},whatIf:{lo:O.d.limitLow-a,hi:O.d.limitHigh+a}})}return r.length>=2&&h.push({...ln(i.map(a=>a.field).flatMap(a=>"test"in a?[a]:[]),n()),title:"Example sweep"}),h}function rn(e){const{x:t,y:n,color:s}=e.fields??{};return e.chart==="scatter"?[t,n,s]:e.chart==="histogram"||e.chart==="probability"?[n,t]:[n]}export function plotOpensBins(e){return plotTestNumber(e)===void 0&&rn(e).some(t=>Ae(t)&&"builtin"in t&&(t.builtin==="yield"||t.builtin==="hbin"||t.builtin==="sbin"))}export function plotTestNumber(e){for(const t of rn(e)){if(Ae(t)&&"test"in t)return t.test;if(ue(t)){const n=t.tests[0],s=typeof n=="number"?n:parseInt(String(n),10);if(Number.isInteger(s))return s;continue}if(Ae(t)&&"passRate"in t)return t.passRate}}export function defaultSweep(e,t){return ln(e.filter(be).map(n=>({test:n.testNumber,name:n.name})),t)}function ln(e,t){const n=[...e].sort((i,o)=>i.test-o.test).slice(0,5),s=Object.fromEntries(n.flatMap(i=>i.name?[[String(i.test),i.name]]:[]));return{id:t,chart:"sweep",sweep:{series:[{label:"Series 1",tests:n.map(i=>i.test),...Object.keys(s).length?{testNames:s}:{}}]}}}
|
|
@@ -140,7 +140,14 @@ export declare function buildSynthesis(input: StatsSummary | LotStatsSummary, ct
|
|
|
140
140
|
* A stable key for an item: what it shows, the same in the panel and in Insights, so a row's Chart link finds the item's
|
|
141
141
|
* card and a card's Show on map finds its row.
|
|
142
142
|
*/
|
|
143
|
-
export declare const synthesisKey: (it: Pick<SynthesisItem, "target">) => string;
|
|
143
|
+
export declare const synthesisKey: (it: Pick<SynthesisItem, "target" | "chart">) => string;
|
|
144
|
+
/** The lot field an item's chart is drawn by (a test by split), or undefined when it is not about groups of wafers. */
|
|
145
|
+
export declare const groupedByField: (it: Pick<SynthesisItem, "chart">) => string | undefined;
|
|
146
|
+
/**
|
|
147
|
+
* Whether an item is about the wafers' yield in each group of a field, not a ring's pass rate in each (whose chart keeps to
|
|
148
|
+
* that ring). Such an item is a row of What divides yield, which reads the same fields the same way, so Insights draws it there.
|
|
149
|
+
*/
|
|
150
|
+
export declare const isGroupYieldItem: (it: Pick<SynthesisItem, "target" | "chart">) => boolean;
|
|
144
151
|
/** The heading over groups that differ with no overlap but that the sample is too small to confirm. */
|
|
145
152
|
export declare const SYNTHESIS_POSSIBLE_HEADING = "Possible, not confirmed";
|
|
146
153
|
/** The heading over the compact list of further items: the floor is the same one that admits an item at all. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{maxOf as be,minOf as $e}from"../core/utils.js";import{isPassBin as Ae,passBinsLabel as Te}from"../core/passBins.js";import{DRIFT_MIN_WAFERS as We}from"./lotDrift.js";import{isOneBinCluster as He}from"./filterFindings.js";import{plainBinTerms as Re}from"../renderer/fmt.js";import{benjaminiHochberg as Ce,normalUpperTail as qe}from"./math.js";import{formatP as ye}from"./groupCompare.js";import{adjustedFits as Ke,mergePartitions as Ye,overlapping as Ge}from"./groupEffects.js";import{ringPlotValue as Ue}from"./dieRegions.js";import{parseRegionKey as Ve}from"./regions.js";import{attributeLabel as ie,buildFacetTable as Xe,facetValueOf as Me}from"./facets.js";const Je=1,Qe=2,Ze=.5,Ie=3,xe=5,Q=.01,et=.02,tt=.04,st=.15,it=.4,ue=.5,nt=.1,rt=2,_e=new Set(["ring","quadrant","sector","reticle-position","test-site","cluster","edge-arc"]);function we(e){const s=e.highlight;return"dieKeysByWafer"in s&&s.dieKeysByWafer?Object.values(s.dieKeysByWafer).reduce((i,n)=>i+n.length,0):"dieKeys"in s&&s.dieKeys&&s.dieKeys.length>0?s.dieKeys.length:e.level==="lot"?void 0:e.stats.sampleSizeLeft}function Ne(e){const s=e.highlight,i=new Set;if("dieKeysByWafer"in s&&s.dieKeysByWafer)for(const[n,c]of Object.entries(s.dieKeysByWafer))for(const o of c)i.add(`${n}:${o}`);else if("dieKeys"in s&&s.dieKeys)for(const n of s.dieKeys)i.add(n);return i}const z=e=>Math.abs(e.effect.absoluteDelta??0),K=e=>z(e)*(we(e)??0),W=e=>(e*100).toFixed(1),ae=e=>{const s=e.variable.label.replace(/ \(same dies\)$/,"").replace(/^HBin and SBin (\d+)/,"HBin $1").replace(/^(HBin \d+(?: \([^)]*\))?) and SBin .*$/,"$1");return Re(s)},_=e=>Math.round(e).toLocaleString("en-GB"),H=(e,s,i=`${s}s`)=>`${_(e)} ${e===1?s:i}`;function Z(e){const s=e.comparison.left;return e.comparison.family==="quadrant"&&!/quadrant/i.test(s)?`${s} quadrant`:s}const De=He;function ot(e){const s=e.map((f,a)=>a),i=f=>s[f]===f?f:s[f]=i(s[f]),n=e.map(Ne),c=(f,a)=>{const h=n[f].size<=n[a].size?n[f]:n[a],v=h===n[f]?n[a]:n[f];let N=0;for(const w of h)v.has(w)&&N++;return N},o=e.map((f,a)=>a).filter(f=>De(e[f])),r=e.map((f,a)=>a).filter(f=>!De(e[f]));for(let f=0;f<r.length;f++)for(let a=f+1;a<r.length;a++){const h=Math.min(n[r[f]].size,n[r[a]].size);h>0&&c(r[f],r[a])>=ue*h&&(s[i(r[f])]=i(r[a]))}for(const f of o){let a=-1,h=0;for(const v of r){if(ve(e[v])&&e[v].variable.bin!==e[f].variable.bin)continue;const N=c(f,v);N>h&&N>=ue*n[f].size&&N>=ue*K(e[v])&&(a=v,h=N)}a>=0&&(s[f]=i(a))}const $=new Map;return e.forEach((f,a)=>{const h=i(a);($.get(h)??$.set(h,[]).get(h)).push(a)}),[...$.values()]}const ve=e=>e.variable.kind==="hardBin"||e.variable.kind==="softBin",ke=(e,s)=>e.level===s.level&&e.comparison.family===s.comparison.family&&e.comparison.left===s.comparison.left;function at(e,s,i){const n=o=>s.filter(r=>r.variable.kind===o&&ke(r,e)&&r.effect.direction==="higher"&&i(r));return(n("hardBin").length>0?n("hardBin"):n("softBin")).filter(o=>o!==e).sort((o,r)=>z(r)-z(o))}const lt={ring:"rings",quadrant:"quadrants",sector:"sectors","edge-arc":"edge arcs",cluster:"clusters","reticle-position":"reticle positions","test-site":"test sites"},ft=2;function Be(e){const s=new Map;for(const n of e){const c=n.comparison.family;(s.get(c)??s.set(c,new Set).get(c)).add(Z(n))}const i=[];for(const[n,c]of s)c.size<=ft?i.push(...c):i.push(`${c.size} ${lt[n]??n}`);return i.join(", ")}const dt=e=>e.charAt(0).toUpperCase()+e.slice(1),ee=e=>({kind:"finding",id:e.id}),ct=e=>({label:dt(ae(e)),target:ee(e),...e.variable.bin!==void 0&&(e.variable.kind==="hardBin"||e.variable.kind==="softBin")?{bin:{kind:e.variable.kind,bin:e.variable.bin}}:{}});function he(e){const s=e.comparison.family;return{builtin:s==="quadrant"||s==="sector"?"quadrant":s==="reticle-position"?"reticleCell":s==="test-site"?"site":"ring"}}const Oe=(e,s)=>({chart:"bar",fields:{x:e,y:s,color:{none:!0}},valueLabels:!0,axes:{y:{references:[{stat:"median"}]}}}),pe=e=>({test:e}),Se=(e,s=!1)=>({chart:"histogram",fields:{y:pe(e),color:{none:!0}},...s?{normalCurve:!0}:{}});function ut(e,s,i,n){const c=[...e].sort((u,D)=>K(D)-K(u))[0],o=e.find(u=>n.isPassRate(u)&&ke(u,c))??c,r=e.filter(u=>u!==o),$=o.level==="lot"&&"waferIndices"in o.highlight?o.highlight.waferIndices?.length:void 0,f=$!==void 0&&i?` on ${$}/${i} wafers`:"",a=!n.isPassRate(o),h=o.comparison.family==="sector"?"the other sectors":"the rest of the wafer";let v=a?`${Z(o)}: ${ae(o)} ${W(z(o))} points higher than ${h}${f}`:`${Z(o)}: pass rate ${W(z(o))} points below ${h}${f}`;const N=`${v} \u2014 about ${_(K(o))} dies lost`,w=at(o,s,n.isFailBin).map(u=>({f:u,share:z(u)/(z(o)||1)})).filter(u=>a||u.share>=nt).slice(0,rt);if(a)for(const{f:u}of w)v+=`, ${ae(u)} ${W(z(u))} points higher`;else if(w.length>0){const u=w.reduce((F,R)=>F+R.share,0)<=1.000000001,D=u&&w[0].share>.5?"mostly ":"";w.forEach(({f:F},R)=>{v+=R===0?`; ${u?D:""}`:", ",v+=ae(F)+(R===0?u?` accounts for ${W(z(F))} of those points`:` is ${W(z(F))} points higher`:u?` for ${W(z(F))}`:` ${W(z(F))} points higher`)})}v+=` \u2014 about ${_(K(o))} dies lost`;const B=r.filter(u=>!ke(u,o));B.length>0&&(v+=` (also seen as ${Be(B)})`);const g=a?ae(o):"pass rate";return{kind:"loss",impact:"low",shareOfDies:0,diesLost:K(o),affected:K(o),measure:"",severity:o.severity,text:v,reason:N,brief:`${Z(o)}: ${g}, ${_(K(o))} dies`,subject:Z(o),target:ee(o),chips:[...a?[o]:[],...w.map(({f:u})=>u)].map(ct),findingIds:[o.id,...r.map(u=>u.id)],testNumbers:[],chart:a?{chart:"bar",fields:{x:he(o),color:{builtin:o.variable.kind==="softBin"?"sbin":"hbin"}},stack:"percent"}:o.level==="lot"?{chart:"heatmap",fields:{x:{builtin:"wafer"},rows:he(o),y:{builtin:"yield"}}}:Oe(he(o),{builtin:"yield"})}}function ht(e,s){return e>=tt||s>=it?"high":e>=et||s>=st?"medium":"low"}function pt(e){const s=i=>i.stats.yieldPercent==null?0:i.stats.analyzedDies*(1-i.stats.yieldPercent/100);return e.level==="wafer"?s(e):e.perWafer.reduce((i,n)=>i+s(n.summary),0)}function mt(e){return e.level==="wafer"?e.stats.analyzedDies:e.perWafer.reduce((s,i)=>s+i.summary.stats.analyzedDies,0)}const Fe=e=>e.id.startsWith("inter-wafer:yield:");function gt(e){const s=[];for(const i of e.findings){if(!Fe(i)||i.effect.direction!=="lower")continue;const n="waferIndices"in i.highlight?i.highlight.waferIndices?.[0]:void 0,c=n===void 0?void 0:e.perWafer.find(o=>o.waferIndex===n)?.summary.stats.analyzedDies;c!==void 0&&s.push({kind:"loss",impact:"low",shareOfDies:0,diesLost:z(i)*c,affected:z(i)*c,measure:"",severity:i.severity,text:`${i.summary.replace(/ percentage points lower than the lot median$/," points below the lot median")} \u2014 about ${_(z(i)*c)} dies lost`,reason:`${i.summary.replace(/ percentage points lower than the lot median$/," points below the lot median")} \u2014 about ${_(z(i)*c)} dies lost`,brief:`${i.comparison.left}: yield, ${_(z(i)*c)} dies`,subject:i.comparison.left,target:ee(i),chips:[],findingIds:[i.id],testNumbers:[],chart:{chart:"control",fields:{x:{builtin:"waferOrder"},y:{builtin:"yield"}}}})}return s}function bt(e,s){if(e.level==="wafer"){const o=e.stats.testFailures?.[s];return o?{keys:new Set(o.dieKeys),lost:o.lostDies}:void 0}const i=new Set;let n=0,c=!1;for(const o of e.perWafer){const r=o.summary.stats.testFailures?.[s];if(r){c=!0,n+=r.lostDies;for(const $ of r.dieKeys)i.add(`${o.waferIndex}:${$}`)}}return c?{keys:i,lost:n}:void 0}function $t(e,s){const i=e.stats,n=[],c=r=>Oe({builtin:e.level==="lot"?"wafer":"ring"},{passRate:r}),o=(r,$,f,a,h,v,N=h,w=!1)=>{if(f<=0||a<=0)return;s.add(r);const B=bt(e,r),g=B?Math.min(B.lost,f):f,u=f-g,D=f/a*100;n.push({testNumber:r,label:$,verb:h,plainVerb:N,failDies:f,passingDies:u,keys:B?.keys,item:{kind:"loss",impact:"low",shareOfDies:0,diesLost:g,affected:g,measure:"",severity:"info",text:`${$} ${h} on ${_(f)} of ${_(a)} dies (${D.toFixed(1)}%)`+(u>0?`; ${_(u)} of them are binned as passing, so about ${_(g)} dies lost`:""),reason:`${$} ${h} on ${_(f)} of ${_(a)} dies (${D.toFixed(1)}%)`,brief:u>0?`${$}: ${v}, ${_(g)} dies lost`:`${$}: ${_(f)} dies ${v}`,subject:$,target:{kind:"test",testNumber:r},chips:[],findingIds:[],testNumbers:[r],chart:w||e.level==="lot"?c(r):Se(r)}})};for(const r of i.testSpecYield??[]){const $=r.failHighDies===0?"is below its low limit":r.failLowDies===0?"is above its high limit":`is outside its limits (${_(r.failLowDies)} low, ${_(r.failHighDies)} high)`;o(r.testNumber,r.label,r.failLowDies+r.failHighDies,r.totalDies,$,"outside limits",r.failLowDies>0&&r.failHighDies>0?"is outside its limits":$)}for(const r of i.functionalYield??[])o(r.testNumber,r.label,r.failDies,r.totalDies,"fails","fail","fails",!0);return n}const yt=.5,wt=2,Nt=2,le=5;function vt(e,s,i,n){const c=new Set,o=new Map,r=new Map,$=[...e].sort((f,a)=>a.failDies-f.failDies||f.testNumber-a.testNumber);for(const f of $){const a=f.keys;if(n>0&&f.failDies/n<Q){c.add(f);continue}let h;if(a&&a.size>0&&n>0)for(const w of s){const B=i.get(w);if(!B||B.size===0)continue;let g=0;for(const D of a)B.has(D)&&g++;const u=g/a.size;u>=yt&&u>=wt*(B.size/n)&&(!h||g>h.inside)&&(h={item:w,inside:g})}if(!h){c.add(f);continue}const v=o.get(h.item)??0;if(v<Nt){const w=h.inside===f.failDies?"all":_(h.inside);h.item.text+=`. ${f.label} ${f.verb} on ${H(f.failDies,"die")}, ${w} of them in ${h.item.subject}`,o.set(h.item,v+1)}const N=r.get(h.item)??0;N<le?(h.item.chips.push({label:f.label,target:f.item.target}),r.set(h.item,N+1)):h.item.moreTests=(h.item.moreTests??0)+1,h.item.testNumbers.push(f.testNumber)}return e.filter(f=>c.has(f))}function te(e){return{kind:"signal",impact:"low",shareOfDies:0,diesLost:0,affected:e.affected,measure:e.measure,severity:e.severity,text:e.text,reason:e.reason??e.text,brief:e.brief,subject:e.subject,target:e.target,chips:[],findingIds:e.findingIds??[],testNumbers:e.testNumbers??[],chart:e.chart}}const me=e=>Math.abs(e)<Ze?0:Math.min(1,(Math.abs(e)/Qe)**2),Y=e=>`${Math.abs(e).toFixed(1)}\u03C3`,kt=e=>e.variable.kind==="test"&&e.variable.measure!=="limitFailRate"&&_e.has(e.comparison.family)&&Number.isFinite(e.effect.effectSize??NaN)&&!e.id.startsWith("drift:");function St(e,s,i){const n=new Map;for(const r of e)!kt(r)||r.variable.index===void 0||(n.get(r.variable.index)??n.set(r.variable.index,[]).get(r.variable.index)).push(r);const c=r=>(we(r)??r.stats.sampleSizeLeft)*me(r.effect.effectSize??0),o=[];for(const[r,$]of[...n].sort((f,a)=>f[0]-a[0])){const f=[...$].sort((g,u)=>c(u)-c(g)),a=f[0],h=a.effect.effectSize??0;if(c(a)===0)continue;const v=Ne(a);let N=s.find(g=>g.target.kind==="test"&&g.target.testNumber===r)??s.find(g=>g.testNumbers.includes(r))??s.find(g=>f.some(u=>g.findingIds.includes(u.id))),w=0;for(const g of N?[]:s){const u=i.get(g);if(!u||u.size===0||v.size===0)continue;let D=0;for(const F of v)u.has(F)&&D++;D>=ue*Math.min(u.size,v.size)&&D>w&&(w=D,N=g)}if(N){N.text+=`. ${a.summary}`,N.testNumbers.includes(r)||(N.chips.filter(u=>u.target.kind==="test"||u.shift).length<le?N.chips.push({label:a.variable.label,target:ee(a),shift:!0}):N.moreTests=(N.moreTests??0)+1,N.testNumbers.push(r));for(const g of f)N.findingIds.includes(g.id)||N.findingIds.push(g.id);continue}const B=we(a)??a.stats.sampleSizeLeft;o.push(te({affected:c(a),measure:Y(h),severity:a.severity,text:`${a.summary}: a shift of ${Y(h)} over ${H(B,"die")}`+(f.length>1?` (also seen as ${Be(f.slice(1))})`:""),reason:`${a.summary}: a shift of ${Y(h)} over ${H(B,"die")}`,brief:`${Z(a)}: ${a.variable.label} ${a.effect.direction}`,subject:Z(a),target:ee(a),findingIds:f.map(g=>g.id),testNumbers:[r],chart:{chart:"box",fields:{x:he(a),y:pe(r),color:{none:!0}},axes:{y:{references:[{stat:"median"}]}}}}))}return o}function Mt(e,s){return e.filter(i=>i.id.startsWith("drift:")).map(i=>{const n=i.variable.kind==="yield",c=i.effect.effectSize??0;return te({affected:s*(n?Math.abs(c):me(c)),measure:n?`${W(Math.abs(c))} pts`:Y(c),severity:i.severity,text:i.summary,brief:`${i.variable.label}: drifts across the wafers`,subject:i.variable.label,target:ee(i),findingIds:[i.id],...i.variable.index!==void 0?{testNumbers:[i.variable.index]}:{},chart:{chart:"control",fields:{x:{builtin:"waferOrder"},y:n||i.variable.index===void 0?{builtin:"yield"}:pe(i.variable.index)}}})})}function It(e,s,i){return(e.stats.capability??[]).filter(n=>n.hasSpec&&n.ppk!==null&&n.ppk!==void 0&&n.ppk<Je&&!s.has(n.testNumber)).map(n=>{const c=n.ppk,o=qe(3*c);return te({affected:i*o,measure:`Ppk ${c.toFixed(2)}`,severity:"notable",text:`${n.label} has Ppk ${c.toFixed(2)} against its limits: a spread that would put about ${W(o)}% of the dies outside them`,brief:`${n.label}: Ppk ${c.toFixed(2)}`,subject:n.label,target:{kind:"test",testNumber:n.testNumber},testNumbers:[n.testNumber],chart:Se(n.testNumber,!0)})})}const ge=.05,xt=8,Le=.01,_t=.05,Dt=.25,Bt=1,Ot=3,je=e=>e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`;function Ft(e,s,i,n=[]){const c={items:[],compared:[],possible:[]},o=e.perWafer;if(o.length<4)return c;const r=Xe(o.map(t=>({metadata:t.summary.wafer,dieCount:t.summary.stats.totalDies})),{facetableOnly:!0,curation:s}).filter(t=>t.splittable&&t.values.length<=Math.max(2,Math.floor(o.length/2)));if(r.length===0)return c;const $=Ye(r.map(t=>({key:t.key,groupOf:o.map(d=>Me(d.summary.wafer,t.key,s))}))),f=t=>e.perWaferTestStats?.find(d=>d.waferIndex===t.waferIndex)?.tests??t.summary.stats.perTestStats??[],a=o.map(t=>new Map(f(t).filter(d=>d.count>=2&&Number.isFinite(d.mean)).map(d=>[d.testNumber,d]))),h=new Map;for(const t of a)for(const[d,p]of t)h.has(d)||h.set(d,p.label);const v=o.map(t=>t.summary.stats.analyzedDies),N=o.map(t=>t.summary.stats.yieldPercent===null?void 0:t.summary.stats.yieldPercent/100),w=o.map(t=>{const d=t.summary.stats.hardBinCounts,p=d?Object.values(d).reduce((m,y)=>m+y,0):0;return d&&p>0?new Map(Object.entries(d).map(([m,y])=>[Number(m),y/p])):void 0}),B=(t,d,p,m)=>{let y;for(const[x,L]of t){const k=L.map(d),j=[...t].filter(([S])=>S!==x).flatMap(([,S])=>S.map(d));if(k.length<2||j.length<2)continue;const A=k.reduce((S,O)=>S+O,0)/k.length-j.reduce((S,O)=>S+O,0)/j.length,b=A/p;(!y||Math.abs(b)>Math.abs(y.d)+1e-9||Math.abs(Math.abs(b)-Math.abs(y.d))<=1e-9&&(L.length<y.groupWafers||L.length===y.groupWafers&&A>0))&&(y=m(x,L,b,A>0))}if(y&&t.size===2){const[x,L]=[...t].find(([k])=>k!==y.group);y.other={group:x,wafers:L.length}}return y},g=[],u=[],D=[];for(const[t,d]of[...h].sort((p,m)=>p[0]-m[0])){const p=a.flatMap(y=>{const x=y.get(t);return x&&Number.isFinite(x.stddev)?[x.stddev**2]:[]}),m=p.length?Math.sqrt(p.reduce((y,x)=>y+x,0)/p.length):NaN;m>0&&D.push({testNumber:t,label:d,values:a.map(y=>y.get(t)?.mean),scale:m})}D.push({testNumber:NaN,label:"Yield",values:N,scale:1,scope:v});const F=[...e.stats.regionYield?.ring??[]].sort((t,d)=>t.yieldPercent-d.yieldPercent)[0];if(F&&o.length>0){const t=o.map(d=>{const p=d.summary.stats.regionYield?.ring?.find(m=>m.key===F.key);return p?p.yieldPercent/100:void 0});if(t.every(d=>d!==void 0)){const d=o.map(p=>p.summary.stats.regionYield?.ring?.find(m=>m.key===F.key)?.n??0);D.push({testNumber:NaN,label:`${F.label} pass rate`,values:t,scale:1,region:F.label,regionValue:Ue(Ve(F.key).ring),scope:d})}}for(const t of D)for(const{partition:d,used:p,fitted:m,allowedFor:y}of Ke(t.values,$)){const x=d.id,L=d.keys;if(!m)continue;const k=B(m.byGroup,b=>p[b],t.scale,(b,P,S,O)=>({part:x,keys:L,testNumber:t.testNumber,label:t.label,group:b,members:P,groupWafers:P.length,groupDies:P.reduce((T,I)=>T+v[I],0),d:S,higher:O,p:m.p,...t.region?{region:t.region,regionValue:t.regionValue}:{},...y?{allowedFor:y}:{}}));if(!k)continue;const j=k.members.map(b=>p[b]),A=[...m.byGroup].filter(([b])=>b!==k.group).flatMap(([,b])=>b.map(P=>p[P]));if(t.scope){const b=S=>S.reduce((O,T)=>O+t.scope[T],0),P=[...m.byGroup].filter(([S])=>S!==k.group).flatMap(([,S])=>S);k.lost=(k.higher?b(P):b(k.members))*Math.abs(k.d)}if(k.separated=$e(j)>be(A)||be(j)<$e(A),Number.isNaN(t.testNumber)){if(i&&!t.region){let b=0;const P=new Set(w.flatMap(O=>O?[...O.keys()]:[])),S=o.map((O,T)=>T).filter(O=>!k.members.includes(O)&&N[O]!==void 0);for(const O of P){if(i.includes(O))continue;const T=U=>U.reduce((ze,Pe)=>ze+(w[Pe]?.get(O)??0),0)/Math.max(1,U.length),I=(T(k.members)-T(S))*(k.higher?-1:1);I>b&&(b=I,k.bin=O)}}u.push(k)}else g.push(k)}const R=Ce([...g,...u].map(t=>t.p)),C=t=>R[t],ne=new Map;g.forEach((t,d)=>{const p=t.groupDies*me(t.d);C(d)>=ge||p===0||(ne.get(t.part)??ne.set(t.part,[]).get(t.part)).push({c:t,q:C(d),weight:p})});const fe=[...new Set([...g,...u].flatMap(t=>t.keys))].map(t=>ie(t,s)),q=t=>je(t.map(d=>ie(d,s))),G=t=>{const d=`${ie(t.keys[0],s)} ${t.group}`;if(t.keys.length===1)return d;const p=o[t.members[0]].summary.wafer,m=t.keys.slice(1).map(y=>`${ie(y,s)} ${Me(p,y,s)??""}`.trim());return`${d} (${je(m)} group${m.length===1?"s":""} the same wafers)`},V=t=>t.allowedFor?`, allowing for ${q(t.allowedFor)}`:"",X=t=>{const d=$.find(m=>m.id===t),p=d?Ge(d,$):[];return p.length===0?"":`. ${p.map(m=>`${q(m.partition.keys.slice(0,1))} puts ${m.agree} of ${m.of} wafers in the same groups`).join("; ")}, so the wafers cannot fully tell ${p.length===1?"the two":"them"} apart`},J=t=>`${ie(t.keys[0],s)} ${t.other.group}`,se=t=>t.other?`${t.label} is ${t.higher?"higher":"lower"} on ${G(t)} than on ${J(t)} (${t.groupWafers} and ${t.other.wafers} wafers)`:`${t.label} is ${t.higher?"higher":"lower"} on ${G(t)} (${t.groupWafers} of ${o.length} wafers) than on the other wafers`,re=[...ne].map(([t,d])=>{d.sort((I,U)=>Math.abs(U.c.d)-Math.abs(I.c.d)||U.weight-I.weight||I.c.testNumber-U.c.testNumber);const p=d.reduce((I,U)=>Math.max(I,U.weight),0),m=d[0].c.keys,y=m[0],x=q(m),[L,...k]=d,j=L.c,A=`${se(j)}: a shift of ${Y(j.d)}${V(j)}`,b=k.slice(0,2).map(({c:I})=>`${I.label} ${I.higher?"higher":"lower"} on ${I.keys.length>1?ie(I.keys[0],s)+" ":""}${I.group} (${Y(I.d)})`),P=k.length-b.length,S=d.length,O=(S===1?`${A}, each wafer one value (q ${ye(L.q)})`:`${S} tests differ by ${x}. Largest: ${A}, each wafer one value (q ${ye(L.q)}); next: ${b.join(", ")}${P>0?`, and ${P} more`:""}`)+X(t),T=te({affected:p,measure:Y(j.d),severity:L.q<.001?"unusual":"notable",text:O,reason:S===1?A:`${S} tests differ by ${x}. Largest: ${A}`,brief:S===1?`${x} ${j.group}: ${j.label} ${j.higher?"higher":"lower"}`:`${x}: ${S} tests differ`,subject:x,target:{kind:"test",testNumber:j.testNumber},testNumbers:d.map(I=>I.c.testNumber),chart:S>1?{chart:"heatmap",level:"wafer",aggregate:"mean",normalize:"zscore",fields:{x:{meta:y},y:{tests:d.slice(0,xt).map(I=>I.c.testNumber)}}}:{chart:"box",level:"wafer",aggregate:"mean",fields:{x:{meta:y},y:pe(j.testNumber),color:{meta:y}}}});return S>1&&(T.chips=d.slice(0,le).map(({c:I})=>({label:`${I.label} ${Y(I.d)}`,target:{kind:"test",testNumber:I.testNumber}})),S>le&&(T.moreTests=S-le)),T});u.forEach((t,d)=>{const p=C(g.length+d),m=t.lost??t.groupDies*Math.abs(t.d);if(p>=ge||Math.abs(t.d)<Le)return;const y=q(t.keys),x=`${(Math.abs(t.d)*100).toFixed(1)} points`,L=`${t.bin!==void 0?`, mostly in hard bin ${t.bin}`:""}${V(t)}`,k=t.other?`${t.label} is ${x} ${t.higher?"higher":"lower"} on ${G(t)} than on ${J(t)} (${t.groupWafers} and ${t.other.wafers} wafers)`:`${t.label} is ${x} ${t.higher?"higher":"lower"} on ${G(t)} (${t.groupWafers} of ${o.length} wafers) than on the other wafers`;re.push(te({affected:m,measure:x,severity:p<.001?"unusual":"notable",text:`${k}${L}, each wafer one value (q ${ye(p)})${X(t.part)}`,reason:`${k}${L}`,brief:`${y} ${t.group}: ${t.region?"ring pass rate":"yield"} ${t.higher?"higher":"lower"}`,subject:y,target:{kind:"group",field:t.keys[0],fields:t.keys},testNumbers:[],chart:{chart:"bar",fields:{x:{meta:t.keys[0]},y:{builtin:"yield"},color:{meta:t.keys[0]}},valueLabels:!0,...t.region?{where:{conditions:[{field:{builtin:"ring"},values:[t.regionValue??t.region]}]}}:{}}}))});const de=v.reduce((t,d)=>t+d,0),oe=new Set([...g.filter((t,d)=>C(d)<ge&&t.groupDies*me(t.d)>0).map(t=>t.part),...u.filter((t,d)=>C(g.length+d)<ge&&Math.abs(t.d)>=Le).map(t=>t.part)]),ce=[...g.filter(t=>Math.abs(t.d)>=Bt),...u.filter(t=>(t.lost??0)>=Math.min(Q*de,...n.map(d=>Dt*d)))].filter(t=>t.separated&&t.p<_t&&!oe.has(t.part)),l=new Map;for(const t of ce)(l.get(`${t.part}|${t.group}`)??l.set(`${t.part}|${t.group}`,[]).get(`${t.part}|${t.group}`)).push(t);const M=[],E=g.length+u.length;for(const t of l.values()){const d=t.find(b=>Number.isNaN(b.testNumber)),p=t.filter(b=>!Number.isNaN(b.testNumber)||!d||b.higher===d.higher);if(p.length<2)continue;const m=p[0],y=b=>Number.isNaN(b.testNumber)?`${b.label} ${b.higher?"higher":"lower"} by ${(Math.abs(b.d)*100).toFixed(1)} points`:`${b.label} ${b.higher?"higher":"lower"} (${Y(b.d)})`,x=m.other?`than on ${J(m)} (${m.groupWafers} and ${m.other.wafers} wafers)`:`than on the other wafers (${m.groupWafers} of ${o.length})`,L=`${G(m)}: ${p.map(y).join("; ")} ${x}`,k=q(m.keys),j=p.reduce((b,P)=>Math.max(b,P.lost??0),0),A=te({affected:j,measure:`${p.length} measures`,severity:"info",text:`Possibly ${L}. No wafer of the group overlaps the others on ${p.length===2?"either":`any of ${p.length}`}, but the sample is too small to confirm it once ${E} comparisons are allowed for`,reason:`Possibly ${L}`,brief:`${k} ${m.group}: possible, not confirmed`,subject:k,target:{kind:"group",field:m.keys[0],fields:m.keys},testNumbers:p.filter(b=>!Number.isNaN(b.testNumber)).map(b=>b.testNumber),chart:{chart:"bar",fields:{x:{meta:m.keys[0]},y:{builtin:"yield"},color:{meta:m.keys[0]}},valueLabels:!0}});M.push(A)}return M.sort((t,d)=>d.affected-t.affected),{items:re,compared:fe,possible:M.slice(0,Ot)}}export function groupColouredChart(e,s){const i=e.fields?.x,n=e.fields?.color;return!s||e.chart!=="bar"||!i||Array.isArray(i)||!("builtin"in i)||i.builtin!=="wafer"||!n||!("none"in n)?e:{...e,fields:{...e.fields,x:[{slot:"groupBy"},{builtin:"wafer"}],color:{follow:"groupBy"}}}}function Lt(e){return e.map(s=>te({affected:s.passingDies,measure:"",severity:"notable",text:`${s.label} ${s.plainVerb} on ${H(s.passingDies,"die")} binned as passing`,brief:`${s.label}: ${_(s.passingDies)} dies out of limits, binned passing`,subject:s.label,target:s.item.target,testNumbers:[s.testNumber],chart:Se(s.testNumber)}))}function jt(e,s){const i=s.passBins&&s.passBins.length>0?`; pass ${Te([s.passBins])}`:"";if(e.level==="wafer"){const a=e.stats.yieldPercent;return a==null?`${_(e.stats.totalDies)} dies, no bin data to judge yield by.`:`Yield ${a.toFixed(1)}% (${_(e.stats.totalDies)} dies${i}).`}const n=e.lotYieldSeries.map(a=>a.yieldPercent).filter(a=>typeof a=="number");if(n.length===0)return`${H(e.stats.waferCount,"wafer")}, no bin data to judge yield by.`;const c=n.reduce((a,h)=>a+h,0)/n.length,o=e.perWafer.reduce((a,h)=>a+h.summary.stats.totalDies,0),[r,$]=[$e(n).toFixed(1),be(n).toFixed(1)],f=r!==$?`, range ${r}\u2013${$}%`:"";return`Yield ${c.toFixed(1)}% (mean of ${H(n.length,"wafer")}, ${_(o)} dies${i})${f}.`}function Et(e,s,i=[]){const n=[],c=e.level==="wafer"?e.stats.testsConsidered.length:new Set(e.perWafer.flatMap(a=>a.summary.stats.testsConsidered)).size,o=e.level==="wafer"?e.stats.hardBinsConsidered.length:new Set(e.perWafer.flatMap(a=>a.summary.stats.hardBinsConsidered)).size,r=e.stats.testValueAnalysis?.state;if(c>0&&r!=="off"&&n.push(H(c,"test")+(r==="skipped"?" (against their limits only)":"")),o>0&&n.push(H(o,"hard bin")),n.push("the ring, quadrant and sector regions"),e.level==="lot"&&e.stats.waferCount>=3){const a=e.findings.filter(Fe);n.push(a.length===0?"wafer-to-wafer yield (no outlier wafers)":`wafer-to-wafer yield (${H(a.length,"outlier wafer")})`),e.stats.waferCount>=We&&n.push("the yield trend across the wafers (input order)"),i.length&&n.push(`the tests between the groups of ${i.join(", ")} (each wafer one value)`)}const $=e.findings.filter(a=>!s.has(a.id)).length,f=$>0?` ${H($,"smaller finding")} not listed above.`:" Nothing else was found.";return`Compared: ${n.join(", ")}.${f}`}export function synthesisSource(e){return e.level==="lot"&&e.perWafer.length===1?e.perWafer[0].summary:e}const Ee=new WeakMap;export function buildSynthesis(e,s={}){const i=`${s.passBins?.join(",")??"-"}|${s.attributes?JSON.stringify(s.attributes):"-"}`;let n=Ee.get(e);n||Ee.set(e,n=new Map);const c=n.get(i),o=e.findings;if(c&&c.findings.length===o.length&&c.findings.every(($,f)=>$===o[f]))return c.synthesis;const r=zt(e,s);return Object.freeze(r.items),r.items.forEach(Object.freeze),r.possible&&(r.possible.forEach(Object.freeze),Object.freeze(r.possible)),r.also&&(Object.freeze(r.also.items),r.also.items.forEach(Object.freeze),Object.freeze(r.also)),n.set(i,{findings:[...o],synthesis:Object.freeze(r)}),r}function zt(e,s){const i=synthesisSource(e),n=i.findings,c=i.level==="lot"?i.stats.waferCount:void 0,o=s.passBins,r=new Map(n.map(l=>[l.id,l])),$=(i.level==="wafer"?[i]:i.perWafer.map(l=>l.summary)).every(l=>(l.stats.hardBinsConsidered??[]).length===0),f=l=>o!==void 0&&ve(l)&&Ae(l.variable.kind,l.variable.bin??NaN,o,!$),a={isPassRate:l=>l.variable.kind==="yield"||o?.length===1&&f(l),isFailBin:l=>o!==void 0&&ve(l)&&!f(l)},h=n.filter(l=>_e.has(l.comparison.family)&&K(l)>0&&(a.isPassRate(l)&&l.effect.direction==="lower"||a.isFailBin(l)&&l.effect.direction==="higher")),N=h.some(l=>l.variable.kind==="hardBin")?h.filter(l=>l.variable.kind!=="softBin"):h,w=[],B=new Map,g=new Set;for(const l of ot(N)){const M=l.map(d=>N[d]),E=ut(M,n,c,a);w.push(E);const t=E.target.kind==="finding"?E.target.id:void 0;B.set(E,Ne(M.find(d=>d.id===t)??M[0]))}for(const l of n.filter(M=>M.variable.kind==="spatialPattern")){const M=new Set((l.relatedIds??[]).filter(p=>r.has(p))),E=w.find(p=>p.findingIds.some(m=>M.has(m)));if(!E)continue;const t=l.level==="lot"&&"waferIndices"in l.highlight?l.highlight.waferIndices?.length:void 0,d=t!==void 0&&c?` on ${t}/${c} wafers`:"";E.text=`${l.variable.label} pattern${d}. ${E.text}`,E.reason=`${l.variable.label} pattern${d}. ${E.reason}`,E.chips.unshift({label:`${l.variable.label} pattern`,target:ee(l)}),E.findingIds.unshift(l.id,...[...M].filter(p=>!w.some(m=>m.findingIds.includes(p))))}const u=mt(i),D=new Set,F=$t(i,D),R=[...w],C=vt(F,R,B,u);i.level==="lot"&&w.push(...gt(i)),w.push(...C.map(l=>l.item));const ne=new Set(C.filter(l=>u>0&&l.item.diesLost/u>=Q).map(l=>l.testNumber));w.push(...St(n,[...R,...C.map(l=>l.item)],B),...Mt(n,u),...It(i,D,u),...Lt(F.filter(l=>l.passingDies>0&&!ne.has(l.testNumber))));let fe=[],q=[];if(i.level==="lot"){const l=Ft(i,s.attributes,s.passBins,w.filter(M=>M.kind==="loss").map(M=>M.diesLost));fe=l.compared,q=l.possible;for(const M of l.items){const E=M.testNumbers[0],t=M.testNumbers.length===1?w.find(d=>d.target.kind==="test"&&d.target.testNumber===E)??w.find(d=>d.testNumbers.includes(E)):void 0;t?t.text+=`. ${M.text}`:w.push(M)}}const G=pt(i),V=w.filter(l=>u>0&&l.affected/u>=Q);for(const l of V)l.shareOfDies=l.affected/u,l.impact=ht(l.shareOfDies,l.kind==="loss"&&G>0?l.diesLost/G:0),l.measure||(l.measure=`${(l.shareOfDies*100).toFixed(1)}%`);const X=l=>`${String(l.testNumbers[0]??"").padStart(10,"0")}${l.findingIds[0]??""}`;V.sort((l,M)=>M.affected-l.affected||(X(l)<X(M)?-1:X(l)>X(M)?1:0));const J=V.slice(0,Ie),se=V.slice(Ie);for(const l of[...J,...se])for(const M of l.findingIds)g.add(M);const re=se.length>0?{items:se.slice(0,xe),more:Math.max(0,se.length-xe)}:void 0,de=i.level==="lot"?"region, fail bin or wafer":"region or fail bin",oe=n.filter(l=>l.severity==="unusual"&&!g.has(l.id)).length,ce=J.length===0?oe>0?`No ${de} costs as much as ${W(Q)} yield points, though ${H(oe,"finding")} below ${oe===1?"is":"are"} marked unusual.`:`Nothing stands out: no ${de} costs as much as ${W(Q)} yield points.`:void 0;return{headline:jt(i,s),items:J,...re?{also:re}:{},...q.length?{possible:q}:{},...ce?{nothing:ce}:{},checked:Et(i,g,fe)}}export const synthesisKey=e=>e.target.kind==="finding"?`finding:${e.target.id}`:e.target.kind==="group"?`group:${e.target.field}`:`test:${e.target.testNumber}`,SYNTHESIS_POSSIBLE_HEADING="Possible, not confirmed",SYNTHESIS_ALSO_HEADING=`Also, each affecting at least ${(Q*100).toFixed(0)}% of the dies`,synthesisRowShare=e=>e.measure,synthesisMoreTests=e=>e.moreTests?`and ${e.moreTests} more test${e.moreTests===1?"":"s"}`:void 0;export function synthesisText(e){return[e.headline,...e.nothing?[e.nothing]:[],...e.items.map((s,i)=>`${i+1}. ${s.text}`),...e.also?[`${SYNTHESIS_ALSO_HEADING}: ${e.also.items.map(s=>`${s.brief} (${synthesisRowShare(s)})`).join("; ")}${e.also.more?`; and ${e.also.more} more`:""}.`]:[],...e.possible?[`${SYNTHESIS_POSSIBLE_HEADING}:`,...e.possible.map(s=>`- ${s.text}`)]:[],e.checked].join(`
|
|
1
|
+
import{maxOf as be,minOf as $e}from"../core/utils.js";import{isPassBin as Pe,passBinsLabel as Te}from"../core/passBins.js";import{DRIFT_MIN_WAFERS as We}from"./lotDrift.js";import{isOneBinCluster as He}from"./filterFindings.js";import{plainBinTerms as Re}from"../renderer/fmt.js";import{benjaminiHochberg as Ce,normalUpperTail as qe}from"./math.js";import{formatP as ye}from"./groupCompare.js";import{adjustedFits as Ke,comparableGrouping as Ye,mergePartitions as Ge,overlapping as Ue}from"./groupEffects.js";import{ringPlotValue as Ve}from"./dieRegions.js";import{parseRegionKey as Xe}from"./regions.js";import{attributeLabel as ie,buildFacetTable as Je,facetValueOf as Me}from"./facets.js";const Qe=1,Ze=2,et=.5,Ie=3,xe=5,Q=.01,tt=.02,st=.04,it=.15,nt=.4,ue=.5,rt=.1,ot=2,_e=new Set(["ring","quadrant","sector","reticle-position","test-site","cluster","edge-arc"]);function we(e){const s=e.highlight;return"dieKeysByWafer"in s&&s.dieKeysByWafer?Object.values(s.dieKeysByWafer).reduce((i,n)=>i+n.length,0):"dieKeys"in s&&s.dieKeys&&s.dieKeys.length>0?s.dieKeys.length:e.level==="lot"?void 0:e.stats.sampleSizeLeft}function Ne(e){const s=e.highlight,i=new Set;if("dieKeysByWafer"in s&&s.dieKeysByWafer)for(const[n,c]of Object.entries(s.dieKeysByWafer))for(const o of c)i.add(`${n}:${o}`);else if("dieKeys"in s&&s.dieKeys)for(const n of s.dieKeys)i.add(n);return i}const z=e=>Math.abs(e.effect.absoluteDelta??0),K=e=>z(e)*(we(e)??0),W=e=>(e*100).toFixed(1),ae=e=>{const s=e.variable.label.replace(/ \(same dies\)$/,"").replace(/^HBin and SBin (\d+)/,"HBin $1").replace(/^(HBin \d+(?: \([^)]*\))?) and SBin .*$/,"$1");return Re(s)},_=e=>Math.round(e).toLocaleString("en-GB"),H=(e,s,i=`${s}s`)=>`${_(e)} ${e===1?s:i}`;function Z(e){const s=e.comparison.left;return e.comparison.family==="quadrant"&&!/quadrant/i.test(s)?`${s} quadrant`:s}const De=He;function at(e){const s=e.map((f,a)=>a),i=f=>s[f]===f?f:s[f]=i(s[f]),n=e.map(Ne),c=(f,a)=>{const h=n[f].size<=n[a].size?n[f]:n[a],v=h===n[f]?n[a]:n[f];let N=0;for(const w of h)v.has(w)&&N++;return N},o=e.map((f,a)=>a).filter(f=>De(e[f])),r=e.map((f,a)=>a).filter(f=>!De(e[f]));for(let f=0;f<r.length;f++)for(let a=f+1;a<r.length;a++){const h=Math.min(n[r[f]].size,n[r[a]].size);h>0&&c(r[f],r[a])>=ue*h&&(s[i(r[f])]=i(r[a]))}for(const f of o){let a=-1,h=0;for(const v of r){if(ve(e[v])&&e[v].variable.bin!==e[f].variable.bin)continue;const N=c(f,v);N>h&&N>=ue*n[f].size&&N>=ue*K(e[v])&&(a=v,h=N)}a>=0&&(s[f]=i(a))}const $=new Map;return e.forEach((f,a)=>{const h=i(a);($.get(h)??$.set(h,[]).get(h)).push(a)}),[...$.values()]}const ve=e=>e.variable.kind==="hardBin"||e.variable.kind==="softBin",ke=(e,s)=>e.level===s.level&&e.comparison.family===s.comparison.family&&e.comparison.left===s.comparison.left;function lt(e,s,i){const n=o=>s.filter(r=>r.variable.kind===o&&ke(r,e)&&r.effect.direction==="higher"&&i(r));return(n("hardBin").length>0?n("hardBin"):n("softBin")).filter(o=>o!==e).sort((o,r)=>z(r)-z(o))}const ft={ring:"rings",quadrant:"quadrants",sector:"sectors","edge-arc":"edge arcs",cluster:"clusters","reticle-position":"reticle positions","test-site":"test sites"},dt=2;function Be(e){const s=new Map;for(const n of e){const c=n.comparison.family;(s.get(c)??s.set(c,new Set).get(c)).add(Z(n))}const i=[];for(const[n,c]of s)c.size<=dt?i.push(...c):i.push(`${c.size} ${ft[n]??n}`);return i.join(", ")}const ct=e=>e.charAt(0).toUpperCase()+e.slice(1),ee=e=>({kind:"finding",id:e.id}),ut=e=>({label:ct(ae(e)),target:ee(e),...e.variable.bin!==void 0&&(e.variable.kind==="hardBin"||e.variable.kind==="softBin")?{bin:{kind:e.variable.kind,bin:e.variable.bin}}:{}});function he(e){const s=e.comparison.family;return{builtin:s==="quadrant"||s==="sector"?"quadrant":s==="reticle-position"?"reticleCell":s==="test-site"?"site":"ring"}}const Oe=(e,s)=>({chart:"bar",fields:{x:e,y:s,color:{none:!0}},valueLabels:!0,axes:{y:{references:[{stat:"median"}]}}}),pe=e=>({test:e}),Se=(e,s=!1)=>({chart:"histogram",fields:{y:pe(e),color:{none:!0}},...s?{normalCurve:!0}:{}});function ht(e,s,i,n){const c=[...e].sort((u,D)=>K(D)-K(u))[0],o=e.find(u=>n.isPassRate(u)&&ke(u,c))??c,r=e.filter(u=>u!==o),$=o.level==="lot"&&"waferIndices"in o.highlight?o.highlight.waferIndices?.length:void 0,f=$!==void 0&&i?` on ${$}/${i} wafers`:"",a=!n.isPassRate(o),h=o.comparison.family==="sector"?"the other sectors":"the rest of the wafer";let v=a?`${Z(o)}: ${ae(o)} ${W(z(o))} points higher than ${h}${f}`:`${Z(o)}: pass rate ${W(z(o))} points below ${h}${f}`;const N=`${v} \u2014 about ${_(K(o))} dies lost`,w=lt(o,s,n.isFailBin).map(u=>({f:u,share:z(u)/(z(o)||1)})).filter(u=>a||u.share>=rt).slice(0,ot);if(a)for(const{f:u}of w)v+=`, ${ae(u)} ${W(z(u))} points higher`;else if(w.length>0){const u=w.reduce((F,R)=>F+R.share,0)<=1.000000001,D=u&&w[0].share>.5?"mostly ":"";w.forEach(({f:F},R)=>{v+=R===0?`; ${u?D:""}`:", ",v+=ae(F)+(R===0?u?` accounts for ${W(z(F))} of those points`:` is ${W(z(F))} points higher`:u?` for ${W(z(F))}`:` ${W(z(F))} points higher`)})}v+=` \u2014 about ${_(K(o))} dies lost`;const B=r.filter(u=>!ke(u,o));B.length>0&&(v+=` (also seen as ${Be(B)})`);const g=a?ae(o):"pass rate";return{kind:"loss",impact:"low",shareOfDies:0,diesLost:K(o),affected:K(o),measure:"",severity:o.severity,text:v,reason:N,brief:`${Z(o)}: ${g}, ${_(K(o))} dies`,subject:Z(o),target:ee(o),chips:[...a?[o]:[],...w.map(({f:u})=>u)].map(ut),findingIds:[o.id,...r.map(u=>u.id)],testNumbers:[],chart:a?{chart:"bar",fields:{x:he(o),color:{builtin:o.variable.kind==="softBin"?"sbin":"hbin"}},stack:"percent"}:o.level==="lot"?{chart:"heatmap",fields:{x:{builtin:"wafer"},rows:he(o),y:{builtin:"yield"}}}:Oe(he(o),{builtin:"yield"})}}function pt(e,s){return e>=st||s>=nt?"high":e>=tt||s>=it?"medium":"low"}function mt(e){const s=i=>i.stats.yieldPercent==null?0:i.stats.analyzedDies*(1-i.stats.yieldPercent/100);return e.level==="wafer"?s(e):e.perWafer.reduce((i,n)=>i+s(n.summary),0)}function gt(e){return e.level==="wafer"?e.stats.analyzedDies:e.perWafer.reduce((s,i)=>s+i.summary.stats.analyzedDies,0)}const Fe=e=>e.id.startsWith("inter-wafer:yield:");function bt(e){const s=[];for(const i of e.findings){if(!Fe(i)||i.effect.direction!=="lower")continue;const n="waferIndices"in i.highlight?i.highlight.waferIndices?.[0]:void 0,c=n===void 0?void 0:e.perWafer.find(o=>o.waferIndex===n)?.summary.stats.analyzedDies;c!==void 0&&s.push({kind:"loss",impact:"low",shareOfDies:0,diesLost:z(i)*c,affected:z(i)*c,measure:"",severity:i.severity,text:`${i.summary.replace(/ percentage points lower than the lot median$/," points below the lot median")} \u2014 about ${_(z(i)*c)} dies lost`,reason:`${i.summary.replace(/ percentage points lower than the lot median$/," points below the lot median")} \u2014 about ${_(z(i)*c)} dies lost`,brief:`${i.comparison.left}: yield, ${_(z(i)*c)} dies`,subject:i.comparison.left,target:ee(i),chips:[],findingIds:[i.id],testNumbers:[],chart:{chart:"control",fields:{x:{builtin:"waferOrder"},y:{builtin:"yield"}}}})}return s}function $t(e,s){if(e.level==="wafer"){const o=e.stats.testFailures?.[s];return o?{keys:new Set(o.dieKeys),lost:o.lostDies}:void 0}const i=new Set;let n=0,c=!1;for(const o of e.perWafer){const r=o.summary.stats.testFailures?.[s];if(r){c=!0,n+=r.lostDies;for(const $ of r.dieKeys)i.add(`${o.waferIndex}:${$}`)}}return c?{keys:i,lost:n}:void 0}function yt(e,s){const i=e.stats,n=[],c=r=>Oe({builtin:e.level==="lot"?"wafer":"ring"},{passRate:r}),o=(r,$,f,a,h,v,N=h,w=!1)=>{if(f<=0||a<=0)return;s.add(r);const B=$t(e,r),g=B?Math.min(B.lost,f):f,u=f-g,D=f/a*100;n.push({testNumber:r,label:$,verb:h,plainVerb:N,failDies:f,passingDies:u,keys:B?.keys,item:{kind:"loss",impact:"low",shareOfDies:0,diesLost:g,affected:g,measure:"",severity:"info",text:`${$} ${h} on ${_(f)} of ${_(a)} dies (${D.toFixed(1)}%)`+(u>0?`; ${_(u)} of them are binned as passing, so about ${_(g)} dies lost`:""),reason:`${$} ${h} on ${_(f)} of ${_(a)} dies (${D.toFixed(1)}%)`,brief:u>0?`${$}: ${v}, ${_(g)} dies lost`:`${$}: ${_(f)} dies ${v}`,subject:$,target:{kind:"test",testNumber:r},chips:[],findingIds:[],testNumbers:[r],chart:w||e.level==="lot"?c(r):Se(r)}})};for(const r of i.testSpecYield??[]){const $=r.failHighDies===0?"is below its low limit":r.failLowDies===0?"is above its high limit":`is outside its limits (${_(r.failLowDies)} low, ${_(r.failHighDies)} high)`;o(r.testNumber,r.label,r.failLowDies+r.failHighDies,r.totalDies,$,"outside limits",r.failLowDies>0&&r.failHighDies>0?"is outside its limits":$)}for(const r of i.functionalYield??[])o(r.testNumber,r.label,r.failDies,r.totalDies,"fails","fail","fails",!0);return n}const wt=.5,Nt=2,vt=2,le=5;function kt(e,s,i,n){const c=new Set,o=new Map,r=new Map,$=[...e].sort((f,a)=>a.failDies-f.failDies||f.testNumber-a.testNumber);for(const f of $){const a=f.keys;if(n>0&&f.failDies/n<Q){c.add(f);continue}let h;if(a&&a.size>0&&n>0)for(const w of s){const B=i.get(w);if(!B||B.size===0)continue;let g=0;for(const D of a)B.has(D)&&g++;const u=g/a.size;u>=wt&&u>=Nt*(B.size/n)&&(!h||g>h.inside)&&(h={item:w,inside:g})}if(!h){c.add(f);continue}const v=o.get(h.item)??0;if(v<vt){const w=h.inside===f.failDies?"all":_(h.inside);h.item.text+=`. ${f.label} ${f.verb} on ${H(f.failDies,"die")}, ${w} of them in ${h.item.subject}`,o.set(h.item,v+1)}const N=r.get(h.item)??0;N<le?(h.item.chips.push({label:f.label,target:f.item.target}),r.set(h.item,N+1)):h.item.moreTests=(h.item.moreTests??0)+1,h.item.testNumbers.push(f.testNumber)}return e.filter(f=>c.has(f))}function te(e){return{kind:"signal",impact:"low",shareOfDies:0,diesLost:0,affected:e.affected,measure:e.measure,severity:e.severity,text:e.text,reason:e.reason??e.text,brief:e.brief,subject:e.subject,target:e.target,chips:[],findingIds:e.findingIds??[],testNumbers:e.testNumbers??[],chart:e.chart}}const me=e=>Math.abs(e)<et?0:Math.min(1,(Math.abs(e)/Ze)**2),Y=e=>`${Math.abs(e).toFixed(1)}\u03C3`,St=e=>e.variable.kind==="test"&&e.variable.measure!=="limitFailRate"&&_e.has(e.comparison.family)&&Number.isFinite(e.effect.effectSize??NaN)&&!e.id.startsWith("drift:");function Mt(e,s,i){const n=new Map;for(const r of e)!St(r)||r.variable.index===void 0||(n.get(r.variable.index)??n.set(r.variable.index,[]).get(r.variable.index)).push(r);const c=r=>(we(r)??r.stats.sampleSizeLeft)*me(r.effect.effectSize??0),o=[];for(const[r,$]of[...n].sort((f,a)=>f[0]-a[0])){const f=[...$].sort((g,u)=>c(u)-c(g)),a=f[0],h=a.effect.effectSize??0;if(c(a)===0)continue;const v=Ne(a);let N=s.find(g=>g.target.kind==="test"&&g.target.testNumber===r)??s.find(g=>g.testNumbers.includes(r))??s.find(g=>f.some(u=>g.findingIds.includes(u.id))),w=0;for(const g of N?[]:s){const u=i.get(g);if(!u||u.size===0||v.size===0)continue;let D=0;for(const F of v)u.has(F)&&D++;D>=ue*Math.min(u.size,v.size)&&D>w&&(w=D,N=g)}if(N){N.text+=`. ${a.summary}`,N.testNumbers.includes(r)||(N.chips.filter(u=>u.target.kind==="test"||u.shift).length<le?N.chips.push({label:a.variable.label,target:ee(a),shift:!0}):N.moreTests=(N.moreTests??0)+1,N.testNumbers.push(r));for(const g of f)N.findingIds.includes(g.id)||N.findingIds.push(g.id);continue}const B=we(a)??a.stats.sampleSizeLeft;o.push(te({affected:c(a),measure:Y(h),severity:a.severity,text:`${a.summary}: a shift of ${Y(h)} over ${H(B,"die")}`+(f.length>1?` (also seen as ${Be(f.slice(1))})`:""),reason:`${a.summary}: a shift of ${Y(h)} over ${H(B,"die")}`,brief:`${Z(a)}: ${a.variable.label} ${a.effect.direction}`,subject:Z(a),target:ee(a),findingIds:f.map(g=>g.id),testNumbers:[r],chart:{chart:"box",fields:{x:he(a),y:pe(r),color:{none:!0}},axes:{y:{references:[{stat:"median"}]}}}}))}return o}function It(e,s){return e.filter(i=>i.id.startsWith("drift:")).map(i=>{const n=i.variable.kind==="yield",c=i.effect.effectSize??0;return te({affected:s*(n?Math.abs(c):me(c)),measure:n?`${W(Math.abs(c))} pts`:Y(c),severity:i.severity,text:i.summary,brief:`${i.variable.label}: drifts across the wafers`,subject:i.variable.label,target:ee(i),findingIds:[i.id],...i.variable.index!==void 0?{testNumbers:[i.variable.index]}:{},chart:{chart:"control",fields:{x:{builtin:"waferOrder"},y:n||i.variable.index===void 0?{builtin:"yield"}:pe(i.variable.index)}}})})}function xt(e,s,i){return(e.stats.capability??[]).filter(n=>n.hasSpec&&n.ppk!==null&&n.ppk!==void 0&&n.ppk<Qe&&!s.has(n.testNumber)).map(n=>{const c=n.ppk,o=qe(3*c);return te({affected:i*o,measure:`Ppk ${c.toFixed(2)}`,severity:"notable",text:`${n.label} has Ppk ${c.toFixed(2)} against its limits: a spread that would put about ${W(o)}% of the dies outside them`,brief:`${n.label}: Ppk ${c.toFixed(2)}`,subject:n.label,target:{kind:"test",testNumber:n.testNumber},testNumbers:[n.testNumber],chart:Se(n.testNumber,!0)})})}const ge=.05,_t=8,Le=.01,Dt=.05,Bt=.25,Ot=1,Ft=3,je=e=>e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`;function Lt(e,s,i,n=[]){const c={items:[],compared:[],possible:[]},o=e.perWafer;if(o.length<4)return c;const r=Je(o.map(t=>({metadata:t.summary.wafer,dieCount:t.summary.stats.totalDies})),{facetableOnly:!0,curation:s}).filter(t=>t.splittable).map(t=>({key:t.key,groupOf:o.map(d=>Me(d.summary.wafer,t.key,s))})).filter(t=>Ye(t.groupOf));if(r.length===0)return c;const $=Ge(r),f=t=>e.perWaferTestStats?.find(d=>d.waferIndex===t.waferIndex)?.tests??t.summary.stats.perTestStats??[],a=o.map(t=>new Map(f(t).filter(d=>d.count>=2&&Number.isFinite(d.mean)).map(d=>[d.testNumber,d]))),h=new Map;for(const t of a)for(const[d,p]of t)h.has(d)||h.set(d,p.label);const v=o.map(t=>t.summary.stats.analyzedDies),N=o.map(t=>t.summary.stats.yieldPercent===null?void 0:t.summary.stats.yieldPercent/100),w=o.map(t=>{const d=t.summary.stats.hardBinCounts,p=d?Object.values(d).reduce((m,y)=>m+y,0):0;return d&&p>0?new Map(Object.entries(d).map(([m,y])=>[Number(m),y/p])):void 0}),B=(t,d,p,m)=>{let y;for(const[x,L]of t){const k=L.map(d),j=[...t].filter(([S])=>S!==x).flatMap(([,S])=>S.map(d));if(k.length<2||j.length<2)continue;const P=k.reduce((S,O)=>S+O,0)/k.length-j.reduce((S,O)=>S+O,0)/j.length,b=P/p;(!y||Math.abs(b)>Math.abs(y.d)+1e-9||Math.abs(Math.abs(b)-Math.abs(y.d))<=1e-9&&(L.length<y.groupWafers||L.length===y.groupWafers&&P>0))&&(y=m(x,L,b,P>0))}if(y&&t.size===2){const[x,L]=[...t].find(([k])=>k!==y.group);y.other={group:x,wafers:L.length}}return y},g=[],u=[],D=[];for(const[t,d]of[...h].sort((p,m)=>p[0]-m[0])){const p=a.flatMap(y=>{const x=y.get(t);return x&&Number.isFinite(x.stddev)?[x.stddev**2]:[]}),m=p.length?Math.sqrt(p.reduce((y,x)=>y+x,0)/p.length):NaN;m>0&&D.push({testNumber:t,label:d,values:a.map(y=>y.get(t)?.mean),scale:m})}D.push({testNumber:NaN,label:"Yield",values:N,scale:1,scope:v});const F=[...e.stats.regionYield?.ring??[]].sort((t,d)=>t.yieldPercent-d.yieldPercent)[0];if(F&&o.length>0){const t=o.map(d=>{const p=d.summary.stats.regionYield?.ring?.find(m=>m.key===F.key);return p?p.yieldPercent/100:void 0});if(t.every(d=>d!==void 0)){const d=o.map(p=>p.summary.stats.regionYield?.ring?.find(m=>m.key===F.key)?.n??0);D.push({testNumber:NaN,label:`${F.label} pass rate`,values:t,scale:1,region:F.label,regionValue:Ve(Xe(F.key).ring),scope:d})}}for(const t of D)for(const{partition:d,used:p,fitted:m,allowedFor:y}of Ke(t.values,$)){const x=d.id,L=d.keys;if(!m)continue;const k=B(m.byGroup,b=>p[b],t.scale,(b,A,S,O)=>({part:x,keys:L,testNumber:t.testNumber,label:t.label,group:b,members:A,groupWafers:A.length,groupDies:A.reduce((T,I)=>T+v[I],0),d:S,higher:O,p:m.p,...t.region?{region:t.region,regionValue:t.regionValue}:{},...y?{allowedFor:y}:{}}));if(!k)continue;const j=k.members.map(b=>p[b]),P=[...m.byGroup].filter(([b])=>b!==k.group).flatMap(([,b])=>b.map(A=>p[A]));if(t.scope){const b=S=>S.reduce((O,T)=>O+t.scope[T],0),A=[...m.byGroup].filter(([S])=>S!==k.group).flatMap(([,S])=>S);k.lost=(k.higher?b(A):b(k.members))*Math.abs(k.d)}if(k.separated=$e(j)>be(P)||be(j)<$e(P),Number.isNaN(t.testNumber)){if(i&&!t.region){let b=0;const A=new Set(w.flatMap(O=>O?[...O.keys()]:[])),S=o.map((O,T)=>T).filter(O=>!k.members.includes(O)&&N[O]!==void 0);for(const O of A){if(i.includes(O))continue;const T=U=>U.reduce((ze,Ae)=>ze+(w[Ae]?.get(O)??0),0)/Math.max(1,U.length),I=(T(k.members)-T(S))*(k.higher?-1:1);I>b&&(b=I,k.bin=O)}}u.push(k)}else g.push(k)}const R=Ce([...g,...u].map(t=>t.p)),C=t=>R[t],ne=new Map;g.forEach((t,d)=>{const p=t.groupDies*me(t.d);C(d)>=ge||p===0||(ne.get(t.part)??ne.set(t.part,[]).get(t.part)).push({c:t,q:C(d),weight:p})});const fe=[...new Set([...g,...u].flatMap(t=>t.keys))].map(t=>ie(t,s)),q=t=>je(t.map(d=>ie(d,s))),G=t=>{const d=`${ie(t.keys[0],s)} ${t.group}`;if(t.keys.length===1)return d;const p=o[t.members[0]].summary.wafer,m=t.keys.slice(1).map(y=>`${ie(y,s)} ${Me(p,y,s)??""}`.trim());return`${d} (${je(m)} group${m.length===1?"s":""} the same wafers)`},V=t=>t.allowedFor?`, allowing for ${q(t.allowedFor)}`:"",X=t=>{const d=$.find(m=>m.id===t),p=d?Ue(d,$):[];return p.length===0?"":`. ${p.map(m=>`${q(m.partition.keys.slice(0,1))} puts ${m.agree} of ${m.of} wafers in the same groups`).join("; ")}, so the wafers cannot fully tell ${p.length===1?"the two":"them"} apart`},J=t=>`${ie(t.keys[0],s)} ${t.other.group}`,se=t=>t.other?`${t.label} is ${t.higher?"higher":"lower"} on ${G(t)} than on ${J(t)} (${t.groupWafers} and ${t.other.wafers} wafers)`:`${t.label} is ${t.higher?"higher":"lower"} on ${G(t)} (${t.groupWafers} of ${o.length} wafers) than on the other wafers`,re=[...ne].map(([t,d])=>{d.sort((I,U)=>Math.abs(U.c.d)-Math.abs(I.c.d)||U.weight-I.weight||I.c.testNumber-U.c.testNumber);const p=d.reduce((I,U)=>Math.max(I,U.weight),0),m=d[0].c.keys,y=m[0],x=q(m),[L,...k]=d,j=L.c,P=`${se(j)}: a shift of ${Y(j.d)}${V(j)}`,b=k.slice(0,2).map(({c:I})=>`${I.label} ${I.higher?"higher":"lower"} on ${I.keys.length>1?ie(I.keys[0],s)+" ":""}${I.group} (${Y(I.d)})`),A=k.length-b.length,S=d.length,O=(S===1?`${P}, each wafer one value (q ${ye(L.q)})`:`${S} tests differ by ${x}. Largest: ${P}, each wafer one value (q ${ye(L.q)}); next: ${b.join(", ")}${A>0?`, and ${A} more`:""}`)+X(t),T=te({affected:p,measure:Y(j.d),severity:L.q<.001?"unusual":"notable",text:O,reason:S===1?P:`${S} tests differ by ${x}. Largest: ${P}`,brief:S===1?`${x} ${j.group}: ${j.label} ${j.higher?"higher":"lower"}`:`${x}: ${S} tests differ`,subject:x,target:{kind:"test",testNumber:j.testNumber},testNumbers:d.map(I=>I.c.testNumber),chart:S>1?{chart:"heatmap",level:"wafer",aggregate:"mean",normalize:"zscore",fields:{x:{meta:y},y:{tests:d.slice(0,_t).map(I=>I.c.testNumber)}}}:{chart:"box",level:"wafer",aggregate:"mean",fields:{x:{meta:y},y:pe(j.testNumber),color:{meta:y}}}});return S>1&&(T.chips=d.slice(0,le).map(({c:I})=>({label:`${I.label} ${Y(I.d)}`,target:{kind:"test",testNumber:I.testNumber}})),S>le&&(T.moreTests=S-le)),T});u.forEach((t,d)=>{const p=C(g.length+d),m=t.lost??t.groupDies*Math.abs(t.d);if(p>=ge||Math.abs(t.d)<Le)return;const y=q(t.keys),x=`${(Math.abs(t.d)*100).toFixed(1)} points`,L=`${t.bin!==void 0?`, mostly in hard bin ${t.bin}`:""}${V(t)}`,k=t.other?`${t.label} is ${x} ${t.higher?"higher":"lower"} on ${G(t)} than on ${J(t)} (${t.groupWafers} and ${t.other.wafers} wafers)`:`${t.label} is ${x} ${t.higher?"higher":"lower"} on ${G(t)} (${t.groupWafers} of ${o.length} wafers) than on the other wafers`;re.push(te({affected:m,measure:x,severity:p<.001?"unusual":"notable",text:`${k}${L}, each wafer one value (q ${ye(p)})${X(t.part)}`,reason:`${k}${L}`,brief:`${y} ${t.group}: ${t.region?"ring pass rate":"yield"} ${t.higher?"higher":"lower"}`,subject:y,target:{kind:"group",field:t.keys[0],fields:t.keys},testNumbers:[],chart:{chart:"bar",fields:{x:{meta:t.keys[0]},y:{builtin:"yield"},color:{meta:t.keys[0]}},valueLabels:!0,...t.region?{where:{conditions:[{field:{builtin:"ring"},values:[t.regionValue??t.region]}]}}:{}}}))});const de=v.reduce((t,d)=>t+d,0),oe=new Set([...g.filter((t,d)=>C(d)<ge&&t.groupDies*me(t.d)>0).map(t=>t.part),...u.filter((t,d)=>C(g.length+d)<ge&&Math.abs(t.d)>=Le).map(t=>t.part)]),ce=[...g.filter(t=>Math.abs(t.d)>=Ot),...u.filter(t=>(t.lost??0)>=Math.min(Q*de,...n.map(d=>Bt*d)))].filter(t=>t.separated&&t.p<Dt&&!oe.has(t.part)),l=new Map;for(const t of ce)(l.get(`${t.part}|${t.group}`)??l.set(`${t.part}|${t.group}`,[]).get(`${t.part}|${t.group}`)).push(t);const M=[],E=g.length+u.length;for(const t of l.values()){const d=t.find(b=>Number.isNaN(b.testNumber)),p=t.filter(b=>!Number.isNaN(b.testNumber)||!d||b.higher===d.higher);if(p.length<2)continue;const m=p[0],y=b=>Number.isNaN(b.testNumber)?`${b.label} ${b.higher?"higher":"lower"} by ${(Math.abs(b.d)*100).toFixed(1)} points`:`${b.label} ${b.higher?"higher":"lower"} (${Y(b.d)})`,x=m.other?`than on ${J(m)} (${m.groupWafers} and ${m.other.wafers} wafers)`:`than on the other wafers (${m.groupWafers} of ${o.length})`,L=`${G(m)}: ${p.map(y).join("; ")} ${x}`,k=q(m.keys),j=p.reduce((b,A)=>Math.max(b,A.lost??0),0),P=te({affected:j,measure:`${p.length} measures`,severity:"info",text:`Possibly ${L}. No wafer of the group overlaps the others on ${p.length===2?"either":`any of ${p.length}`}, but the sample is too small to confirm it once ${E} comparisons are allowed for`,reason:`Possibly ${L}`,brief:`${k} ${m.group}: possible, not confirmed`,subject:k,target:{kind:"group",field:m.keys[0],fields:m.keys},testNumbers:p.filter(b=>!Number.isNaN(b.testNumber)).map(b=>b.testNumber),chart:{chart:"bar",fields:{x:{meta:m.keys[0]},y:{builtin:"yield"},color:{meta:m.keys[0]}},valueLabels:!0}});M.push(P)}return M.sort((t,d)=>d.affected-t.affected),{items:re,compared:fe,possible:M.slice(0,Ft)}}export function groupColouredChart(e,s){const i=e.fields?.x,n=e.fields?.color;return!s||e.chart!=="bar"||!i||Array.isArray(i)||!("builtin"in i)||i.builtin!=="wafer"||!n||!("none"in n)?e:{...e,fields:{...e.fields,x:[{slot:"groupBy"},{builtin:"wafer"}],color:{follow:"groupBy"}}}}function jt(e){return e.map(s=>te({affected:s.passingDies,measure:"",severity:"notable",text:`${s.label} ${s.plainVerb} on ${H(s.passingDies,"die")} binned as passing`,brief:`${s.label}: ${_(s.passingDies)} dies out of limits, binned passing`,subject:s.label,target:s.item.target,testNumbers:[s.testNumber],chart:Se(s.testNumber)}))}function Et(e,s){const i=s.passBins&&s.passBins.length>0?`; pass ${Te([s.passBins])}`:"";if(e.level==="wafer"){const a=e.stats.yieldPercent;return a==null?`${_(e.stats.totalDies)} dies, no bin data to judge yield by.`:`Yield ${a.toFixed(1)}% (${_(e.stats.totalDies)} dies${i}).`}const n=e.lotYieldSeries.map(a=>a.yieldPercent).filter(a=>typeof a=="number");if(n.length===0)return`${H(e.stats.waferCount,"wafer")}, no bin data to judge yield by.`;const c=n.reduce((a,h)=>a+h,0)/n.length,o=e.perWafer.reduce((a,h)=>a+h.summary.stats.totalDies,0),[r,$]=[$e(n).toFixed(1),be(n).toFixed(1)],f=r!==$?`, range ${r}\u2013${$}%`:"";return`Yield ${c.toFixed(1)}% (mean of ${H(n.length,"wafer")}, ${_(o)} dies${i})${f}.`}function zt(e,s,i=[]){const n=[],c=e.level==="wafer"?e.stats.testsConsidered.length:new Set(e.perWafer.flatMap(a=>a.summary.stats.testsConsidered)).size,o=e.level==="wafer"?e.stats.hardBinsConsidered.length:new Set(e.perWafer.flatMap(a=>a.summary.stats.hardBinsConsidered)).size,r=e.stats.testValueAnalysis?.state;if(c>0&&r!=="off"&&n.push(H(c,"test")+(r==="skipped"?" (against their limits only)":"")),o>0&&n.push(H(o,"hard bin")),n.push("the ring, quadrant and sector regions"),e.level==="lot"&&e.stats.waferCount>=3){const a=e.findings.filter(Fe);n.push(a.length===0?"wafer-to-wafer yield (no outlier wafers)":`wafer-to-wafer yield (${H(a.length,"outlier wafer")})`),e.stats.waferCount>=We&&n.push("the yield trend across the wafers (input order)"),i.length&&n.push(`the tests between the groups of ${i.join(", ")} (each wafer one value)`)}const $=e.findings.filter(a=>!s.has(a.id)).length,f=$>0?` ${H($,"smaller finding")} not listed above.`:" Nothing else was found.";return`Compared: ${n.join(", ")}.${f}`}export function synthesisSource(e){return e.level==="lot"&&e.perWafer.length===1?e.perWafer[0].summary:e}const Ee=new WeakMap;export function buildSynthesis(e,s={}){const i=`${s.passBins?.join(",")??"-"}|${s.attributes?JSON.stringify(s.attributes):"-"}`;let n=Ee.get(e);n||Ee.set(e,n=new Map);const c=n.get(i),o=e.findings;if(c&&c.findings.length===o.length&&c.findings.every(($,f)=>$===o[f]))return c.synthesis;const r=At(e,s);return Object.freeze(r.items),r.items.forEach(Object.freeze),r.possible&&(r.possible.forEach(Object.freeze),Object.freeze(r.possible)),r.also&&(Object.freeze(r.also.items),r.also.items.forEach(Object.freeze),Object.freeze(r.also)),n.set(i,{findings:[...o],synthesis:Object.freeze(r)}),r}function At(e,s){const i=synthesisSource(e),n=i.findings,c=i.level==="lot"?i.stats.waferCount:void 0,o=s.passBins,r=new Map(n.map(l=>[l.id,l])),$=(i.level==="wafer"?[i]:i.perWafer.map(l=>l.summary)).every(l=>(l.stats.hardBinsConsidered??[]).length===0),f=l=>o!==void 0&&ve(l)&&Pe(l.variable.kind,l.variable.bin??NaN,o,!$),a={isPassRate:l=>l.variable.kind==="yield"||o?.length===1&&f(l),isFailBin:l=>o!==void 0&&ve(l)&&!f(l)},h=n.filter(l=>_e.has(l.comparison.family)&&K(l)>0&&(a.isPassRate(l)&&l.effect.direction==="lower"||a.isFailBin(l)&&l.effect.direction==="higher")),N=h.some(l=>l.variable.kind==="hardBin")?h.filter(l=>l.variable.kind!=="softBin"):h,w=[],B=new Map,g=new Set;for(const l of at(N)){const M=l.map(d=>N[d]),E=ht(M,n,c,a);w.push(E);const t=E.target.kind==="finding"?E.target.id:void 0;B.set(E,Ne(M.find(d=>d.id===t)??M[0]))}for(const l of n.filter(M=>M.variable.kind==="spatialPattern")){const M=new Set((l.relatedIds??[]).filter(p=>r.has(p))),E=w.find(p=>p.findingIds.some(m=>M.has(m)));if(!E)continue;const t=l.level==="lot"&&"waferIndices"in l.highlight?l.highlight.waferIndices?.length:void 0,d=t!==void 0&&c?` on ${t}/${c} wafers`:"";E.text=`${l.variable.label} pattern${d}. ${E.text}`,E.reason=`${l.variable.label} pattern${d}. ${E.reason}`,E.chips.unshift({label:`${l.variable.label} pattern`,target:ee(l)}),E.findingIds.unshift(l.id,...[...M].filter(p=>!w.some(m=>m.findingIds.includes(p))))}const u=gt(i),D=new Set,F=yt(i,D),R=[...w],C=kt(F,R,B,u);i.level==="lot"&&w.push(...bt(i)),w.push(...C.map(l=>l.item));const ne=new Set(C.filter(l=>u>0&&l.item.diesLost/u>=Q).map(l=>l.testNumber));w.push(...Mt(n,[...R,...C.map(l=>l.item)],B),...It(n,u),...xt(i,D,u),...jt(F.filter(l=>l.passingDies>0&&!ne.has(l.testNumber))));let fe=[],q=[];if(i.level==="lot"){const l=Lt(i,s.attributes,s.passBins,w.filter(M=>M.kind==="loss").map(M=>M.diesLost));fe=l.compared,q=l.possible;for(const M of l.items){const E=M.testNumbers[0],t=M.testNumbers.length===1?w.find(d=>d.target.kind==="test"&&d.target.testNumber===E)??w.find(d=>d.testNumbers.includes(E)):void 0;t?t.text+=`. ${M.text}`:w.push(M)}}const G=mt(i),V=w.filter(l=>u>0&&l.affected/u>=Q);for(const l of V)l.shareOfDies=l.affected/u,l.impact=pt(l.shareOfDies,l.kind==="loss"&&G>0?l.diesLost/G:0),l.measure||(l.measure=`${(l.shareOfDies*100).toFixed(1)}%`);const X=l=>`${String(l.testNumbers[0]??"").padStart(10,"0")}${l.findingIds[0]??""}`;V.sort((l,M)=>M.affected-l.affected||(X(l)<X(M)?-1:X(l)>X(M)?1:0));const J=V.slice(0,Ie),se=V.slice(Ie);for(const l of[...J,...se])for(const M of l.findingIds)g.add(M);const re=se.length>0?{items:se.slice(0,xe),more:Math.max(0,se.length-xe)}:void 0,de=i.level==="lot"?"region, fail bin or wafer":"region or fail bin",oe=n.filter(l=>l.severity==="unusual"&&!g.has(l.id)).length,ce=J.length===0?oe>0?`No ${de} costs as much as ${W(Q)} yield points, though ${H(oe,"finding")} below ${oe===1?"is":"are"} marked unusual.`:`Nothing stands out: no ${de} costs as much as ${W(Q)} yield points.`:void 0;return{headline:Et(i,s),items:J,...re?{also:re}:{},...q.length?{possible:q}:{},...ce?{nothing:ce}:{},checked:zt(i,g,fe)}}export const synthesisKey=e=>{if(e.target.kind==="finding")return`finding:${e.target.id}`;if(e.target.kind==="group")return`group:${e.target.field}${isGroupYieldItem(e)?"":":ring"}`;const s=groupedByField(e);return`test:${e.target.testNumber}${s!==void 0?`:by:${s}`:""}`},groupedByField=e=>{const s=e.chart.fields?.x;return s&&!Array.isArray(s)&&"meta"in s?s.meta:void 0},isGroupYieldItem=e=>e.target.kind==="group"&&!e.chart.where,SYNTHESIS_POSSIBLE_HEADING="Possible, not confirmed",SYNTHESIS_ALSO_HEADING=`Also, each affecting at least ${(Q*100).toFixed(0)}% of the dies`,synthesisRowShare=e=>e.measure,synthesisMoreTests=e=>e.moreTests?`and ${e.moreTests} more test${e.moreTests===1?"":"s"}`:void 0;export function synthesisText(e){return[e.headline,...e.nothing?[e.nothing]:[],...e.items.map((s,i)=>`${i+1}. ${s.text}`),...e.also?[`${SYNTHESIS_ALSO_HEADING}: ${e.also.items.map(s=>`${s.brief} (${synthesisRowShare(s)})`).join("; ")}${e.also.more?`; and ${e.also.more} more`:""}.`]:[],...e.possible?[`${SYNTHESIS_POSSIBLE_HEADING}:`,...e.possible.map(s=>`- ${s.text}`)]:[],e.checked].join(`
|
|
2
2
|
`)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wafertools/wafermap",
|
|
3
|
-
"version": "0.40.
|
|
3
|
+
"version": "0.40.1",
|
|
4
4
|
"description": "Interactive wafer map visualization and yield analysis for semiconductor test data. Hard bins, soft bins, test values, retests, edge exclusion, reticle overlays, spatial statistics, failure clustering, and lot-level trend analysis — pure ES modules, no runtime dependencies, no server required.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|