@wafertools/wafermap 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +79 -3
  2. package/README.md +4 -3
  3. package/dist/packages/canvas-adapter/cellShade.d.ts +21 -0
  4. package/dist/packages/canvas-adapter/cellShade.js +1 -0
  5. package/dist/packages/canvas-adapter/charts/chartShell.d.ts +19 -3
  6. package/dist/packages/canvas-adapter/charts/chartShell.js +1 -1
  7. package/dist/packages/canvas-adapter/charts/commonality.js +4 -1
  8. package/dist/packages/canvas-adapter/charts/correlation.d.ts +11 -0
  9. package/dist/packages/canvas-adapter/charts/correlation.js +1 -1
  10. package/dist/packages/canvas-adapter/charts/divergingScale.d.ts +23 -0
  11. package/dist/packages/canvas-adapter/charts/divergingScale.js +1 -0
  12. package/dist/packages/canvas-adapter/charts/groupComparison.js +1 -1
  13. package/dist/packages/canvas-adapter/charts/palette.d.ts +10 -3
  14. package/dist/packages/canvas-adapter/charts/palette.js +1 -1
  15. package/dist/packages/canvas-adapter/charts/plotChart.d.ts +8 -0
  16. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  17. package/dist/packages/canvas-adapter/charts/regionYieldDiagram.js +1 -1
  18. package/dist/packages/canvas-adapter/charts/sweep.js +1 -1
  19. package/dist/packages/canvas-adapter/dataTab.js +1 -1
  20. package/dist/packages/canvas-adapter/differenceMapPanel.d.ts +1 -0
  21. package/dist/packages/canvas-adapter/differenceMapPanel.js +1 -1
  22. package/dist/packages/canvas-adapter/filterJson.d.ts +25 -0
  23. package/dist/packages/canvas-adapter/filterJson.js +5 -0
  24. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  25. package/dist/packages/canvas-adapter/pageFilter.js +2 -2
  26. package/dist/packages/canvas-adapter/plotEditor.js +10 -1
  27. package/dist/packages/canvas-adapter/plotJsonComplete.d.ts +46 -0
  28. package/dist/packages/canvas-adapter/plotJsonComplete.js +4 -0
  29. package/dist/packages/canvas-adapter/plotJsonHistory.d.ts +12 -0
  30. package/dist/packages/canvas-adapter/plotJsonHistory.js +1 -0
  31. package/dist/packages/canvas-adapter/plotJsonSuggest.d.ts +16 -0
  32. package/dist/packages/canvas-adapter/plotJsonSuggest.js +1 -0
  33. package/dist/packages/canvas-adapter/plotModal.js +1 -1
  34. package/dist/packages/canvas-adapter/plotTab.js +1 -1
  35. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  36. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  37. package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
  38. package/dist/packages/canvas-adapter/sweepEditor.js +1 -1
  39. package/dist/packages/canvas-adapter/toCanvas.d.ts +1 -0
  40. package/dist/packages/canvas-adapter/toCanvas.js +1 -1
  41. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  42. package/dist/packages/canvas-adapter/userGuideHtml.js +81 -43
  43. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  44. package/dist/packages/canvas-adapter/version.js +1 -1
  45. package/dist/packages/canvas-adapter/virtualTable.d.ts +2 -0
  46. package/dist/packages/canvas-adapter/virtualTable.js +1 -1
  47. package/dist/packages/core/compact.js +2 -2
  48. package/dist/packages/core/dieTable.js +1 -1
  49. package/dist/packages/core/utils.d.ts +6 -0
  50. package/dist/packages/core/utils.js +1 -1
  51. package/dist/packages/renderer/fmt.js +1 -1
  52. package/dist/packages/stats/chartCatalogue.js +1 -1
  53. package/dist/packages/stats/coFailure.d.ts +11 -0
  54. package/dist/packages/stats/coFailure.js +1 -0
  55. package/dist/packages/stats/commonality.d.ts +37 -4
  56. package/dist/packages/stats/commonality.js +1 -1
  57. package/dist/packages/stats/correlation.d.ts +7 -0
  58. package/dist/packages/stats/correlation.js +1 -1
  59. package/dist/packages/stats/dieRegions.d.ts +2 -0
  60. package/dist/packages/stats/dieRegions.js +1 -1
  61. package/dist/packages/stats/differenceMap.d.ts +2 -0
  62. package/dist/packages/stats/differenceMap.js +1 -1
  63. package/dist/packages/stats/examplePicks.d.ts +6 -0
  64. package/dist/packages/stats/examplePicks.js +1 -1
  65. package/dist/packages/stats/groupEffects.d.ts +66 -0
  66. package/dist/packages/stats/groupEffects.js +1 -0
  67. package/dist/packages/stats/plotData.d.ts +11 -2
  68. package/dist/packages/stats/plotData.js +1 -1
  69. package/dist/packages/stats/plotSpec.d.ts +31 -2
  70. package/dist/packages/stats/plotSpec.js +4 -4
  71. package/dist/packages/stats/plotTable.d.ts +18 -0
  72. package/dist/packages/stats/plotTable.js +1 -0
  73. package/dist/packages/stats/renderFindingsReport.js +1 -1
  74. package/dist/packages/stats/renderSummaryReport.js +7 -7
  75. package/dist/packages/stats/reportHtml.js +18 -13
  76. package/dist/packages/stats/sweep.d.ts +3 -3
  77. package/dist/packages/stats/sweepXFromName.js +1 -1
  78. package/dist/packages/stats/synthesis.d.ts +19 -0
  79. package/dist/packages/stats/synthesis.js +1 -1
  80. package/dist/packages/stats/testsByWafer.d.ts +11 -0
  81. package/dist/packages/stats/testsByWafer.js +1 -0
  82. package/package.json +1 -1
@@ -1 +1 @@
1
- import{GUIDE_SECTIONS as Ne}from"./guideSections.js";import{hasPosition as nt,isYieldEligibleDie as Dt}from"../core/dies.js";import{DIE_REGIONS as je,DIE_REGION_KEYS as un,dieRadialPosition as fn}from"./dieRegions.js";import{excludedBy as cn,excludedValue as dn,testValue as it,testsPresent as st}from"../core/dieTable.js";import{limitSetName as mn}from"../renderer/valueFilter.js";import{compareNatural as Mt,minOf as ze,maxOf as Ge}from"../core/utils.js";import{isParametricTest as be,getTestPassStatus as hn}from"../renderer/buildWaferMap.js";import{attributeLabel as bt,facetValueOf as pn,buildFacetTable as Rt,FACET_NONE_VALUE as gt}from"./facets.js";import{yieldCounts as yt}from"./yield.js";import{sameTestName as wt}from"./sweep.js";import{sameField as Fe,plotIssue as bn,plotConditions as _t,isField as Ce,isTestSet as le,isBinned as Ve,isStatReference as gn,isPassRateSet as yn,xFieldsOf as ke,PLOT_X_LEVELS as Bt,PLOT_FACET_LIMIT as Pt,PLOT_BINS_DEFAULT as wn}from"./plotSpec.js";import{fmtExact as jt,fmt as Xe}from"../renderer/fmt.js";import{parseTestReference as $n}from"../renderer/derivedTests/parser.js";import{capabilityLimits as zt}from"./capability.js";import{mean as Gt,median as $t}from"../core/utils.js";import{sampleVariance as Ut,quantile as vt,tQuantileTwoSided as vn,robustFence as xn}from"./math.js";import{pickExamples as Nn}from"./examplePicks.js";import{compareGroups as kn,formatP as Ht}from"./groupCompare.js";import{dieTestVerdict as Wt}from"./testPassRate.js";import{pearsonOfPairs as Sn}from"./correlation.js";import{individualsLimits as Fn,westernElectric as Ln,CONTROL_RULE_TEXT as An}from"./control.js";import{buildCapabilityFigures as On}from"./capability.js";import{patTests as Vt,waferPatLimits as Tn,waferPatVerdicts as In,PAT_VERDICT_LABEL as Cn,PAT_VERDICT_ORDER as En,PAT_K as Dn}from"./pat.js";function Xt(e){if(!e)return;const t={};for(const i of["limitLow","limitHigh","specLow","specHigh"])Number.isFinite(e[i])&&(t[i]=e[i]);return Object.keys(t).length?t:void 0}export function fitLine(e,t,i){const s=e.length;if(s<3)return;let n=0,a=0;for(let p=0;p<s;p++)n+=e[p],a+=t[p];n/=s,a/=s;let r=0,f=0,c=0;for(let p=0;p<s;p++){const d=e[p]-n,l=t[p]-a;r+=d*d,f+=l*l,c+=d*l}if(!(r>0))return;const o=f>0?c*c/(r*f):1,m=i==="linear"||c===0?c/r:(f-r+Math.sqrt((f-r)**2+4*c*c))/(2*c);return{slope:m,intercept:a-m*n,r2:o,n:s}}function ge(e){let t=0;for(const a of e)t+=a.dies.length;const i=new Array(t),s=new Uint32Array(t);let n=0;return e.forEach((a,r)=>{for(const f of a.dies)i[n]=f,s[n++]=r}),{dies:i,item:s}}const Ee={wafer:"Wafer",x:"Die X",y:"Die Y",ring:je.ring.label,quadrant:je.quadrant.label,reticleCell:je.reticleCell.label,reticleShot:je.reticleShot.label,hbin:"Hard bin",sbin:"Soft bin",site:"Site",yield:"Yield",dieCount:"Dies",waferOrder:"Wafer order",test:"Test",pat:"PAT",radius:"Radial position"};export function fieldLabel(e,t,i){if(Ve(e))return fieldLabel(e.binned,t,i);if(le(e))return _n(e,t);if("passRate"in e)return`${t?.find(n=>n.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),n=s?.name||e.name||`Test ${e.test}`;return s!==void 0&&!be(s)?`${n} (pass/fail)`:n}return"builtin"in e?Ee[e.builtin]??String(e.builtin):bt(e.meta,i)}function Ue(e,t,i){if(Ve(e)){const s=qt.get(e);return s?s.filter(n=>t.includes(n)):[...t].sort((n,a)=>parseFloat(n)-parseFloat(a))}return"builtin"in e&&(e.builtin==="wafer"||e.builtin==="test")?[...t]:"builtin"in e&&e.builtin==="pat"?En.filter(s=>t.includes(s)):Yt(t,i)}const Yt=(e,t)=>t?[...e].sort((i,s)=>(Number(i)||0)-(Number(s)||0)):[...e].sort(Mt);export function orderFieldValues(e){return Yt(e,e.every(t=>t===gt||xt.test(t.trim())))}const Ye=e=>!!e.num&&(e.kind==="numeric"||"meta"in e.field),Mn=e=>`Bin ${e}`;export function binOfLabel(e){const t=/^Bin (-?\d+)$/.exec(e);return t?Number(t[1]):void 0}const ue=e=>e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`,Rn=e=>!!e&&"builtin"in e&&e.builtin==="pat",Le=e=>!!e&&"builtin"in e&&e.builtin==="test";function _n(e,t){const{tests:i}=expandTestSet(e,t??[]),s=n=>t?.find(a=>a.testNumber===n)?.name||e.names?.[String(n)]||`Test ${n}`;return e.passRate?e.judge==="flag"?"Pass rate (tester flag)":"Pass rate":i.length===0?e.tests.length===1?`Tests ${e.tests[0]}`:`${e.tests.length} test entries`:i.length>3?`${i.length} tests`:ue(i.map(s))}export function passKindOf(e,t){return be(e)?t==="flag"?"testFlag":"spec":"functional"}export function expandTestSet(e,t){const i=new Map(t.map(a=>[a.testNumber,a])),s=[],n=[];for(const a of e.tests){if(typeof a=="number"){s.includes(a)||s.push(a);continue}const r=$n(String(a),i);if(!r.ok){n.push(`"${a}": ${r.message}`);continue}for(const f of r.tests)s.includes(f)||s.push(f)}return{tests:s,problems:n}}export function withTestSetNames(e,t){const i={};for(const a of expandTestSet(e,t).tests){const r=t.find(f=>f.testNumber===a)?.name;r&&(i[String(a)]=r)}const{names:s,...n}=e;return Object.keys(i).length?{...n,names:i}:n}export const TEST_SET_VALUE_LIMIT=4e6;const xt=/^[+-]?(?:\d+\.?\d*|\.\d+)$/;export function binEdges(e,t,i){const s=Array.from(e).filter(Number.isFinite).sort((f,c)=>f-c);if(s.length===0)return[];const n=s[0],a=s[s.length-1],r=[];for(let f=1;f<t;f++)r.push(i==="width"?n+(a-n)*f/t:vt(s,f/t));return r.filter((f,c)=>f>n&&f<=a&&(c===0||f>r[c-1]))}const Bn=(e,t)=>{let i=0,s=t.length;for(;i<s;){const n=i+s>>1;e>=t[n]?i=n+1:s=n}return i};function Pn(e,t,i,s){const n=[t,...e,i],a=f=>f.every((c,o)=>o===0||c!==f[o-1]);let r=s?n.map(f=>Xe(f,s)):[];if(!a(r)||r.length===0){const f=s==="%"?"%":s?` ${s}`:"";for(let c=3;c<=15&&(r=n.map(o=>`${Number(o.toPrecision(c))}${f}`),!a(r));c++);}return n.slice(0,-1).map((f,c)=>`${r[c]} to ${r[c+1]}`)}const qt=new WeakMap;function jn(e,t,i){const{ctx:s}=t,n=J(e.binned,t),a=n.label;if(n.issue)return{...n,...i,label:a,kind:"categorical",num:void 0,issue:n.issue};if(!n.num)return{...n,...i,label:a,kind:"categorical",issue:`${n.label} is already a category: only a measured value or a number can be put into ranges`};const r=e.bins??wn,f=e.by??"count",c=`${JSON.stringify(e)}`;let o=s.binEdges?.get(c),m=n.num;if(!o){if(s.wholeItems&&s.wholeItems!==t.items){const w=J(e.binned,{items:s.wholeItems,rows:ge(s.wholeItems),ctx:{...s,wholeItems:void 0}});w.num&&(m=w.num)}o=binEdges(m,r,f),s.binEdges?.set(c,o)}let p=1/0,d=-1/0;for(let w=0;w<m.length;w++){const g=m[w];Number.isFinite(g)&&(g<p&&(p=g),g>d&&(d=g))}if(p===1/0)return{...n,...i,label:a,kind:"categorical",num:void 0,issue:`${n.label} has no values to put into ranges`};const l=Pn(o,p,d,n.unit);qt.set(e,l);const b=Array.from(n.num,w=>Number.isFinite(w)?l[Bn(w,o)]:void 0);return{...i,label:a,unit:void 0,level:n.level,kind:"categorical",cat:b}}function Kt(e,t){const i=new Float64Array(e),s=new Float64Array(e),n=new Int8Array(e);for(let a=0;a<e;a++){const r=t(a);i[a]=r===void 0?NaN:r==="pass"?100:0,s[a]=r===void 0?0:1,n[a]=r==="failLow"?-1:r==="failHigh"?1:0}return{num:i,weights:s,failSide:n}}function J(e,t){const{items:i,rows:s,ctx:n}=t,a=fieldLabel(e,n.testDefs,n.curation),r={field:e,label:a},f=s.dies.length,c=i.length;if(Ve(e))return jn(e,t,r);if(le(e)){const o=t.melt;if(!o)return{...r,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=o.tests.map(g=>n.testDefs?.find(O=>O.testNumber===g)),{num:l,weights:b,failSide:w}=Kt(f,g=>{const O=d[o.testOf[s.item[g]]];return Wt(s.dies[g],O,passKindOf(O,e.judge))});return{...r,level:"die",kind:"numeric",unit:"%",num:l,weights:b,failSide:w,perDie:!0,labelOf:g=>o.labels[o.testOf[g]]}}const m=new Float64Array(f);for(let d=0;d<f;d++)m[d]=it(s.dies[d],o.tests[o.testOf[s.item[d]]])??NaN;const p=new Set(o.tests.map(d=>n.testDefs?.find(l=>l.testNumber===d)?.unit).filter(d=>!!d));return{...r,level:"die",kind:"numeric",unit:p.size===1?[...p][0]:void 0,num:m,labelOf:d=>o.labels[o.testOf[d]]}}if("passRate"in e){const o=e.passRate,m=n.testDefs?.find(w=>w.testNumber===o);if(!m)return{...r,level:"die",kind:"numeric",issue:`Needs test ${o}${e.name?` (${e.name})`:""}, which is not in these dies`};if(e.name&&m.name&&!wt(e.name,m.name))return{...r,level:"die",kind:"numeric",issue:`Test ${o} is "${e.name}" in this plot and "${m.name}" here`};const p=passKindOf(m,e.judge);if(p==="spec"&&m.limitLow===void 0&&m.limitHigh===void 0)return{...r,level:"die",kind:"numeric",issue:`${m.name||`Test ${o}`} has no test limits to judge a pass by`};const{num:d,weights:l,failSide:b}=Kt(f,w=>Wt(s.dies[w],m,p));return{...r,level:"die",kind:"numeric",unit:"%",num:d,weights:l,failSide:b,perDie:!0}}if("test"in e){const o=n.testDefs?.find(d=>d.testNumber===e.test);if(o===void 0){if(t.present??=new Set(s.dies.length?st(s.dies,"values"):[]),!t.present.has(e.test))return{...r,level:"die",kind:"numeric",issue:`Needs test ${e.test}${e.name?` (${e.name})`:""}, which is not in these dies`}}else if(e.name&&o.name&&!wt(e.name,o.name))return{...r,level:"die",kind:"numeric",unit:o.unit,issue:`Test ${e.test} is "${e.name}" in this plot and "${o.name}" here`};if(o!==void 0&&!be(o)){const d=s.dies.map(l=>{const b=hn(l,e.test,o);return b===void 0?void 0:b?"Pass":"Fail"});return{...r,level:"die",kind:"categorical",cat:d}}const m=new Float64Array(f);for(let d=0;d<f;d++)m[d]=it(s.dies[d],e.test)??NaN;let p=Xt(o);if(i.length===1&&!t.melt&&o){const d=i[0],l=Tn(d.allDies??d.dies,n.testDefs??[],d.passBins).limits.get(e.test);l&&(p={...p,patLow:l.lo,patHigh:l.hi})}return{...r,level:"die",kind:"numeric",unit:o?.unit,num:m,limits:p}}if("meta"in e){const o=i.map(d=>pn(d.metadata,e.meta,n.curation));if(o.every(d=>d===void 0))return{...r,level:"wafer",kind:"categorical",cat:o,issue:`No wafer has a "${a}" value`};const m=o.map(d=>d===void 0||!xt.test(d.trim())?NaN:Number(d)),p=o.every((d,l)=>d===void 0||Number.isFinite(m[l]));return{...r,level:"wafer",kind:p?"numeric":"categorical",cat:o,num:p?Float64Array.from(m):void 0}}switch(e.builtin){case"wafer":return{...r,level:"wafer",kind:"categorical",cat:i.map(o=>o.label)};case"waferOrder":return{...r,level:"wafer",kind:"numeric",num:Float64Array.from(i,(o,m)=>(t.melt?t.melt.realOf[m]:m)+1)};case"test":return t.melt?{...r,level:"wafer",kind:"categorical",cat:i.map((o,m)=>t.melt.labels[t.melt.testOf[m]])}:{...r,level:"wafer",kind:"categorical",issue:"Test divides a set of tests: choose several tests as the values"};case"dieCount":return{...r,level:"wafer",kind:"numeric",num:Float64Array.from(i,o=>o.dies.length)};case"yield":{const o=new Float64Array(c),m=new Float64Array(c);return i.forEach((p,d)=>{const{pass:l,total:b}=yt(p.dies,p.passBins);o[d]=b>0?l/b*100:NaN,m[d]=b}),{...r,level:"wafer",kind:"numeric",unit:"%",num:o,weights:m}}case"x":case"y":{const o=new Float64Array(f);for(let m=0;m<f;m++){const p=s.dies[m];o[m]=nt(p)?e.builtin==="x"?p.x:p.y:NaN}return{...r,level:"die",kind:"numeric",num:o}}case"hbin":case"sbin":{const o=s.dies.map(m=>{const p=e.builtin==="hbin"?m.hbin:m.sbin;return p===void 0?void 0:Mn(p)});return{...r,level:"die",kind:"categorical",cat:o}}case"site":return{...r,level:"die",kind:"categorical",cat:s.dies.map(o=>o.siteNum===void 0?void 0:`Site ${o.siteNum}`)};case"radius":{const o=new Float64Array(f);for(let m=0;m<f;m++){const p=fn(s.dies[m],{wafer:i[s.item[m]].wafer});o[m]=p===void 0?NaN:p*100}return{...r,level:"die",kind:"numeric",unit:"%",num:o}}case"pat":{const o=n.testDefs??[];if(Vt(o).length===0)return{...r,level:"die",kind:"categorical",issue:"PAT needs tests with both a low and a high limit"};const m=new Map,p=s.dies.map((d,l)=>{const b=i[s.item[l]];let w=m.get(b);if(!w){const g=b.allDies??b.dies,O=In(g,o,b.passBins);w=new Map(g.map((v,k)=>[v,O[k].verdict?Cn[O[k].verdict]:void 0])),m.set(b,w)}return w.get(d)});return{...r,level:"die",kind:"categorical",cat:p}}case"ring":case"quadrant":case"reticleCell":case"reticleShot":{const o=je[e.builtin],m=s.dies.map((p,d)=>{const l=i[s.item[d]];return o.valueOf(p,{wafer:l.wafer,ringCount:l.ringCount})});return{...r,level:"die",kind:"categorical",cat:m}}default:return{...r,level:"die",kind:"categorical",issue:"Needs a newer version of this tool"}}}function zn(e,t){const i=e.rows.dies.length,s=new Float64Array(i),n=new Float64Array(i);for(let a=0;a<i;a++){const r=e.items[e.rows.item[a]],{pass:f,total:c}=yt([e.rows.dies[a]],r.passBins);s[a]=c>0?f*100:NaN,n[a]=c}return{...t,level:"die",num:s,weights:n,perDie:!0}}export const probabilityPosition=(e,t)=>(e+.5)/t;export function combine(e,t){const i=e.filter(Number.isFinite);if(t==="count")return i.length;if(i.length===0)return NaN;switch(t){case"sum":return i.reduce((s,n)=>s+n,0);case"min":return ze(i);case"max":return Ge(i);case"median":{const s=[...i].sort((a,r)=>a-r),n=s.length>>1;return s.length%2?s[n]:(s[n-1]+s[n])/2}default:return i.reduce((s,n)=>s+n,0)/i.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"},qe={mean:"Mean",median:"Median",min:"Min",max:"Max",sum:"Sum",count:"Count",yield:"Pooled yield"};function fe(e,t,i,s,n,a){const r=s.axes?.[e]??{};let f=r.scale??"linear";if(f==="log"){for(const c of n)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:r.label??t,unit:i,scale:f,min:r.min,max:r.max,reverse:r.reverse}}function Gn(e,t){const{chart:i}=e,s=e.fields??{},n=ke(s.x),a=n.filter(c=>!Le(c)),r=n.length?a.length?ue(a.map(c=>fieldLabel(c,t.testDefs,t.curation))):void 0:(i==="box"||i==="bar")&&!le(s.y)?"Wafer":void 0,f=s.y?fieldLabel(s.y,t.testDefs,t.curation):void 0;if((i==="box"||i==="bar")&&f&&!r)return f;switch(i){case"scatter":return r&&f?`${f} vs ${r}`:"Scatter";case"histogram":return f??(n[0]?fieldLabel(n[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 r&&f?`${f} over ${r}`:"Line";case"box":return f&&r?`${f} by ${r}`:"Box";case"bar":return r?f?`${f} by ${r}`:`Dies by ${r}`:"Bar";default:return""}}function De(e,t,i,s={}){return{spec:e,issues:i,notes:[],level:"die",autoTitle:Gn(e,s),groups:[""],population:{wafers:t.length,dies:t.reduce((n,a)=>n+a.dies.length,0)},plotted:0,omitted:[]}}export function combinationIssue(e,t,i={}){const s=[t.x,i.continuousColor?void 0:t.color].filter(c=>!!c&&c.level==="die"),n=!!t.y&&t.y.yield&&t.y.level==="wafer",a=(e==="bar"||e==="line")&&(i.aggregate===void 0||i.aggregate==="yield"||i.aggregate==="mean");if(n&&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 r=[t.x,t.y].filter(c=>!!c);let f=i.level??(r.some(c=>c.level==="die")?"die":"wafer");if(e==="bar"&&!t.y&&s.length&&(f="die"),t.color?.level==="die"&&f==="wafer"&&!i.continuousColor&&!(n&&(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`}}const Un={limits:"position in limits",zscore:"z-score",robust:"robust z-score"};function Hn(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 Qt(e,t,i,s,n){const a=new Map,r=[],f=new Set;for(const c of e){if(s==="limits"){const d=i.find(b=>b.testNumber===c),l=d&&zt(d);if(!l){r.push(`${n(c)} has no low and high limit to place it by`);continue}f.add(l.basis),a.set(c,{offset:l.lsl,scale:l.usl-l.lsl});continue}const o=[];for(const d of t){const l=it(d,c);l!==void 0&&Number.isFinite(l)&&o.push(l)}if(o.length<2){r.push(`${n(c)} has fewer than two values to measure a spread in`);continue}let m,p;if(s==="zscore"?(m=Gt(o),p=Math.sqrt(Ut(o,m))):(m=$t(o),p=1.4826*$t(o.map(d=>Math.abs(d-m)))),!(p>0)||!Number.isFinite(p)){r.push(`${n(c)} has no spread: its values ${s==="robust"?"are mostly":"are all"} the same`);continue}a.set(c,{offset:m,scale:p})}return{scales:a,dropped:r,bases:f}}function Wn(e,t,i){const s={};for(const n of["limitLow","limitHigh","specLow","specHigh","patLow","patHigh"]){let a,r=!0;for(const f of e){const c=t(f)?.[n],o=i.get(f);if(c===void 0||!Number.isFinite(c)||!o){r=!1;break}const m=(c-o.offset)/o.scale;if(a===void 0)a=m;else if(Math.abs(m-a)>1e-9*Math.max(1,Math.abs(a))){r=!1;break}}r&&a!==void 0&&(s[n]=a)}return Object.keys(s).length?s:void 0}function Zt(e,t){let i;switch(e.type){case"scatter":i=e.points.map(n=>t==="x"?n.x:n.y);break;case"histogram":case"probability":i=t==="x"?e.values.flat():[];break;case"box":i=t==="y"?e.cells.flat(2):[];break;case"bar":i=t==="y"?e.values.flat():[];break;case"line":i=t==="x"?e.xs:[...e.values.flat(),...e.band?[...e.band.lo.flat(),...e.band.hi.flat()]:[]];break;case"control":i=t==="x"?e.xs:[...e.values,e.limits.ucl,e.limits.lcl];break;case"goal":i=e.points.map(n=>t==="x"?n.x:n.y);break;case"heatmap":i=[];break}const s=i.filter(Number.isFinite);return s.length?[ze(s),Ge(s)]:void 0}function Vn(e,t,i){if(e.issues.length||!e.marks)return e;const s=e.groups.map(f=>i.groups.indexOf(f));if(s.some(f=>f<0))return e;const n=Jt(e.marks,t,s,i.groups.length),a=i.marks&&Zt(i.marks,"x"),r=i.marks&&Zt(i.marks,"y");return{...e,marks:n,groups:i.groups,colorScale:i.colorScale??e.colorScale,x:e.x&&a?{...e.x,extent:a}:e.x,y:e.y&&r?{...e.y,extent:r}:e.y}}function Xn(e,t){return e.issues.length||!e.marks?e:{...e,marks:Jt(e.marks,t,e.groups.map((i,s)=>s),e.groups.length)}}function Jt(e,t,i,s){const n=(c,o)=>{const m=Array.from({length:s},o);return c.forEach((p,d)=>{m[i[d]]=p}),m},a=c=>t[c],r=c=>o=>{const m=c(o);return{...m,item:a(m.item)}};let f;switch(e.type){case"scatter":f={type:"scatter",points:e.points.map(c=>({...c,item:a(c.item),group:i[c.group]}))};break;case"histogram":f={type:"histogram",values:n(e.values,()=>[]),units:n(e.units,()=>[]),unit:r(e.unit)};break;case"probability":f={type:"probability",values:n(e.values,()=>[]),units:n(e.units,()=>[]),unit:r(e.unit)};break;case"box":case"bar":f={...e,cells:n(e.cells,()=>e.categories.map(()=>[])),cellUnits:n(e.cellUnits,()=>e.categories.map(()=>[])),values:n(e.values,()=>e.categories.map(()=>NaN)),categoryItems:e.categoryItems?.map(c=>c>=0?a(c):c),unit:r(e.unit)};break;case"line":f={...e,values:n(e.values,()=>e.xs.map(()=>NaN)),counts:n(e.counts,()=>e.xs.map(()=>0)),cellUnits:n(e.cellUnits,()=>e.xs.map(()=>[])),unit:r(e.unit),...e.band?{band:{lo:n(e.band.lo,()=>e.xs.map(()=>NaN)),hi:n(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:i[c.group]}))};break;case"heatmap":f={...e,unit:r(e.unit)};break}return f}function Yn(e,t,i){let s=0,n=0;const a=t.map(f=>{let c;for(let o=0;o<f.dies.length;o++){const m=f.dies[o];if(Dt(m)){c?.push(m);continue}c??=f.dies.slice(0,o),m.partial?s++:n++}return c?{...f,dies:c,allDies:f.allDies??f.dies}:f}),r=qn(resolvePlot(e,a,{...i,eligibleOnly:!0}));return s+n>0?{...r,leftOut:{partial:s,edge:n}}:r}export const axisValues=(e,t)=>e.marks?kt(e.marks,t).filter(Number.isFinite):[];function kt(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(i=>t==="x"?i.x:i.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 qn(e){const t=[],i=p=>{const d=e.spec.axes?.[p]?.references;if(!d?.length||!e[p])return;let l;return d.flatMap(b=>gn(b)?(l??=e.marks?kt(e.marks,p).filter(Number.isFinite):[],l.length===0?(t.push(`No ${b.stat} line: nothing is drawn along that axis`),[]):[{at:b.stat==="median"?$t(l):Gt(l),label:b.label??b.stat}]):[b])},s=p=>{if(!e.spec.axes?.[p]?.clip||!e[p]||!e.marks)return;const d=kt(e.marks,p).filter(Number.isFinite),l=xn(d);if(!l||d.length===0)return;const b=Math.max(ze(d),l.lo),w=Math.min(Ge(d),l.hi);if(!(w>b))return;const g=d.reduce((O,v)=>O+(v<b||v>w?1:0),0);return{lo:b,hi:w,outside:g}},n=i("x"),a=i("y"),r=s("x"),f=s("y");if(!n&&!a&&!r&&!f)return e;const c=(p,d,l)=>p&&(d||l)?{...p,...d?{references:d}:{},...l?{clip:l}:{}}:p,o=p=>({...p,x:c(p.x,n,r),y:c(p.y,a,f)}),m=o(e);m.facets&&(m.facets=m.facets.map(p=>({...p,plot:o(p.plot)})));for(const p of[r,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?{...m,notes:[...m.notes,...t]}:m}export function conditionUnit(e,t){if(Ce(e)&&"test"in e)return t?.find(i=>i.testNumber===e.test)?.unit;if(Ce(e)&&"builtin"in e&&(e.builtin==="yield"||e.builtin==="radius"))return"%"}const en=(e,t)=>{const i=String(Number(e.toPrecision(6)));return t==="%"?`${i}%`:t?Xe(e,t):i};export function conditionText(e,t,i){const s=fieldLabel(e.field,t,i);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 n=conditionUnit(e.field,t),a=e.min!==void 0?en(e.min,n):void 0,r=e.max!==void 0?en(e.max,n):void 0;return a!==void 0&&r!==void 0?`${s} ${e.not?"outside":"from"} ${a} to ${r}`:a!==void 0?`${s} ${e.not?"below":"at least"} ${a}`:`${s} ${e.not?"above":"at most"} ${r}`}export function applyConditions(e,t,i={}){const s=ge(t),n=s.dies.length,a={items:[...t],index:t.map((w,g)=>g),said:"",dies:{kept:n,total:n},wafers:{kept:t.length,total:t.length}};if(e.length===0)return a;const r=new Uint8Array(t.length).fill(1),f=new Uint8Array(n).fill(1),c=[],o=[];for(const w of e){const g=J(w.field,{items:t,rows:s,ctx:i});if(g.issue)return{...a,issue:g.issue};let O;if(w.values){if(!g.cat)return{...a,issue:`${g.label} is a number: keep a range of it, not values`};const k=new Set(w.values),_=g.cat;O=B=>_[B]!==void 0&&k.has(_[B])!==!!w.not}else{if(!g.num)return{...a,issue:`${g.label} is a category: keep some of its values, not a range`};const k=g.num,_=w.min??-1/0,B=w.max??1/0;O=W=>Number.isFinite(k[W])&&(k[W]>=_&&k[W]<=B)!=!!w.not}const v=g.level==="wafer"?r:f;for(let k=0;k<v.length;k++)v[k]&&!O(k)&&(v[k]=0);(g.level==="wafer"?c:o).push(conditionText(w,i.testDefs,i.curation))}const m=t.map(()=>[]);let p=0;for(let w=0;w<n;w++)f[w]&&r[s.item[w]]&&(m[s.item[w]].push(s.dies[w]),p++);const d=[],l=[];t.forEach((w,g)=>{if(r[g]){if(o.length===0){d.push(w),l.push(g);return}m[g].length&&(d.push({...w,dies:m[g],allDies:w.allDies??w.dies}),l.push(g))}});const b=[c.length?`only wafers where ${ue(c)}`:"",o.length?`only dies where ${ue(o)}`:""].filter(Boolean).join("; ");return{items:d,index:l,said:b,dies:{kept:p,total:n},wafers:{kept:d.length,total:t.length}}}function Kn(e,t,i){const s=(...r)=>De(e,t,r,i),n=applyConditions(_t(e),t,i);return n.issue?s(n.issue):n.items.length===0?s(`Nothing is left: no ${n.said.replace(/^only /,"").replace(/; only /," and ")}`):{...Xn(resolvePlot(e,n.items,{...i,whereApplied:!0}),n.index),filterNote:n.said}}function Qn(e,t,i){const s=e.fields.facet,{facet:n,...a}=e.fields,r={...e,fields:a},f=(...v)=>De(e,t,v,i),c=fieldLabel(s,i.testDefs,i.curation),o=t.flatMap(v=>v.dies),m={...i,inFacet:!0,scaleDies:i.scaleDies??o,wholeWafers:i.wholeWafers??t.length,wholeItems:i.wholeItems??t,binEdges:i.binEdges??new Map},p=Le(s);if(p&&!le(e.fields?.y))return f("Test panels need several tests as the values");if(p&&(ke(e.fields?.x).some(Le)||Le(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(v=>Fe(v,s))||e.fields?.color&&Ce(e.fields.color)&&Fe(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(r,t,p?{...m,facetByTest:!0}:m),l=v=>({...v,autoTitle:`${v.autoTitle} \xB7 panels by ${c}`});if(d.issues.length||!d.marks)return l(d);let b=[];const w=[];if(p){const v=d.setTests;if(!v)return f("Test panels need several tests as the values");const k=t.map((_,B)=>B);b=v.tests.map((_,B)=>({label:v.labels[B],items:[...t],index:k,spec:{...r,fields:{...a,y:{test:_,...i.testDefs?.find(W=>W.testNumber===_)?.name?{name:i.testDefs.find(W=>W.testNumber===_).name}:{}}}}}))}else{const v=ge(t),k=J(s,{items:t,rows:v,ctx:i});if(k.issue)return f(k.issue);if(!k.cat)return f(`${c} is continuous: panels need a category, such as split, ring or site`);if(k.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 D of k.cat)D!==void 0&&!_.includes(D)&&_.push(D);const B=Ue(s,_,Ye(k));if(B.length>Pt)return f(`${c} has ${B.length} values, and a plot draws at most ${Pt} panels: choose a field with fewer, or narrow Show`);const W=k.cat.filter(D=>D===void 0).length;W&&w.push(`${W.toLocaleString("en-GB")} ${k.level==="die"?"dies":"wafers"} with no ${c} value are in no panel`),b=B.map(D=>{const Q=[],se=[];if(k.level==="wafer")t.forEach((P,E)=>{k.cat[E]===D&&(Q.push(P),se.push(E))});else{const P=t.map(()=>[]);for(let E=0;E<v.dies.length;E++)k.cat[E]===D&&P[v.item[E]].push(v.dies[E]);t.forEach((E,u)=>{P[u].length&&(Q.push({...E,dies:P[u],allDies:E.allDies??E.dies}),se.push(u))})}return{label:D,items:Q,index:se,spec:r}})}const g=b.map(v=>({label:v.label,plot:Vn(resolvePlot(v.spec,v.items,m),v.index,d)})),O=d.usesPat||Rn(s)||g.some(v=>v.plot.usesPat);return{...l(d),notes:[...d.notes,...w],facets:g,facetLabel:c,...O?{usesPat:!0}:{}}}function Zn(e,t,i){const s=e.fields??{},n=(...B)=>De(e,t,B,i),a=ke(s.x)[0]??{builtin:"wafer"},r=s.rows??(le(s.y)?{builtin:"test"}:void 0);if(!r)return n("Choose a field for the rows: a heatmap has one row per value of it");if(Fe(r,a))return n("The rows and the columns need two different fields");const{rows:f,...c}=s,o={...e,chart:"bar",fields:{...c,x:[r,a],color:{none:!0}}};delete o.stack,delete o.sort,delete o.top,delete o.cumulative;const m=resolvePlot(o,t,{...i,asHeatmap:!0,inFacet:!0,whereApplied:i.whereApplied});if(m.issues.length||!m.marks||m.marks.type!=="bar")return{...m,spec:e};const p=m.marks,d=p.nest?.parts??[],l=[...new Set(d.map(B=>B[0]))],b=[...new Set(d.map(B=>B[1]))],w=Ue(a,b,b.every(B=>xt.test(B))),g=l.map(()=>w.map(()=>NaN)),O=l.map(()=>w.map(()=>[]));d.forEach((B,W)=>{const D=l.indexOf(B[0]),Q=w.indexOf(B[1]);g[D][Q]=p.values[0][W],O[D][Q]=p.cellUnits[0][W]});const v=g.flat().filter(Number.isFinite),k=fieldLabel(r,i.testDefs,i.curation),_=fieldLabel(a,i.testDefs,i.curation);return{...m,spec:e,marks:{type:"heatmap",rows:l,cols:w,values:g,cellUnits:O,unit:p.unit},autoTitle:`${m.y?.label??"Dies"} by ${k} and ${_}`,x:{label:e.axes?.x?.label??_,scale:"linear"},y:{label:e.axes?.y?.label??k,scale:"linear"},colorScale:v.length?{label:m.y?.label??"Count",unit:m.y?.unit,lo:ze(v),hi:Ge(v),...v.every(Number.isInteger)?{integer:!0}:{}}:void 0,groups:[""]}}function Jn(e,t,i){const s=(...D)=>De(e,t,D,i),n=e.fields??{};if(!n.y)return s("Choose a field for the values");if(le(n.y))return s("A control chart follows one value: choose one test");const a=ke(n.x)[0]??{builtin:"waferOrder"},r=ge(t),f={items:t,rows:r,ctx:i},c=J(a,f),o=J(n.y,f),m=c.issue??o.issue;if(m)return s(m);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(!o.num)return s(`${o.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(o.level==="die")for(let D=0;D<r.dies.length;D++)d[r.item[D]].push(o.num[D]);const l=D=>o.level==="wafer"?o.num[D]:combine(d[D],o.perDie?"mean":p),b=t.map((D,Q)=>Q).filter(D=>Number.isFinite(c.num[D])&&Number.isFinite(l(D))).sort((D,Q)=>c.num[D]-c.num[Q]||D-Q),w=t.length-b.length;if(b.length<3)return s("A control chart needs at least three wafers with a value");const g=b.map(l),O=b.map(D=>c.num[D]),v=Fn(g,e.baseline),k=Ln(g,v),_=o.perDie||o.level==="wafer"?o.label:`${qe[p]} ${o.label}`,B=[];n.color&&!("none"in n.color)&&!("follow"in n.color)&&B.push("A control chart is one series: its points are not coloured");const W=k.length?`${k.length} point${k.length===1?"":"s"} break${k.length===1?"s":""} a Western Electric rule (${[...new Set(k.flatMap(D=>D.rules))].sort().map(D=>`${D}: ${An[D]}`).join("; ")})`:"no point breaks a Western Electric rule";return{spec:e,issues:[],notes:B,level:"wafer",marks:{type:"control",xs:O,values:g,items:b,limits:v,violations:k},autoTitle:`${_} control chart`,x:fe("x",c.label,c.unit,e,O,B),y:{...fe("y",_,o.unit,e,g,B),limits:!o.perDie&&o.level==="die"&&(p==="mean"||p==="median")?o.limits:void 0},groups:[""],aggregation:`individuals chart: centre the mean of ${v.baseline===g.length?"all":`the first ${v.baseline}`} wafers, limits \xB13\u03C3 with \u03C3 the average moving range / 1.128; ${W}`,population:{wafers:t.length,dies:r.dies.length},plotted:g.length,omitted:w?[{field:o.label,count:w}]:[]}}function ei(e,t,i){const s=(...g)=>De(e,t,g,i),n=i.testDefs??[],a=e.fields??{};let r;if(!a.y)r=n.filter(be);else if(le(a.y)){const g=new Set(expandTestSet(a.y,n).tests);r=n.filter(O=>g.has(O.testNumber))}else if("test"in a.y)r=n.filter(g=>g.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(r=r.filter(g=>be(g)&&zt(g)!==void 0),r.length===0)return s("No test here has both a low and a high limit to set a goal by");const f=ge(t),c={items:t,rows:f,ctx:i},o=a.color,m=o===void 0||"follow"in o?i.groupBy?{meta:i.groupBy}:void 0:"none"in o?void 0:o;let p=[""],d=()=>0;if(m){const g=J(m,c);if(g.issue)return s(g.issue);if(!g.cat)return s(`${g.label} is continuous: colour a goal plot by a category such as split`);const O=k=>g.level==="die"?g.cat[k]:g.cat[f.item[k]],v=[];for(let k=0;k<f.dies.length;k++){const _=O(k);_!==void 0&&!v.includes(_)&&v.push(_)}p=Ue(m,v,Ye(g)),d=k=>{const _=O(k);return _===void 0?-1:p.indexOf(_)}}const l=p.map(()=>[]);for(let g=0;g<f.dies.length;g++){const O=d(g);O>=0&&l[O].push(f.dies[g])}const b=[];if(l.forEach((g,O)=>{for(const v of On([{dies:g}],r)){if(!v.hasSpec||v.lsl===void 0||v.usl===void 0||!(v.stdOverall>0)||v.ppk===null)continue;const k=v.usl-v.lsl;b.push({x:(v.mean-(v.lsl+v.usl)/2)/k,y:v.stdOverall/k,group:O,testNumber:v.testNumber,label:v.label,ppk:v.ppk,n:v.n,basis:v.limitBasis??"test"})}}),b.length===0)return s("No test has values with a spread to place");const w=[];return{spec:e,issues:[],notes:w,level:"die",marks:{type:"goal",points:b},autoTitle:m?`Capability goal plot \xB7 by ${fieldLabel(m,n,i.curation)}`:"Capability goal plot",x:fe("x","Mean offset from the centre of the limits",void 0,e,b.map(g=>g.x),w),y:fe("y","Standard deviation",void 0,e,b.map(g=>g.y),w),groups:p,colorLabel:m?fieldLabel(m,n,i.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:b.length,omitted:[]}}export function resolvePlot(e,t,i={}){const s=ti(e,t,i);return i.populationLabel&&!i.inFacet?{...s,populationLabel:i.populationLabel}:s}function ti(e,t,i={}){const s=bn(e);if(s)return De(e,t,[s],i);const n=(...h)=>De(e,t,h,i);if(e.chart==="sweep")return n("A sweep is drawn by the sweep panel");if(!i.eligibleOnly)return Yn(e,t,i);if(!i.whereApplied&&_t(e).length)return Kn(e,t,i);if(e.fields?.facet&&!i.inFacet)return Qn(e,t,i);if(e.chart==="control")return Jn(e,t,i);if(e.chart==="goal")return ei(e,t,i);if(e.chart==="heatmap"&&!i.asHeatmap)return Zn(e,t,i);const a=e.chart,r=e.fields??{},f=i.testDefs??[],c=t.flatMap(h=>h.dies),o=[],m=le(r.y)?r.y:void 0;if(le(r.x)||le(r.color))return n("A set of tests can only be the values (Y) of a plot");if(e.normalize&&a==="scatter")return n("Rescaling applies to the values of a box, bar, line or histogram, not to a scatter");if(m&&a==="scatter")return n("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=h=>f.find(x=>x.testNumber===h)?.name||m?.names?.[String(h)]||`Test ${h}`;let d,l,b=new Set,w=t;if(m){const{tests:h,problems:x}=expandTestSet(m,f);if(x.length)return n(...x);const N=new Set(c.length?st(c,"values"):[]),A=[];let $=[];for(const T of h){const R=f.find(X=>X.testNumber===T),G=m.names?.[String(T)];if(R&&G&&R.name&&!wt(G,R.name))return n(`Test ${T} is "${G}" in this plot and "${R.name}" here`);if(m.passRate){if(!R){A.push(G?`${G} (test ${T})`:`test ${T}`);continue}if(passKindOf(R,m.judge)==="spec"&&R.limitLow===void 0&&R.limitHigh===void 0){A.push(`${p(T)} (no test limits)`);continue}$.push(T);continue}if(R&&!be(R)){A.push(`${p(T)} (pass/fail, no value)`);continue}if(!N.has(T)){A.push(G?`${G} (test ${T})`:`test ${T}`);continue}$.push(T)}if($.length===0)return n(`None of these tests has ${m.passRate?"a verdict to judge":"values"} in these dies${A.length?`: ${A.join(", ")}`:""}`);if(m.passRate&&e.normalize)return n("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 T=Math.max(1,Math.floor(TEST_SET_VALUE_LIMIT/Math.max(1,c.length)));return n(`${$.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 ${T} tests, or show fewer wafers`)}if(A.length&&o.push(`Left out, with no values here: ${A.join(", ")}`),e.normalize){const T=Qt($,i.scaleDies??c,f,e.normalize,p);if(T.scales.size===0)return n(...T.dropped);T.dropped.length&&o.push(`Left out: ${T.dropped.join("; ")}`),$=$.filter(R=>T.scales.has(R)),l=T.scales,b=T.bases}else if(!m.passRate){const T=[...new Set($.map(R=>f.find(G=>G.testNumber===R)?.unit).filter(R=>!!R))];if(T.length>1)return n(`These tests are measured in different units (${T.join(", ")}): rescale them to compare them on one axis`)}const L=$.map(p),F=L.map((T,R)=>L.indexOf(T)!==L.lastIndexOf(T)?`${T} \xB7 ${$[R]}`:T),S=[],U=[],j=[];$.forEach((T,R)=>t.forEach((G,X)=>{S.push(G),U.push(X),j.push(R)})),d={realOf:Int32Array.from(U),testOf:Int32Array.from(j),tests:$,labels:F},w=S}const g=h=>d?d.realOf[h]:h,O=ge(w),v={items:w,rows:O,ctx:i,melt:d},k=ke(r.x);if(k.length>1&&a!=="box"&&a!=="bar")return n("Nested categories need a box or bar chart: choose one field for X");if(k.length>Bt)return n(`At most ${Bt} fields can be nested on X`);if(k.some((h,x)=>k.findIndex(N=>Fe(h,N))!==x))return n("A field can be only one level of the categories");const _=k.length?k:a==="box"||a==="bar"?[{builtin:m?"test":"wafer"}]:[],B=_[0],W=_.some(Le),D=r.y,Q=a==="histogram"||a==="probability",se=Q?D??B:D;if(a==="scatter"||a==="line"){if(!B)return n("Choose a field for X");if(!D)return n("Choose a field for Y")}if(a==="box"&&!D)return n("Choose a field for Y");if(a==="histogram"&&!se)return n("Choose a field to count");if(a==="probability"&&!se)return n("Choose the values to plot");const P=Q?[]:_.map(h=>J(h,v)),E=P[0];let u=se?J(se,v):void 0;if(e.normalize&&u&&!u.issue){if(!d){if(!("test"in u.field)||!u.num)return n("Rescaling applies to a measured test: choose a test for the values");const F=u.field.test,S=Qt([F],i.scaleDies??O.dies,f,e.normalize,()=>u.label);if(S.scales.size===0)return n(...S.dropped);l=S.scales,b=S.bases}const h=F=>d?d.tests[d.testOf[O.item[F]]]:u.field.test,x=new Float64Array(u.num.length);for(let F=0;F<x.length;F++){const S=l.get(h(F));x[F]=(u.num[F]-S.offset)/S.scale}const N=d?d.tests:[h(0)],A=d?N.length>3?`${N.length} tests`:ue(d.labels):u.label,$=u.limits;u={...u,num:x,unit:void 0,limits:Wn(N,d?F=>Xt(f.find(S=>S.testNumber===F)):()=>$,l),label:`${A} (${Un[e.normalize]})`}}else d&&u&&!u.issue&&!yn(u.field)&&(u={...u,label:d.tests.length>3?`${d.tests.length} tests`:ue(d.labels)});const ae=a==="scatter"||a==="line"?[["X",E],["Y",u]]:a==="histogram"?[["to count",u]]:a==="probability"?[["values",u]]:a==="box"||a==="bar"?[["Y",u]]:[];for(const[h,x]of ae)if(x&&!x.issue&&x.kind==="categorical"&&!x.num)return n(`${x.label} is a category, not a number, so it cannot be ${h==="to count"?"the field a histogram counts":h==="values"?"the values of a probability plot":`the ${h} 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 ye=m&&!W&&!i.facetByTest&&(r.color===void 0||"follow"in r.color)?{builtin:"test"}:r.color;if(m&&!W&&!i.facetByTest&&!Le(ye))return n("Put Test on the X axis or the colour, so each test is drawn on its own");let M,Lt=!1,at;ye===void 0||"follow"in ye?i.groupBy?at=i.groupBy:(i.wholeWafers??t.length)>1&&(Lt=!0):"none"in ye||(M=J(ye,v)),at&&(M=J({meta:at},v)),Lt&&(M=J({builtin:"wafer"},v)),M?.issue&&(ye===void 0||"follow"in ye)&&(M=void 0);const ot=[...P.map(h=>h.issue),u?.issue,M?.issue].filter(h=>!!h),Me=!!M&&M.kind==="numeric"&&!("meta"in M.field);if(Me&&a!=="scatter"&&ot.push(`${M.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 n(...ot);const nn=[...P,u].filter(h=>!!h);let q=e.level??(nn.some(h=>h.level==="die")?"die":"wafer");const rt=[...P,Me?void 0:M].filter(h=>!!h&&h.level==="die"),lt=h=>h&&{label:h.label,level:h.level,kind:h.kind,yield:!!h.weights},At=combinationIssue(a,{x:lt(P.find(h=>h.level==="die")??E),y:lt(u),color:lt(M)},{aggregate:e.aggregate,level:e.level,continuousColor:Me});if(At)return n(At.long);if(a==="bar"&&!u&&rt.length&&(q="die"),u&&u.level==="wafer"&&u.weights&&rt.length&&(u=zn(v,u),q="die"),q==="die"&&u?.weights&&!u.perDie&&!rt.length&&(q="wafer"),u&&"passRate"in u.field&&q==="die"&&a!=="bar"&&a!=="line")return n(`${u.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 ie=q==="die"?O.dies.length:w.length,Ke=h=>q==="die"?O.item[h]:h,Qe=h=>({item:g(Ke(h)),die:q==="die"?O.dies[h]:void 0}),Ot=e.aggregate&&e.aggregate!=="yield"?e.aggregate:"mean",we=h=>{if(!h.num)throw new Error("numeric field expected");if(h.level===q)return h.num;if(h.level==="wafer"){const N=new Float64Array(ie);for(let A=0;A<ie;A++)N[A]=h.num[Ke(A)];return N}const x=w.map(()=>[]);for(let N=0;N<h.num.length;N++)x[O.item[N]].push(h.num[N]);return Float64Array.from(x,N=>combine(N,Ot))},Tt=h=>{if(!h.cat)throw new Error("category field expected");if(h.level===q)return h.cat;if(h.level==="wafer")return Array.from({length:ie},(x,N)=>h.cat[Ke(N)]);throw new Error("a per-die category cannot be used at wafer level")},sn=h=>h.weights&&h.level===q?h.weights:void 0;let Ze=[""],$e=new Int32Array(ie),Ae,ve;if(M&&Me)Ae=M.label,ve=we(M);else if(M){Ae=M.label;const h=Tt(M),x=new Map,N=[];for(let $=0;$<ie;$++){const L=h[$]??gt;x.has(L)||(x.set(L,0),N.push(L))}const A=Ue(M.field,N,Ye(M));A.forEach(($,L)=>x.set($,L)),Ze=A;for(let $=0;$<ie;$++)$e[$]=x.get(h[$]??gt)}const ut=new Map,xe=h=>ut.set(h,(ut.get(h)??0)+1),He=(h,x)=>h.labelOf?h.labelOf(q==="die"?O.item[x]:x):h.label,Je=q==="die"?"dies":"wafers";let Re,ee,de,Oe,ft,It,ct,_e=0;const V=Ze.length,We=h=>h.level==="die"&&q==="wafer"?`${qe[Ot].toLowerCase()} of ${h.label} per wafer`:void 0;if(a==="scatter"){const h=we(E),x=we(u),N=[];for(let L=0;L<ie;L++){if(!Number.isFinite(h[L])){xe(E.label);continue}if(!Number.isFinite(x[L])){xe(He(u,L));continue}if(ve&&!Number.isFinite(ve[L])){xe(M.label);continue}N.push({x:h[L],y:x[L],group:$e[L],item:Ke(L),die:q==="die"?O.dies[L]:void 0,...ve?{value:ve[L]}:{}})}if(_e=N.length,ve&&N.length){const L=N.map(F=>F.value);It={label:M.label,unit:M.unit,lo:ze(L),hi:Ge(L)}}let A;if(e.fit){A=(ve?[N]:Array.from({length:V},(S,U)=>N.filter(j=>j.group===U))).flatMap((S,U)=>{const j=fitLine(S.map(T=>T.x),S.map(T=>T.y),e.fit);return j?[{group:U,...j}]:[]});const F=(E.unit??"")===(u.unit??"");ct=A.map(S=>{const U=V>1&&!ve?`${Ze[S.group]||"(none)"}: `:"",j=+S.slope.toPrecision(4),T=`${j<0?"\u2212":""}${jt(Math.abs(j))}`,R=F?T:`${T} ${u.unit??""}/${E.unit??""}`.trim(),G=S.intercept<0?"\u2212":"+";return`${U}y = ${R} x ${G} ${Xe(Math.abs(S.intercept),u.unit)}, R\xB2 ${S.r2.toFixed(3)}, n ${S.n.toLocaleString("en-GB")}`})}let $=!1;if(e.identity&&((E.unit??"")!==(u.unit??"")?o.push(`y = x is left off: ${E.label} and ${u.label} are in different units`):$=!0),Re={type:"scatter",points:N,...A?.length?{fits:A}:{},...$?{identity:!0}:{}},ft=Sn(N),ee=fe("x",E.label,E.unit,e,N.map(L=>L.x),o),de=fe("y",u.label,u.unit,e,N.map(L=>L.y),o),!i.inFacet){const L=[M?.field,e.fields?.facet].flatMap(S=>S&&"meta"in S?[S.meta]:[]),F=Rt(t.map(S=>({metadata:S.metadata,dieCount:S.dies.length})),{facetableOnly:!0,curation:i.curation}).filter(S=>S.splittable&&!L.includes(S.key)).map(S=>S.label);F.length&&o.push(`Mixed ${ue(F)} 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`)}Oe=[We(E),We(u),A?.length?`${e.fit==="orthogonal"?"orthogonal (Deming) fit":"least-squares fit of Y on X"} per ${V>1&&!ve?"colour":"plot"}`:void 0].filter(Boolean).join("; ")||void 0}else if(a==="histogram"){const h=we(u),x=Array.from({length:V},()=>[]),N=Array.from({length:V},()=>[]);for(let $=0;$<ie;$++){if(!Number.isFinite(h[$])){xe(He(u,$));continue}x[$e[$]].push(h[$]),N[$e[$]].push($),_e++}Re={type:"histogram",values:x,units:N,unit:Qe},ee=fe("x",u.label,u.unit,e,x.flat(),o);const A=e.histNorm==="percent";de={label:A?V>1?`Share of each colour's ${Je}`:`Share of ${Je}`:"Count",scale:"linear",...A?{unit:"%"}:{},...e.axes?.y?.label?{label:e.axes.y.label}:{}},e.normalCurve&&ee.scale==="log"&&o.push("The normal curve is left off a log axis, where a normal distribution is not the shape its bars would follow"),Oe=[We(u),e.normalCurve&&ee.scale!=="log"?`curve: the normal distribution with ${V>1?"each colour's":"the"} mean and standard deviation`:void 0].filter(Boolean).join("; ")||void 0}else if(a==="probability"){const h=we(u),x=Array.from({length:V},()=>[]);for(let $=0;$<ie;$++){if(!Number.isFinite(h[$])){xe(He(u,$));continue}x[$e[$]].push($),_e++}for(const $ of x)$.sort((L,F)=>h[L]-h[F]);const N=x.map($=>$.map(L=>h[L]));Re={type:"probability",values:N,units:x,unit:Qe},ee=fe("x",u.label,u.unit,e,N.flat(),o);const A=e.probabilityAxis==="linear";de={label:e.axes?.y?.label??"Cumulative share",scale:"linear"},Oe=[We(u),`each ${q==="die"?"die":"wafer"} at (rank \u2212 \xBD) / n of its ${V>1?"group":"population"}${A?"":", on a normal-probability scale"}`].filter(Boolean).join("; ")}else if(a==="line"){const h=we(E),x=we(u),N=new Set,A=new Map,$=new Map;for(let z=0;z<ie;z++){if(!Number.isFinite(h[z])){xe(E.label);continue}if(!Number.isFinite(x[z])){xe(He(u,z));continue}N.add(h[z]);const Y=`${$e[z]}|${h[z]}`;(A.get(Y)??A.set(Y,[]).get(Y)).push(x[z]),_e++,($.get(Y)??$.set(Y,[]).get(Y)).push(z)}const L=[...N].sort((z,Y)=>z-Y),F=e.aggregate??"mean",S=Array.from({length:V},(z,Y)=>L.map(me=>{const te=A.get(`${Y}|${me}`);return te?combine(te,F==="yield"?"mean":F):NaN})),U=Array.from({length:V},(z,Y)=>L.map(me=>A.get(`${Y}|${me}`)?.length??0)),j=Array.from({length:V},(z,Y)=>L.map(me=>$.get(`${Y}|${me}`)??[]));let T;const R=e.spread;if(R){if(u.perDie)return n(`A band shows how values spread, and ${u.label} is a share of passing dies, not a value: leave the band off`);if(F!=="mean"&&F!=="median")return n(`A band goes round a mean or a median, not ${Nt[F]}`);const z=new Map,Y=(re,Se,ce)=>{const K=(A.get(`${re}|${Se}`)??[]).filter(Number.isFinite);if(K.length===0)return[NaN,NaN];if(R==="minmax")return[ze(K),Ge(K)];if(R==="iqr"){const Ie=K.sort((Pe,y)=>Pe-y);return[vt(Ie,.25),vt(Ie,.75)]}if(K.length<2)return[NaN,NaN];const Be=K.reduce((Ie,Pe)=>Ie+Pe,0)/K.length,Te=Math.sqrt(Ut(K,Be));let et=1;R==="ci95"&&(et=z.get(K.length-1)??vn(.05,K.length-1),z.set(K.length-1,et));const tt=R==="sd"?Te:et*Te/Math.sqrt(K.length);return[S[re][ce]-tt,S[re][ce]+tt]},me=S.map(()=>[]),te=S.map(()=>[]);S.forEach((re,Se)=>L.forEach((ce,K)=>{const[Be,Te]=Y(Se,ce,K);me[Se].push(Be),te[Se].push(Te)})),T={lo:me,hi:te}}Re={type:"line",xs:L,values:S,counts:U,cellUnits:j,unit:Qe,...T?{band:T}:{}},ee=fe("x",E.label,E.unit,e,L,o);const G=F==="yield"?"mean":F;de=fe("y",u.perDie?u.label:`${qe[G]} ${u.label}`,u.unit,e,S.flat(),o);const X=q==="die"?"dies":"wafers",oe={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=(u.perDie?`passing dies over judged dies, per ${E.label.toLowerCase()}`:`${qe[G].toLowerCase()} of ${u.label} per ${E.label}`)+(R?`; band: ${oe[R]} at each ${E.label.toLowerCase()}`:"")}else{const h=[],x=[];for(const y of P){const I="builtin"in y.field&&(y.field.builtin==="x"||y.field.builtin==="y");if(y.kind==="numeric"&&y.level==="die"&&!I)return n(`${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 C=y.cat?Tt(y):Array.from(we(y),ne=>Number.isFinite(ne)?jt(ne):void 0),H=new Set,Z=[];for(let ne=0;ne<ie;ne++){const pe=C[ne];pe!==void 0&&!H.has(pe)&&(H.add(pe),Z.push(pe))}const he=Ue(y.field,Z,Ye(y));h.push(C),x.push(new Map(he.map((ne,pe)=>[ne,pe])))}const N="",A=new Map,$=[],L=y=>{const I=[];for(let C=0;C<h.length;C++){const H=h[C][y];if(H===void 0)return{missing:C};I.push(H)}return I.join(N)};for(let y=0;y<ie;y++){const I=L(y);typeof I=="string"&&!A.has(I)&&(A.set(I,0),$.push(I.split(N)))}$.sort((y,I)=>{for(let C=0;C<y.length;C++){const H=x[C].get(y[C])-x[C].get(I[C]);if(H)return H}return 0});const F=$.map(y=>y.join(" \xB7 "));$.forEach((y,I)=>A.set(y.join(N),I));const S=h.length===1?h[0]:void 0,U=a==="bar"&&!u,j=e.aggregate??(U?"count":u?.weights?"yield":"mean");if(j==="yield"&&!u?.weights)return n("Pooled yield needs Yield as the Y field");if(a==="box"&&j==="count")return n("A box plot needs a measured field for Y");const T=u?we(u):void 0,R=u?sn(u):void 0,G=Array.from({length:V},()=>F.map(()=>[])),X=Array.from({length:V},()=>F.map(()=>[])),oe=Array.from({length:V},()=>F.map(()=>[]));for(let y=0;y<ie;y++){const I=L(y);if(typeof I!="string"){xe(P[I.missing].label);continue}const C=A.get(I);if(T&&!Number.isFinite(T[y])){xe(He(u,y));continue}G[$e[y]][C].push(T?T[y]:1),X[$e[y]][C].push(y),R&&oe[$e[y]][C].push(R[y]),_e++}const z=G.map((y,I)=>y.map((C,H)=>{if(C.length===0)return NaN;if(j==="yield"){const Z=oe[I][H],he=Z.reduce((ne,pe)=>ne+pe,0);return he>0?C.reduce((ne,pe,ln)=>ne+pe*Z[ln],0)/he:NaN}return combine(C,j)})),Y=a==="bar"&&(j==="count"||j==="sum");if(e.stack&&a!=="bar")return n("Only a bar chart stacks its colours");if(e.stack&&!Y)return n(`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&&!(Y&&e.sort==="value"))return n("A cumulative line needs a bar of counts or sums sorted by value, largest first");if(e.barNorm==="percent"&&!Y)return n(`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 n("Bars are either stacked or each colour's share of its own total, not both");if(e.barNorm==="percent"&&Y)for(let y=0;y<V;y++){const I=z[y].reduce((C,H)=>C+(Number.isFinite(H)?H:0),0);z[y]=z[y].map(C=>Number.isFinite(C)&&I>0?C/I*100:NaN)}if((e.sort||e.top)&&P.length>1)return n("Sorting by value and keeping the top categories need one category field on X");const me=y=>{if(a==="box"){const C=G.flatMap(H=>H[y]);return C.length?combine(C,"median"):NaN}if(Y||e.barNorm==="percent"){let C=0,H=!1;for(const Z of z)Number.isFinite(Z[y])&&(C+=Z[y],H=!0);return H?C:NaN}const I=G.flatMap(C=>C[y]);if(I.length===0)return NaN;if(j==="yield"){const C=oe.flatMap(Z=>Z[y]),H=C.reduce((Z,he)=>Z+he,0);return H>0?I.reduce((Z,he,ne)=>Z+he*C[ne],0)/H:NaN}return combine(I,j)},te=F.map((y,I)=>me(I));let re=F.map((y,I)=>I);e.sort==="value"&&re.sort((y,I)=>(Number.isFinite(te[I])?te[I]:-1/0)-(Number.isFinite(te[y])?te[y]:-1/0)),e.sort==="ascending"&&re.sort((y,I)=>(Number.isFinite(te[y])?te[y]:1/0)-(Number.isFinite(te[I])?te[I]:1/0));const Se=te.reduce((y,I)=>y+(Number.isFinite(I)?I:0),0);e.top&&e.top<re.length&&(o.push(`Showing the first ${e.top} of ${re.length} ${P[0].label.toLowerCase()} values${e.sort==="value"?", largest first":e.sort==="ascending"?", smallest first":""}`),re=re.slice(0,e.top));const ce=y=>re.map(I=>y[I]);F.splice(0,F.length,...ce(F));for(let y=0;y<V;y++)G[y]=ce(G[y]),X[y]=ce(X[y]),z[y]=ce(z[y]);const K=ce(te);if($.length&&$.splice(0,$.length,...ce($)),e.stack==="percent")for(let y=0;y<V;y++)z[y]=z[y].map((I,C)=>Number.isFinite(I)&&K[C]>0?I/K[C]*100:NaN);let Be=0;const Te=e.cumulative&&Se>0?K.map(y=>(Be+=Number.isFinite(y)?y:0,Be/Se*100)):void 0,tt=!!S&&"builtin"in P[0].field&&P[0].field.builtin==="wafer"?F.map(y=>S.findIndex((I,C)=>I===y&&C>=0)):void 0,Ie=P.length>1?{levels:P.map(y=>y.label),parts:$}:void 0;Re={type:a==="box"?"box":"bar",categories:F,cells:G,cellUnits:X,unit:Qe,values:z,categoryItems:tt?.map(y=>g(q==="die"?O.item[y]:y)),...Ie?{nest:Ie}:{},...e.stack&&V>1?{stack:e.stack}:{},...Te?{cumulative:Te}:{},...a==="bar"&&q==="die"&&u?.perDie?{passFail:u.failSide?.some(y=>y!==0)?{failSide:u.failSide}:{}}:{}};const Pe=ue(P.map(y=>y.label.toLowerCase()));if(ee={label:e.axes?.x?.label??P.map(y=>y.label).join(" \u203A "),scale:"linear"},a==="bar"){const y=j==="count"?"Count":qe[j],I=U?`Count of ${Je}`:j==="yield"?"passRate"in u.field?u.label:"Pooled yield":`${y} ${u.label}`,C=e.stack==="percent"&&V>1,H=e.barNorm==="percent",Z=U?Je:I.toLowerCase(),he=C?`Share of each ${P[0].label.toLowerCase()}'s ${Z}`:H?V>1?`Share of each ${Ae?Ae.toLowerCase():"colour"}'s ${Z}`:`Share of ${Z}`:I,ne=C?[0,100]:e.stack&&V>1?K.filter(Number.isFinite):z.flat();de=fe("y",he,C||H||j==="yield"?"%":j==="count"?void 0:u?.unit,e,ne,o),Oe=U?void 0:j==="yield"?`passing dies over judged dies, pooled per ${Pe}`:`${y.toLowerCase()} of ${u.label}${u.level==="die"&&q==="wafer"?" per wafer":""} per ${Pe}`}else de=fe("y",u.label,u.unit,e,G.flat(2),o),Oe=We(u)}const dt=(h,x)=>h&&!h.perDie&&(x===void 0||x==="mean"||x==="median"||x==="min"||x==="max")?h.limits:void 0,an=e.aggregate??"mean";ee&&(a==="scatter"||a==="line")&&(ee.limits=dt(E)),de&&a!=="histogram"&&(de.limits=dt(u,a==="scatter"||a==="box"?void 0:an)),Q&&ee&&(ee.limits=dt(u));const on=()=>{const h=u?.label,x=P.filter($=>!Le($.field)),N=a==="box"||a==="bar"?x.length?ue(x.map($=>$.label)):void 0:E?.label,A=a==="scatter"?`${h} vs ${N}`:a==="histogram"?`${h}`:a==="probability"?`${h}, cumulative`:a==="line"?`${h} over ${N}`:N?a==="box"?`${h} by ${N}`:h?`${h} by ${N}`:`Dies by ${N}`:`${h}`;return Ae&&M&&!_.some($=>Fe(M.field,$))&&!Le(M.field)?`${A} \xB7 by ${Ae}`:A},Ct=[];let mt;const Et=d?d.tests.map((h,x)=>({field:d.labels[x],test:h})):[];for(const h of new Set([...P,d?void 0:u,M]))h&&"test"in h.field&&Et.push({field:h.label,test:h.field.test});for(const{field:h,test:x}of Et){let N=0;for(const A of c)dn(A,x)!==void 0&&(N++,mt??=mn(cn(A)));N>0&&Ct.push({field:h,count:N})}let ht;if((a==="box"||a==="bar")&&!d&&u&&"test"in u.field&&u.level==="die"&&u.num&&!u.perDie){const h=N=>!!N&&N.level==="wafer"&&N.kind==="categorical"&&!!N.cat&&!("builtin"in N.field&&(N.field.builtin==="wafer"||N.field.builtin==="test")),x=P.length===1&&h(P[0])?P[0]:!Me&&h(M)?M:void 0;if(x){const N=new Float64Array(t.length),A=new Uint32Array(t.length);for(let F=0;F<O.dies.length;F++){const S=u.num[F];Number.isFinite(S)&&(N[O.item[F]]+=S,A[O.item[F]]++)}const $=new Map;t.forEach((F,S)=>{const U=x.cat[S];U===void 0||A[S]===0||($.get(U)??$.set(U,[]).get(U)).push(N[S]/A[S])});const L=[...$.keys()].sort(Mt);L.length>=2&&(ht={by:x.label,result:kn(L.map(F=>({key:F,values:$.get(F)})))})}}let pt;if(e.whatIf){if(!(a==="histogram"||a==="probability"))return n("What-if limits go on a histogram or a probability plot of one test");if(d||!u||!("test"in u.field))return n("What-if limits need one measured test as the values");if(e.normalize)return n("What-if limits are in the test's own unit: turn rescaling off to set them");const h=u.field.test,x=f.find(X=>X.testNumber===h),N=x?.limitLow??-1/0,A=x?.limitHigh??1/0,$=e.whatIf.lo??x?.limitLow??-1/0,L=e.whatIf.hi??x?.limitHigh??1/0;let F=0,S=0,U=0;for(let X=0;X<O.dies.length;X++){const oe=it(O.dies[X],h);oe===void 0||!Number.isFinite(oe)||!Dt(O.dies[X])||(F++,oe>=N&&oe<=A&&S++,oe>=$&&oe<=L&&U++)}const j=X=>F?`${(X/F*100).toFixed(1)}%`:"\u2014",T=`${Number.isFinite($)?Xe($,u.unit):"\u2212\u221E"} to ${Number.isFinite(L)?Xe(L,u.unit):"\u221E"}`,R=U-S,G=`what-if: ${u.label} passes ${j(S)} of ${F.toLocaleString("en-GB")} dies by its test limits, ${j(U)} from ${T} (${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:F,passNow:S,passThen:U,sentence:G},ee&&(ee.limits={...ee.limits,...e.whatIf.lo!==void 0?{whatIfLow:e.whatIf.lo}:{},...e.whatIf.hi!==void 0?{whatIfHigh:e.whatIf.hi}:{}})}const rn=[...P,u,M].some(h=>!!h&&"builtin"in h.field&&h.field.builtin==="pat")||[ee,de].some(h=>h?.limits?.patLow!==void 0||h?.limits?.patHigh!==void 0);return{spec:e,issues:[],notes:o,marks:Re,level:q,...ht?{comparison:ht}:{},...rn?{usesPat:!0}:{},...ct?.length?{fitNotes:ct}:{},...pt?{whatIf:pt}:{},...mt?{excluded:{limitSet:mt,fields:Ct}}:{},autoTitle:on(),x:ee,y:de,groups:Ze,colorScale:It,colorLabel:Ae,aggregation:Oe,...ft?{correlation:ft}:{},...M&&!Me&&"builtin"in M.field&&(M.field.builtin==="hbin"||M.field.builtin==="sbin")?{colorBins:M.field.builtin==="hbin"?"hard":"soft"}:{},...M&&_.some(h=>Fe(M.field,h))?{colorRepeatsX:!0}:{},...e.normalize&&l?{normalization:Hn(e.normalize,b)}:{},population:{wafers:t.length,dies:c.length},...d?{setTests:{tests:d.tests,labels:d.labels}}:{},plotted:_e,omitted:[...ut].map(([h,x])=>({field:h,count:x}))}}export function plotTitle(e){return e.spec.title?.trim()?e.spec.title:e.autoTitle}function ni(e,t){const i=t.groups.map(r=>`${r.key} ${r.n}`).join(", "),s=`by ${e.toLowerCase()}, wafer means (wafers: ${i})`;if(!t.welch&&!t.kruskal)return`${s}: ${t.issue?.toLowerCase()??"not comparable"}`;const n=t.welch?`${t.welch.method==="welch-t"?"Welch t":"Welch ANOVA"} p ${Ht(t.welch.p)}`:void 0,a=t.kruskal?`rank p ${Ht(t.kruskal.p)}${t.kruskal.approximate?" (approximate)":""}`:void 0;return`${s}: ${[n,a].filter(Boolean).join(", ")}`}export function plotFootnote(e){const{wafers:t,dies:i}=e.population,s=[e.populationLabel?`${i.toLocaleString("en-GB")} dies \xB7 ${e.populationLabel}`:`${t.toLocaleString("en-GB")} wafer${t===1?"":"s"} \xB7 ${i.toLocaleString("en-GB")} dies`];if(e.leftOut){const{partial:n,edge:a}=e.leftOut,r=(f,c)=>`${f.toLocaleString("en-GB")} ${c} di${f===1?"e":"es"}`;s.push(`${ue([...a?[r(a,"edge-excluded")]:[],...n?[r(n,"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(ni(e.comparison.by,e.comparison.result)),e.usesPat&&s.push(`PAT per wafer: median \xB1 ${Dn} \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 n of e.omitted)s.push(`${n.count.toLocaleString("en-GB")} ${e.level==="die"?"dies":"wafers"} without ${n.field} not plotted`);if(e.excluded)for(const n of e.excluded.fields)s.push(`${n.count.toLocaleString("en-GB")} ${n.field} value${n.count===1?"":"s"} outside ${e.excluded.limitSet} excluded`);return s.join(" \xB7 ")}export function plotGuideSections(e){const{spec:t}=e,i=t.fields??{},s=[...ke(i.x),i.y,i.color,i.rows,i.facet],n=[ii[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(Ve)||e.facets||e.whatIf)&&Ne.ranges];return[...new Set(n.filter(a=>!!a))]}const ii={probability:Ne.probability,control:Ne.control,goal:Ne.goal,heatmap:Ne.heatmap};export function fieldKey(e){return Ve(e)?`binned:${fieldKey(e.binned)}`:le(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 i=[],s=e.flatMap(l=>l.dies),n=new Set(s.length?st(s,"values"):[]),a=t.testDefs??[],r=new Map;for(const l of a)l.testType!=="F"&&(n.has(l.testNumber)||!s.length)&&r.set(l.testNumber,l.name);for(const l of n)!r.has(l)&&!a.some(b=>b.testNumber===l&&b.testType==="F")&&r.set(l,void 0);for(const[l,b]of[...r].sort((w,g)=>w[0]-g[0]))i.push({field:{test:l,...b?{name:b}:{}},label:b?`${b} \xB7 ${l}`:`Test ${l}`,name:b||`Test ${l}`,group:"Tests",kind:"numeric",level:"die",categorical:!1});r.size>=2&&i.push({field:{builtin:"test"},label:Ee.test,name:Ee.test,group:"Tests",kind:"categorical",level:"wafer",categorical:!0});const f=new Set(s.length?st(s,"all"):[]);for(const l of a){if(be(l)||!(f.has(l.testNumber)||!s.length))continue;const b=l.name||`Test ${l.testNumber}`;i.push({field:{test:l.testNumber,...l.name?{name:l.name}:{}},label:`${b} \xB7 ${l.testNumber} (pass/fail)`,name:b,group:"Verdicts",kind:"categorical",level:"die",categorical:!0})}for(const l of a){if(!(be(l)?(l.limitLow!==void 0||l.limitHigh!==void 0)&&(n.has(l.testNumber)||!s.length):f.has(l.testNumber)||!s.length))continue;const w=l.name||`Test ${l.testNumber}`;i.push({field:{passRate:l.testNumber,...l.name?{name:l.name}:{}},label:`${w} \xB7 ${l.testNumber} pass rate`,name:`${w} pass rate`,group:"Pass rates",kind:"numeric",level:"die",categorical:!1})}const c=l=>s.some(l),o=(l,b,w)=>i.push({field:{builtin:l},label:Ee[l],name:Ee[l],group:"Die",kind:b,level:"die",categorical:w});c(l=>nt(l))&&(o("x","numeric",!1),o("y","numeric",!1)),e.some(l=>l.wafer)&&c(l=>nt(l)&&l.physX!==void 0)&&o("radius","numeric",!1);const m=c(l=>nt(l));for(const l of un)e.some(b=>je[l].available({wafer:b.wafer,ringCount:b.ringCount},m))&&o(l,"categorical",!0);c(l=>l.hbin!==void 0)&&o("hbin","categorical",!0),c(l=>l.sbin!==void 0)&&o("sbin","categorical",!0),c(l=>l.siteNum!==void 0)&&o("site","categorical",!0),s.length&&Vt(a.filter(l=>n.has(l.testNumber))).length&&o("pat","categorical",!0);const p=(l,b,w)=>i.push({field:{builtin:l},label:Ee[l],name:Ee[l],group:"Wafer",kind:b,level:"wafer",categorical:w});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 l of Rt(e.map(b=>({metadata:b.metadata,dieCount:b.dies.length})),{facetableOnly:!0,curation:t.curation})){if(l.values.length===0)continue;const b=J({meta:l.key},d);i.push({field:{meta:l.key},label:l.label||bt(l.key,t.curation),name:l.label||bt(l.key,t.curation),group:"Wafer",kind:b.kind,level:"wafer",categorical:!0,distinct:l.values.length})}return i}export function fieldExtent(e,t,i={}){const s=J(e,{items:t,rows:ge(t),ctx:i});if(s.issue||!s.num)return;let n=1/0,a=-1/0;for(let r=0;r<s.num.length;r++){const f=s.num[r];Number.isFinite(f)&&(f<n&&(n=f),f>a&&(a=f))}return n===1/0?void 0:[n,a]}export function fieldValues(e,t,i={}){const s=J(e,{items:t,rows:ge(t),ctx:i});if(s.issue||!s.cat)return[];const n=[];for(const a of s.cat)a!==void 0&&!n.includes(a)&&n.push(a);return Ue(e,n,Ye(s))}export function fieldsForRole(e,t,i){if(t==="control"&&i==="x")return e.filter(n=>n.kind==="numeric"&&n.level==="wafer");const s=i==="y"||i==="x"&&(t==="scatter"||t==="line"||t==="histogram");return i==="color"?e.filter(n=>n.categorical||t==="scatter"&&n.kind==="numeric"):s?e.filter(n=>n.kind==="numeric"&&(i==="y"||n.group!=="Pass rates")):e.filter(n=>n.categorical)}export function defaultPlot(e,t){const i=e.filter(s=>s.group==="Tests"&&"test"in s.field);return i.length>=2?{id:t,chart:"scatter",fields:{x:i[0].field,y:i[1].field}}:i.length===1?{id:t,chart:"histogram",fields:{y:i[0].field}}:{id:t,chart:"scatter",fields:{x:{builtin:"waferOrder"},y:{builtin:"yield"}}}}const St=new Set(["wafer","dies","die x","die y","wafer order"]),si=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ft=(e,t)=>t.length>=3&&new RegExp(`(^|[^A-Za-z0-9_])${si(t)}($|[^A-Za-z0-9_])`,"i").test(e);export function titleDrift(e,t){const i=e.title?.trim(),s={names:[],omits:[]};if(!i)return s;const n=e.fields?.color,a=[...ke(e.fields?.x),e.fields?.y,n,e.fields?.facet].filter(l=>Ce(l)),r=l=>a.some(b=>Fe(b,l)),f=t.filter(l=>!St.has(l.name.toLowerCase())&&!("meta"in l.field)&&!r(l.field)&&Ft(i,l.name)).map(l=>l.name),c=[...ke(e.fields?.x),e.fields?.y].filter(l=>Ce(l)),o=l=>t.find(b=>Fe(b.field,l))?.name??fieldLabel(l),m=c.filter(l=>!St.has(o(l).toLowerCase())&&Ft(i,o(l))),p=c.filter(l=>!St.has(o(l).toLowerCase())&&!Ft(i,o(l))),d=m.length>0||f.length>0?p.map(o):[];return{names:f,omits:d}}export function describeTitleDrift(e){const t=[];return e.names.length&&t.push(`The title names ${ue(e.names)}, which this plot does not show.`),e.omits.length&&t.push(`It does not name ${ue(e.omits)}, which this plot shows.`),t.length?t.join(" "):null}function ai(e,t={}){const i=ge(e),s=J({builtin:"ring"},{items:e,rows:i,ctx:t});if(s.issue||!s.cat)return;const n=new Map;let a=0,r=0;for(let o=0;o<i.dies.length;o++){const m=s.cat[o];if(m===void 0)continue;const p=yt([i.dies[o]],e[i.item[o]].passBins),d=n.get(m)??{pass:0,total:0};d.pass+=p.pass,d.total+=p.total,a+=p.pass,r+=p.total,n.set(m,d)}let f,c=r?a/r*100-1:-1/0;for(const[o,m]of n)m.total&&m.pass/m.total*100<c&&(c=m.pass/m.total*100,f=o);return f}function oi(e,t){if(!t||e.length<2)return e[0];const i=ge(t.items);let s=e[0],n=1/0;for(const a of e){const r=J({passRate:a.d.testNumber},{items:t.items,rows:i,ctx:t.ctx??{}});if(!r.num||!r.weights)continue;let f=0,c=0;for(let o=0;o<r.num.length;o++)r.weights[o]&&(c++,f+=r.num[o]/100);c&&f/c<n&&(n=f/c,s=a)}return s}export function examplePlots(e,t,i,s){const n=e.filter(u=>u.group==="Tests"&&"test"in u.field),a=e.flatMap(u=>"meta"in u.field?[u.field.meta]:[]),r=s?Nn(s.items,n.map(u=>u.field.test),a,s.ctx?.curation):void 0,f=new Map(n.map(u=>[u.field.test,u])),c=r?[...r.ranked.map(u=>f.get(u)).filter(Boolean).filter(u=>u.field.test!==r.partner)]:n;r?.partner!==void 0&&c.length&&c.splice(1,0,f.get(r.partner));const o=c.map(u=>u.field),m=[],p=t>1,d=u=>e.some(ae=>"builtin"in ae.field&&ae.field.builtin===u),l=(r?.splitKey?e.find(u=>"meta"in u.field&&u.field.meta===r.splitKey):void 0)??e.find(u=>"meta"in u.field&&u.distinct!==void 0&&u.distinct>=2&&u.distinct<=Math.max(2,Math.floor(t/2))),b=u=>m.push({id:i(),...u}),w=c.length>=2?{tests:c.slice(0,8).map(u=>u.field.test),names:Object.fromEntries(c.slice(0,8).map(u=>[String(u.field.test),u.name]))}:void 0,g=l?.field,O=g??(d("ring")?{builtin:"ring"}:void 0),v={color:O??{none:!0}},k={color:g??{none:!0}};o.length>=2&&b({chart:"scatter",fields:{x:o[0],y:o[1],...g?{color:g}:{}},fit:"linear"}),o.length>=1&&b({chart:"histogram",fields:{y:o[0],...v},normalCurve:!0,...O?{histNorm:"percent"}:{}}),o.length>=1&&p&&b({chart:"box",fields:{x:{builtin:"wafer"},y:o[0],...k},axes:{y:{references:[{stat:"median"}]}}}),p&&b({chart:"bar",fields:{x:g??{builtin:"wafer"},y:{builtin:"yield"},color:g??{none:!0}},valueLabels:!0,axes:{y:{references:[{stat:"median"}]}}});const _=p&&d("ring")&&s?ai(s.items,s.ctx):void 0;_&&b({chart:"bar",fields:{x:{builtin:"wafer"},y:{builtin:"yield"},color:{none:!0}},where:{conditions:[{field:{builtin:"ring"},values:[_]}]}}),o.length>=1&&p&&t<5&&b({chart:"line",fields:{x:{builtin:"waferOrder"},y:o[0],color:{none:!0}},aggregate:"mean",spread:"sd"}),o.length>=1&&b({chart:"probability",fields:{y:o[0],...k}});const B=s?.ctx?.testDefs??[],W=o.flatMap(u=>{const ae="test"in u?B.find(ye=>ye.testNumber===u.test):void 0;return ae&&be(ae)?[{f:u,d:ae}]:[]}),D=W.filter(({d:u})=>u.limitLow!==void 0&&u.limitHigh!==void 0).slice(0,8),Q=D.length>=2?{tests:D.map(({f:u})=>u.test),names:Object.fromEntries(D.filter(({d:u})=>u.name).map(({f:u,d:ae})=>[String(u.test),ae.name]))}:void 0;Q?b({chart:"box",fields:{x:{builtin:"test"},y:Q,...k},normalize:"limits"}):w&&b({chart:"box",fields:{x:{builtin:"test"},y:w,...k},normalize:"zscore"}),w&&p&&b({chart:"heatmap",fields:{x:{builtin:"wafer"},y:w},aggregate:"mean",normalize:"zscore"}),o.length>=1&&g&&b({chart:"box",fields:{x:g,y:o[0],color:g}}),o.length>=1&&g&&b({chart:"box",fields:{x:[g,{builtin:"wafer"}],y:o[0],color:g}}),o.length>=1&&d("ring")&&b({chart:"histogram",fields:{y:o[0],...k,facet:{builtin:"ring"}}}),o.length>=2&&b({chart:"box",fields:{x:{binned:o[1],bins:5},y:o[0],...v}}),o.length>=1&&d("radius")&&b({chart:"box",fields:{x:{binned:{builtin:"radius"},bins:6,by:"width"},y:o[0],...k}}),d("hbin")&&b({chart:"bar",fields:{x:{builtin:"hbin"},color:{none:!0}},sort:"value",cumulative:!0}),d("hbin")&&p&&b({chart:"bar",fields:{x:{builtin:"wafer"},color:{builtin:"hbin"}},stack:"percent"}),o.length>=1&&d("pat")&&b({chart:"box",fields:{x:{builtin:"pat"},y:o[0],color:{builtin:"pat"}}});const se=e.find(u=>u.group==="Verdicts");o.length>=1&&se&&b({chart:"box",fields:{x:se.field,y:o[0],color:se.field}}),o.length>=1&&t>=5&&b({chart:"control",fields:{x:{builtin:"waferOrder"},y:o[0]}}),W.some(({d:u})=>u.limitLow!==void 0&&u.limitHigh!==void 0)&&b({chart:"goal",fields:l?{color:l.field}:{}});const P=W.filter(({d:u})=>u.limitLow!==void 0||u.limitHigh!==void 0).slice(0,8);P.length>=2&&p&&b({chart:"heatmap",fields:{x:l?l.field:{builtin:"wafer"},y:{tests:P.map(({f:u})=>u.test),passRate:!0,names:Object.fromEntries(P.filter(({d:u})=>u.name).map(({f:u,d:ae})=>[String(u.test),ae.name]))}},aggregate:"mean"});const E=oi(W.filter(({d:u})=>u.limitLow!==void 0||u.limitHigh!==void 0).slice(0,8),s);if(E&&p&&b({chart:"bar",fields:{x:l?l.field:{builtin:"wafer"},y:{passRate:E.f.test,...E.d.name?{name:E.d.name}:{}},color:{none:!0}}}),E&&E.d.limitLow!==void 0&&E.d.limitHigh!==void 0){const u=(E.d.limitHigh-E.d.limitLow)*.1;b({chart:"histogram",fields:{y:E.f,color:{none:!0}},whatIf:{lo:E.d.limitLow-u,hi:E.d.limitHigh+u}})}return o.length>=2&&m.push({...tn(n.map(u=>u.field).flatMap(u=>"test"in u?[u]:[]),i()),title:"Example sweep"}),m}export function plotTestNumber(e){const{x:t,y:i,color:s}=e.fields??{},n=e.chart==="scatter"?[t,i,s]:e.chart==="histogram"||e.chart==="probability"?[i,t]:[i];for(const a of n){if(Ce(a)&&"test"in a)return a.test;if(le(a)){const r=a.tests[0],f=typeof r=="number"?r:parseInt(String(r),10);if(Number.isInteger(f))return f;continue}if(Ce(a)&&"passRate"in a)return a.passRate}}export function defaultSweep(e,t){return tn(e.filter(be).map(i=>({test:i.testNumber,name:i.name})),t)}function tn(e,t){const i=[...e].sort((n,a)=>n.test-a.test).slice(0,5),s=Object.fromEntries(i.flatMap(n=>n.name?[[String(n.test),n.name]]:[]));return{id:t,chart:"sweep",sweep:{series:[{label:"Series 1",tests:i.map(n=>n.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 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}:{}}]}}}
@@ -9,7 +9,7 @@ export declare const SWEEPS_FORMAT = "tsmap-sweeps";
9
9
  export type SweepPayload = Omit<SweepSpec, 'id' | 'title'>;
10
10
  export declare const PLOT_CHARTS: readonly ["scatter", "histogram", "box", "bar", "line", "sweep", "probability", "control", "goal", "heatmap"];
11
11
  export type PlotChart = (typeof PLOT_CHARTS)[number];
12
- export declare const PLOT_BUILTINS: readonly ["wafer", "x", "y", "ring", "quadrant", "reticleCell", "reticleShot", "hbin", "sbin", "site", "yield", "dieCount", "waferOrder", "test", "pat", "radius"];
12
+ export declare const PLOT_BUILTINS: readonly ["wafer", "x", "y", "ring", "quadrant", "reticleCell", "reticleShot", "hbin", "sbin", "site", "yield", "dieCount", "waferOrder", "test", "pat", "radius", "reprobed"];
13
13
  export type PlotBuiltin = (typeof PLOT_BUILTINS)[number];
14
14
  /** A series a plot can put on an axis or use for colour. */
15
15
  export type PlotField =
@@ -137,6 +137,25 @@ export declare const PLOT_NORMALIZE: readonly ["limits", "zscore", "robust"];
137
137
  * outliers do not set the scale.
138
138
  */
139
139
  export type PlotNormalize = (typeof PLOT_NORMALIZE)[number];
140
+ /**
141
+ * Every setting that takes one of a few words, and the words. The reader checks a plot against this table and the plot
142
+ * editor's JSON tab suggests from it, so the two cannot disagree about what is allowed.
143
+ */
144
+ export declare const PLOT_CHOICES: {
145
+ readonly chart: readonly ["scatter", "histogram", "box", "bar", "line", "sweep", "probability", "control", "goal", "heatmap"];
146
+ readonly level: readonly ["die", "wafer"];
147
+ readonly aggregate: readonly ["mean", "median", "min", "max", "sum", "count", "yield"];
148
+ readonly limits: readonly ["both", "test", "spec", "none"];
149
+ readonly normalize: readonly ["limits", "zscore", "robust"];
150
+ readonly stack: readonly ["stack", "percent"];
151
+ readonly sort: readonly ["value", "ascending"];
152
+ readonly barNorm: readonly ["count", "percent"];
153
+ readonly histNorm: readonly ["count", "percent"];
154
+ readonly orientation: readonly ["vertical", "horizontal"];
155
+ readonly spread: readonly ["sd", "ci95", "iqr", "minmax"];
156
+ readonly fit: readonly ["linear", "orthogonal"];
157
+ readonly probabilityAxis: readonly ["normal", "linear"];
158
+ };
140
159
  /**
141
160
  * One condition of a filter. A category field keeps the units whose value is one of `values`; a number keeps those
142
161
  * from `min` to `max` inclusive, either end open. `not` keeps everything else. A unit with no value for the field
@@ -251,6 +270,14 @@ export interface PlotSpec {
251
270
  where?: PlotFilter;
252
271
  /** Rescale the measured values on Y, each test on its own. Absent = the values as measured. */
253
272
  normalize?: PlotNormalize;
273
+ /**
274
+ * The gradient of a continuous colour (a heatmap's cells, a scatter coloured by a value): a name from the plot's own
275
+ * gradients (`diverging`, `rating`) or a map's value gradient (`default`, `cividis`, `plasma`, `traffic`…). Absent = `diverging` for a value rescaled around zero,
276
+ * else the map's default.
277
+ */
278
+ colorGradient?: string;
279
+ /** Flip that gradient, so the high end takes the colour the low end had. */
280
+ colorReverse?: boolean;
254
281
  /** The definition of a `sweep` chart: ordered runs of tests read as curves. Such a plot has no `fields`. */
255
282
  sweep?: SweepPayload;
256
283
  }
@@ -272,6 +299,8 @@ export declare function sameField(a: PlotField | undefined, b: PlotField | undef
272
299
  /** A field that names several tests. */
273
300
  export declare const isTestSet: (f: unknown) => f is PlotTestSet;
274
301
  export declare function isField(v: unknown): v is PlotField;
302
+ /** The option `given` was most likely meant to be (another case, or a slip of a letter or two), or undefined. */
303
+ export declare function nearest(given: string, options: readonly string[]): string | undefined;
275
304
  /**
276
305
  * A filter from a file: `{ conditions, off }`. A single condition written without the list (`{ field, values }`) is read
277
306
  * as a list of one. A condition that cannot be read is named and left out; a filter left with none is no filter.
@@ -290,7 +319,7 @@ export declare function plotToSweep(plot: PlotSpec): SweepSpec | undefined;
290
319
  * One plot from parsed JSON, or `null` when it cannot be a plot at all (no chart). Unknown keys survive; a
291
320
  * setting that is wrong is dropped with a warning and the rest of the plot is kept.
292
321
  */
293
- export declare function readPlot(raw: unknown, where: string, warnings: string[]): PlotSpec | null;
322
+ export declare function readPlot(given: unknown, where: string, warnings: string[]): PlotSpec | null;
294
323
  /** Offset of a JSON syntax error as line and column, where the engine's message states a position. */
295
324
  export declare function syntaxErrorAt(text: string, message: string): string;
296
325
  /**
@@ -1,4 +1,4 @@
1
- import{newPlotId as m}from"./plotId.js";export{m as newPlotId};export const PLOTS_FORMAT="wafermap-plots",PLOTS_VERSION=1,SWEEPS_FORMAT="tsmap-sweeps",PLOT_CHARTS=["scatter","histogram","box","bar","line","sweep","probability","control","goal","heatmap"],PLOT_BUILTINS=["wafer","x","y","ring","quadrant","reticleCell","reticleShot","hbin","sbin","site","yield","dieCount","waferOrder","test","pat","radius"],PLOT_JUDGES=["limits","flag"],isPassRateSet=e=>isTestSet(e)&&e.passRate===!0,PLOT_BIN_BY=["count","width"],PLOT_BINS_MIN=2,PLOT_BINS_MAX=20,PLOT_BINS_DEFAULT=5,isBinned=e=>r(e)&&"binned"in e,PLOT_REFERENCES_MAX=8,PLOT_REFERENCE_STATS=["median","mean"],isStatReference=e=>"stat"in e,PLOT_AGGREGATES=["mean","median","min","max","sum","count","yield"],PLOT_LIMITS=["both","test","spec","none"],PLOT_NORMALIZE=["limits","zscore","robust"];export function plotConditions(e){const t=e.where;return t&&!t.off?t.conditions:[]}const r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),p=e=>typeof e=="number"&&Number.isFinite(e),A=/^\s*\d+\s*(\.\.\s*\d+\s*)?$/,b=e=>typeof e=="number"&&Number.isInteger(e)||typeof e=="string"&&A.test(e);export const PLOT_FACET_LIMIT=24,PLOT_X_LEVELS=3,xFieldsOf=e=>e===void 0?[]:Array.isArray(e)?e:[e];export function sameField(e,t){return!e||!t?e===t:isBinned(e)||isBinned(t)?isBinned(e)&&isBinned(t)&&sameField(e.binned,t.binned):"test"in e?"test"in t&&e.test===t.test:"builtin"in e?"builtin"in t&&e.builtin===t.builtin:"tests"in e?"tests"in t&&!!e.passRate==!!t.passRate&&(e.judge??"limits")===(t.judge??"limits")&&e.tests.length===t.tests.length&&e.tests.every((i,o)=>String(i)===String(t.tests[o])):"passRate"in e?"passRate"in t&&!("tests"in t)&&e.passRate===t.passRate&&(e.judge??"limits")===(t.judge??"limits"):"meta"in t&&e.meta===t.meta}export const isTestSet=e=>r(e)&&"tests"in e&&Array.isArray(e.tests);export function isField(e){return r(e)?"binned"in e?isField(e.binned)&&!isBinned(e.binned)&&!isTestSet(e.binned)&&!("passRate"in e.binned):"test"in e?Number.isInteger(e.test):"builtin"in e?PLOT_BUILTINS.includes(e.builtin):"meta"in e?typeof e.meta=="string"&&e.meta!=="":"tests"in e?Array.isArray(e.tests)&&e.tests.length>0&&e.tests.every(b):"passRate"in e?Number.isInteger(e.passRate)&&(e.judge===void 0||PLOT_JUDGES.includes(e.judge)):!1:!1}function x(e,t,i){"judge"in e&&!PLOT_JUDGES.includes(e.judge)&&(i.push(`${t}.judge: "${String(e.judge)}" is not limits or flag, left out`),delete e.judge)}function a(e,t,i){if(e!==void 0){if(!r(e)){i.push(`${t}: not a field, left out`);return}if("binned"in e){const o=a(e.binned,`${t}.binned`,i);if(!o||isBinned(o)||isTestSet(o)||"passRate"in o){o&&i.push(`${t}: only one test or value can be binned, left out`);return}const n={...e,binned:o};return"bins"in e&&!(Number.isInteger(e.bins)&&e.bins>=PLOT_BINS_MIN&&e.bins<=PLOT_BINS_MAX)&&(i.push(`${t}.bins: ${JSON.stringify(e.bins)} is not a whole number from ${PLOT_BINS_MIN} to ${PLOT_BINS_MAX}, left out`),delete n.bins),"by"in e&&!PLOT_BIN_BY.includes(e.by)&&(i.push(`${t}.by: "${String(e.by)}" is not count or width, left out`),delete n.by),n}if("test"in e){if(!Number.isInteger(e.test)){i.push(`${t}: test number ${JSON.stringify(e.test)} is not an integer, left out`);return}const o={...e,test:e.test};return typeof e.name=="string"&&e.name!==""?o.name=e.name:delete o.name,o}if("builtin"in e)return PLOT_BUILTINS.includes(e.builtin)?{...e,builtin:e.builtin}:e;if("meta"in e){if(typeof e.meta!="string"||e.meta===""){i.push(`${t}: metadata key is empty, left out`);return}return{...e,meta:e.meta}}if("passRate"in e&&!("tests"in e)){if(!Number.isInteger(e.passRate)){i.push(`${t}: pass-rate test ${JSON.stringify(e.passRate)} is not an integer, left out`);return}const o={...e};return typeof e.name=="string"&&e.name!==""||delete o.name,x(o,t,i),o}if("tests"in e){if(!Array.isArray(e.tests)||e.tests.length===0||!e.tests.every(b)){i.push(`${t}: its tests must be test numbers or ranges such as "1010..1030", left out`);return}const o={...e,tests:e.tests};return"passRate"in e&&e.passRate!==!0&&(i.push(`${t}.passRate: not true, left out`),delete o.passRate),x(o,t,i),"names"in e&&!(r(e.names)&&Object.values(e.names).every(n=>typeof n=="string"))&&(i.push(`${t}.names: not a list of names, left out`),delete o.names),o}return e}}export function readFilter(e,t,i){const o=Array.isArray(e.conditions)?e.conditions:"field"in e?[{field:e.field,values:e.values}]:[],n=[];if(o.forEach((c,$)=>{const h=Array.isArray(e.conditions)?`${t}.conditions[${$}]`:t,y=S(c,h,i);y&&n.push(y)}),n.length===0)return;const{field:f,values:s,conditions:l,...u}=e,d={...u,conditions:n};return"off"in e&&typeof e.off!="boolean"&&(i.push(`${t}.off: not true or false, left out`),delete d.off),d}function S(e,t,i){if(!r(e)){i.push(`${t}: not a condition, left out`);return}const o=a(e.field,`${t}.field`,i);if(!o)return;const n={...e,field:o};if("values"in e){const f=Array.isArray(e.values)?e.values.filter(s=>typeof s=="string"):[];f.length?n.values=f:(i.push(`${t}.values: not a list of values, left out`),delete n.values)}for(const f of["min","max"])f in e&&!p(e[f])&&(i.push(`${t}.${f}: not a number, left out`),delete n[f]);if(n.min!==void 0&&n.max!==void 0&&n.min>n.max&&(i.push(`${t}: min is above max, the range left out`),delete n.min,delete n.max),"not"in e&&typeof e.not!="boolean"&&(i.push(`${t}.not: not true or false, left out`),delete n.not),!n.values&&n.min===void 0&&n.max===void 0){i.push(`${t}: needs values or a range, left out`);return}return n}function g(e,t,i){if(e===void 0)return;if(!r(e)){i.push(`${t}: not an object, left out`);return}const o={...e};"label"in e&&typeof e.label!="string"&&(i.push(`${t}.label: not text, left out`),delete o.label),"scale"in e&&e.scale!=="linear"&&e.scale!=="log"&&(i.push(`${t}.scale: "${String(e.scale)}" is not linear or log, left out`),delete o.scale);for(const n of["min","max"])n in e&&!p(e[n])&&(i.push(`${t}.${n}: not a number, left out`),delete o[n]);for(const n of["reverse","includeLimits","clip"])n in e&&typeof e[n]!="boolean"&&(i.push(`${t}.${n}: not true or false, left out`),delete o[n]);if("references"in e){const n=[],f=Array.isArray(e.references)?e.references:[];Array.isArray(e.references)||i.push(`${t}.references: not a list, left out`),f.forEach((s,l)=>{const u=r(s)&&(s.label===void 0||typeof s.label=="string"),d=u&&p(s.at)&&(s.to===void 0||p(s.to)&&s.to!==s.at),c=u&&!d&&PLOT_REFERENCE_STATS.includes(s.stat);d||c?n.length<PLOT_REFERENCES_MAX?n.push(d?{...s,at:s.at,...s.to!==void 0?{to:s.to}:{}}:{...s}):i.push(`${t}.references[${l}]: more than ${PLOT_REFERENCES_MAX}, left out`):i.push(`${t}.references[${l}]: needs a number (and a different number for a band), or median or mean, left out`)}),n.length?o.references=n:delete o.references}return o}export function readSweepPayload(e,t,i){if(!r(e))return i.push(`${t}: no sweep definition, left empty`),{series:[]};const o={...e};delete o.id,delete o.title;const n=Array.isArray(e.series)?e.series:[];Array.isArray(e.series)||i.push(`${t}.series: not a list, left empty`);const f=[];n.forEach((s,l)=>{const u=`${t}.series ${l+1}`;if(!r(s)){i.push(`${u}: not an object, skipped`);return}const d={...s};if((typeof s.label!="string"||s.label.trim()==="")&&(d.label=`Series ${l+1}`),!Array.isArray(s.tests)||!s.tests.every(b)){i.push(`${u}: its tests must be test numbers or ranges such as "1010..1030", skipped`);return}"xValues"in s&&!(Array.isArray(s.xValues)&&s.xValues.every(p))&&(i.push(`${u}.xValues: not a list of numbers, left out`),delete d.xValues),"xFromName"in s&&typeof s.xFromName!="string"&&(i.push(`${u}.xFromName: not text, left out`),delete d.xFromName),"color"in s&&typeof s.color!="string"&&delete d.color,"testNames"in s&&!(r(s.testNames)&&Object.values(s.testNames).every(c=>typeof c=="string"))&&(i.push(`${u}.testNames: not a list of names, left out`),delete d.testNames),f.push(d)}),o.series=f;for(const s of["xLabel","xUnit","yLabel"])s in e&&typeof e[s]!="string"&&(i.push(`${t}.${s}: not text, left out`),delete o[s]);return"xScale"in e&&e.xScale!=="linear"&&e.xScale!=="log"&&(i.push(`${t}.xScale: "${String(e.xScale)}" is not linear or log, left out`),delete o.xScale),"crossing"in e&&typeof e.crossing!="boolean"&&(i.push(`${t}.crossing: not true or false, left out`),delete o.crossing),"separationAt"in e&&!(Array.isArray(e.separationAt)&&e.separationAt.every(p))&&(i.push(`${t}.separationAt: not a list of numbers, left out`),delete o.separationAt),o}export function sweepToPlot(e){const{id:t,title:i,...o}=e;return{id:t,...i?{title:i}:{},chart:"sweep",sweep:o}}export function plotToSweep(e){if(e.chart==="sweep")return{...e.sweep??{series:[]},id:e.id,title:e.title??"Sweep"}}export function readPlot(e,t,i){if(!r(e))return i.push(`${t}: not an object, skipped`),null;const o=e.chart;if(typeof o!="string"||o==="")return i.push(`${t}: no chart, skipped`),null;const n={...e};(typeof e.id!="string"||e.id==="")&&(n.id=m(),i.push(`${t}: no id, given a new one`)),"title"in e&&typeof e.title!="string"?(i.push(`${t}.title: not text, left out`),delete n.title):typeof e.title=="string"&&e.title.trim()===""&&delete n.title;const f=r(e.fields)?e.fields:{};e.fields!==void 0&&!r(e.fields)&&i.push(`${t}.fields: not an object, left empty`);const s={...f};for(const l of["x","y"]){if(l==="x"&&Array.isArray(f.x)){const d=f.x.map((c,$)=>a(c,`${t}.fields.x ${$+1}`,i)).filter(c=>!!c);d.length?s.x=d:delete s.x;continue}const u=a(f[l],`${t}.fields.${l}`,i);u?s[l]=u:delete s[l]}if(f.rows!==void 0){const l=a(f.rows,`${t}.fields.rows`,i);l?s.rows=l:delete s.rows}if(f.facet!==void 0){const l=a(f.facet,`${t}.fields.facet`,i);l?s.facet=l:delete s.facet}if(f.color!==void 0){const l=f.color;if(r(l)&&"follow"in l)l.follow==="groupBy"?s.color={follow:"groupBy"}:s.color=l;else if(r(l)&&"none"in l)s.color={none:!0};else{const u=a(l,`${t}.fields.color`,i);u?s.color=u:delete s.color}}if(o==="sweep"&&Object.keys(s).length===0?delete n.fields:n.fields=s,"level"in e&&e.level!=="die"&&e.level!=="wafer"&&(i.push(`${t}.level: "${String(e.level)}" is not die or wafer, left out`),delete n.level),"aggregate"in e&&!PLOT_AGGREGATES.includes(e.aggregate)&&(i.push(`${t}.aggregate: "${String(e.aggregate)}" is not known to this version, left out`),delete n.aggregate),"where"in e){const l=e.where,u=r(l)?readFilter(l,`${t}.where`,i):void 0;u?n.where=u:(i.push(`${t}.where: needs at least one condition, left out`),delete n.where)}"stack"in e&&e.stack!=="stack"&&e.stack!=="percent"&&(i.push(`${t}.stack: "${String(e.stack)}" is not stack or percent, left out`),delete n.stack),"sort"in e&&e.sort!=="value"&&e.sort!=="ascending"&&(i.push(`${t}.sort: "${String(e.sort)}" is not known to this version, left out`),delete n.sort),"top"in e&&!(Number.isInteger(e.top)&&e.top>=1)&&(i.push(`${t}.top: not a whole number of at least 1, left out`),delete n.top),"baseline"in e&&!(Number.isInteger(e.baseline)&&e.baseline>=3)&&(i.push(`${t}.baseline: not a whole number of at least 3, left out`),delete n.baseline),"fit"in e&&e.fit!=="linear"&&e.fit!=="orthogonal"&&(i.push(`${t}.fit: "${String(e.fit)}" is not linear or orthogonal, left out`),delete n.fit);for(const l of["identity","normalCurve","valueLabels"])l in e&&typeof e[l]!="boolean"&&(i.push(`${t}.${l}: not true or false, left out`),delete n[l]);if("orientation"in e&&e.orientation!=="vertical"&&e.orientation!=="horizontal"&&(i.push(`${t}.orientation: "${String(e.orientation)}" is not vertical or horizontal, left out`),delete n.orientation),"barNorm"in e&&e.barNorm!=="count"&&e.barNorm!=="percent"&&(i.push(`${t}.barNorm: "${String(e.barNorm)}" is not count or percent, left out`),delete n.barNorm),"histNorm"in e&&e.histNorm!=="count"&&e.histNorm!=="percent"&&(i.push(`${t}.histNorm: "${String(e.histNorm)}" is not count or percent, left out`),delete n.histNorm),"whatIf"in e){const l=e.whatIf,u=r(l)&&p(l.lo)?l.lo:void 0,d=r(l)&&p(l.hi)?l.hi:void 0;u===void 0&&d===void 0?(i.push(`${t}.whatIf: needs a low or a high limit, left out`),delete n.whatIf):n.whatIf={...u!==void 0?{lo:u}:{},...d!==void 0?{hi:d}:{}}}if("spread"in e&&!["sd","ci95","iqr","minmax"].includes(e.spread)&&(i.push(`${t}.spread: "${String(e.spread)}" is not known to this version, left out`),delete n.spread),"cumulative"in e&&typeof e.cumulative!="boolean"&&(i.push(`${t}.cumulative: not true or false, left out`),delete n.cumulative),"probabilityAxis"in e&&e.probabilityAxis!=="normal"&&e.probabilityAxis!=="linear"&&(i.push(`${t}.probabilityAxis: "${String(e.probabilityAxis)}" is not normal or linear, left out`),delete n.probabilityAxis),"normalize"in e&&!PLOT_NORMALIZE.includes(e.normalize)&&(i.push(`${t}.normalize: "${String(e.normalize)}" is not known to this version, left out`),delete n.normalize),"limits"in e&&!PLOT_LIMITS.includes(e.limits)&&(i.push(`${t}.limits: "${String(e.limits)}" is not both, test, spec or none, left out`),delete n.limits),"bins"in e&&!(Number.isInteger(e.bins)&&e.bins>=1)&&(i.push(`${t}.bins: not a whole number of at least 1, left out`),delete n.bins),o==="sweep"&&(n.sweep=readSweepPayload(e.sweep,`${t}.sweep`,i)),e.axes!==void 0)if(!r(e.axes))i.push(`${t}.axes: not an object, left out`),delete n.axes;else{const l={...e.axes};for(const u of["x","y"]){const d=g(e.axes[u],`${t}.axes.${u}`,i);d?l[u]=d:delete l[u]}n.axes=l}return n}export function syntaxErrorAt(e,t){const i=/position (\d+)/.exec(t);if(!i)return t;const o=Math.min(Number(i[1]),e.length),n=e.slice(0,o),f=n.split(`
2
- `).length,s=o-(n.lastIndexOf(`
3
- `)+1)+1;return`${t} (line ${f}, column ${s})`}export function readIdentified(e,t,i){const o=[],n=new Set;return e.forEach((f,s)=>{const l=i.labelOf(f,s),u=i.read(f,l,t);u&&(n.has(u.id)&&(u.id=i.newId(),t.push(`${l}: its id was already used, given a new one`)),n.add(u.id),o.push(u))}),o}export function unwrapListFile(e,t){let i;try{i=JSON.parse(e)}catch(f){return{error:`Not valid JSON: ${syntaxErrorAt(e,f instanceof Error?f.message:String(f))}`}}let o;if(Array.isArray(i))o=i;else if(r(i)){const f=t.legacy?.(i);if(typeof f=="string")return{error:f};if(f)o=f;else{if(i.format!==t.format)return{error:`This is not a ${t.noun} file (expected "format": "${t.format}")`};o=i[t.key]}}else return{error:`This is not a ${t.noun} file`};if(!Array.isArray(o))return{error:`The file has no "${t.key}" list`};const n=[];return r(i)&&p(i.version)&&i.version>t.version&&n.push(`Written by a newer version (${i.version}); settings this version does not know are kept but not used`),{list:o,warnings:n}}export function readPlotsFile(e){const t=unwrapListFile(e,{format:PLOTS_FORMAT,noun:"plots",key:"plots",version:PLOTS_VERSION,legacy:f=>{if(f.format===SWEEPS_FORMAT)return Array.isArray(f.sweeps)?f.sweeps.map(s=>r(s)?{id:s.id,title:s.title,chart:"sweep",sweep:s}:s):'The file has no "sweeps" list'}});if("error"in t)return{plots:[],warnings:[],error:t.error};const{list:i,warnings:o}=t,n=readIdentified(i,o,{labelOf:(f,s)=>r(f)&&typeof f.title=="string"&&f.title?`"${f.title}"`:`plot ${s+1}`,read:readPlot,newId:m});return n.length===0&&i.length>0?{plots:n,warnings:o,error:"No plot in the file could be read"}:{plots:n,warnings:o}}export function writePlotsFile(e){return JSON.stringify({format:PLOTS_FORMAT,version:PLOTS_VERSION,plots:e},null,2)+`
4
- `}export function addPlots(e,t){const{items:i,copies:o}=addIdentified(e,t,n=>n.title??n.id,m);return{plots:i,copies:o}}export function addIdentified(e,t,i,o){const n=new Set(e.map(l=>l.id)),f=[],s=t.map(l=>{if(!n.has(l.id))return n.add(l.id),l;const u=o();return n.add(u),f.push(i(l)),{...l,id:u}});return{items:[...e,...s],copies:f}}export function plotIssue(e){if(!PLOT_CHARTS.includes(e.chart))return"Needs a newer version of this tool";const t=e.fields??{};for(const i of[...xFieldsOf(t.x),t.y,t.color,t.facet,t.rows,...e.where?.conditions.map(o=>o.field)??[]])if(!(i===void 0||r(i)&&("follow"in i||"none"in i))&&!isField(i))return"Needs a newer version of this tool"}
1
+ import{newPlotId as b}from"./plotId.js";export{b as newPlotId};export const PLOTS_FORMAT="wafermap-plots",PLOTS_VERSION=1,SWEEPS_FORMAT="tsmap-sweeps",PLOT_CHARTS=["scatter","histogram","box","bar","line","sweep","probability","control","goal","heatmap"],PLOT_BUILTINS=["wafer","x","y","ring","quadrant","reticleCell","reticleShot","hbin","sbin","site","yield","dieCount","waferOrder","test","pat","radius","reprobed"],PLOT_JUDGES=["limits","flag"],isPassRateSet=e=>isTestSet(e)&&e.passRate===!0,PLOT_BIN_BY=["count","width"],PLOT_BINS_MIN=2,PLOT_BINS_MAX=20,PLOT_BINS_DEFAULT=5,isBinned=e=>d(e)&&"binned"in e,PLOT_REFERENCES_MAX=8,PLOT_REFERENCE_STATS=["median","mean"],isStatReference=e=>"stat"in e,PLOT_AGGREGATES=["mean","median","min","max","sum","count","yield"],PLOT_LIMITS=["both","test","spec","none"],PLOT_NORMALIZE=["limits","zscore","robust"],PLOT_CHOICES={chart:PLOT_CHARTS,level:["die","wafer"],aggregate:PLOT_AGGREGATES,limits:PLOT_LIMITS,normalize:PLOT_NORMALIZE,stack:["stack","percent"],sort:["value","ascending"],barNorm:["count","percent"],histNorm:["count","percent"],orientation:["vertical","horizontal"],spread:["sd","ci95","iqr","minmax"],fit:["linear","orthogonal"],probabilityAxis:["normal","linear"]};const O=e=>e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`;export function plotConditions(e){const t=e.where;return t&&!t.off?t.conditions:[]}const d=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),m=e=>typeof e=="number"&&Number.isFinite(e),T=/^\s*\d+\s*(\.\.\s*\d+\s*)?$/,h=e=>typeof e=="number"&&Number.isInteger(e)||typeof e=="string"&&T.test(e);export const PLOT_FACET_LIMIT=24,PLOT_X_LEVELS=3,xFieldsOf=e=>e===void 0?[]:Array.isArray(e)?e:[e];export function sameField(e,t){return!e||!t?e===t:isBinned(e)||isBinned(t)?isBinned(e)&&isBinned(t)&&sameField(e.binned,t.binned):"test"in e?"test"in t&&e.test===t.test:"builtin"in e?"builtin"in t&&e.builtin===t.builtin:"tests"in e?"tests"in t&&!!e.passRate==!!t.passRate&&(e.judge??"limits")===(t.judge??"limits")&&e.tests.length===t.tests.length&&e.tests.every((n,i)=>String(n)===String(t.tests[i])):"passRate"in e?"passRate"in t&&!("tests"in t)&&e.passRate===t.passRate&&(e.judge??"limits")===(t.judge??"limits"):"meta"in t&&e.meta===t.meta}export const isTestSet=e=>d(e)&&"tests"in e&&Array.isArray(e.tests);export function isField(e){return d(e)?"binned"in e?isField(e.binned)&&!isBinned(e.binned)&&!isTestSet(e.binned)&&!("passRate"in e.binned):"test"in e?Number.isInteger(e.test):"builtin"in e?PLOT_BUILTINS.includes(e.builtin):"meta"in e?typeof e.meta=="string"&&e.meta!=="":"tests"in e?Array.isArray(e.tests)&&e.tests.length>0&&e.tests.every(h):"passRate"in e?Number.isInteger(e.passRate)&&(e.judge===void 0||PLOT_JUDGES.includes(e.judge)):!1:!1}function A(e,t,n){"judge"in e&&!PLOT_JUDGES.includes(e.judge)&&(n.push(`${t}.judge: "${String(e.judge)}" is not limits or flag, left out`),delete e.judge)}export function nearest(e,t){const n=e.toLowerCase(),i=t.find(f=>f.toLowerCase()===n);if(i)return i;const o=(f,s)=>{let u=Array.from({length:s.length+1},(c,a)=>a);for(let c=1;c<=f.length;c++){const a=[c];for(let p=1;p<=s.length;p++)a[p]=Math.min(u[p]+1,a[p-1]+1,u[p-1]+(f[c-1]===s[p-1]?0:1));u=a}return u[s.length]};let r,l=3;for(const f of t){const s=o(n,f.toLowerCase());s<l&&(r=f,l=s)}return r}const $=(e,t)=>{const n=typeof e=="string"?nearest(e,t):void 0;return n?` Did you mean "${n}"?`:""},g={id:!0,title:!0,chart:!0,fields:!0,level:!0,aggregate:!0,axes:!0,bins:!0,limits:!0,probabilityAxis:!0,stack:!0,sort:!0,top:!0,barNorm:!0,orientation:!0,valueLabels:!0,cumulative:!0,spread:!0,fit:!0,identity:!0,histNorm:!0,normalCurve:!0,whatIf:!0,baseline:!0,where:!0,normalize:!0,sweep:!0,colorGradient:!0,colorReverse:!0},S={x:!0,y:!0,color:!0,rows:!0,facet:!0},N='{ "test": 1050 }, { "builtin": "wafer" } or { "meta": "split" }';function y(e,t,n){if(e!==void 0){if(!d(e)){n.push(`${t}: not a field, left out. A field is written like ${N}`);return}if("binned"in e){const i=y(e.binned,`${t}.binned`,n);if(!i||isBinned(i)||isTestSet(i)||"passRate"in i){i&&n.push(`${t}: only one test or value can be binned, left out`);return}const o={...e,binned:i};return"bins"in e&&!(Number.isInteger(e.bins)&&e.bins>=PLOT_BINS_MIN&&e.bins<=PLOT_BINS_MAX)&&(n.push(`${t}.bins: ${JSON.stringify(e.bins)} is not a whole number from ${PLOT_BINS_MIN} to ${PLOT_BINS_MAX}, left out`),delete o.bins),"by"in e&&!PLOT_BIN_BY.includes(e.by)&&(n.push(`${t}.by: "${String(e.by)}" is not count or width, left out`),delete o.by),o}if("test"in e){if(!Number.isInteger(e.test)){n.push(`${t}: test number ${JSON.stringify(e.test)} is not an integer, left out${typeof e.test=="string"?" (write the number without quotes)":""}`);return}const i={...e,test:e.test};return typeof e.name=="string"&&e.name!==""?i.name=e.name:delete i.name,i}if("builtin"in e)return PLOT_BUILTINS.includes(e.builtin)?{...e,builtin:e.builtin}:e;if("meta"in e){if(typeof e.meta!="string"||e.meta===""){n.push(`${t}: metadata key is empty, left out`);return}return{...e,meta:e.meta}}if("passRate"in e&&!("tests"in e)){if(!Number.isInteger(e.passRate)){n.push(`${t}: pass-rate test ${JSON.stringify(e.passRate)} is not an integer, left out`);return}const i={...e};return typeof e.name=="string"&&e.name!==""||delete i.name,A(i,t,n),i}if("tests"in e){if(!Array.isArray(e.tests)||e.tests.length===0||!e.tests.every(h)){n.push(`${t}: its tests must be test numbers or ranges such as "1010..1030", left out`);return}const i={...e,tests:e.tests};return"passRate"in e&&e.passRate!==!0&&(n.push(`${t}.passRate: not true, left out`),delete i.passRate),A(i,t,n),"names"in e&&!(d(e.names)&&Object.values(e.names).every(o=>typeof o=="string"))&&(n.push(`${t}.names: not a list of names, left out`),delete i.names),i}return e}}export function readFilter(e,t,n){const i=Array.isArray(e.conditions)?e.conditions:"field"in e?[{field:e.field,values:e.values}]:[],o=[];if(i.forEach((c,a)=>{const p=Array.isArray(e.conditions)?`${t}.conditions[${a}]`:t,x=v(c,p,n);x&&o.push(x)}),o.length===0)return;const{field:r,values:l,conditions:f,...s}=e,u={...s,conditions:o};return"off"in e&&typeof e.off!="boolean"&&(n.push(`${t}.off: not true or false, left out`),delete u.off),u}function v(e,t,n){if(!d(e)){n.push(`${t}: not a condition, left out`);return}const i=y(e.field,`${t}.field`,n);if(!i)return;const o={...e,field:i};if("values"in e){const r=Array.isArray(e.values)?e.values.filter(l=>typeof l=="string"):[];r.length?o.values=r:(n.push(`${t}.values: not a list of values, left out`),delete o.values)}for(const r of["min","max"])r in e&&!m(e[r])&&(n.push(`${t}.${r}: not a number, left out`),delete o[r]);if(o.min!==void 0&&o.max!==void 0&&o.min>o.max&&(n.push(`${t}: min is above max, the range left out`),delete o.min,delete o.max),"not"in e&&typeof e.not!="boolean"&&(n.push(`${t}.not: not true or false, left out`),delete o.not),!o.values&&o.min===void 0&&o.max===void 0){n.push(`${t}: needs values or a range, left out`);return}return o}function I(e,t,n){if(e===void 0)return;if(!d(e)){n.push(`${t}: not an object, left out`);return}const i={...e};"label"in e&&typeof e.label!="string"&&(n.push(`${t}.label: not text, left out`),delete i.label),"scale"in e&&e.scale!=="linear"&&e.scale!=="log"&&(n.push(`${t}.scale: "${String(e.scale)}" is not linear or log, left out`),delete i.scale);for(const o of["min","max"])o in e&&!m(e[o])&&(n.push(`${t}.${o}: not a number, left out`),delete i[o]);for(const o of["reverse","includeLimits","clip"])o in e&&typeof e[o]!="boolean"&&(n.push(`${t}.${o}: not true or false, left out`),delete i[o]);if("references"in e){const o=[],r=Array.isArray(e.references)?e.references:[];Array.isArray(e.references)||n.push(`${t}.references: not a list, left out`),r.forEach((l,f)=>{const s=d(l)&&(l.label===void 0||typeof l.label=="string"),u=s&&m(l.at)&&(l.to===void 0||m(l.to)&&l.to!==l.at),c=s&&!u&&PLOT_REFERENCE_STATS.includes(l.stat);u||c?o.length<PLOT_REFERENCES_MAX?o.push(u?{...l,at:l.at,...l.to!==void 0?{to:l.to}:{}}:{...l}):n.push(`${t}.references[${f}]: more than ${PLOT_REFERENCES_MAX}, left out`):n.push(`${t}.references[${f}]: needs a number (and a different number for a band), or median or mean, left out`)}),o.length?i.references=o:delete i.references}return i}export function readSweepPayload(e,t,n){if(!d(e))return n.push(`${t}: no sweep definition, left empty`),{series:[]};const i={...e};delete i.id,delete i.title;const o=Array.isArray(e.series)?e.series:[];Array.isArray(e.series)||n.push(`${t}.series: not a list, left empty`);const r=[];o.forEach((l,f)=>{const s=`${t}.series ${f+1}`;if(!d(l)){n.push(`${s}: not an object, skipped`);return}const u={...l};if((typeof l.label!="string"||l.label.trim()==="")&&(u.label=`Series ${f+1}`),!Array.isArray(l.tests)||!l.tests.every(h)){n.push(`${s}: its tests must be test numbers or ranges such as "1010..1030", skipped`);return}"xValues"in l&&!(Array.isArray(l.xValues)&&l.xValues.every(m))&&(n.push(`${s}.xValues: not a list of numbers, left out`),delete u.xValues),"xFromName"in l&&typeof l.xFromName!="string"&&(n.push(`${s}.xFromName: not text, left out`),delete u.xFromName),"color"in l&&typeof l.color!="string"&&delete u.color,"testNames"in l&&!(d(l.testNames)&&Object.values(l.testNames).every(c=>typeof c=="string"))&&(n.push(`${s}.testNames: not a list of names, left out`),delete u.testNames),r.push(u)}),i.series=r;for(const l of["xLabel","xUnit","yLabel"])l in e&&typeof e[l]!="string"&&(n.push(`${t}.${l}: not text, left out`),delete i[l]);return"xScale"in e&&e.xScale!=="linear"&&e.xScale!=="log"&&(n.push(`${t}.xScale: "${String(e.xScale)}" is not linear or log, left out`),delete i.xScale),"crossing"in e&&typeof e.crossing!="boolean"&&(n.push(`${t}.crossing: not true or false, left out`),delete i.crossing),"separationAt"in e&&!(Array.isArray(e.separationAt)&&e.separationAt.every(m))&&(n.push(`${t}.separationAt: not a list of numbers, left out`),delete i.separationAt),i}export function sweepToPlot(e){const{id:t,title:n,...i}=e;return{id:t,...n?{title:n}:{},chart:"sweep",sweep:i}}export function plotToSweep(e){if(e.chart==="sweep")return{...e.sweep??{series:[]},id:e.id,title:e.title??"Sweep"}}function L(e){if(!d(e)||"chart"in e||typeof e.mark!="string")return e;const{mark:t,encoding:n,...i}=e;return{...i,chart:t,...!("fields"in i)&&n!==void 0?{fields:n}:{}}}export function readPlot(e,t,n){const i=L(e);if(!d(i))return n.push(`${t}: not an object, skipped`),null;const o=i.chart;if(typeof o!="string"||o==="")return n.push(`${t}: no chart, skipped`),null;const r={...i};for(const s of Object.keys(i))s in g||n.push(`${t}.${s}: not a setting this version uses, kept.${$(s,Object.keys(g))}`);if(d(i.fields))for(const s of Object.keys(i.fields))s in S||n.push(`${t}.fields.${s}: not a field role this version uses (x, y, color, rows, facet), kept.${$(s,Object.keys(S))}`);(typeof i.id!="string"||i.id==="")&&(r.id=b(),n.push(`${t}: no id, given a new one`)),"title"in i&&typeof i.title!="string"?(n.push(`${t}.title: not text, left out`),delete r.title):typeof i.title=="string"&&i.title.trim()===""&&delete r.title;const l=d(i.fields)?i.fields:{};i.fields!==void 0&&!d(i.fields)&&n.push(`${t}.fields: not an object, left empty`);const f={...l};for(const s of["x","y"]){if(s==="x"&&Array.isArray(l.x)){const c=l.x.map((a,p)=>y(a,`${t}.fields.x ${p+1}`,n)).filter(a=>!!a);c.length?f.x=c:delete f.x;continue}const u=y(l[s],`${t}.fields.${s}`,n);u?f[s]=u:delete f[s]}if(l.rows!==void 0){const s=y(l.rows,`${t}.fields.rows`,n);s?f.rows=s:delete f.rows}if(l.facet!==void 0){const s=y(l.facet,`${t}.fields.facet`,n);s?f.facet=s:delete f.facet}if(l.color!==void 0){const s=l.color;if(d(s)&&"follow"in s)s.follow==="groupBy"?f.color={follow:"groupBy"}:f.color=s;else if(d(s)&&"none"in s)f.color={none:!0};else{const u=y(s,`${t}.fields.color`,n);u?f.color=u:delete f.color}}o==="sweep"&&Object.keys(f).length===0?delete r.fields:r.fields=f;for(const s of Object.keys(PLOT_CHOICES)){if(s==="chart"||!(s in i))continue;const u=PLOT_CHOICES[s];u.includes(i[s])||(n.push(`${t}.${s}: "${String(i[s])}" is not ${O(u)}, left out.${$(i[s],u)}`),delete r[s])}if("where"in i){const s=i.where,u=d(s)?readFilter(s,`${t}.where`,n):void 0;u?r.where=u:(n.push(`${t}.where: needs at least one condition, left out`),delete r.where)}"colorGradient"in i&&!(typeof i.colorGradient=="string"&&i.colorGradient.trim()!=="")&&(n.push(`${t}.colorGradient: not the name of a gradient, left out`),delete r.colorGradient),"top"in i&&!(Number.isInteger(i.top)&&i.top>=1)&&(n.push(`${t}.top: not a whole number of at least 1, left out`),delete r.top),"baseline"in i&&!(Number.isInteger(i.baseline)&&i.baseline>=3)&&(n.push(`${t}.baseline: not a whole number of at least 3, left out`),delete r.baseline);for(const s of["identity","normalCurve","valueLabels","colorReverse"])s in i&&typeof i[s]!="boolean"&&(n.push(`${t}.${s}: not true or false, left out`),delete r[s]);if("whatIf"in i){const s=i.whatIf,u=d(s)&&m(s.lo)?s.lo:void 0,c=d(s)&&m(s.hi)?s.hi:void 0;u===void 0&&c===void 0?(n.push(`${t}.whatIf: needs a low or a high limit, left out`),delete r.whatIf):r.whatIf={...u!==void 0?{lo:u}:{},...c!==void 0?{hi:c}:{}}}if("cumulative"in i&&typeof i.cumulative!="boolean"&&(n.push(`${t}.cumulative: not true or false, left out`),delete r.cumulative),"bins"in i&&!(Number.isInteger(i.bins)&&i.bins>=1)&&(n.push(`${t}.bins: not a whole number of at least 1, left out`),delete r.bins),o==="sweep"&&(r.sweep=readSweepPayload(i.sweep,`${t}.sweep`,n)),i.axes!==void 0)if(!d(i.axes))n.push(`${t}.axes: not an object, left out`),delete r.axes;else{const s={...i.axes};for(const u of["x","y"]){const c=I(i.axes[u],`${t}.axes.${u}`,n);c?s[u]=c:delete s[u]}r.axes=s}return r}export function syntaxErrorAt(e,t){const n=/position (\d+)/.exec(t);if(!n||/line \d+/.test(t))return t;const i=Math.min(Number(n[1]),e.length),o=e.slice(0,i),r=o.split(`
2
+ `).length,l=i-(o.lastIndexOf(`
3
+ `)+1)+1;return`${t} (line ${r}, column ${l})`}export function readIdentified(e,t,n){const i=[],o=new Set;return e.forEach((r,l)=>{const f=n.labelOf(r,l),s=n.read(r,f,t);s&&(o.has(s.id)&&(s.id=n.newId(),t.push(`${f}: its id was already used, given a new one`)),o.add(s.id),i.push(s))}),i}export function unwrapListFile(e,t){let n;try{n=JSON.parse(e)}catch(r){return{error:`Not valid JSON: ${syntaxErrorAt(e,r instanceof Error?r.message:String(r))}`}}let i;if(Array.isArray(n))i=n;else if(d(n)){const r=t.legacy?.(n);if(typeof r=="string")return{error:r};if(r)i=r;else{if(n.format!==t.format)return{error:`This is not a ${t.noun} file (expected "format": "${t.format}")`};i=n[t.key]}}else return{error:`This is not a ${t.noun} file`};if(!Array.isArray(i))return{error:`The file has no "${t.key}" list`};const o=[];return d(n)&&m(n.version)&&n.version>t.version&&o.push(`Written by a newer version (${n.version}); settings this version does not know are kept but not used`),{list:i,warnings:o}}export function readPlotsFile(e){const t=unwrapListFile(e,{format:PLOTS_FORMAT,noun:"plots",key:"plots",version:PLOTS_VERSION,legacy:r=>{if(r.format===SWEEPS_FORMAT)return Array.isArray(r.sweeps)?r.sweeps.map(l=>d(l)?{id:l.id,title:l.title,chart:"sweep",sweep:l}:l):'The file has no "sweeps" list'}});if("error"in t)return{plots:[],warnings:[],error:t.error};const{list:n,warnings:i}=t,o=readIdentified(n,i,{labelOf:(r,l)=>d(r)&&typeof r.title=="string"&&r.title?`"${r.title}"`:`plot ${l+1}`,read:readPlot,newId:b});return o.length===0&&n.length>0?{plots:o,warnings:i,error:"No plot in the file could be read"}:{plots:o,warnings:i}}export function writePlotsFile(e){return JSON.stringify({format:PLOTS_FORMAT,version:PLOTS_VERSION,plots:e},null,2)+`
4
+ `}export function addPlots(e,t){const{items:n,copies:i}=addIdentified(e,t,o=>o.title??o.id,b);return{plots:n,copies:i}}export function addIdentified(e,t,n,i){const o=new Set(e.map(f=>f.id)),r=[],l=t.map(f=>{if(!o.has(f.id))return o.add(f.id),f;const s=i();return o.add(s),r.push(n(f)),{...f,id:s}});return{items:[...e,...l],copies:r}}export function plotIssue(e){const t="a plot from a newer version may use one this version does not";if(!PLOT_CHARTS.includes(e.chart))return`The chart "${String(e.chart)}" is not one this version draws (${PLOT_CHARTS.join(", ")}; ${t}).${$(e.chart,PLOT_CHARTS)}`;const n=e.fields??{},i=[...xFieldsOf(n.x).map(o=>["X",o]),["Y",n.y],["Colour",n.color],["Facet",n.facet],["Rows",n.rows],...e.where?.conditions.map(o=>["A filter condition",o.field])??[]];for(const[o,r]of i)if(!(r===void 0||d(r)&&("follow"in r||"none"in r))&&!isField(r))return d(r)&&"builtin"in r?`${o}: "${String(r.builtin)}" is not a built-in field of this version (${PLOT_BUILTINS.join(", ")}; ${t}).${$(r.builtin,PLOT_BUILTINS)}`:`${o}: ${JSON.stringify(r)} is not a field this version reads (a newer version may have added it). A field is written like ${N}`}
@@ -0,0 +1,18 @@
1
+ import type { CsvColumn } from '../core/tableCsv.js';
2
+ import { type ResolvedPlot } from './plotData.js';
3
+ export type PlotTableCell = string | number | null;
4
+ export type PlotTableRow = PlotTableCell[];
5
+ export interface PlotTable {
6
+ /** A file name stem: the plot's title, safe to use. */
7
+ name: string;
8
+ columns: CsvColumn<PlotTableRow>[];
9
+ rows: PlotTableRow[];
10
+ }
11
+ /** A title as a file name stem: letters, numbers and single dashes. */
12
+ export declare function fileStem(title: string): string;
13
+ /**
14
+ * The table behind a resolved plot, or undefined when nothing is drawn. `waferLabel(i)` names the wafer of item i.
15
+ * A plot of panels gives each panel's rows under a Panel column.
16
+ */
17
+ export declare function plotTable(r: ResolvedPlot, waferLabel: (item: number) => string): PlotTable | undefined;
18
+ //# sourceMappingURL=plotTable.d.ts.map
@@ -0,0 +1 @@
1
+ import{quantile as x}from"./math.js";import{probabilityPosition as E}from"./plotData.js";const p=(t,e)=>t?t.unit?`${t.label} (${t.unit})`:t.label:e,f=t=>Number.isFinite(t)?t:null,v=t=>t.map((e,d)=>({header:e,get:g=>g[d]??null}));export function fileStem(t){return t.normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,80)||"plot"}function y(t,e,d){const g=o=>t.groups[o]??"",w=t.groups.length>1,r=w?[t.colorLabel??"Group"]:[],h=o=>w?[g(o)]:[];switch(e.type){case"scatter":{const o=e.points.some(n=>n.die&&n.die.x!==void 0),i=["Wafer",...o?["Die X","Die Y"]:[],p(t.x,"X"),p(t.y,"Y"),...r,...t.colorScale?[t.colorScale.label]:[]],l=e.points.map(n=>[d(n.item),...o?[n.die?.x??null,n.die?.y??null]:[],f(n.x),f(n.y),...h(n.group),...t.colorScale?[n.value===void 0?null:f(n.value)]:[]]);return{headers:i,rows:l}}case"histogram":case"probability":{const o=e.type==="probability",i=e.values.flatMap((s,a)=>s.map((u,c)=>e.unit(e.units[a][c]).die)).some(s=>s&&s.x!==void 0),l=["Wafer",...i?["Die X","Die Y"]:[],...r,p(t.x,"Value"),...o?["Cumulative share (%)"]:[]],n=[];return e.values.forEach((s,a)=>{s.forEach((u,c)=>{const b=e.unit(e.units[a][c]);n.push([d(b.item),...i?[b.die?.x??null,b.die?.y??null]:[],...h(a),f(u),...o?[100*E(c,s.length)]:[]])})}),{headers:l,rows:n}}case"box":{const i=[...e.nest?.levels??[t.x?.label??"Category"],...r,"N","Min","Q1","Median","Q3","Max"],l=[];return e.categories.forEach((n,s)=>{e.cells.forEach((a,u)=>{const c=a[s].filter(Number.isFinite).sort((N,m)=>N-m);if(c.length===0)return;const b=e.nest?e.nest.parts[s]:[n];l.push([...b,...h(u),c.length,c[0],x(c,.25),x(c,.5),x(c,.75),c[c.length-1]])})}),{headers:i,rows:l}}case"bar":{const i=[...e.nest?.levels??[t.x?.label??"Category"],...r,p(t.y,"Value"),"N",...e.cumulative?["Cumulative share (%)"]:[]],l=[];return e.categories.forEach((n,s)=>{e.values.forEach((a,u)=>{const c=a[s];if(!Number.isFinite(c))return;const b=e.nest?e.nest.parts[s]:[n];l.push([...b,...h(u),c,e.cells[u]?.[s]?.length??null,...e.cumulative?[f(e.cumulative[s])]:[]])})}),{headers:i,rows:l}}case"line":{const o=e.band,i=[p(t.x,"X"),...r,p(t.y,"Value"),"N",...o?["Band low","Band high"]:[]],l=[];return e.xs.forEach((n,s)=>{e.values.forEach((a,u)=>{const c=a[s];Number.isFinite(c)&&l.push([n,...h(u),c,e.counts[u]?.[s]??null,...o?[f(o.lo[u][s]),f(o.hi[u][s])]:[]])})}),{headers:i,rows:l}}case"control":{const o=new Map(e.violations.map(n=>[n.index,n.rules.join(" ")])),i=[p(t.x,"Order"),"Wafer",p(t.y,"Value"),"Centre","Lower limit","Upper limit","Rules broken"],l=e.xs.map((n,s)=>[n,d(e.items[s]),f(e.values[s]),e.limits.centre,e.limits.lcl,e.limits.ucl,o.get(s)??""]);return{headers:i,rows:l}}case"heatmap":{const o=[t.y?.label??"Row",t.x?.label??"Column",t.colorScale?.label??"Value","N"],i=[];return e.rows.forEach((l,n)=>e.cols.forEach((s,a)=>{const u=e.values[n][a];Number.isFinite(u)&&i.push([l,s,u,e.cellUnits[n][a].length])})),{headers:o,rows:i}}case"goal":{const o=["Test number","Test",...r,"Mean offset (share of limit window)","Spread (share of limit window)","Ppk","N","Limits"],i=e.points.map(l=>[l.testNumber,l.label,...h(l.group),f(l.x),f(l.y),f(l.ppk),l.n,l.basis==="spec"?"spec":"test"]);return{headers:o,rows:i}}}}export function plotTable(t,e){const d=r=>e(r)??"",g=fileStem(t.spec.title??t.autoTitle);if(t.facets?.length){let r;const h=[];for(const o of t.facets){if(!o.plot.marks)continue;const i=y(o.plot,o.plot.marks,d);if(i){r??=[t.facetLabel??"Panel",...i.headers];for(const l of i.rows)h.push([o.label,...l])}}return r?{name:g,columns:v(r),rows:h}:void 0}if(!t.marks)return;const w=y(t,t.marks,d);return w?{name:g,columns:v(w.headers),rows:w.rows}:void 0}